<!--
  -    Copyright (c) 2018-2025, lengleng All rights reserved.
  -
  - Redistribution and use in source and binary forms, with or without
  - modification, are permitted provided that the following conditions are met:
  -
  - Redistributions of source code must retain the above copyright notice,
  - this list of conditions and the following disclaimer.
  - Redistributions in binary form must reproduce the above copyright
  - notice, this list of conditions and the following disclaimer in the
  - documentation and/or other materials provided with the distribution.
  - Neither the name of the pig4cloud.com developer nor the names of its
  - contributors may be used to endorse or promote products derived from
  - this software without specific prior written permission.
  - Author: lengleng (wangiegie@gmail.com)
  -->
<template>
  <div class="execution">
    <div class="filter">
      <div class="startTime" style="display: inline-block">
        <span class="timeText" style="font-weight: bold;font-size: 14px">&#12288;短期、风速日期:</span>
        <el-date-picker
          value-format="timestamp"
          v-model="ycDate"
          :clearable="false"
          type="date"
          placeholder="选择日期">
        </el-date-picker>
      </div>
      <div class="endTime" style="display: inline-block">
        <span class="timeText" style="font-weight: bold;font-size: 14px">&#12288;超短期日期:</span>
        <el-date-picker
          value-format="timestamp"
          v-model="cdqDate"
          :clearable="false"
          type="date"
          placeholder="选择日期">
        </el-date-picker>
      </div>
      <div class="endTime" style="display: inline-block">
        <span class="timeText" style="font-weight: bold;font-size: 14px">&#12288;实际功率日期:</span>
        <el-date-picker
          value-format="timestamp"
          v-model="sjDate"
          :clearable="false"
          type="date"
          placeholder="选择日期">
        </el-date-picker>
      </div>
      <div class="endTime" style="display: inline-block">
        <span class="timeText" style="font-weight: bold;font-size: 14px">&#12288;AGC限电指令日期:</span>
        <el-date-picker
          value-format="timestamp"
          v-model="agcDate"
          :clearable="false"
          type="date"
          placeholder="选择日期">
        </el-date-picker>
      </div>
      <div class="timeQuery" style="display: inline-block">
        &#12288;<el-button size="small" :loading="loading" @click="fetchStationData">查询</el-button>
        <el-button size="small" :loading="loading" @click="exportDataEvent">导出</el-button>
      </div>
    </div>

    <div class="station-container">
      <el-tabs v-model="activeStation" type="card" @tab-click="handleClick">
        <el-tab-pane
          v-for="(stationData, stationName) in stationMap"
          :key="stationName"
          :label="stationName"
          :name="stationName"
        >
        </el-tab-pane>
      </el-tabs>
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        :cell-style="{ textAlign: 'center' }"
        v-loading="loading"
        height="720"
      >
        <el-table-column header-align="center" prop="time" label="时间" ></el-table-column>
        <el-table-column header-align="center" prop="windSpeed" label="风速" ></el-table-column>
        <el-table-column header-align="center" prop="shortTerm" label="短期功率预测" ></el-table-column>
        <el-table-column header-align="center" prop="ultraShortTerm" label="超短期功率预测" ></el-table-column>
        <el-table-column header-align="center" prop="actualPower" label="实际发电" ></el-table-column>
        <el-table-column header-align="center" prop="agc" label="AGC指令" ></el-table-column>
      </el-table>
    </div>


  </div>


</template>

