<template>
  <div class="statisicalAn">
    <div style="display: flex; justify-content: space-between; height: 50px">
      <div class="tab-header">
        <div v-for="item in tabList" :key="item.key" class="tab">
          <span
            :class="[activeKey == item.key ? 'actived' : 'uactived']"
            @click="activeKey = item.key"
            >{{ item.name }}</span
          >
        </div>
      </div>
      <searchBox
        class="searchBox"
        ref="searchBox"
        :btn-option-list="[]"
        :search-options="searchOptions"
        :title-option="{ title: '', info: '' }"
        @onSearch="onSearch"
      >
        <template #stationSelect="item">
          <a-select
            style="width: 120px"
            :dropdown-match-select-width="false"
            v-model:value="stationId"
            allow-clear
            @change="changeStation"
          >
            <a-select-option
              :value="option.value"
              v-for="option in stationList"
              :key="option.value"
            >
              {{ option.label }}
            </a-select-option>
          </a-select>
        </template>
      </searchBox>
    </div>
    <div class="main_content">
      <a-spin :spinning="loading.chart || loading.table">
        <energyEchart
          :key="`${activeKey}_${renderKey}`"
          :chart-options="echartsInfo[activeKey].chartOptions"
          :chart-data="echartsInfo[activeKey].chartData"
          :chart-datav="echartsInfo[activeKey].chartDatav"
          :columns="tableList[activeKey].columns"
          :page-option="tableList[activeKey].pageOption"
          :table-info="tableList[activeKey].tableInfo"
          :table-data="tableList[activeKey].tableData"
          @pagesizeChange="pagesizeChange()"
        ></energyEchart>
      </a-spin>
    </div>
  </div>
</template>

<script>
import energyEchart from '@/components/statisticalAnalysis/energyEchart.vue'
import searchBox from '@/components/SearchBox.vue'
import { postReq, getReq } from '@/request/api'
import { getRunDays, getDateDaysAgo } from '@/utils/dealWithData'

