<template>
  <div class="manage-container">
    <el-form ref="form" :model="queryForm" label-width="100px">
      <vab-query-form>
        <el-form-item width="100" :label="$t('defalult.sj')">
          <el-date-picker
            v-model="startDate"
            type="daterange"
            range-separator="-"
            :start-placeholder="$t('defalult.ksrq')"
            :end-placeholder="$t('defalult.jsrq')"
            @change="handleStartDateChange"
          ></el-date-picker>
        </el-form-item>
        <el-form-item width="100" prop="deviceCode" :label="$t('sensor.qgq')">
          <el-select
            v-model="queryForm.dataKey"
            :placeholder="$t('sensor.qxzqgq')"
          >
            <el-option
              v-for="item in sensorsData"
              :key="item.transferId"
              :label="item.name"
              :value="item.transferId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item width="100">
          <el-button type="primary" size="medium" @click="search">
            {{ $t('defalult.cx') }}
          </el-button>
        </el-form-item>
      </vab-query-form>
    </el-form>
    <el-card style="height: 380px">
      <div id="main3" ref="echarts" style="height: 380px"></div>
    </el-card>
    <el-table
      v-loading="listLoading"
      :data="newTableData"
      border
      stripe
      style="width: 100%"
    >
      <el-table-column
        prop="time"
        :label="$t('sensor.ccsj')"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="name"
        :label="$t('sensor.cgqmc')"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="dataKey"
        :label="$t('sensor.csid')"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="value"
        :label="$t('sensor.zhi')"
        label="值"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="unit"
        :label="$t('sensor.dw')"
        align="center"
      ></el-table-column>
    </el-table>
    <vab-query-form>
      <vab-query-form-right-panel>
        <el-pagination
          :background="background"
          :current-page="queryForm.page"
          :layout="layout"
          :page-size="queryForm.size"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        ></el-pagination>
      </vab-query-form-right-panel>
    </vab-query-form>
  </div>
</template>
<script>
import {
  getHistoryData,
  sensorInfo,
  sensors,
  getReportHistoryData,
} from '@/api/device';
import { getFMdate, getDate, formatDateTime } from '@/common/times';
import * as echarts from 'echarts';
export default {
  components: {},
  data() {
    return {
      newTableData: [],
      data: [],
      deviceCode: '',
      projectId: '',
      lazy: true,
      layout: 'total, sizes, prev, pager, next, jumper',
      total: 0,
      background: true,
      listLoading: true,
      elementLoadingText: '正在加载...',
      deviceId: '',
      historyData: [],
      sensorsData: [],
      sensorInfoData: [],
      startDate: '',
      queryForm: {
        page: 1,
        size: 10,
        dataKey: '',
        deviceCode: '',
        start: '',
        end: '',
      },
    };
  },
  computed: {
    height() {
      return 500;
    },
  },
  methods: {
    async fetchData() {
      this.listLoading = true;
      const { data } = await getHistoryData(this.queryForm);
      this.data = data;
      this.total = data.length;
      this.handleCurrentChange(1);
      setTimeout(() => {
        this.listLoading = false;
        this.getReportHistory();
        console.log(123);
      }, 500);
    },
    async getReportHistoryData() {},
    async getSensorsData() {
      const { data } = await sensors(this.queryForm);
      this.sensorsData = data;
    },
    showData(row) {
      this.queryForm.dataKey = row.dataKey;
      this.queryForm.deviceCode = row.deviceCode;
      this.queryForm.end = getFMdate(0);
      this.queryForm.start = getFMdate(-1);
      this.startDate = [getFMdate(-1), getFMdate(0)];
      this.sensorInfo();
      this.fetchData();
      this.getSensorsData();
    },
    async sensorInfo() {
      const { data } = await sensorInfo(this.queryForm);
      this.sensorInfoData = data;
    },
    handleStartDateChange() {
      if (this.startDate && this.startDate.length > 0) {
        const timestampBegin = +new Date(this.startDate[0]);
        const timestampEnd = +new Date(this.startDate[1]);
        if (timestampEnd > timestampBegin + 3600 * 1000 * 24 * 30) {
          this.$alert('日期的起止时间跨度不能超过30天', '提示', {
            confirmButtonText: '确定',
            type: 'warning',
          })
            .then(() => (this.startDate = null))
            .catch(() => (this.startDate = null));
        } else {
          this.queryForm.end = getDate(this.startDate[1]);
          this.queryForm.start = getDate(this.startDate[0]);
        }
      }
    },
    async getReportHistory() {
      var myChart = echarts.init(document.getElementById('main3'));
      var option;
      const { data } = await getReportHistoryData(this.queryForm);
      var yData = [];
      for (let i = 0; i < data.length; i++) {
        yData.push(data[i][1]);
      }
      var min = Math.min.apply(null, yData);
      var max = Math.max.apply(null, yData);
      option = {
        tooltip: {
          trigger: 'axis',
          position: function (pt) {
            return [pt[0], '10%'];
          },
        },
        title: {
          left: 'center',
          text: '折线图',
        },
        toolbox: {
          feature: {
            dataZoom: {
              yAxisIndex: 'none',
            },
            restore: {},
            saveAsImage: {},
          },
        },
        xAxis: {
          type: 'time',
          boundaryGap: false,
        },
        yAxis: {
          type: 'value',
          boundaryGap: [0, '100%'],
          min: min,
          max: max,
        },
        dataZoom: [
          {
            type: 'inside',
            start: 0,
            end: 20,
          },
          {
            start: 0,
            end: 20,
          },
        ],
        series: [
          {
            name: '数据',
            type: 'line',
            smooth: true,
            symbol: 'none',
            areaStyle: {},
            data: data,
          },
        ],
      };
      option && myChart.setOption(option);
    },
    search() {
      this.sensorInfo();
      this.fetchData();
    },
    timeToStr() {
      var sensorInfo = this.sensorInfoData;
      this.newTableData.forEach(item => {
        item['time'] = formatDateTime(item[0]);
        item['value'] = item[1];
        item['name'] = sensorInfo.name;
        item['unit'] = sensorInfo.unit;
        item['dataKey'] = sensorInfo.dataKey;
      });
    },
    handleQuery() {
      this.queryForm.page = 1;
    },
    handleSizeChange(val) {
      this.queryForm.size = val;
    },
    handleCurrentChange(val) {
      this.queryForm.page = val;
      const size = this.queryForm.size;
      this.newTableData = this.data.slice((val - 1) * size, val * size);
      this.timeToStr();
    },
  },
};
</script>

<style lang="scss" scoped>
.manage-container {
  width: 100%;
  .vab-query-form {
    margin-bottom: 30px;
    .el-input {
      width: 180px;
      margin-right: 20px;
    }
  }
}
</style>
