<template>
  <div class="searchPage">
    <div class="searchBox">
      <el-form ref="form" :model="form" inline label-width="80px">
        <el-form-item label="点名：">
          <el-input style="width: 250px;" placeholder="请输入点名" size="middle" v-model="form.pointId" clearable></el-input>
        </el-form-item>
        <el-form-item label="描述：">
          <el-input placeholder="请输入描述" size="middle" v-model="form.pointName" clearable></el-input>
        </el-form-item>
        <el-form-item label=" ">
          <el-checkbox v-model="form.autoReq" label="刷新" border @change="reReqAjax"></el-checkbox>
        </el-form-item>
      </el-form>
      <div class="btnBox">
        <el-button type="primary" size="middle" @click="getTableData">查询</el-button>
        <el-button type="warning" size="middle" @click="exportExcel('tableData')" v-if="tableData.length">导出</el-button>
      </div>
    </div>
    <div class="tableBox">
      <el-table :data="tableData" align="center" header-align="center" style="width: 100%;" height="700" max-height="700"
        :fit="true">
        <el-table-column type="index" :index="indexMethod" label="序号" width="100"></el-table-column>
        <el-table-column prop="pointId" label="点名" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="pointName" label="描述" width="400" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="value" label="值" width="300"></el-table-column>
        <el-table-column prop="timeDate" label="时间戳" width="260"></el-table-column>
        <el-table-column fixed="right" label="操作" width="150">
          <template slot-scope="scope">
            <el-button @click="goDetails(scope.row)" type="text" size="small">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="block" style="margin-top:5px;" align="right">
      <el-pagination @size-change="handleSizerealChange" @current-change="getPaginationCurrent" :current-page="currentPage"
        :page-sizes="[100, 200, 300, 400]" :page-size="pagesizereal" layout="total, sizes, prev, pager, next, jumper"
        :total="currentPageTotal">
      </el-pagination>
      <!-- <el-pagination
          background
          layout="prev, pager, next"
          :page-size="pagesize"
          :current-page.sync="currentPage"
          @current-change="getPaginationCurrent"
          :total="currentPageTotal">
        </el-pagination> -->
    </div>
    <el-dialog title="查看详情" top="50px" :visible.sync="showDialog" width="95%" @closed="(res) =>{ this.form.dateArea=[this.fmtDate(new Date(new Date().setTime(new Date().getTime() - 3600 * 1000 * 24))), this.fmtDate(new Date()) ];this.detailsTableData=[]; }">
      <div class="searchBox">
        <el-form ref="form" :model="form" inline label-width="80px">
          <el-form-item label="点名：">
            <el-input readonly style="width: 300px;" size="middle" v-model="pointId" clearable></el-input>
          </el-form-item>
          <el-form-item label="日期：">
            <el-date-picker size="medium" value-format="yyyy-MM-dd HH:mm:ss" v-model="form.dateArea" type="datetimerange"
              :picker-options="pickerOptions" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" align="right"
              @change="(res) => { this.getDatePickerChange(res); }">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="间隔：">
            <el-input placeholder="请输入间隔" clearable v-model="form.interval" type="number"></el-input>
          </el-form-item>
        </el-form>
        <div class="btnBox">
          <el-button type="primary" size="middle" @click="getDetails">查询</el-button>
          <el-button type="warning" size="middle" @click="exportExcel('detailsTableData')" v-if="detailsTableData.length">导出</el-button>
          <el-button type="success" size="middle" @click="renderCharts" v-if="detailsTableData.length">查看折线图</el-button>
        </div>
      </div>
      <div class="tableBox" style="margin-top:0;">
        <el-table :data="detailsTableData.slice((currentPage-1)*pagesize,currentPage*pagesize)" align="center"
          header-align="center" style="width: 100%" max-height="450" height="450" :fit="true">
          <el-table-column type="index" :index="indexMethod" label="序号" width="100"></el-table-column>
          <!-- <el-table-column prop="pointId" label="点名" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column prop="pointName" label="描述" width="400" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column prop="timeDate" label="时间戳" width="260"></el-table-column>
          <el-table-column prop="value" label="值" width="300"></el-table-column> -->
          <el-table-column prop="timeDate" label="时间戳"></el-table-column>
          <el-table-column prop="value" label="值"></el-table-column>
        </el-table>
      </div>
      <div class="block" style="margin-top:5px;">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]" :page-size="pagesize" layout="total, sizes, prev, pager, next, jumper" :total="detailsTableData.length">
        </el-pagination>
      </div>
    </el-dialog>
    <el-dialog title="查看折线图" top="100px" :visible.sync="chartDialogShow" width="60%">
      <div id="lineChart" style="width:100%;height:500px;"></div>
    </el-dialog>
  </div>