export default {
  name: 'StatisicalAnView',
  components: { energyEchart, searchBox },

  data() {
    return {
      loading: {
        chart: false,
        table: false
      },
      stationId: undefined,
      renderKey: 0,
      categoryArr: [
        {
          type: 1,
          label: '储能设备',
          infoKey: 'energy'
        },
        {
          type: 2,
          label: '充电设备',
          infoKey: 'charge'
        },
        {
          type: 3,
          label: '光伏设备',
          infoKey: 'pv'
        }
      ],
      paramsDate: {},
      searchOptions: [
        {
          label: '日期',
          type: 'datePick1',
          value: [],
          key: 'time'
        },
        {
          label: '场站切换',
          type: 'slot',
          value: [],
          key: 'station',
          slotName: 'stationSelect'
        }
      ],
      stationList: [],
      echartsInfo: {
        1: {
          chartOptions: [
            {
              title: '充放电分析',
              type: 'bar',
              dataKey: 'sales',
              infoKeys: [
                { key: 'storage_elect_in', label: '日充电电量', lineColor: '#2A82E4' },
                { key: 'storage_elect_out', label: '日放电电量', lineColor: '#5AABF2' }
              ]
            },
            {
              title: '运行状态分析',
              type: 'bar',
              dataKey: 'users',
              infoKeys: [
                { key: 'storage_num_err', label: '日故障次数', lineColor: '#0CDAF5' },
                { key: 'key2', label: '日充电工作时长', lineColor: '#2A82E4' },
                { key: 'key3', label: '日放电工作时长', lineColor: '#5AABF2' }
              ]
            },
            {
              title: '今日电压与电流分析',
              type: 'line',
              dataKey: 'stock',
              infoKeys: [
                {
                  key: 'V',
                  label: '电压',
                  lineColor: '#3F80F2',
                  colorStart: ' rgba(10, 250, 106, 0.15)',
                  colorEnd: ' rgba(171, 255, 249, 0.3)'
                },
                {
                  key: 'I',
                  label: '电流',
                  lineColor: '#A9A6FF',
                  colorStart: ' rgba(10, 250, 106, 0.15)',
                  colorEnd: ' rgba(171, 255, 249, 0.3)'
                }
              ]
            },
            {
              title: '今日功率分析',
              type: 'line',
              dataKey: 'yearly',
              infoKeys: [
                {
                  key: 'P',
                  label: '功率',
                  lineColor: '#00FFFB',
                  colorStart: ' rgba(10, 250, 106, 0.15)',
                  colorEnd: ' rgba(171, 255, 249, 0.3)'
                }
              ]
            }
          ],
          chartData: {},
          chartDatav: {}
        },
        2: {
          chartOptions: [
            {
              title: '发电电量分析',
              type: 'bar',
              dataKey: 'sales',
              infoKeys: [{ key: 'storage_elect_in', label: '日发电电量', lineColor: '#2A82E4' }]
            },
            {
              title: '运行状态分析',
              type: 'bar',
              dataKey: 'users',
              infoKeys: [
                { key: 'storage_num_err', label: '日故障次数', lineColor: '#0CDAF5' },
                { key: 'key3', label: '日发电时长', lineColor: '#5AABF2' }
              ]
            },
            {
              title: '今日电压与电流分析',
              type: 'line',
              dataKey: 'stock',
              infoKeys: [
                {
                  key: 'V',
                  label: '电压',
                  lineColor: '#3F80F2',
                  colorStart: ' rgba(10, 250, 106, 0.15)',
                  colorEnd: ' rgba(171, 255, 249, 0.3)'
                },
                {
                  key: 'I',
                  label: '电流',
                  lineColor: '#A9A6FF',
                  colorStart: ' rgba(10, 250, 106, 0.15)',
                  colorEnd: ' rgba(171, 255, 249, 0.3)'
                }
              ]
            },
            {
              title: '今日功率分析',
              type: 'line',
              dataKey: 'yearly',
              infoKeys: [
                {
                  key: 'P',
                  label: '功率',
                  lineColor: '#00FFFB',
                  colorStart: ' rgba(10, 250, 106, 0.15)',
                  colorEnd: ' rgba(171, 255, 249, 0.3)'
                }
              ]
            }
          ],
          chartData: {}
        },
        3: {
          chartOptions: [
            {
              title: '充电分析',
              type: 'bar',
              dataKey: 'sales',
              infoKeys: [{ key: 'storage_elect_in', label: '日充电电量', lineColor: '#2A82E4' }]
            },
            {
              title: '运行状态分析',
              type: 'bar',
              dataKey: 'users',
              infoKeys: [
                { key: 'storage_num_err', label: '日充电次数', lineColor: '#0CDAF5' },
                { key: 'key3', label: '日故障次数', lineColor: '#5AABF2' },
                { key: 'key3', label: '日充电时长', lineColor: '#5AABF2' }
              ]
            },
            {
              title: '今日电压与电流分析',
              type: 'line',
              dataKey: 'stock',
              infoKeys: [
                {
                  key: 'V',
                  label: '电压',
                  lineColor: '#3F80F2',
                  colorStart: ' rgba(10, 250, 106, 0.15)',
                  colorEnd: ' rgba(171, 255, 249, 0.3)'
                },
                {
                  key: 'I',
                  label: '电流',
                  lineColor: '#A9A6FF',
                  colorStart: ' rgba(10, 250, 106, 0.15)',
                  colorEnd: ' rgba(171, 255, 249, 0.3)'
                }
              ]
            },
            {
              title: '今日功率分析',
              type: 'line',
              dataKey: 'yearly',
              infoKeys: [
                {
                  key: 'P',
                  label: '功率',
                  lineColor: '#00FFFB',
                  colorStart: ' rgba(10, 250, 106, 0.15)',
                  colorEnd: ' rgba(171, 255, 249, 0.3)'
                }
              ]
            }
          ],
          chartData: {}
        }
      },
      activeKey: 1,
      interval: null,
      tabList: [
        {
          key: 1,
          name: '储能设备'
        },

        {
          key: 3,
          name: '充电设备'
        },
        {
          key: 2,
          name: '光伏设备'
        }
      ],
      tableList: {
        1: {
          columns: [
            {
              title: '设备ID',
              dataIndex: 'ID',
              key: 'ID',
              width: 120,
              ellipsis: true
            },
            {
              title: '设备名称',
              dataIndex: 'key2',
              key: 'key2',
              width: 120,
              ellipsis: true
            },
            {
              title: '设备类型',
              dataIndex: 'key3',
              key: 'key3',
              width: 120,
              ellipsis: true
            },
            {
              title: '充电电量',
              dataIndex: 'storage_elect_in',
              key: 'storage_elect_in',
              width: 120,
              ellipsis: true
            },
            {
              title: '充电时长',
              dataIndex: 'key5',
              key: 'key5',
              width: 120,
              ellipsis: true
            },
            {
              title: '放电时长',
              dataIndex: 'key6',
              key: 'key6',
              width: 120,
              ellipsis: true
            },
            {
              title: '放电电量',
              dataIndex: 'storage_elect_out',
              key: 'storage_elect_out',
              width: 120,
              ellipsis: true
            },
            {
              title: '故障次数',
              dataIndex: 'storage_num_err',
              key: 'storage_num_err',
              width: 120,
              ellipsis: true
            },
            {
              title: '日期',
              dataIndex: 'dt',
              key: 'dt',
              width: 120,
              ellipsis: true
            }
          ],
          geturl: '',
          tableData: [],
          pageOption: {
            page: 1,
            pageSize: 10,
            count: 1
          }
        },
        2: {
          columns: [
            {
              title: '设备ID',
              dataIndex: 'ID',
              key: 'ID',
              width: 120,
              ellipsis: true
            },
            {
              title: '设备名称',
              dataIndex: 'key2',
              key: 'key2',
              width: 120,
              ellipsis: true
            },
            {
              title: '设备类型',
              dataIndex: 'key3',
              key: 'key3',
              width: 120,
              ellipsis: true
            },
            {
              title: '发电电量',
              dataIndex: 'storage_elect_in',
              key: 'storage_elect_in',
              width: 120,
              ellipsis: true
            },
            {
              title: '发电时长',
              dataIndex: 'key5',
              key: 'key5',
              width: 120,
              ellipsis: true
            },
            {
              title: '故障次数',
              dataIndex: 'key6',
              key: 'key6',
              width: 120,
              ellipsis: true
            },

            {
              title: '日期',
              dataIndex: 'dt',
              key: 'dt',
              width: 120,
              ellipsis: true
            }
          ],
          geturl: '',
          tableData: [],
          pageOption: {
            page: 1,
            pageSize: 10,
            count: 1
          }
        },
        3: {
          columns: [
            {
              title: '设备ID',
              dataIndex: 'ID',
              key: 'ID',
              width: 120,
              ellipsis: true
            },
            {
              title: '设备名称',
              dataIndex: 'key2',
              key: 'key2',
              width: 120,
              ellipsis: true
            },
            {
              title: '设备类型',
              dataIndex: 'key3',
              key: 'key3',
              width: 120,
              ellipsis: true
            },
            {
              title: '充电电量',
              dataIndex: 'storage_elect_in',
              key: 'storage_elect_in',
              width: 120,
              ellipsis: true
            },
            {
              title: '充电时长',
              dataIndex: 'key5',
              key: 'key5',
              width: 120,
              ellipsis: true
            },
            {
              title: '充电次数',
              dataIndex: 'key6',
              key: 'key6',
              width: 120,
              ellipsis: true
            },
            {
              title: '故障次数',
              dataIndex: 'key6',
              key: 'key6',
              width: 120,
              ellipsis: true
            },
            {
              title: '日期',
              dataIndex: 'dt',
              key: 'dt',
              width: 120,
              ellipsis: true
            }
          ],
          geturl: '',
          tableData: [],
          pageOption: {
            page: 1,
            pageSize: 10,
            count: 1
          }
        }
      }
    }
  },
  watch: {
    activeKey: {
      handler(newVal) {
        if (!newVal) return

        // 清除之前的数据
        this.resetDataForInactiveKey()

        // 并行加载新数据
        Promise.all([this.getEchartsListForActiveKey(), this.getTableListForActiveKey()]).then(
          () => {
            this.$nextTick(() => {
              this.getStatCharts()
            })
          }
        )
      },
      immediate: true // 添加立即执行
    }
  },
  async mounted() {
    // 优先加载第一个页面(activeKey=1)所需的数据
    await Promise.all([
      this.getStationList(),
      this.getEchartsListForActiveKey(),
      this.getTableListForActiveKey()
    ])

    // 初始化实时刷新
    this.startRealtimeRefresh()
  },
  beforeUnmount() {
    clearInterval(this.interval) // 组件销毁时清除定时器
  },
  methods: {
    forceRerender() {
      this.renderKey += 1
    },
    resetDataForInactiveKey() {
      // 重置非当前激活页面的数据，减少内存占用
      Object.keys(this.echartsInfo).forEach((key) => {
        if (key != this.activeKey) {
          this.echartsInfo[key].chartData = {}
          this.echartsInfo[key].chartDatav = {}
        }
      })

      Object.keys(this.tableList).forEach((key) => {
        if (key != this.activeKey) {
          this.echartsInfo[key].tableData = {}
        }
      })
    },
    async getEchartsListForActiveKey() {
      if (!this.activeKey) return
      this.loading.chart = true

      const currentInfo = this.echartsInfo[this.activeKey]
      const query = {
        ...this.paramsDate,
        category: this.activeKey
      }

      try {
        const res = await getReq('/queryStatDayList', query)
        if (res.errcode === 0) {
          this.echartsInfo[this.activeKey].chartData = res.data
          this.loading.chart = false
        } else {
          throw res
        }
      } catch (error) {
        this.loading.chart = false
        this.echartsInfo[this.activeKey].chartData = {}
      }
    },
    // 专门获取当前激活页面的表格数据
    async getTableListForActiveKey() {
      this.loading.table = true
      if (!this.activeKey) return

      const currentInfo = this.tableList[this.activeKey]
      const query = {
        ...this.paramsDate,
        category: this.activeKey,
        page_size: currentInfo.pageOption.pageSize,
        pageNumber: currentInfo.pageOption.page
      }

      try {
        const res = await getReq('/queryStatDayList', query)
        if (res.errcode === 0) {
          this.tableList[this.activeKey].tableData = res.data.list || res.data
          this.tableList[this.activeKey].pageOption.count = res.data.count || 0
          this.loading.table = false
        } else {
          throw res
        }
      } catch (error) {
        this.tableList[this.activeKey].tableData = []
        this.tableList[this.activeKey].pageOption.count = 0
        this.loading.table = false
      }
    },
    startRealtimeRefresh() {
      this.interval = setInterval(() => {
        if (this.activeKey) {
          this.getStatCharts() // 定时获取最新实时数据
        }
      }, 10000) // 30秒刷新一次
    },

    async getStationList() {
      const params = {
        page_size: 1000,
        page: 1
      }

      try {
        const res = await getReq('/queryStationList', params)
        if (res.errcode === 0) {
          this.stationList = res.data.map((item) => {
            return {
              value: item.station_id,
              label: item.name
            }
          })
          if (this.stationList.length) {
            if (!this.stationId) {
              this.stationId = this.stationList[0].value
            }
            //V I P
          }
        } else {
          const err = { tip: res.errmsg }
          throw err
        }
      } catch (error) {
        //统一处理报错提示
      }
    },
    pagesizeChange(e) {
      this.tableList[this.activeKey].pageOption.pageSize = e.pageSize
      this.tableList[this.activeKey].pageOption.page = e.page
      this.getTableListForActiveKey()
    },
    onSearch(data) {
      this.paramsDate.start_date = data.time ? data.time[0] : ''
      this.paramsDate.end_date = data.time ? data.time[1] : ''

      this.tableList[this.activeKey].pageOption.page = 1
      this.getStationList(), this.getEchartsListForActiveKey(), this.getTableListForActiveKey()
    },
    changeStation() {
      this.getStatCharts()
    },

    
    async getStatCharts() {
      const currentInfo = this.echartsInfo[this.activeKey]
      const query = {
        dt: this.paramsDate.end_date,
        station_id: this.stationId,
        category: this.activeKey
      }
      try {
        const res = await getReq('/queryStatCharts', query)
        if (res.errcode === 0) {
          this.echartsInfo[this.activeKey].chartDatav = res.data
          // x轴0点到24点
        } else {
          throw res
        }
      } catch (error) {
        this.echartsInfo[this.activeKey].chartDatav = {
          V: [100.0, 100.0, 100.0], // 电压曲线
          I: [10.0, 10.0, 10.0], // 电流曲线
          P: [1000.0, 1000.0, 1000.0] // 功率曲线
        }
      }
    }

   
  }
}
</script>

<style scoped lang="scss">
@import url(@/style/color.scss);
.statisicalAn {
  width: 100%;
  height: 100%;
  padding: 20px;
  background: $bg1-color;
  border-radius: 15px;
  .tab-header {
    display: flex;

    .tab {
      & > span {
        font-size: 14px;
        margin-right: 15px;
        display: inline-block;
        padding: 10px 50px;
        cursor: pointer;
        border: 1px solid $tab-border;
        border-radius: 4px;
      }
    }
  }

  .actived {
    color: #ffffff;

    background-color: $green;
  }
  .uactived {
    color: #a6b8dd;
    background-color: $bg2-color;
  }
}
.main_content {
  overflow: scroll;
  height: calc(100% - 30px);
  // margin-top: 10px;
}
</style>
