<template>
  <div>
    <div class="myCarousel">
      <span>{{ text }}</span>
    </div>
    <div class="condition">
      <div class="conditionOne">
        <span>测风塔：</span>
        <el-select v-model="cftId" placeholder="请选择" @change="changeCft" size="small" style="width: 170px">
          <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="结束日期"
          @change="changeMonth"
          :picker-options="pickerOptions"
          style="width: 200px"
          size="small"
        >
        </el-date-picker>
      </div>
      <!--      <div class="conditionTwo">-->
      <!--        <span>层高：</span>-->
      <!--        <el-select v-model="height" placeholder="请选择" clearable size="small" style="width: 150px">-->
      <!--          <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-thumb" :loading="loading" size="mini"
                 @click="getPdfData()">生成报告模板
      </el-button>
      <el-button class="seachBtu" type="primary" plain icon="el-icon-download" :loading="downLoading" size="mini"
                 @click="getPdf()">导出
      </el-button>
    </div>
    <div id="dataAnalysisPdf" v-loading="loading">
      <pdf-home-page :param="info"/>
      <!--pdf主体-->
      <div style="width: 90%;margin: 0 auto">
        <div style="height: 2220px">
          <!--     1项目综述和概况 -->
          <div>
            <h1>1.项目综述和概况</h1>
            <h2>1.1 项目综述</h2>
            <div><span class="text">测风设备部分参数统计结果如下表所示。</span></div>
            <div class="pdfTableDiv" style="width: 50%;">
              <div class="tableTitle"><span>表1 测风设备主要参数表</span></div>
              <div class="descriptionsDiv" style="font-size: 20px">
                <el-descriptions class="margin-top" :column="1" border>
                  <el-descriptions-item>
                    <template slot="label">测风设备命名</template>
                    {{ windTowerInfo.name }}
                  </el-descriptions-item>
                  <el-descriptions-item>
                    <template slot="label">仪器编号</template>
                    {{ windTowerInfo.equipmentNo }}
                  </el-descriptions-item>
                  <el-descriptions-item>
                    <template slot="label">安装完成时间</template>
                    {{ windTowerInfo.installationTime }}
                  </el-descriptions-item>
                  <el-descriptions-item>
                    <template slot="label">数据起时间</template>
                    {{ windTowerInfo.startTime }}
                  </el-descriptions-item>
                  <el-descriptions-item>
                    <template slot="label">数据止时间</template>
                    {{ windTowerInfo.endTime }}
                  </el-descriptions-item>
                </el-descriptions>
              </div>
            </div>
          </div>
          <!--    2.测风数据分析  -->
          <div>
            <h1>2.测风数据分析</h1>
            <h2>2.1气象要素分析</h2>
            <div><span class="text">具体测风设备相关信息及位置分布如下所示。</span></div>
            <div class="pdfTableDiv">
              <div class="tableTitle"><span>表2  测风基本信息</span></div>
              <div class="rowDiv">
                <div>
                  <el-table
                    :show-header="false" :span-method="arraySpanMethod"
                    :data="tableData"
                    border
                    class="pdfTable">
                    <el-table-column
                      prop="name" align="center"
                      label="日期"
                      width="180">
                    </el-table-column>
                    <el-table-column
                      prop="column" align="center"
                      label="日期"
                      width="180">
                    </el-table-column>
                  </el-table>
                </div>
                <div style="width: 40%">
                  <el-row>
                    <el-col class="tableCol">{{ windTowerInfo.name }}</el-col>
                    <el-col class="tableCol">{{ windTowerInfo.equipmentNo }}</el-col>
                    <el-col class="tableCol">{{ windTowerInfo.longitude }}</el-col>
                    <el-col class="tableCol">{{ windTowerInfo.latitude }}</el-col>
                    <el-col class="tableCol">{{ windTowerInfo.wsHeight }}</el-col>
                    <el-col class="tableCol">{{ windTowerInfo.wdHeight }}</el-col>
                  </el-row>
                </div>
              </div>
            </div>
          </div>

          <!--    2.2数据完整性  -->
          <div>
            <h2>2.2 数据完整性</h2>
            <div><span class="text">自{{ dataIntegrity.time }}起测风设备安装完毕，{{
                dataIntegrity.startTime
              }}起均正常存取数据。数据总条数为{{ dataIntegrity.totalNum }}，测风数据完整率
            {{ dataIntegrity.integrityRate }}%。</span></div>
          </div>

          <div>
            <h2>2.3 风能要素</h2>
            <h3>2.3.1 空气密度</h3>
            <div style="line-height: 30px">
              <div><span class="text">由于空气密度直接影响风能的大小，在同等风速条件下，空气密度越大风能越大；根据风电场测风塔的实测温度和气压数据推算测风塔处空气密度计算公式如下：</span>
              </div>
              <div><span class="text">ρ=P/(R*T)</span>
              </div>
              <div><span class="text">其中：</span>
              </div>
              <div><span class="text">ρ为空气密度(kg/m3)；</span>
              </div>
              <div><span class="text">P为平均大气压(Pa)；</span>
              </div>
              <div><span class="text">R为空气常数(287J/kg*K)；</span>
              </div>
              <div><span class="text">T为绝对温度(℃+273)</span>
              </div>
            </div>
            <div class="pdfTableDiv">
              <div class="tableTitle"><span>表3 {{ windTowerInfo.name }}测风设备温湿压六要素/空气密度统计结果</span></div>
              <div class="rowDiv" style="width: 60%;margin: 0 auto;">
                <el-table
                  :data="envTableData"
                  border
                  :header-row-style="{color: '#000'}"
                 class="pdfTable" style="border: 1px solid #000">
                  <el-table-column prop="parameter" align="center" label="参数"></el-table-column>
                  <el-table-column prop="ave" align="center" label="平均值"></el-table-column>
                  <el-table-column prop="max" align="center" label="最大值"></el-table-column>
                  <el-table-column prop="min" align="center" label="最小值"></el-table-column>
                </el-table>
              </div>
            </div>
          </div>
        </div>
        <ws-and-wd :info="windTowerInfo" :pData="wsAndwd"/>
        <wd-rose :info="windTowerInfo" :pData="roseData"/>
        <ws-frequency :p-data="weibull"/>
        <turbulence style="height: 2220px" :p-data="turbulenceData"/>
        <wind-shear style="height: 2220px" :pData="shearData"/>
      </div>

    </div>
  </div>

