<template>
  <div>
    <div class="query mg-b-8">
      <div class="query-items">
        <div class="query-item">
          <div class="lable">点名：</div>
          <div class="search-input">
            <el-input style="width: 250px;" placeholder="请输入点名" size="middle" v-model="form.pointId" clearable></el-input>
          </div>
        </div>
        <div class="query-item">
          <div class="lable">描述：</div>
          <div class="search-input">
            <el-input placeholder="请输入描述" size="middle" v-model="form.pointName" clearable></el-input>
          </div>
        </div>
        <div class="query-item">
          <div class="lable"></div>
          <div class="search-input">
            <el-checkbox v-model="form.autoReq" label="刷新" border @change="reReqAjax"></el-checkbox>
          </div>
        </div>
      </div>
      <div class="query-actions">
        <button class="btn green" @click="getTableData">查询</button>
        <button class="btn green" @click="exportExcel('tableData')">导出</button>
      </div>
    </div>
    <div class="searchPage">
      <div style="width:200px;height:100vh">
        <CollapseList :list="menus" @click="clickMenu" />
      </div>
      <div class="df-table">
        <ComTable height="78vh" :data="tableData" :pageSize="20" @onPagging="onChangePage"></ComTable>
      </div>
    </div>
    <el-dialog title="查看详情" v-model="showDialog" width="85%" top="10vh" custom-class="modal" :close-on-click-modal="true" @closed="(res) => { pointId=''; }">
      <div class="query mg-b-8">
      <div class="query-items">
        <div class="query-item">
          <div class="lable">点名：</div>
          <div class="search-input">
            <el-input readonly style="width: 300px;" size="middle" v-model="pointId" clearable></el-input>
          </div>
        </div>
        <div class="query-item">
          <div class="lable">日期：</div>
          <div class="search-input">
            <el-date-picker size="medium" v-model="form.dateArea" type="datetimerange"
              :picker-options="pickerOptions" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" align="right"
              @change="(res) => { getDatePickerChange(res); }">
            </el-date-picker>
          </div>
        </div>
        <div class="query-item">
          <div class="lable">间隔：</div>
          <div class="search-input">
            <el-input placeholder="请输入间隔" clearable v-model="form.interval" type="number"></el-input>
          </div>
        </div>
      </div>
      <div class="query-actions">
        <button class="btn green" @click="getDetails">查询</button>
        <button class="btn green" @click="exportExcel('detailsTableData')" v-if="detailsTableData.data.length">导出</button>
        <button class="btn green" @click="renderCharts" v-if="detailsTableData.data.length">查看折线图</button>
      </div>
    </div>
    <ComTable height="50vh" :data="detailsTableData"></ComTable>
    </el-dialog>
    <el-dialog title="查看折线图" v-model="chartDialogShow" width="60%" top="10vh" custom-class="modal" :close-on-click-modal="true">
      <div id="lineChart" style="width:100%;height:500px;"></div>
    </el-dialog>
  </div>
</template>

<script>
import { Message } from 'element-plus';
import CollapseList from "@com/coms/collapse/collapse-list.vue";
import ComTable from "@com/coms/table/table.vue";
import * as echarts from "echarts";

