<template>
  <div class="manage-container">
    <el-form ref="queryForm" :model="queryForm" label-width="100px">
      <vab-query-form>
        <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 @click="resetForm()">
            {{ $t('defalult.chongz') }}
          </el-button>
          <el-button type="primary" size="medium" @click="search">
            {{ $t('defalult.cx') }}
          </el-button>
          <el-button type="primary" size="medium" @click="exportData">
            {{ $t('defalult.dc') }}
          </el-button>
        </el-form-item>
      </vab-query-form>
    </el-form>
    <el-card style="height: 380px">
      <div id="main2" 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,
  getReportHistoryData,
  exportIotData,
  sensors,
  sensorInfo,
} from '@/api/device';
import { formatDateTime, getDate, getFMdate } from '@/common/times';
import * as echarts from 'echarts';
import ajax from '@/api/download';
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: [],
      queryForm: {
        page: 1,
        size: 10,
        sensorName: '',
        deviceCode: '',
        dataKey: '',
        end: '',
      },
      startDate: '',
    };
  },
  computed: {
    height() {
      return 500;
    },
  },
  created() {
    this.queryForm.end = this.queryForm.start = getFMdate(-1);
    this.queryForm.dataKey = this.$route.query.dataKey;
    this.queryForm.deviceCode = this.$route.query.deviceCode;
    this.setDefaultTime();
    this.getSensorsData();
    this.sensorInfo();
    this.fetchData();
  },
  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.getHistoryData();
      }, 500);
    },
    async sensorInfo() {
      const { data } = await sensorInfo(this.queryForm);
      this.sensorInfoData = data;
    },
    async getSensorsData() {
      const { data } = await sensors(this.queryForm);
      this.sensorsData = data;
    },
    async getHistoryData() {
      var myChart = echarts.init(document.getElementById('main2'));
      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',
          },
        ],
        series: [
          {
            name: '数据',
            type: 'line',
            smooth: true,
            symbol: 'none',
            areaStyle: {},
            data: data,
          },
        ],
      };
      option && myChart.setOption(option);
    },
    setDefaultTime() {
      this.queryForm.end = getFMdate(0);
      this.queryForm.start = getFMdate(-1);
      this.startDate = [getFMdate(-1), getFMdate(0)];
    },
    //导出
    async exportData() {
      const url = await exportIotData(this.queryForm);
      ajax.downloadFile(url, { fileName: '站点最新数据.xls' });
    },
    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;
      });
    },
    resetForm() {
      this.$refs.queryForm.resetFields();
    },
    showData(row) {
      this.queryForm.dataKey = row.dataKey;
      this.fetchData();
    },
    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);
      console.log(this.newTableData);
      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>