</template>

<script>
import pdfHomePage from './pdfHomePage'
import wsAndWd from './components/wsAndWpd'
import wdRose from './components/wdRose'
import windShear from './components/windShear'
import wsFrequency from './components/wsFrequency'
import turbulence from './components/turbulence'
import {listEquipmentIdAndDataTime} from "@/api/biz/dataQuery/windTowerStatusInfo";
import {getDataTimeForEveryTower,generatePDF} from "@/api/biz/dataQuery/pdf";
import defaultOption from "@/api/biz/dataQuery/defaultOption";
import WsFrequency from "@/views/dataAnalysis/components/wsFrequency";
import htmlToPdf from "@/utils/htmlToPdf";
import Cookies from "js-cookie";

export default {
  name: "index",
  components: {WsFrequency, pdfHomePage, wsAndWd, wdRose, windShear, wsFrequency, turbulence},
  data() {
    return {
      loading: false,
      downLoading: false,
      text: '****  生成pdf报告流程：  1.选择测风塔和层高    2.生成报告模板    3.导出  ****',
      cftId: '',
      pdfData:[],
      intervalID: null,
      startDateAndEndDate: [],
      dataTime: [],
      pickerMinDate: null,
      pickerMaxDate: null,
      pickerOptions: {
        //点击时间回调
        onPick: ({maxDate, minDate}) => {
          if (minDate) {
            let currentYear = minDate.getMonth()
            this.pickerMinDate = new Date(minDate).setMonth(currentYear - 11)
            this.pickerMaxDate = new Date(minDate).setMonth(currentYear + 11)
          }
        },
        //禁用时间 打开选择器就调用
        disabledDate: (time) => {
          if (this.pickerMinDate != null) {
            //点击月份后只允许选前后1年的时间
            //return true是禁用
            return time.getTime() < this.pickerMinDate || this.pickerMaxDate < time.getTime()
          }
        },
      },
      height: '',
      options: [],
      allOptions: [],
      /*pdf数据*/
      info: {equipmentId: '声雷达6172'},
      /*测风塔基本信息*/
      windTowerInfo: {},
      tableData: [
        {name: "测风设备命名", column: 0},
        {name: "仪器编号", column: 0},
        {name: "地理位置", column: '经度'},
        {name: "地理位置", column: '纬度'},
        {name: "通道信息", column: '风速高度（m）'},
        {name: "通道信息", column: '风向高度（m）'},
      ],
      /*数据完整性*/
      dataIntegrity: {},
      /*环境数据*/
      envTableData: [],
      wsAndwd:{},
      roseData:[],
      weibull:[],
      turbulenceData:[],
      shearData: {},
      defaultTimeData: [],//默认时间范围集合
    }
  },
  destroyed() {
    clearInterval(this.intervalID)
    this.intervalID = null
  },
  mounted() {
    this.allOptions = defaultOption.allHeightOptions
    this.getlistEquipmentIdAndDataTime()
  },
  methods: {
    getlistEquipmentIdAndDataTime() {
      // this.changeMonth(this.dataTime)
      /*简易走马灯*/
      if (this.intervalID != null) return;
      this.intervalID = setInterval(() => {
        var start = this.text.substring(0, 1)
        var end = this.text.substring(1)
        this.text = end + start
      }, 400)

      /*****/
      listEquipmentIdAndDataTime().then(res => {
        this.startDateAndEndDate = res.data
        this.cftId = res.data[0].value
        // this.changeHeight(res.data[0])
      })
      /*****/
      getDataTimeForEveryTower().then(res => {
        this.defaultTimeData = res.data
        let startAndEndTime = this.defaultTimeData.find(w => w.eqId == this.cftId)
        this.dataTime = [startAndEndTime.startTime, startAndEndTime.endTime]
      }).catch(err => {
        console.log('获取所有测风塔的开始结束时间异常：' + err)
      })
    },
    /*pdf查询*/
    getPdfData(){
      this.loading = true
      this.downLoading = true
      generatePDF({
        equipmentId: this.cftId,
        startDay: new Date(this.dataTime[0]).getTime(),
        endDay: new Date(this.dataTime[1]).getTime()
      }).then(res => {
        this.pdfData = res.data
        let windTowerInfo = this.pdfData.windTowerInfo.windTowerInfo
        /*基本信息*/
        this.windTowerInfo = {
          name: windTowerInfo.name,
          equipmentNo: windTowerInfo.equipmentNo,
          installationTime: windTowerInfo.installationTime,
          startTime: this.pdfData.windTowerInfo.startTime,
          endTime: this.pdfData.windTowerInfo.endTime,
          longitude: windTowerInfo.longitude,
          latitude: windTowerInfo.latitude,
          wsHeight: windTowerInfo.heights,
          wdHeight: windTowerInfo.wdHeights
        }
        /*完整性*/
        this.dataIntegrity= {
          time: windTowerInfo.installationTime,
          startTime: this.pdfData.windTowerInfo.startTime,
          integrityRate: this.pdfData.windTowerInfo.percentage,
          totalNum: this.pdfData.windTowerInfo.allCount
        }
        /*环境数据*/
        this.envTableData= this.pdfData.statisticsData.environment
        this.wsAndwd = {
          statisticsDataFen:this.pdfData.statisticsDataFen,
          statisticsWindTowerStatusDataFenMonth:this.pdfData.statisticsWindTowerStatusDataFenMonth,
          statisticsWindTowerStatusDataFenWpd:this.pdfData.statisticsWindTowerStatusDataFenWpd
        }
        this.roseData = this.pdfData.roseChart
        this.weibull = this.pdfData.weibull
        this.turbulenceData = this.pdfData.statisticsWindTowerStatusDataFenTur
        this.shearData =  this.pdfData.statisticsWindTowerStatusDataShear
        this.loading = false
        this.downLoading = false
      }).catch(err => {
        this.loading = false
        this.downLoading = false
      })
    },
    changeCft() {
      let data = this.startDateAndEndDate.find(w => w.value == this.cftId)
      let time = this.defaultTimeData.find(w => w.eqId == this.cftId)
      console.log(time)
      this.dataTime = [time.startTime,time.endTime]
      this.changeHeight(data)
    },
    changeMonth(value) {
      // 今天是月初并且选择的月份是当月
      let endTime = new Date(value[1])
      let startTime = new Date(value[0])
      this.dataTime[0] = startTime.getTime()
      if (new Date().getDate() === 1 && endTime.getMonth() + 1 === new Date().getMonth() + 1) {
        this.dataTime[1] = endTime.getTime() - 1000 * 60 * 60 * 24
      } else {
        var data = new Date(value[1]);
        data.setMonth(data.getMonth() + 1);
        data.setDate(1);
        data.setHours(0);
        data.setSeconds(0);
        data.setMinutes(0);
        var timeEnd = (parseInt(data.getTime() / 1000) - 1) * 1000;
        this.dataTime[1] = timeEnd //最后一天23:59:59的时间戳
      }
    },
    async getPdf() {
      if(this.windTowerInfo.name  !== undefined && this.windTowerInfo.name  !== null){
        this.downLoading = true
        await htmlToPdf.downloadPDF(document.querySelector('#dataAnalysisPdf'), this.windTowerInfo.name + '测风设备数据分析报告')
        this.downPdfTimer = setInterval(() => {
          if (Cookies.get('pdfKey')) {
            this.downLoading = false
            clearInterval(this.downPdfTimer)
            Cookies.remove("pdfKey");
          }
        }, 500)
      }else {
        this.$message.warning('请先生成报告模板')
      }

    },
    /*切换测风塔时改变层高option*/
    changeHeight(data) {
      if (data.heights != null) {
        var option = []
        let str = data.heights.split(',')
        this.height = str[0]
        // this.height = null
        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.height = null
        this.options = this.allOptions
      }

    },
    /*合并单元格*/
    arraySpanMethod({row, column, rowIndex, columnIndex}) {
      if (rowIndex === 0 || rowIndex === 1) {
        if (columnIndex === 0) {
          return [1, 2];
        } else if (columnIndex === 1) {
          return [0, 0];
        }
      }
      if (columnIndex === 0) {
        if (rowIndex % 2 === 0) {
          return {
            rowspan: 2,
            colspan: 1
          };
        } else {
          return {
            rowspan: 0,
            colspan: 0
          };
        }
      }
    },
  }
}
</script>