</template>

<script>
import { Message } from 'element-ui';
import * as echarts from "echarts";

export default {
  data () {
    return {
      tableid: "",
      pointId: "",
      form: {
        pointId: "",
        pointName: "",
        autoReq: false,
        dateArea: [
          this.fmtDate(new Date(new Date().setTime(new Date().getTime() - 3600 * 1000 * 24))),
          this.fmtDate(new Date())
        ],
        interval: ""
      },
      showDialog: false,
      chartDialogShow: false,
      tableData: [],
      detailsTableData: [],
      autoReqTimmer: null,

      currentPage: 1,
      pagesize: 10,
      pagesizereal: 100,
      currentPageTotal: 0,
      pickerOptions: {
        shortcuts: [{
          text: '最近一天',
          onClick (picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一周',
          onClick (picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick (picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick (picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      }
    }
  },

  mounted () {
    let that = this;
    that.$nextTick(() => {
      that.tableid = that.$route.query.tableid;
      that.getTableData();
    });
  },

  destroyed () {
    clearInterval(this.autoReqTimmer);
    this.autoReqTimmer = null;
  },

  created () {
    let that = this
    that.tableid = "JSFW";
    that.getTableData();
  },

  methods: {
    // 获取表格数据
    getTableData (skipLoading) {
      if (!skipLoading) {
        this.$store.commit("loadingStore", true);
      }
      this.API.get("datacenter/realtimeData?tableid=" + this.tableid + "&pointId=" + this.form.pointId + "&pointName=" + this.form.pointName + "&pageNum=" + this.currentPage + "&pageSize=" + this.pagesizereal).then((res) => {
        res.data.forEach(ele => {
          ele.timeDate = this.fmtDate(new Date(ele.time));
          if (ele.value > 0) {
            ele.value = parseFloat(ele.value).toFixed(4);
          }
        });
        this.tableData = res.data || [];
        this.currentPageTotal = res.count || [];
        if (!skipLoading) {
          this.$store.commit("loadingStore", false);
        }
      });
    },

    // index渲染函数
    indexMethod (index) {
      return index + 1;
    },

    // 查看详情按钮被点击
    goDetails (row) {
      this.pointId = row.pointId;
      this.showDialog = true;
    },

    // 获取详情
    getDetails () {
      if (!this.form.dateArea || !this.form.dateArea.length) {
        Message.error("请先选择要查询的日期区间后再试");
      } else {
        this.$store.commit("loadingStore", true);
        let begin = (this.form.dateArea.length ? this.form.dateArea[0] : '');
        let end = (this.form.dateArea.length ? this.form.dateArea[1] : '');

        this.API.get("datacenter/historyData?pointId=" + this.pointId + "&begin=" + begin + "&end=" + end + (this.form.interval ? ("&interval=" + this.form.interval) : '')).then((res) => {
          if (res.data.length) {
            res.data.forEach(ele => {
              ele.timeDate = this.fmtDate(new Date(ele.time));
              if (ele.value > 0) {
                ele.value = parseFloat(ele.value).toFixed(4);
              }
            });
            this.detailsTableData = res.data || [];
          } else {
            Message.warning("所选日期区间之内暂无数据，请重试");
          }
          this.$store.commit("loadingStore", false);
        });
      }
    },

    // 初始页currentPage、初始每页数据数pagesize和数据data
    handleSizeChange: function (size) {
      this.pagesize = size;
    },
    handleSizerealChange: function (size) {
      this.currentPage = 1;
      this.pagesizereal = size;
      this.getTableData();
    },
    handleCurrentChange: function (currentPage) {
      this.currentPage = currentPage;
    },

    // 导出excel
    exportExcel (tableDataName) {
      if (tableDataName === 'tableData') {
        let tableid = this.tableid;
        let pointId = this.form.pointId || '';
        let pointName = this.form.pointName || '';
        this.API.get("datacenter/realtimeExport?tableid=" + tableid + "&pointId=" + pointId + "&pointName=" + pointName).then(res => {
          const { export_json_to_excel } = require('@tools/excel/Export2Excel.js'); // 注意这个Export2Excel路径      
          const tHeader = ['点名', '描述']; // 上面设置Excel的表格第一行的标题       
          const filterVal = ['id', 'name']; // 上面的index、nickName、name是tableData里对象的属性key值   
          const list = res.data; //把要导出的数据tableData存到list 
          const data = this.formatJson(filterVal, list);
          export_json_to_excel(tHeader, data, '导出的Excel'); // 最后一个是表名字
        });
      } else {
        const { export_json_to_excel } = require('@tools/excel/Export2Excel.js'); // 注意这个Export2Excel路径      
        const tHeader = ['点名', '描述', '时间戳', '值']; // 上面设置Excel的表格第一行的标题       
        const filterVal = ['pointId', 'pointName', 'timeDate', 'value']; // 上面的index、nickName、name是tableData里对象的属性key值   
        const list = this[tableDataName]; //把要导出的数据tableData存到list 
        const data = this.formatJson(filterVal, list);
        export_json_to_excel(tHeader, data, '导出的Excel'); // 最后一个是表名字
      }
    },

    formatJson (filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]));
    },

    // 刷新开关
    reReqAjax () {
      clearInterval(this.autoReqTimmer);
      this.autoReqTimmer = null;
      if (this.form.autoReq) {
        Message.success("已开启自动刷新数据，每间隔 1 秒自动刷新一次数据");
        this.autoReqTimmer = setInterval(() => {
          this.getTableData(true);
        }, 1000);
      } else {
        Message.warning("已关闭自动刷新数据");
      }
    },

    // 分页器每页数量修改
    getPaginationSize (value) {
      this.currentPageSize = value;
      this.getDetails();
    },

    // 分页器页数修改
    getPaginationCurrent (value) {
      this.currentPage = value;
      this.getTableData();
    },

    // 获取选中的时间
    getDatePickerChange (value) {
      this.detailsTableData = [];
    },

    // 渲染折线图
    renderCharts () {
      this.chartDialogShow = true;
      this.$nextTick(() => {

        let xAxisData = [];
        let seriesData = [];

        this.detailsTableData.forEach(ele => {
          xAxisData.push(ele.timeDate);
          seriesData.push(ele.value);
        });
        document.getElementById("lineChart").removeAttribute("_echarts_instance_");
        let chartDom = document.getElementById('lineChart');
        let myChart = echarts.init(chartDom);

        let option = {
          xAxis: {
            type: 'category',
            data: xAxisData
          },
          yAxis: {
            type: 'value'
          },
          series: [{
            data: seriesData,
            type: 'line',
            smooth: true,
            name: "值"
          }],
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross',
              label: {
                backgroundColor: '#6a7985'
              }
            }
          }
        };
        option && myChart.setOption(option);
      });
    },

    // 格式化日期
    fmtDate (date) {
      let curDate = date || new Date();
      let year = curDate.getFullYear();
      let mouth = curDate.getUTCMonth() + 1;
      let day = curDate.getDate();
      let hour = curDate.getHours();
      let minutes = curDate.getMinutes();
      let seconds = curDate.getSeconds();
      return year + '-' + (mouth < 10 ? '0' + mouth : mouth) + '-' + (day < 10 ? '0' + day : day) + ' ' + (hour < 10 ? '0' + hour : hour) + ':' + (minutes < 10 ? '0' + minutes : minutes) + ':' + (seconds < 10 ? '0' + seconds : seconds);
    },
  },

  watch: {
    $route (value) {
      this.tableid = value.query.tableid;
      this.form.pointName = "";
      this.form.autoReq = false;
      clearInterval(this.autoReqTimmer);
      this.autoReqTimmer = null;
      this.getTableData();
    }
  }
}
</script>
  
<style lang="scss" scoped>
.searchBox {
  width: 80%;
  display: flex;
  justify-content: start;
  align-items: center;
  position: relative;

  .btnBox {
    position: absolute;
    left: calc(100% + 20px);
    top: 0;
    display: flex;
    justify-content: start;
    align-items: center;
  }

  .el-input {
    width: 150px;
  }
}

.tableBox {
  margin-top: 10px;
}

.paginationBox {
  width: 100%;
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
</style>
<style lang="scss">
.tableBox {
  .cell {
    text-align: center;
  }
}
.searchPage {
  .el-dialog__body {
    padding: 10px 20px;
    max-height: 570px;
    overflow: hidden;
  }
}
</style>
