<template>
  <div class="manage-container">
    <el-form ref="queryForm" :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="开始日期"
            end-placeholder="结束日期"
            @change="handleStartDateChange"
          ></el-date-picker>
        </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="data"
      border
      stripe
      style="width: 100%"
    >
      <el-table-column
        prop="name"
        :label="$t('sensor.cgqmc')"
        width="200"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="type"
        label="传感器类型"
        width="120"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="dataKey"
        label="传输id"
        width="120"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="dataValue"
        label="值"
        width="120"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="unit"
        :label="$t('sensor.dw')"
        width="120"
        align="center"
      ></el-table-column>
    </el-table>
  </div>
</template>
<script>
import {
  getHistoryData,
  getLatestDataByDevices,
  exportData,
} from '@/api/device';
import { getDate, getFMdate } from '@/common/times';
import * as echarts from 'echarts';
import ajax from '@/api/download';
export default {
  components: {},
  data() {
    return {
      newTableData1: [],
      data: [],
      deviceCode: '',
      projectId: '',
      lazy: true,
      layout: 'total, sizes, prev, pager, next, jumper',
      total: 0,
      background: true,
      listLoading: true,
      elementLoadingText: '正在加载...',
      deviceId: '',
      historyData: [],
      queryForm: {
        sensorName: '',
        deviceCode: '',
      },
      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.fetchData();
  },
  methods: {
    async fetchData() {
      this.listLoading = true;
      const { data } = await getLatestDataByDevices(this.queryForm);
      this.data = data;
      this.total = data.length;
      this.handleCurrentChange(1);
      setTimeout(() => {
        this.listLoading = false;
        this.getHistoryData();
      }, 500);
    },
    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 getHistoryData() {
      var myChart = echarts.init(document.getElementById('main2'));
      var option;
      const { data } = await getHistoryData(this.queryForm);
      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%'],
        },
        dataZoom: [
          {
            type: 'inside',
            start: 0,
            end: 20,
          },
          {
            start: 0,
            end: 20,
          },
        ],
        series: [
          {
            name: '数据',
            type: 'line',
            smooth: true,
            symbol: 'none',
            areaStyle: {},
            data: data,
          },
        ],
      };
      console.log(option);
      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 exportData(this.queryForm);
      ajax.downloadFile(url, { fileName: '站点最新数据.xls' });
    },
    search() {
      this.getHistoryData();
    },
    resetForm() {
      this.$refs.queryForm.resetFields();
    },
    showData(row) {
      this.queryForm.dataKey = row.dataKey;
    },
    handleQuery() {
      this.queryForm.page = 1;
    },
    handleSizeChange(val) {
      this.queryForm.size = val;
    },
    handleCurrentChange(val) {
      this.queryForm.page = val;
      const size = this.queryForm.size;
      this.newTableData1 = this.data.slice((val - 1) * size, val * size);
    },
  },
};
</script>

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