<style scoped>
.myCarousel {
  width: 600px;
  height: 30px;
  background-color: #ffba00;
  border-radius: 5px;
  color: #f8f8f8;
  display: flex;
  justify-content: center;
  align-items: center;
}

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

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

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

/deep/ .seachBtu .el-loading-spinner {
  font-size: 30px;
}

/deep/ .condition .el-button--mini {
  height: 32px;
}

#dataAnalysisPdf {
  width: 1661px;
  font-size: 20px;
}

#dataAnalysisPdf h1, #dataAnalysisPdf h2, #dataAnalysisPdf h3 {
  font-weight: bold;
}

.text {
  margin-left: 40px;
  font-size: 24px;
}

.pdfTableDiv {
  margin: 0 auto;
  display: flex;
  flex-direction: column;
}

.tableTitle {
  margin: 0 auto;
}

.tableTitle span {
  font-weight: bold;
}

.descriptionsDiv /deep/ .el-descriptions__body .el-descriptions__table .el-descriptions-item__cell {
  text-align: center;
}

.descriptionsDiv /deep/ .el-descriptions-item__label.is-bordered-label {
  font-size: 20px;
  font-weight: bold;
  color: #000000;
  background: #ffffff;
}

.descriptionsDiv /deep/ .el-descriptions .is-bordered .el-descriptions-item__cell {
  border: 2px solid #000000;
}

.descriptionsDiv /deep/ .el-descriptions--medium.is-bordered .el-descriptions-item__cell {
  padding: 8px;
}

.descriptionsDiv /deep/ .el-descriptions-item__content {
  font-size: 20px;
  font-weight: bold;
  color: #000;
}

.rowDiv {
  display: flex;
  justify-content: center;
}

.pdfTable {
  width: 100%;
  border: 1px solid;
  border-right: none;
  font-weight: bold;
  color: #000;
  font-size: 20px
}

.rowDiv /deep/ .el-row {
  text-align: center;
  font-size: 20px;
  font-weight: bold;
  color: #000;
  line-height: 50px;
  /*border: 1px solid #000;*/
  border-top: 1px solid #000;
  border-left: 1px solid #000;
}

.rowDiv .tableCol {
  border: 1px solid #000;
  height: 44px;
  border-top: none;
  border-left: none;
}

.rowDiv /deep/ .el-table--border .el-table__cell {
  border-right: 1px solid #000000;
  border-bottom: 1px solid #000;
}

.rowDiv /deep/ .el-table .el-table__header-wrapper th, .el-table .el-table__fixed-header-wrapper th {
  background-color: #ffffff;
  color: #000000;
  font-size: 20px;
}
</style>
