<template>
  <div class="chart-container">
    <basic-container>
      <div class="filter">
        <div class="startTime">
          <span class="timeText" style="font-weight: bold;font-size: 14px">&#12288;时间:</span>
          <el-date-picker
            v-model="startTime"
            :clearable="false"
            type="daterange"
            :default-time="['00:00:00','23:59:59']"
            value-format="timestamp"
            placeholder="选择日期">
          </el-date-picker>
        </div>
        <div style="display: inline-block">
          <span style="font-weight: bold;font-size: 14px">&#12288;场站名称：</span>
          <el-select style="width:250px" v-model="stationCode" size="small" @change="getManufactor">
            <el-option
              v-for="item in stationList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
              <span style="float: left">{{ item.label }}</span>
              <span style="float: right; color: #8492a6;font-size: 13px">{{ item.value }}</span>
            </el-option>
          </el-select>
        </div>
        <div style="display: inline-block">
          <span style="font-weight: bold;font-size: 14px">&#12288;类型：</span>
          <el-select style="width:250px" v-model="accType" size="small">
            <el-option
              v-for="item in accList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
              <span style="float: left">{{ item.label }}</span>
              <span style="float: right; color: #8492a6;font-size: 13px">{{ item.value }}</span>
            </el-option>
          </el-select>
        </div>
        &nbsp;
        <div style="display: inline-block">
          <span style="font-weight: bold;font-size: 14px">&#12288;预测厂家：</span>
          <el-select style="width:250px" v-model="forecastManufactor" size="small">
            <el-option
              v-for="item in forecastManufactorList"
              :key="item.sign"
              :label="item.name"
              :value="item.sign">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6;font-size: 13px">{{ item.sign }}</span>
            </el-option>
          </el-select>
        </div>
        <div class="timeQuery">
          &#12288;<el-button size="small" :loading="tableLoading" @click="dateQuery">查询</el-button>
        </div>
        <div class="timeQuery">
          <!--        &#12288;<el-button size="small" :loading="tableLoading" @click="dialogVisible = true">显示设置</el-button>-->
        </div>
      </div>
      <div style="width: 100%;height: 90%">
        <div class="tableContent">
          <avue-crud ref="crud"
                     :page.sync="page"
                     :data="tableData.slice((page.currentPage-1)*page.pageSize,page.currentPage*page.pageSize)"
                     :table-loading="tableLoading"
                     :option="tableOption"
                     @search-change="searchChange"
                     @refresh-change="refreshChange"
                     @size-change="sizeChange"
                     @current-change="currentChange"/>
          <div style="display: flex;justify-content:space-around;width: 100%;height: 50%">
            <div class="accuracyPassRate one" id="rtChats"/>
            <!--            <div class="accuracyPassRate two" id="statisticsChats"/>-->
          </div>
        </div>
      </div>
    </basic-container>
  </div>
</template>

<script>
import {
  findByTimeBetween,
  accuracyPassRateQueryForCharts,
} from '@/api/accuracyCalculation'
import {tableOption} from '@/const/crud/accuracyCalculation'
import {mapGetters} from 'vuex'
import * as echarts from 'echarts';
import {getStation} from "@/api/forecastpowerultrashortterm";
import {getManufactorByStationCode} from "@/api/forecastmanufactor";