export default {
  data () {
    const that=this;
    return {
      menus:[],
      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: {
        column: [
          {
            name: "序号",
            field: "index",
            is_num: false,
            is_light: false,
            sortable: true
          },
          {
            name: "点名",
            field: "pointId",
            is_num: false,
            is_light: false,
            sortable: true
          },
          {
            name: "描述",
            field: "pointName",
            is_num: false,
            is_light: false,
            sortable: true
          },
          {
            name: "值",
            field: "value",
            is_num: true,
            is_light: false,
            sortable: true
          },
          {
            name: "时间戳",
            field: "timeDate",
            is_num: false,
            is_light: false,
            sortable: true
          },
          {
            name: "操作",
            field: "",
            is_num: false,
            is_light: false,
            template() {
								return "<el-button type='text' style='cursor: pointer;'>详情</el-button>";
						},
            click(e, row){
              that.goDetails(row);
            }
          }
        ],
        data: [],
      },
      detailsTableData: {
        column: [
          {
            name: "序号",
            field: "index",
            is_num: false,
            is_light: false,
            sortable: true
          },
          {
            name: "时间戳",
            field: "timeDate",
            is_num: false,
            is_light: false,
            sortable: true
          },
          {
            name: "值",
            field: "value",
            is_num: true,
            is_light: false,
            sortable: true
          }
        ],
        data: [],
      },
      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]);
          }
        }]
      },
    }
  },

  components:{
    CollapseList,
    ComTable
  },

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

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

  methods: {

    // 获取左侧菜单
    getMenuList(){
      let that=this;
      that.API.requestData({
        method: "GET",
        baseURL: "http://10.155.32.4:8031/",
        subUrl: "datacenter/tables",
        success(res){
          let JSFW = {
            text: '计算服务',
            children: []
          };
          let MHS_FDC = {
            text: "麻黄山",
            children: []
          };
          let NSS_FDC = {
            text: "牛首山",
            children: []
          };
          let QS_FDC = {
            text: "青山",
            children: []
          };
          let SBQ_FDC = {
            text: "石板泉",
            children: []
          };
          let XS_FDC = {
            text: "香山",
            children: []
          };
          let DWK_GDC = {
            text: "大武口",
            children: []
          };
          let PL_GDC = {
            name: "平罗",
            children: []
          };
          let XH_GDC = {
            text: "宣和",
            children: []
          };
          let MCH_GDC = {
            text: "马场湖",
            children: []
          };
          res.data.forEach(ele => {
            ele.text=ele.tablename;
            if (ele.windpowerstationid === 'MHS_FDC') {
              MHS_FDC.children.push(ele);
            } else if (ele.windpowerstationid === 'NSS_FDC') {
              NSS_FDC.children.push(ele);
            } else if (ele.windpowerstationid === 'QS_FDC') {
              QS_FDC.children.push(ele);
            } else if (ele.windpowerstationid === 'SBQ_FDC') {
              SBQ_FDC.children.push(ele);
            } else if (ele.windpowerstationid === 'XS_FDC') {
              XS_FDC.children.push(ele);
            } else if (ele.windpowerstationid === 'DWK_GDC') {
              DWK_GDC.children.push(ele);
            } else if (ele.windpowerstationid === 'PL_GDC') {
              PL_GDC.children.push(ele);
            } else if (ele.windpowerstationid === 'XH_GDC') {
              XH_GDC.children.push(ele);
            } else if (ele.windpowerstationid === 'MCH_GDC') {
              MCH_GDC.children.push(ele);
            } else {
              JSFW.children.push(ele);
            }
          });
          that.menus.push(JSFW, MHS_FDC, NSS_FDC, QS_FDC, SBQ_FDC, XS_FDC, DWK_GDC, PL_GDC, XH_GDC, MCH_GDC);
        }
      });
    },

    // 获取表格数据
    getTableData () {
      let that=this;
      that.API.requestData({
        baseURL:"http://10.155.32.4:8031/",
        subUrl:"datacenter/realtimeData",
        method:"GET",
        data:{
          tableid:that.tableid,
          pointId:that.pointId,
          pointName:that.form.pointName || "",
          pageNum:that.currentPage,
          pageSize:that.pagesizereal,
        },
        success(res){
          res.data.forEach((ele,index) => {
            ele.index = (index+1);
            ele.timeDate = that.fmtDate(new Date(ele.time));
            if (ele.value > 0) {
              ele.value = parseFloat(ele.value).toFixed(4);
            }
          });
          that.tableData.data = res.data || [];
          that.currentPageTotal = res.count || [];
        }
      });
    },

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

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

    // 获取详情
    getDetails () {
      let that=this;
      if (!that.form.dateArea || !that.form.dateArea.length) {
        that.BASE.showMsg({
          msg:"请先选择要查询的日期区间后再试"
        });
      } else {
        let begin = (this.form.dateArea.length ? new Date(this.form.dateArea[0]).formatDate("yyyy-MM-dd hh:mm:ss") : '');
        let end = (this.form.dateArea.length ? new Date(this.form.dateArea[1]).formatDate("yyyy-MM-dd hh:mm:ss") : '');

        let data = {
          pointId:that.pointId || "",
          begin,
          end,
        };

        if(this.form.interval) data.interval = that.form.interval;
        
        that.API.requestData({
          baseURL:"http://10.155.32.4:8031/",
          subUrl:"datacenter/historyData",
          method:"GET",
          data,
          success(res){
            if (res.data.length) {
              res.data.forEach((ele,index) => {
                ele.index = (index+1);
                ele.timeDate = that.fmtDate(new Date(ele.time));
                if (ele.value > 0) {
                  ele.value = parseFloat(ele.value).toFixed(4);
                }
              });
              that.detailsTableData.data = res.data || [];
            } else {
              that.BASE.showMsg({
                type:"warning",
                msg:"所选日期区间之内暂无数据，请重试"
              });
            }
            that.showDialog = true;
          }
        });
      }
    },

    // 初始页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) {
      let that = this;
      if (tableDataName === 'tableData') {
        let tableid = that.tableid;
        let pointId = that.form.pointId || '';
        let pointName = that.form.pointName || '';

        that.API.requestData({
          baseURL:"http://10.155.32.4:8031/",
          subUrl:"datacenter/realtimeExport",
          method:"GET",
          data:{
            tableid,
            pointId,
            pointName
          },
          success(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 = that.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 = that[tableDataName].data; //把要导出的数据tableData存到list 
        const data = that.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) {
        this.BASE.showMsg({
          type:"success",
          msg:"已开启自动刷新数据，每间隔 1 秒自动刷新一次数据"
        });
        this.autoReqTimmer = setInterval(() => {
          this.getTableData(true);
        }, 1000);
      } else {
        this.BASE.showMsg({
          type:"warning",
          msg:"已关闭自动刷新数据"
        });
      }
    },

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

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

    onChangePage(page) {
      this.getPaginationCurrent(page.pageIndex);
    },

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

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

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

        this.detailsTableData.data.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);
    },

    // 点击左侧菜单
    clickMenu(item){
      this.tableid = item.tableid;
      this.getTableData();
    }
  }
}
</script>
  
<style lang="less" 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;
}

.df-table {
    border: 0.093vh solid fade(@darkgray, 50%);
    position: relative;
    overflow: auto;
    width:calc(100% - 220px);
    height: 87vh;
    margin-left:20px;

    &:before {
      content: "";
      width: 0.37vh;
      height: 0.37vh;
      background: @write;
      position: absolute;
      left: 0.278vh;
      top: 0.278vh;
    }

    tbody {
      height: calc(100vh - 166px);
    }
  }
</style>
<style lang="less">
.tableBox {
  .cell {
    text-align: center;
  }
}
.searchPage {
  margin-top: 1.481vh;
  display: flex;
  justify-content: start;
  align-items: flex-start;
  width:100%;

  .el-dialog__body {
    padding: 10px 20px;
    max-height: 570px;
    overflow: hidden;
  }
}
</style>
