<template>
  <div class="chart-container">
    <div class="filter">
      <div class="startTime">
        <span class="timeText">起始时间</span>
        <el-date-picker
          v-model="startTime"
          :clearable="false"
          type="datetime"
          value-format="timestamp"
          placeholder="选择日期">
        </el-date-picker>
      </div>
      <div class="endTime">
        <span class="timeText">截止时间</span>
        <el-date-picker
          v-model="endTime"
          :clearable="false"
          type="datetime"
          value-format="timestamp"
          placeholder="选择日期">
        </el-date-picker>
      </div>
      <div>
        <span class="timeText">间隔时间</span>
        <el-select v-model="jgTime" placeholder="请选择" @change="changeJgTime">
          <el-option
            v-for="item in jgTimes"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </div>
      <div class="timeQuery">
        <el-button size="small" :loading="loading" @click="dateQuery">查询</el-button>
      </div>


      <div class="toolbar" v-show="this.showToolBar">
        <vxe-toolbar ref="fstToolBar" custom>
          <template v-slot:buttons>
            <vxe-button class="downloadButton" style="border:none;" @click="exportDataEvent"><i
              class="vxe-icon--download" ></i></vxe-button>
          </template>
        </vxe-toolbar>
      </div>
      <div class="toolbar" v-show="this.showToolBar">
        <vxe-toolbar ref="nwpToolBar" custom></vxe-toolbar>
      </div>

    </div>


    <div class="content">
      <el-tabs type="card" v-model="activeName" @tab-click="Byresize">
        <el-tab-pane label="图表" name="first">
          <chart :drawData=this.drawData :resizeKey=this.resizeKey @onChart="onChart"/>
        </el-tab-pane>
        <el-tab-pane label="表格" name="second">
          <div class="tableContent">
            <vxe-grid
              id="nwpTable"
              ref="nwpRef"
              border
              :loading="loading"
              :custom-config="{storage: true, checkMethod: checkColumnMethod}"
              :auto-resize="true"
              highlight-hover-row
              :header-cell-style="styleStr"
              max-height="90%"
              :cell-style="styleTableStr"
              align="center"
              :data="tableData.slice((currentPage-1)*pageSize,currentPage*pageSize)"
              :columns="tableColumn"
            />
            <div class="rtPageturning">
              <vxe-pager
                background
                :loading="loading"
                :current-page="currentPage"
                :page-size="pageSize"
                :total="tableData.length"
                @page-change="handlePageChange"
                :layouts="['PrevJump', 'PrevPage', 'JumpNumber', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']">
              </vxe-pager>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
import Chart from './charts/index'
import resize from '../../components/Charts/mixins/resize'
import moment from "moment";
import draggable from 'vuedraggable'