export default {
  name: 'accuracyPassRate',
  data() {
    return {
      forecastManufactor: '',
      forecastManufactorList: [],
      tableOption: tableOption,
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 10, // 每页显示多少条
      },
      styleStr: {},
      styleTableStr: {},
      lineColor: 'black',
      queryStartTime: '',
      queryEndTime: '',
      startTime: [],
      endTime: new Date().getTime() - 900000,
      rtStartTime: '',
      rtEndTime: new Date().getTime() - 900000,
      tableLoading: false,
      displayConfig: {
        id: "",
        displayCode: "accuracyPassRate",
        showCode: "",
        hiddenCode: ""
      },
      accType: 'day',
      accList: [{label: "日", value: "day"}, {label: "单点", value: "point"}],
      showCode: [],
      tableColumn: [],
      sortOrder: 'asc',
      dialogVisible: false,
      listh: [],
      lists: [],
      listhquery: [],
      listsquery: [],
      tableData: [],
      rpDrawData: {},
      stDrawData: {},
      dqAccuracyAVG: "--- ",
      cdqAccuracyAVG: "--- ",
      dqRateValueAVG: "--- ",
      cdqRateValueAVG: "--- ",
      chart1: null,
      chart2: null,
      stationList: [],
      stationCode: '',
    }
  },
  created() {
    this.init()
  },
  computed: {
    ...mapGetters(['permissions']),

  },
  mounted() {
    this.getStationCode()
  },
  destroyListener() {
    window.removeEventListener('resize', this.handleResize)
    window.removeEventListener('transitionend', this.handleResize)
  },
  methods: {

    getManufactor(val) {
      this.forecastManufactorList = []
      this.forecastManufactor = []
      getManufactorByStationCode(val).then(response => {
        this.forecastManufactorList = response.data.data
        if (this.forecastManufactorList != '') {
          this.forecastManufactor = this.forecastManufactorList[0].sign;
        }
        this.tableLoading = false
      })
    },


    handleResize() {
      this.chart.resize()
      this.chart2.resize()
    },
    init() {
      this.startTime = [new Date(new Date(this.endTime).toLocaleDateString()).getTime(), new Date(new Date(this.rtEndTime).toLocaleDateString()).getTime()]
      this.rtStartTime = new Date(new Date(this.rtEndTime).toLocaleDateString()).getTime()
      this.queryStartTime = this.startTime[0]
      this.queryEndTime = this.startTime[1]
      this.tableLoading = true
      /*this.getShowCode()*/

    },
    dateQuery() {
      this.tableLoading = true
      /*if (this.queryEndTime < this.queryStartTime) {
        this.$message.error("开始时间不能小于结束时间")
        this.tableLoading = false
        return
      }

      if (this.queryEndTime - this.queryStartTime > 60 * 60 * 24 * 1000 * 31) {
        this.$message.error("只能最多查询31天的数据哦")
        this.tableLoading = false
        return
      }*/
      this.queryStartTime = this.startTime[0]
      this.queryEndTime = this.startTime[1]
      this.getTable()
      this.getRealTimeDraw()
    },
    getShowCode() {
      this.$axios.get('displayConfig/' + this.displayConfig.displayCode).then((res) => {
        if (res.data != null) {
          this.displayConfig = res.data
          var showCodes = this.displayConfig.showCode.split(",");
          var hiddenCodes = this.displayConfig.hiddenCode.split(",");
          for (let i = 0; i < showCodes.length; i++) {
            if (showCodes[i] == "shortTermAccuracy") {
              this.lists.push({key: '短期准确率', value: 'shortTermAccuracy'})
              this.listsquery.push({key: '短期准确率', value: 'shortTermAccuracy'})
            }
            if (showCodes[i] == "ultraShortTermAccuracy") {
              this.lists.push({key: '超短期准确率', value: 'ultraShortTermAccuracy'})
              this.listsquery.push({key: '超短期准确率', value: 'ultraShortTermAccuracy'})
            }
          }

          for (let i = 0; i < hiddenCodes.length; i++) {
            if (hiddenCodes[i] == "shortTermAccuracy") {
              this.listh.push({key: '短期准确率', value: 'shortTermAccuracy'})
              this.listhquery.push({key: '短期准确率', value: 'shortTermAccuracy'})
            }
            if (hiddenCodes[i] == "ultraShortTermAccuracy") {
              this.listh.push({key: '超短期准确率', value: 'ultraShortTermAccuracy'})
              this.listhquery.push({key: '超短期准确率', value: 'ultraShortTermAccuracy'})
            }
          }

          this.getTable()
          this.getRealTimeDraw()
        } else {
          this.displayConfig.showCode = "shortTermAccuracy,shortTermPass,ultraShortTermAccuracy,ultraShortTermPass"
          this.displayConfig.hiddenCode = ""
          this.displayConfig.displayCode = "accuracyPassRate"


          this.lists.push({key: '短期准确率', value: 'shortTermAccuracy'})
          this.lists.push({key: '超短期准确率', value: 'ultraShortTermAccuracy'})


          this.$axios.post('/displayConfig', this.displayConfig).then((res) => {
            this.$message.success('展示设置成功')
            this.displayConfig = res.data
          }).catch((error) => {
            this.$message.error('展示设置出错' + error)
          })
          this.getTable()
          this.getRealTimeDraw()
        }
        this.tableLoading = false
      }).catch((error) => {
        this.tableLoading = false
        this.$message.error('查询准确率table出错' + error)
      })
    },

    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
      }).catch((error) => {
        this.$message.error('展示设置出错' + error)
      })

      this.getTable()
      this.getRealTimeDraw()
    },
    getStationCode() {
      this.tableLoading = true
      getStation().then(response => {
        this.stationList = response.data.data
        if (this.stationList.length > 0) {
          this.stationCode = this.stationList[0].value
          this.getManufactor(this.stationCode)
        }
        this.tableLoading = false
      })
    },
    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
    },

    getTable() {
      this.displayConfig.showCode = "shortTermAccuracy,shortTermPass,ultraShortTermAccuracy,ultraShortTermPass"
      const param = new URLSearchParams()
      param.append('stationCode', this.stationCode)
      param.append('startTime', this.queryStartTime)
      param.append('endTime', this.queryEndTime)
      param.append("showCode", "shortTermAccuracy,shortTermPass,ultraShortTermAccuracy,ultraShortTermPass")
      param.append("sortOrder", this.sortOrder)
      param.append("type", this.accType)
      param.append("forecastManufactor", this.forecastManufactor)
      findByTimeBetween(param).then(res => {
        this.tableData = res.data.data.content
        this.page.total = this.tableData.length
        this.page.currentPage = 1
        this.stDrawData = res.data.data.charts
        let times = []
        let ultraShortTermAccuracy = []
        let shortTermAccuracy = []
        let shortTermPass = []
        let ultraShortTermPass = []
        let accuracyRate = ""
        for (let info of this.stDrawData) {
          for (var key in info) {
            switch (key) {
              case 'times':
                if (info[key].toString() !== '') {
                  times.push(info[key].toString())
                }
                break;
              case 'ultraShortTermAccuracy':
                ultraShortTermAccuracy.push(info[key].toString().substring(0, info[key].toString().length - 1))
                break;
              case 'shortTermAccuracy':
                shortTermAccuracy.push(info[key].toString().substring(0, info[key].toString().length - 1))
                break;
              case 'shortTermPass':
                shortTermPass.push(info[key].toString().substring(0, info[key].toString().length - 1))
                break;
              case 'ultraShortTermPass':
                ultraShortTermPass.push(info[key].toString().substring(0, info[key].toString().length - 1))
                break;
              case 'accuracyRate':
                accuracyRate = info[key].toString()
                break;
            }
            if (key !== "times" && key !== "accuracyRate") {
              var sum = 0;
              var total = 0;
              for (let i = 0; i < info[key].length; i++) {
                if (info[key][i] != null) {
                  info[key][i] = parseFloat(info[key][i])
                  sum += info[key][i]
                  total += 1;
                }
              }
              if (key == 'shortTermAccuracy' && total != 0) {
                this.dqAccuracyAVG = (sum / total).toFixed(2) + " "
              }
              if (key == 'shortTermPassRate' && total != 0) {
                this.dqRateValueAVG = (sum / total).toFixed(2) + " "
              }
              if (key == 'ultraShortTermAccuracy' && total != 0) {
                this.cdqAccuracyAVG = (sum / total).toFixed(2) + " "
              }
              if (key == 'ultraShortTermPassRate' && total != 0) {
                this.cdqRateValueAVG = (sum / total).toFixed(2) + " "
              }
            }
          }
        }

        /*this.statisticsDraw(times, ultraShortTermAccuracy, shortTermAccuracy, shortTermPass, ultraShortTermPass, accuracyRate)*/
        this.tableLoading = false
      }).catch((error) => {
        this.tableLoading = false
        this.$message.error('查询准确率table出错' + error)
      })
    },
    getRealTimeDraw() {
      const param = new URLSearchParams()
      param.append('stationCode', this.stationCode)
      param.append('startTime', this.rtStartTime)
      param.append('endTime', this.rtEndTime)
      param.append("type", this.accType)
      param.append("showCode", "shortTermAccuracy,shortTermPass,ultraShortTermAccuracy,ultraShortTermPass")
      param.append("forecastManufactor", this.forecastManufactor)
      accuracyPassRateQueryForCharts(param).then((res) => {
        this.rpDrawData = res.data.data
        for (var key in this.rpDrawData) {
          if (key != "times" && key != "accuracyRate") {
            for (let i = 0; i < this.rpDrawData[key].length; i++) {
              if (this.rpDrawData[key][i] != null) {
                this.rpDrawData[key][i] = parseFloat(this.rpDrawData[key][i])
              }
            }
          }
        }
        this.realTimeDraw(this.rpDrawData)
      })
    },
    realTimeDraw(data) {

      var lastindex = data.times.length - 1
      this.chart = echarts.init(document.getElementById('rtChats'))
      var option = {
        title: {
          text: '今日 ',
          subtext: data.times[0] + '-' + data.times[lastindex],
          textStyle: {
            fontWeight: 'normal',
            fontSize: 16,
            color: this.lineColor
          },
          left: '1%'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            lineStyle: {
              color: '#57617B'
            }
          }
        },
        legend: {
          top: 20,
          icon: 'rect',
          itemWidth: 14,
          itemHeight: 5,
          itemGap: 13,
          data: [],
          right: '4%',
          textStyle: {
            fontSize: 12,
            color: this.lineColor
          }
        },
        dataZoom: [{
          show: true,
          realtime: true,
          start: 0,
          end: 100,
          left: "15%",
          right: "15%",
          textStyle: {
            color: this.lineColor
          }
        },
          {
            type: 'inside'
          }],
        grid: {
          top: 100,
          left: '2%',
          right: '5%',
          bottom: '10%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: data.times,
          axisLine: {
            lineStyle: {
              color: this.lineColor
            }
          }
        },
        yAxis: {
          type: 'value',
          name: '(%)',
          max: 100,
          min: 0,
          axisLine: {
            lineStyle: {
              color: this.lineColor
            }
          },
          axisLabel: {
            margin: 10,
            textStyle: {
              fontSize: 14
            }
          },
          splitLine: {
            lineStyle: {
              color: '#57617B'
            }
          }
        },
        series: []
      };
      var optionTitleText = "";
      if (data.shortTermAccuracy != undefined) {
        optionTitleText += '短期准确率:' + (data.shortTermAccuracy[lastindex] == null ? "--- " : data.shortTermAccuracy[lastindex] + " ")
        option.series.push({
          name: '短期准确率',
          type: 'line',
          showSymbol: false,
          itemStyle: {
            normal: {

              color: '#cccc99',
              borderColor: 'rgba(50,194,219,0.2)',
              borderWidth: 12
            }
          },
          markLine: {
            silent: true,
            itemStyle: {
              normal: {
                show: true,
                color: 'red'
              }
            },
            data: [{
              label: {
                position: 'end',
                formatter: "准确率"
              },
              yAxis: data.accuracyRate.split(',')[0]
            }]
          },
          data: data.shortTermAccuracy
        })
        option.legend.data.push('短期准确率')
      }

      if (data.ultraShortTermAccuracy != undefined) {
        optionTitleText += '超短期准确率:' + (data.ultraShortTermAccuracy[lastindex] == null ? "--- " : data.ultraShortTermAccuracy[lastindex] + " ")
        option.series.push({
          name: '超短期准确率',
          type: 'line',
          showSymbol: false,
          itemStyle: {
            normal: {
              color: '#669966',
              borderColor: 'rgba(50,194,219,0.2)',
              borderWidth: 12
            }
          },
          markLine: {
            silent: true,
            itemStyle: {
              normal: {
                show: true,
                color: 'red'
              }
            },
            data: [{
              label: {
                position: 'end',
                formatter: "准确率"
              },
              yAxis: data.accuracyRate.split(',')[0]
            }]
          },
          data: data.ultraShortTermAccuracy
        })
        option.legend.data.push('超短期准确率')
      }

      option.title.text = "今日 " + optionTitleText
      this.chart.setOption(option, true)
    },
    formatDate: function (time) {//工夫戳转日期
      let date = new Date(time);
      let y = date.getFullYear();
      let MM = date.getMonth() + 1;
      MM = MM < 10 ? ('0' + MM) : MM;
      let d = date.getDate();
      d = d < 10 ? ('0' + d) : d;
      let h = date.getHours();
      h = h < 10 ? ('0' + h) : h;
      let m = date.getMinutes();
      m = m < 10 ? ('0' + m) : m;
      let s = date.getSeconds();
      s = s < 10 ? ('0' + s) : s;
      //return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s;
      return y + '-' + MM + '-' + d;
    },

    sortChangeEvent({column, property, order}) {
      if (order == null) {
        order = 'asc'
      }
      this.currentPage = 1
      this.sortOrder = order
      this.tableLoading = true
      this.getTable()
    },

    sizeChange(pageSize) {
      this.page.pageSize = pageSize
    },
    currentChange(current) {
      this.page.currentPage = current
    },
    searchChange(form, done) {
      this.searchForm = form
      this.page.currentPage = 1
      done()
    },
    refreshChange() {
      this.getStationCode()
    }
  }
}
</script>

<style scoped>
.filter {
  display: flex;
  flex-wrap: wrap;
}

.tableContent {
  /*width: 100%;*/
  height: 40%;
}

.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;
}

.accuracyPassRate {
  width: 79%;
  height: calc(40vh - 5px);
  margin-top: 20px;
}

/deep/ .tableContent .avue-crud__pagination {
  padding: 5px 0 3px 20px;
}
</style>

