<template>
  <el-card class="box-card">
    <div class="seachBox">
      <div class="conditionOne">
        <span>测风塔：</span>
        <el-select v-model="cftId" placeholder="请选择" @change="changeCft">
          <el-option
            v-for="item in startDateAndEndDate"
            :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.date }}</span>
          </el-option>
        </el-select>
      </div>
      <div class="conditionTwo">
        <span>时间：</span>
        <el-date-picker
          v-model="dataTime"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </div>
      <div class="conditionThree">
        <span>层高：</span>
        <el-select v-model="height" placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </div>
      <el-button class="seachBtu" type="primary" plain icon="el-icon-search" size="small" @click="getData" :loading="btuLoading">搜索
      </el-button>
    </div>
    <div class="mainBox">
      <el-tabs type="border-card" v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="对比图" name="first">
          <div class="chartBox">
            形状参数K: <span class="chartText">{{ K }}</span>&nbsp;,&nbsp;
            参数A: <span class="chartText">{{ A }}</span>&nbsp;m/s,&nbsp;
            平均风速：<span class="chartText">{{ avgWs }}</span> &nbsp;m/s
          </div>
          <div id="frequeryChart"/>
        </el-tab-pane>
      </el-tabs>
    </div>
  </el-card>
</template>

<script>
import {listAllInfo, listEquipmentIdAndDataTime} from "@/api/biz/dataQuery/windTowerStatusInfo";
import {getWeibull} from "@/api/biz/dataQuery/RealTimeDisplay";
import defaultOption from "@/api/biz/dataQuery/defaultOption";
import {startTimeAndEndTime} from "@/api/biz/dataQuery/RealTimeDisplay";