export default {
  name: 'cq',
  components: {Chart, draggable},
  mixins: [resize],
  data() {
    return {
      styleStr:{},
      styleTableStr:{},
      columns: {},
      dqAgo: 1,
      cdqAgo: 1,
      nwpAgo: 1,
      chart: null,
      queryStartTime: '',
      queryEndTime: '',
      startTime: new Date(new Date().toLocaleDateString()).getTime(),
      endTime: new Date(new Date().toLocaleDateString()).getTime() + 60 * 60 * 24 * 1000 - 1,
      loading: true,
      drawLoading: true,
      tableLoading: true,
      resizeKey: 1,
      activeName: 'first',
      drawData: {},
      tableData: [],
      total: 0,
      sortOrder: 'asc',
      pageSize: 10,
      currentPage: 1,
      showToolBar: false,
      dialogVisible: false,
      dialogVisiblePoint: false,
      equipments: "",
      equipmentId: "",
      electricField: {},
      displayCode: 'comprehensiveContrast',
      displayConfig: {
        id: "",
        displayCode: "comprehensiveContrast",
        showCode: "",
        hiddenCode: ""
      },
      displayPointConfig: {
        id: "",
        displayCode: "comprehensivePoint",
        showCode: "",
        hiddenCode: ""
      },
      displayConfigJgTime: {
        id: "",
        displayCode: "timeInterval",
        showCode: "",
        hiddenCode: ""
      },
      displayConfigPageSize: {
        id: "",
        displayCode: "pageSize",
        showCode: "",
        hiddenCode: ""
      },
      listh: [],
      lists: [],
      listhquery: [],
      listsquery: [],
      tableColumn: [],
      jgTime: 3600000,
      jgTimes: [
        {label: "15分钟", value: 900000},
        {label: "1小时", value: 3600000}
      ],
      base64:'',
      width:'',
      height:'',
    }
  },
  created() {
    if(sessionStorage.getItem('styleSwitch') === 'blue'){
      this.styleStr = {background:'black',color:'white',border:'white'}
      this.styleTableStr = {background:'black',color:'white'}
    }
    document.body.ondrop = function (event) {
      event.preventDefault();
      event.stopPropagation();
    };
    this.$nextTick(() => {
      // 手动将表格和工具栏进行关联
      this.$refs.nwpRef.connect(this.$refs.nwpToolBar)
    })
  },
  mounted() {
    this.getJgTimeAndPageSize()
    this.init()

  },
  methods: {
    onChart(val){
      this.base64 = val[0].url;
      this.width = val[0].width;
      this.height = val[0].height;
    },
    initShow(){
      this.dialogVisible = false

      this.$XModal.confirm('您确定要初始化？').then(type => {

        if (type === 'confirm') {
          this.$axios.delete("displayConfig/deleteById/"+this.displayConfig.id).then(res =>{
            if(res.code == 0 ){
              this.$message.success("执行成功！")
              location.reload()
            }
          })
        }
      })
    },
    downloadFile(name){
      const formData = new FormData();
        formData.append('path', "/home/syjy/ipfcstV3/reportForm")
        //formData.append('path', "/Users/wanghongchen")
        formData.append('name', name)
        formData.append('type', "")
        this.$axios({ // 用axios发送post请求
          method: 'post',
          url: '/downLoadFileTwo', // 请求地址
          data: formData, // 参数
          responseType: 'blob', // 表明返回服务器返回的数据类型
          headers: {
            'Content-Type': 'application/json'
          }
        }).then(res => { // 处理返回的文件流
          this.tableLoading = false
          if (res && res.code === 0) {
            this.$message.error('下载失败！')
          }
        })
    },
    exportDataEvent() {
      this.loading = true
      const formData = new FormData()
      formData.append("startTime",this.startTime)
      formData.append("endTime",this.endTime)
      formData.append("jgTime",this.jgTime)
      formData.append("base64",this.base64)
      //this.$axios.get('ComprehensiveContrastExports/' + this.startTime + '/' + this.endTime + '/' + this.equipmentId + '/' + this.electricField.electricFieldTypeEnum + '/' + this.jgTime+ '/' +this.base64+ '/' +this.width+ '/' +this.height, {
      this.$axios.post('/ComprehensiveContrastTwoExports', formData).then((response) => {
        this.downloadFile(response.data)
      }).then((response) => {
        this.loading = false
      }).catch((error) => {
        this.loading = false
        this.$message.error('导出失败' + error)
      })
    },
    init() {
      this.$axios.get("nwpTwo/getNwpDay").then(res=>{
        var days = res.data + 1
        this.endTime = new Date(new Date().toLocaleDateString()).getTime() + 60 * 60 * 24 * 1000*days-1
        this.$axios.get("/comprehensiveContrast/getSpeedColumn").then(res => {
          this.columns = res.data
        })
        this.queryStartTime = this.startTime
        this.queryEndTime = this.endTime
        this.loading = true
        this.getElectricField()
      })

      // this.getTable()

    },
    changeJgTime() {
      this.displayConfigJgTime.showCode = this.jgTime
      this.$axios.post('displayConfig/', this.displayConfigJgTime).then((res) => {
        this.displayConfigJgTime = res.data
        // this.$message.success('间隔时间设置成功' )
        this.dialogVisible = false
        this.getDraw(this.startTime, this.endTime)
      }).catch((error) => {
        this.$message.error('间隔时间设置出错' + error)
      })
    },
    changePageSize(pageSize) {
      this.displayConfigPageSize.showCode = pageSize
      this.$axios.post('displayConfig/', this.displayConfigPageSize).then((res) => {
        this.displayConfigPageSize = res.data
        // this.$message.success('PageSize设置成功' )
        this.dialogVisible = false
      }).catch((error) => {
        this.$message.error('PageSize设置出错' + error)
      })
    },
    getJgTimeAndPageSize() {
      this.$axios.get('displayConfig/timeInterval').then((res) => {
        this.displayConfigJgTime = res.data
        this.jgTime = parseInt(this.displayConfigJgTime.showCode)
        // this.$message.success('间隔时间获取成功' )
        this.dialogVisible = false
      }).catch((error) => {
        this.$message.error('间隔时间获取出错' + error)
      })
      this.$axios.get('displayConfig/pageSize').then((res) => {
        this.displayConfigPageSize = res.data
        this.pageSize = parseInt(this.displayConfigPageSize.showCode)
        // this.$message.success('PageSize获取成功' )
        this.dialogVisible = false
      }).catch((error) => {
        this.$message.error('PageSize获取出错' + error)
      })
    },
    getElectricField() {
      this.$axios.get('/electricField/').then((res) => {
        this.electricField = res.data
        this.getEquipments(this.electricField.electricFieldTypeEnum)
      }).catch((error) => {
        this.$message.error('查询场站信息出错' + error)
      })
    },
    getEquipments(eType) {
      this.displayConfig.displayCode = 'rtWindTowerInfos'
      this.getDisplay()
    },
    initDisplay() {
        this.lists.push({key:'实际功率(MW)',value:'realValue'})
        this.lists.push({key: '实时短期(MW)', value: 'rDq'})
        this.listsquery.push({key:'实际功率(MW)',value:'realValue'})
        this.listsquery.push({key: '实时短期(MW)', value: 'rDq'})
        this.changeDisplay()
    },
    getDisplay() {
      this.$axios.get('displayConfig/' + this.displayConfig.displayCode).then((res) => {
        if (res.data == null || res.data.code == 0) {
          this.initDisplay()
        } else {
          this.displayConfig = res.data
          var showlist = this.displayConfig.showCode.split(',')
          var hiddenlist = this.displayConfig.hiddenCode.split(',')
          for (var i = 0; i < showlist.length; i++) {
            switch (showlist[i]) {
              case 'realValue':
                this.lists.push({key:'实际功率(MW)',value:'realValue'})
                this.listsquery.push({key:'实际功率(MW)',value:'realValue'})
                break;
              case 'rDq':
                this.lists.push({key: '实时短期(MW)', value: 'rDq'})
                this.listsquery.push({key: '实时短期(MW)', value: 'rDq'})
                break;
            }
          }
          for (var i = 0; i < hiddenlist.length; i++) {
            switch (hiddenlist[i]) {
              case 'realValue':
                this.lists.push({key:'实际功率(MW)',value:'realValue'})
                this.listsquery.push({key:'实际功率(MW)',value:'realValue'})
                break;
              case 'rDq':
                this.listh.push({key: '实时短期(MW)', value: 'rDq'})
                this.listhquery.push({key: '实时短期(MW)', value: 'rDq'})
                break;
            }
          }
        }
        this.getDraw(this.queryStartTime, this.queryEndTime)
      })

    },
    changeDisplay() {
      this.displayConfig.showCode = ""
      this.displayConfig.hiddenCode = ""
      this.listsquery = []
      this.listhquery = []
      for (var i = 0; i < this.listh.length; i++) {
        this.listhquery.push(this.listh[i])
      }
      for (var i = 0; i < this.lists.length; i++) {
        this.listsquery.push(this.lists[i])
      }
      for (var i = 0; i < this.listsquery.length; i++) {
        this.displayConfig.showCode += this.listsquery[i].value + ","
      }
      for (var i = 0; i < this.listhquery.length; i++) {
        this.displayConfig.hiddenCode += this.listhquery[i].value + ","
      }
      this.$axios.post('displayConfig/', this.displayConfig).then((res) => {
        this.displayConfig = res.data
        this.$message.success('展示设置成功')
        this.dialogVisible = false
        this.getDraw(this.startTime, this.endTime)
      }).catch((error) => {
        this.$message.error('展示设置出错' + error)
      })
    },
    cancelDisplay() {
      this.lists = []
      this.listh = []
      for (var i = 0; i < this.listhquery.length; i++) {
        this.listh.push(this.listhquery[i])
      }
      for (var i = 0; i < this.listsquery.length; i++) {
        this.lists.push(this.listsquery[i])
      }
      this.dialogVisible = false
    },
    cancelDisplayPoint() {
      this.dialogVisiblePoint = false
    },
    getDraw(startTime, endTime) {
      this.drawLoading = true
      this.tableData = []

      if (isNaN(this.dqAgo)) {
        this.dqAgo = 1
      }
      if (isNaN(this.cdqAgo)) {
        this.cdqAgo = 1
      }
      if (isNaN(this.nwpAgo)) {
        this.nwpAgo = 1
      }
      this.$axios.get('realTimeComprehensiveContrastTwo/' + startTime + '/' + endTime + '/' + this.jgTime).then((res) => {

        this.tableColumn = [
          { field: 'times', title: '时间', width:200},
        ]

        for(let i = 0;i<this.listsquery.length;i++){
          var colunm = {
            field:this.listsquery[i].value , title: this.listsquery[i].key
          }
          this.tableColumn.push(colunm)
        }
        this.drawData = {
          times: [],
          realValue: [],
          rDq: [],
          electricField: this.electricField,
          columns: this.columns
        }
        const data = res.data.tableResult
        const data1 = res.data.resultList
        this.tableData = []
        // console.log(data)
        //因为后台设置两个结果的长度肯定一样的所以放在一个for循环中
        for (let i = 0; i < data.length; i++) {

          var object = {}
          this.drawData.times.push(data[i].time)
          object.times = data[i].time

          if (data[i].realValue != undefined) {
            this.drawData.realValue.push(data[i].realValue)
            object.realValue = data[i].realValue;
          }

          if (data[i].rDq != undefined) {
            this.drawData.rDq.push(data[i].rDq)
            object.rDq = data[i].rDq;
          }


          this.tableData.push(object)


        }
        this.tableLoading = false
        if (!this.drawLoading && !this.tableLoading) {
          this.loading = false
        }
        this.drawLoading = false
        if (!this.drawLoading && !this.tableLoading) {
          this.loading = false
        }

      }).catch((error) => {
        this.drawLoading = false
        if (!this.drawLoading && !this.tableLoading) {
          this.loading = false
        }
        this.$message.error('查询对比数据出错' + error)
      })

    },
    // getTable(){
    //   this.tableLoading = true
    //   this.$axios.get('/forecastPowerShortTerm/'+this.queryStartTime+'/'+this.queryEndTime+'/'+this.currentPage+'/'+this.pageSize+'?sortOrder='+this.sortOrder).then((res) => {
    //     // this.tableData = res.data.content
    //     // 表分页格数据总条数
    //     this.total = res.data.count
    //     this.tableLoading = false
    //     if(!this.drawLoading && !this.tableLoading){
    //       this.loading = false
    //     }
    //   }).catch((error) => {
    //     this.tableLoading = false
    //     if(!this.drawLoading && !this.tableLoading){
    //       this.loading = false
    //     }
    //     this.$message.error('查询table出错' + error)
    //   })
    //
    // },
    handlePageChange({currentPage, pageSize}) {
      this.currentPage = currentPage
      if (this.pageSize != pageSize) {
        this.changePageSize(pageSize)
      }
      this.pageSize = pageSize

    },
    dateFormat({cellValue, row, column}) {
      return this.$XEUtils.toDateString(cellValue, 'yyyy-MM-dd HH:mm:ss')
    },
    enumToWord({cellValue, row, column}) {
      if (cellValue == "E1") {
        return "云端模型"
      }
      if (cellValue == 'E2') {
        return "物理模型"
      }
      if (cellValue == 'E3') {
        return "统计模型"
      }
      if (cellValue == 'E4') {
        return "补录数据"
      }
      if (cellValue == 'E5') {
        return "差值模型"
      }
    },
    dateMoment({cellValue, row, column}) {
      return moment(cellValue).format('YYYY-MM-DD HH:mm:ss')
    },
    // sortChangeEvent ({ column, property, order }) {
    //   if(order == null){
    //     order = 'asc'
    //   }
    //   this.currentPage = 1
    //   this.sortOrder = order
    //   this.loading = true
    //   this.getTable()
    // },

    checkColumnMethod({column}) {
      if (column.property === 'preTime') {
        return false
      }
      return true
    },
    dateQuery() {
      this.loading = true
      if (this.endTime <= this.startTime) {
        this.$message.error("开始时间不能大于结束时间")
        this.startTime = this.queryStartTime
        this.endTime = this.queryEndTime
        this.loading = false
        return
      }
      if (this.endTime - this.startTime > 60 * 60 * 24 * 1000 * 31) {
        this.startTime = this.queryStartTime
        this.endTime = this.queryEndTime
        this.$message.error("只能最多查询31天的数据哦")
        this.loading = false
        return
      }
      this.queryStartTime = this.startTime
      this.queryEndTime = this.endTime
      this.getDraw(this.queryStartTime, this.queryEndTime)
      // this.getTable()
    },
    Byresize(tab) {
      if (tab.name == 'first') {
        this.resizeKey++
        this.showToolBar = false
      } else {
        this.showToolBar = true
      }

    },
    log: function (evt) {
      /*window.console.log(evt);*/
      /*     console.log(this.lists)
           console.log(this.listh)*/

      /*   this.changeDisplay()*/
    },
    // 初始页currentPage、初始每页数据数pagesize和数据data
    handleSizeChange: function (size) {
      this.pageSize = size;
      // console.log(this.pageSize)  //每页下拉显示数据
    },
    handleCurrentChange: function (currentPage) {
      this.currentPage = currentPage;
      // console.log(this.currentPage)  //点击第几页
    }
  }
}
</script>

<style scoped>
.drag-box-item {
  /*margin:10px;*/
  flex: 1;
  height: 220px;
  max-width: 100%;
  min-width: 100%;
  background-color: #eff1f5;
  margin-right: 16px;
  border-radius: 6px;
  border: 1px #e1e4e8 solid;
}

.item-title {
  padding: 8px 8px 8px 12px;
  font-size: 14px;
  line-height: 1.5;
  color: #24292e;
  font-weight: 600;
}

.item-ul {
  padding: 0 8px 8px;
  height: 200px;
  overflow-y: scroll;
}

.item-ul::-webkit-scrollbar {
  width: 0;
}

.drag-list {
  width: 14%;
  float: left;
  border: 1px #e1e4e8 solid;
  padding: 10px;
  /*margin: 5px 0 10px;*/
  list-style: none;
  background-color: #fff;
  border-radius: 6px;
  cursor: pointer;
  -webkit-transition: border .3s ease-in;
  transition: border .3s ease-in;
}

.drag-list:hover {
  border: 1px solid #20a0ff;
}

.inputNum {
  height: 50px;
  text-align: right;
}
</style>

