<template>
  <view class="data-view">
    <view class="select-box">
      <uni-row >
        <uni-col :span="8">
          <uni-data-select :clear="false"  v-model="imei" :localdata="agriList" @change="changeAgri"></uni-data-select>
        </uni-col>
        <uni-col :span="16">
          <uni-datetime-picker v-model="dateRange" type="datetimerange" :end="end" @change="changeDate"/>
        </uni-col>
      </uni-row>
    </view>
    <view class="charts-box">
      <qiun-data-charts
          type="line"
          :opts="opts"
          background="#ffffff"
          :chartData="chartData"
          :canvas2d="true"
          canvasId="nMPkeQGNEosMwoWKKNRBZBIEhguMoMWp"
          :ontouch="true"
          :disableScroll="true"
          :onmovetip="true"
          tooltipFormat="tooltipDemo"
      />
    </view>
    <view class="uni-padding-wrap uni-common-mt tag-row">
      <button @click.stop="jumpDate(-1)" style="margin-right: 20rpx;" type="primary" size="mini">前一天</button>
      <button :disabled="isTodayDate(dateRange[0]) || isTodayDate(dateRange[1]) || dateRange.length===0" @click.stop="jumpDate(1)" style="margin-right: 20rpx;" type="default" size="mini">后一天</button>
      <button @click.stop="jumpDate(0)" type="warn" size="mini">回到当天</button>
    </view>
    <!--  暂无数据 -->
  </view>
</template>

<script>
import { getHistoryData} from "../../api/system/data";
import {listAgri} from "../../api/system/assets/agri";
import {parseTime, isIntervalMoreThanNDays, getExactDiffDays, isTodayDate} from "../../utils/agri";

export default {
  data: function () {
    return {
      chartData: {},
      //这里的 opts 是图表类型 type="line" 的全部配置参数，您可以将此配置复制到 config-ucharts.js 文件中下标为 ['line'] 的节点中来覆盖全局默认参数。实际应用过程中 opts 只需传入与全局默认参数中不一致的【某一个属性】即可实现同类型的图表显示不同的样式，达到页面简洁的需求。
      opts: {
        legend: {
        },
        xAxis: {
          rotateAngle: 75,
          format: "xAxisDemo"
        },
        yAxis: {
          gridType: "dash",
          dashLength: 2,
          disabled: false,
          disableGrid: false,
          splitNumber: 5,
          gridColor: "#CCCCCC",
          padding: 10,
          showTitle: true,
          data: [
            {
              type: "value",
              position: "left",
              disabled: false,
              axisLine: true,
              axisLineColor: "#CCCCCC",
              calibration: true,
              fontColor: "#666666",
              fontSize: 13,
              textAlign: "left",
              title: "温度（℃）",
              titleFontSize: 14,
              titleOffsetY: -10,
              titleOffsetX: 5,
              titleFontColor: "#333333",
              min: 0,
              max: 50,
              tofix: 1,
              unit: "",
              format: ""
            },
            {
              type: "value",
              position: "right",
              disabled: false,
              axisLine: true,
              axisLineColor: "#CCCCCC",
              calibration: true,
              fontColor: "#666666",
              fontSize: 13,
              textAlign: "right",
              title: "湿度（%RH）",
              titleFontSize: 14,
              titleOffsetY: -10,
              titleOffsetX: 0,
              titleFontColor: "#333333",
              min: 0,
              max: 100,
              tofix: 1,
              unit: "",
              format: ""
            }
          ]
        }
      },
      dateRange:[],
      end:Date.now(),
      agriList:[],
      imei:null
    };
  },
  mounted() {
    // this.getAgriList();
  },
  methods: {
    isTodayDate,
    getServerData() {
      const param = {
        imei: this.imei,
        startTime: this.dateRange[0],
        endTime: this.dateRange[1]
      }
      //模拟从服务器获取数据时的延时
      getHistoryData(param).then(response => {
        if (response.code === 200 && response.data) {
          var data = response.data;
          this.chartData = JSON.parse(JSON.stringify(data));
        }
      })
    },
    getAgriList() {
      listAgri({status: 1}).then(response => {
        if (response.code === 200) {
          this.agriList = response.rows.map(item => ({
            agriId: item.id,
            text: item.agriName,
            value: item.imei // 提取并改名
          }));

          this.imei = this.agriList[0].value;
          this.getServerData();
        }
      })
    },
    changeAgri(imei) {
      if (imei) {
        this.getServerData();
      }
    },
    changeDate(date) {
      // date[0]-date[1]
      if (isIntervalMoreThanNDays(date[0],date[1],7)) {
        this.$modal.alert('时间范围暂不支持查询超过7天以上的数据！');
        return;
      }
      if (date[0] === date[1]) {
        this.dateRange[0] = parseTime(date[0], '{y}-{m}-{d} 00:00:00')
      }
      if (this.imei) {
        this.getServerData();
      }
    },
    jumpDate(days) {

      // 多选情况 ||  时间范围今天以后不能选
      // days: 前一天(-1) 后一天(1) 回到当天(0)
      let targetDate;
      if (this.dateRange.length === 0 || getExactDiffDays(this.dateRange[0],this.dateRange[1])>1) {
        this.dateRange[0] = new Date();
      }
      if (days === 0) {
        // 回到当天
        targetDate = new Date();
      } else {
        // 前一天或后一天
        const currentStartDate = new Date(this.dateRange[0]);
        targetDate = new Date(currentStartDate);
        targetDate.setDate(targetDate.getDate() + days);
      }

      // 设置开始时间为目标日期的 00:00:00
      const startDate = new Date(targetDate);
      startDate.setHours(0, 0, 0, 0);

      // 设置结束时间
      let endDate;
      if (days === 0) {
        // 回到当天，结束时间为当前时间
        endDate = new Date();
      } else {
        // 前一天或后一天，结束时间为目标日期的 23:59:59
        endDate = new Date(targetDate);
        endDate.setHours(23, 59, 59, 999);
      }

      // 更新 dateRange
      this.dateRange = [
        parseTime(startDate ),
        parseTime(endDate)
      ];

      setTimeout(() => {
        this.$nextTick(() => {
          // 如果已选择设备，重新获取数据
          if (this.imei) {
            this.getServerData();
          }
        })
      }, 500)
    }
  }
};
</script>

<style scoped>
.data-view {
  background: #ffffff;
}
.select-box {
  margin-top: 10rpx;
}
.charts-box {
  width: 100%;
  height: 500px;
}
/deep/ .uni-select, /deep/ .uni-date-editor--x {
  background: #fff !important;
  height: 68rpx;
}
.tag-row {
  text-align: center;
  padding-bottom: 20rpx;
}
</style>