export default {
  name: "index",
  data() {
    return {
      btuLoading:true,
      frequeryChart: null,
      dataTime: [new Date(new Date().toLocaleDateString()).getTime() - 168 * 60 * 60 * 1000, new Date(new Date().toLocaleDateString()).getTime()],
      height: "10",
      options: [],
      allOptions: [],
      cftId: '',
      startDateAndEndDate: [],
      activeName: 'first',
      A: '',//威布尔参数A
      K: '',//威布尔参数K
      avgWs: ''//平均风速
    }
  },
  mounted() {
    this.allOptions = defaultOption.allHeightOptions
    this.getTimeFrame()
  },
  destroyed() {
    if (!this.frequeryChart) {
      return
    }
    this.frequeryChart.dispose()
    this.frequeryChart = null
  },
  methods: {
    /*获取所有的测风塔*/
    getlistEquipmentIdAndDataTime() {
      listEquipmentIdAndDataTime().then(res => {
        this.startDateAndEndDate = res.data
        this.cftId = res.data[0].value
        this.changeHeight(res.data[0])
        this.getDataTime(this.cftId)
        this.getData()
      })
    },
    /*切换测风塔找到它对应的层高*/
    changeCft() {
      let data = this.startDateAndEndDate.find(w => w.value == this.cftId)
      this.getDataTime(this.cftId)
      this.changeHeight(data)
    },
    /*切换测风塔时改变层高option*/
    changeHeight(data) {
      if (data.heights != null) {
        var option = []
        let str = data.heights.split(',')
        this.height = str[0]
        for (let i = 0; i < str.length; i++) {
          let filter = this.allOptions.find(w => w.value == str[i])
          option.push(filter)
        }
        this.options = option
      } else {
        this.height = "10"
        this.options = this.allOptions
      }
    },
    /*获取默认的时间段*/
    getTimeFrame() {
      startTimeAndEndTime().then(res => {
        this.defaultTimeData = res.data
        this.getlistEquipmentIdAndDataTime()
      }).catch(err => {
        this.getlistEquipmentIdAndDataTime()
        this.$message.error('获取时间范围异常')
        console.log('获取时间范围异常：' + err)
      })
    },
    /*设置时间范围默认值*/
    getDataTime(cftId) {
      this.dataTime = [new Date(new Date().toLocaleDateString()).getTime() - 168 * 60 * 60 * 1000, new Date(new Date().toLocaleDateString()).getTime()]
      if (cftId != null || cftId != undefined) {
        if (this.defaultTimeData.length > 0) {
          let filterData = this.defaultTimeData.find(w => w.equipmentId == cftId)
          if (JSON.stringify(filterData) != '{}') {
            this.dataTime = [filterData.startTime, filterData.endTime]
          }
        }
      }
    },
    getData() {
      this.btuLoading = true
      var param = {
        startTime: new Date(this.dataTime[0]).getTime(),
        endTime: new Date(this.dataTime[1]).getTime() - 1,
        equipmentId: this.cftId,
        height: this.height
      }
      //添加loading
      if (!this.frequeryChart) {
        this.frequeryChart = this.$echarts.init(document.getElementById('frequeryChart'))
      }
      // 调用showLoading方法
      this.frequeryChart.showLoading({
        text: 'loading',
        color: '#c23531',
        textColor: '#000',
        maskColor: 'rgba(255, 255, 255, 0.2)',
        zlevel: 0,
      });
      getWeibull(param).then(res => {
        if (res.rows.length > 0) {
          this.A = res.rows[2].A.toFixed(4)
          this.K = res.rows[2].K.toFixed(4)
          this.avgWs = res.rows[2].avgWs
          let data = res.rows[0]
          let wsFreData = res.rows[1]
          let parameter = []
          let wsFrequery = []
          for (let i = 0; i < data.length; i++) {
            parameter.push([data[i].ws, data[i].Weibull])
          }
          for (let j = 0; j < wsFreData.length; j++) {
            wsFrequery.push([wsFreData[j].ws, wsFreData[j].cont])
          }
          this.drawFrequeryChart(parameter, wsFrequery)
          this.btuLoading = false
        } else {
          this.btuLoading = false
          this.$message.warning('此时间段测风塔没有数据')
          this.frequeryChart.hideLoading();
        }
      }).catch(err => {
        this.frequeryChart.hideLoading();
        if (err == 'Error: 98') {
          this.$message.warning('此时间段的测风塔风速为同一个值，不可计算威布尔')
        } else {
          this.$message.error('查询威布尔异常：' + err)
        }
        console.log('查询威布尔异常：' + err)
      })
    },
    drawFrequeryChart(param, ws) {
      if (!this.frequeryChart) {
        this.frequeryChart = this.$echarts.init(document.getElementById('frequeryChart'))
      }
      var option = {
        title: {
          text: '风速频率与威布尔',
        },
        legend: {
          data: ['风速频率(%)']
        },
        grid: {
          left: '2%',
          right: '4%',
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          formatter(params) {
            let str = '';
            let qj = ''
            if (params[0].name == 0) {
              qj = '<0.5'
            } else {
              qj = (params[0].name - 0.5) + " - " + (parseInt(params[0].name) + 0.5)
            }
            str += `<div>` + qj + `</div>`;
            for (let i = 0; i < params.length; i += 1) {
              str += `${params[i].marker}  <span>${params[i].seriesName}</span> : <span>${params[i].value[1]}</br>`;
            }
            return str;
          },
        },
        // color: ['#00FF00', '#3b5bde', '#fbdfa2'],
        xAxis: {
          name: '风速区间 [x-0.5,x+0.5)',
          type: 'category',
          axisLabel: {
            // interval: 1
          },
          // axisTick: {alignWithLabel: true},
          nameLocation: 'center',
          nameGap: 25,
          data: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]
        },
        yAxis: [{
          type: 'value',
          name: '频率(%)',
          min: 0,
          // interval: 5,
          alignTicks: true,
          axisLine: {
            show:true
          },
          axisLabel: {
            formatter: '{value}'
          },
        }, {
          show: false,
          type: 'value',
          alignTicks: true,
          axisLine: {
            show:true
          },
          name: '参数',
          min: 0,
        }],
        series: [{
          name: '风速频率(%)',
          type: 'bar',
          // barWidth: '98%',
          smooth: false,
          symbol: 'none', // 这句就是去掉点的
          data: ws
        },
          {
            name: '威布尔曲线值',
            type: 'line',
            smooth: 0.45,
            symbol: 'none', // 这句就是去掉点的
            yAxisIndex: 1, //在单个图表实例中存在多个y轴的时候有用
            data: param,
          }
        ]
      }
      this.frequeryChart.setOption(option, true)
      this.frequeryChart.hideLoading();
      window.addEventListener('resize', () => {
        if (this.frequeryChart) {
          this.frequeryChart.resize()
        }
      })
    },
    handleClick(tab, event) {
      if (this.activeName == 'first') {
        this.frequeryChart = null
        this.frequeryChart.resize()

      }
    },
  }
}
</script>

<style scoped>
.seachBox {
  display: flex;
  margin: .5%;
}

.conditionOne, .conditionTwo, .conditionThree, .seachBtu {
  display: inline-block;
}

.conditionTwo, .conditionThree, .seachBtu {
  margin-left: .5%;
}

#frequeryChart {
  width: 95%;
  height: calc(71vh);
}

.chartBox {
  font-weight: bold;
  margin-left: .5%;
  margin-bottom: .3%;
}

.chartText {
  font-weight: bold;
  color: #1ab394;
}
</style>
