<template>
  <div>
    <el-card class="box-card">
      <div class="seachBox">
        <div class="conditionOne">
          <span>测风塔：</span>
          <el-select v-model="cftId" filterable placeholder="请选择">
            <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="monthrange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        >
        </el-date-picker>
      </div>
        <div class="conditionTwo">
          <span>时间维度：</span>
          <el-select v-model="uid" placeholder="请选择">
            <el-option
              v-for="item in uidOption"
              :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="getListAirDensity" :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="avgTextDiv">
              <div v-html="avgAirText"/>
            </div>
            <div id="airChart"/>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-card>
  </div>

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

export default {
  name: "index",
  data() {
    return {
      btuLoading:true,
      dataTime: [new Date(new Date().getFullYear(), new Date().getMonth() - 1, 1).getTime(), new Date(new Date().getFullYear(), new Date().getMonth(), 1)],
      cftId: '',
      uid: '1',
      uidOption: [{value: '1', label: '月'}, {value: '2', label: '年'}],
      activeName: 'first',
      defaultTimeData: [],//默认时间范围集合
      avgAirText: '',//空气密度平均值
      startDateAndEndDate: [],
    }
  },
  mounted() {
    this.getlistEquipmentIdAndDataTime()
    this.getTimeFrame()
  },
  destroyed() {
    if (!this.turChart) {
      return
    }
    this.turChart.dispose()
    this.turChart = null

  },
  methods: {
    /*获取所有的测风塔*/
    getlistEquipmentIdAndDataTime() {
      listEquipmentIdAndDataTime().then(res => {
        this.startDateAndEndDate = res.data
        this.cftId = res.data[0].value
        this.getDataTime(this.cftId)
        this.getListAirDensity()
      })
    },
    /*获取默认的时间段*/
    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().getFullYear(), new Date().getMonth() - 1, 1).getTime(), new Date(new Date().getFullYear(), new Date().getMonth(), 1)]
      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 = [new Date(new Date(filterData.endTime).getFullYear(), new Date(filterData.endTime).getMonth() - 1, 1).getTime(), new Date(new Date(filterData.endTime).getFullYear(), new Date(filterData.endTime).getMonth() + 1, 1)]            // this.dataTime = [filterData.startTime, filterData.endTime]
          }
        }
      }
    },
    async getListAirDensity() {
      this.btuLoading=true
      const param = {
        startTime: new Date(this.dataTime[0]).getTime(),
        endTime: new Date(this.dataTime[1]).getTime(),
        equipmentId: this.cftId,
        uid: this.uid
      }
      if (!this.airChart) {
        this.airChart = this.$echarts.init(document.getElementById('airChart'))
      }
      // 调用showLoading方法
      this.airChart.showLoading({
        text: 'loading',
        color: '#c23531',
        textColor: '#000',
        maskColor: 'rgba(255, 255, 255, 0.2)',
        zlevel: 0,
      });
      await listAirDensity(param).then(async res => {

        let data = res.rows[1]
        this.avgAirText = ""
        if (data.ave != null) {
          this.avgAirText += ' <span style="color: #1c84c6;font-weight: bold">平均值：</span>' + '<span style="color: #1ab394">' + data.ave + '</span>' + '，'
        }

        if (this.avgAirText != '') {
          this.avgAirText = this.avgAirText.slice(0, this.avgAirText.length - 1)
        }
        this.airData = res.rows[0]
        this.drawAirDensityInChart(this.airData)
        this.btuLoading = false
      }).catch(err => {
        this.airChart.hideLoading();
        this.btuLoading = false
        this.$message.error('获取空气密度数据异常')
        console.log('获取空气密度数据异常：' + err)
      })

    },
    //曲线图
    drawAirDensityInChart(data) {
      this.airChart = this.$echarts.init(document.getElementById('airChart'))
      /*拼接曲线图的serise*/
      let serise = []
      let legend = []
      let seriseData = []
      for (let i = 0; i < data.length; i++) {
        seriseData.push([data[i].time, data[i].air])
        legend.push(data[i].height + 'm')
      }
      serise.push({
        name: '空气密度',
        type: 'line',
        smooth: false,
        symbol: 'none', // 这句就是去掉点的
        data: seriseData
      })


      var option = {
        title: {
          text: '空气密度统计折线图',
        },
        legend: {

          data: legend
        },
        grid: {
          left: '2%',
          right: '3%',
          // bottom: '8%',
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',
        },
        // color: ['#1a9f00', '#2f4554', '#61a0a8','#d48265'],
        xAxis: {
          name: '时间',
          type: 'category',
          axisLine: {
            lineStyle: {
              color: '#666b8f',
              width: 4// 这里是为了突出显示加上的
            }
          },

        },
        dataZoom: [
          {
            startValue: ''
          },
          {
            type: 'inside'
          }
        ],
        yAxis: {
          type: 'value',
          name: '空气密度',
          min: 0,
          // interval: 5,
          axisLabel: {
            formatter: '{value}'
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: '#666b8f',
              width: 4// 这里是为了突出显示加上的
            }
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: ['#315070'],
              width: 2,
              type: 'dotted'
            }
          }
        },
        series: serise
      }
      this.airChart.setOption(option, true)
      this.airChart.hideLoading();
      window.addEventListener('resize', () => {
        if (this.airChart) {
          this.airChart.resize()
        }
      })
    },


    handleClick() {
      if (this.activeName == 'first') {
        this.airChart = null
        this.$nextTick(() => {
          this.drawAirDensityInChart(this.airData)
          this.airChart.resize()
        })
      }
    }
  }
}
</script>
<style scoped>
.box-card {
  height: calc(90vh);
}

.seachBox {
  display: flex;
  margin: .5%;
}

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

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

#airChart {
  width: 100%;
  height: calc(72vh);
}

</style>