<script>
import {mapGetters} from 'vuex'
import * as echarts from 'echarts';
import {
  queryCharts

} from '@/api/windtotalpowercontrast'
export default {
  name: 'forecastReport',
  data() {
    return {
      activeStation: '', // 当前激活的场站名称
      stationMap: {},   // 存储所有场站数据
      ycDate: new Date(new Date().toLocaleDateString()).getTime(),
      cdqDate: new Date(new Date().toLocaleDateString()).getTime() - 60 * 60 * 24 * 1000,
      sjDate: new Date(new Date().toLocaleDateString()).getTime() - 60 * 60 * 24 * 1000,
      agcDate: new Date(new Date().toLocaleDateString()).getTime() - 60 * 60 * 24 * 1000,
      dynamicColumns: [], // 动态风电场信息，例如: [{ name: '哈斯风电场' }, { name: '千伏苏加风电场' }]
      columns: [],
      searchForm: {},
      tableData: [],
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20 // 每页显示多少条
      },
      total: 0, // 总页数
      currentPage: 1, // 当前页数
      pageSize: 10, // 每页显示多少条
      wsChart:null,
      tableLoading: false,
      stationCode: '',
      stationType:'',
      stationList: [],
      forecastManufactor: '',
      forecastManufactorList: [],
      drawData: {datas: [], times: []},
      resizeKey: 1,
      activeName: 'first',
      loading: false,
      ultraShortData: [],
      shortData: [],
      powerStationStatusData: [],
      timeStamp: [],
      arrays: [],
      fromHead: []
    }
  },
  computed: {
    ...mapGetters(['permissions']),
  },
  mounted() {
    this.$nextTick(() => {
      this.$refs.table.doLayout();
    });
  },
  methods: {
    // 获取场站数据
    async fetchStationData() {
      this.loading = true;
      var queryParams = {
        ycDate:this.ycDate,
        cdqDate:this.cdqDate,
        sjDate:this.sjDate,
        agcDate:this.agcDate
      }
      this.$axios.get('/forecastReportController/queryReport',{params: queryParams}).then((res) => {
        this.stationMap = res.data.data;
        // 设置默认激活第一个场站
        const stationNames = Object.keys(this.stationMap);
        if (stationNames.length > 0) {
          this.activeStation = stationNames[0];
          this.tableData = this.stationMap[this.activeStation];
        }
      })
      this.loading = false;
    },
    queryDataForCharts() {
      if (this.startTime==null){
        this.$message.warning('请选择开始时间')
        return
      }
      if (this.endTime==null){
        this.$message.warning('请选择结束时间')
        return
      }
      const param = new URLSearchParams()
      param.append('startTime', this.startTime)
      param.append('endTime', this.endTime)

      queryCharts(param).then((res) => {
        this.drawData = res.data.data
        // 保存动态列（风电场名称）
        this.dynamicColumns = res.data.data.columns;
        // 转换数据为扁平结构
        this.tableData = res.data.data.tableData.map((item, rowIndex) => {
          const newItem = {
            time: item.time,
            predictedTotalPower: item.predictedTotalPower,
            actualTotalPower: item.actualTotalPower,
          };

          // 遍历每个风电场，添加预测和实际功率
          res.data.data.columns.forEach((site, index) => {
            newItem[`site_${index}_pred`] = item[site].predicted;
            newItem[`site_${index}_actual`] = item[site].actual;
          });
          return newItem;
        });

        // this.tableData = res.data.data.tableData; // 表格数据
        this.total = res.data.data.tableData.length

        this.dqDraw(this.drawData)
      }).catch((error) => {
        if (!this.tableLoading) {
          this.loading = false
        }
        console.log(error)
        this.$message.error('查询总功率charts出错' + error)
      })

    },
    handleClick(tab, event) {
      this.tableData = this.stationMap[tab.name];
      console.log(tab.name);
    },
    exportDataEvent() {
      if (this.startTime==null){
        this.$message.warning('请选择开始时间')
        return
      }
      if (this.endTime==null){
        this.$message.warning('请选择结束时间')
        return
      }
      this.$axios.get("/windtotalpowercontrast/exportDataEvent/" +this.startTime + "/" + this.endTime, {
        responseType: 'blob'// 用于解决中文乱码
      }).then((response) => {
        this.loading = false
      }).catch((error) => {
        this.loading = false
        this.$message.error('导出失败' + error)
      })
    },

    getCapacity(param) {
      return new Promise(function (resolve, reject) {
        getCapacity(param).then(response => {
          resolve(response.data.data)
        })
      })
    },
    handlePageChange({currentPage, pageSize}) {
      this.currentPage = currentPage;//当前页
      this.pageSize = pageSize//每页显示的条数
    },
    refreshChange() {
      // this.getCompositeData()
      this.getStationCode()
    }
  }
}
</script>
