<template>
  <div class="Home">
    <div class="content-left">
      <div v-for="item in listLeft" :key="item.componentId" :class="`grid-item ${item.class}`">
        <div class="tool">
          <div class="title">
            <i class="iconfont icon-hebing linear-text"></i>
            <span class="linear-text">{{ item.title }}</span>
          </div>
        </div>

        <component :is="item.componentId" :prop-key="item.infoKey" :prop-option="compInfo[item.infoKey]"
          :prop-data="compData[item.infoKey]">
        </component>
      </div>
    </div>
    <div class="tianditu">
      <Map @changeStation="getCurrentStation"></Map>
    </div>
    <div class="content-right">
      <div style="width:100%; height:32px;">
        <span style="width:120px">场站选择</span>
        <a-select v-model:value="selectStationId" style="margin-left: 10px; width: 200px;" @change="getStationChange">
          <a-select-option v-for="station in stationList" :value="station['station_id']">{{ station.name }}
          </a-select-option>
        </a-select>
      </div>
      <div v-for="item in listRight" :key="item.componentId" :class="`grid-item ${item.class}`">
        <div class="tool">
          <div class="title">
            <i class="iconfont icon-hebing linear-text"></i>
            <span class="linear-text">{{ item.title }}</span>
          </div>
        </div>
        <component :is="item.componentId" :prop-key="item.infoKey" :prop-option="compInfo[item.infoKey]"
          :prop-data="compDataStation[item.infoKey]">
        </component>
      </div>
    </div>
  </div>
</template>

<script>
import onLine from '@/components/Home/onLine.vue'
import TotalStation from '@/components/Home/TotalStation.vue'
import Operational from '@/components/Home/Operational.vue'
import Energy from '@/components/Home/Energy.vue'
import Charge from '@/components/Home/Charge.vue'
import Pv from '@/components/Home/Pv.vue'
import Alarm from '@/components/Home/Alarm.vue'
import Map from '@/components/Home/Map.vue'
import MyChartBar from '@/components/Home/MyChartBar.vue'
import { getReq, postReq } from '@/request/api'
import { getRunDays, getDateDaysAgo } from '@/utils/dealWithData'
import { markRaw } from 'vue'
export default {
  name: 'Home',
  components: { Map },
  data() {
    return {
      refreshInterval: null,
      showFlag: false,
      stationId: null,
      compData: {
        total: {},
        energy: [],
        charge: [],
        pv: [],
        stateGrid: [],
      },
      compDataStation: {
        totalStation: {},
        energy: [],
        charge: [],
        pv: [],
        stateGrid: [],
      },
      compInfo: {
        total: {},
        energy: {
          yAxis: ['电量(kWh)'],
          series: [
            { name: '日充电电量', key: 'storage_elect_in', color: '#22E4FF' },
            { name: '日放电电量', key: 'storage_elect_out', color: '#0E68E4' },
          ]
        },
        pv: {
          yAxis: ['电量(kWh)'],
          series: [
            { name: '日发电电量', key: 'solar_elect_gen', color: '#22E4FF' },
          ]
        },
        charge: {
          yAxis: ['电量(kWh)'],
          series: [
            { name: '日充电电量', key: 'charge_elect', color: '#22E4FF' },
          ]
        },
        stateGrid: {
          yAxis: ['电量(kWh)'],
          series: [
            { name: '日上网电量', key: 'solar_elect_grid', color: '#22E4FF' },
          ]
        }
      },
      listLeft: [
        { title: '系统运行统计', class: 'online-status', componentId: markRaw(onLine), infoKey: 'total' },
        { title: '储能设备', class: 'energy-status', componentId: markRaw(MyChartBar), infoKey: 'energy' },
        { title: '充电设备', class: 'charge-analysis', componentId: markRaw(MyChartBar), infoKey: 'charge' },
        { title: '光伏设备', class: 'work-order', componentId: markRaw(MyChartBar), infoKey: 'pv' },
        { title: '电网侧', class: 'work-order', componentId: markRaw(MyChartBar), infoKey: 'stateGrid' },
      ],
      listRight: [
        { title: '场站运行统计', class: 'online-status', componentId: markRaw(TotalStation), infoKey: 'totalStation' },
        { title: '储能设备', class: 'energy-status', componentId: markRaw(MyChartBar), infoKey: 'energy' },
        { title: '充电设备', class: 'charge-analysis', componentId: markRaw(MyChartBar), infoKey: 'charge' },
        { title: '光伏设备', class: 'work-order', componentId: markRaw(MyChartBar), infoKey: 'pv' },
        { title: '电网侧', class: 'work-order', componentId: markRaw(MyChartBar), infoKey: 'stateGrid' },
      ],
      stationList: [],
      selectStationId: '',
      list: [
        {
          title: '系统运行统计',
          class: 'online-status',
          componentId: markRaw(onLine),
          infoKey: 'onLineTotal'
        },
        {
          title: '运行分析',
          class: 'stats-cards',
          componentId: markRaw(Operational),
          infoKey: 'operationTotal'
        },
        {
          title: '储能设备',
          class: 'energy-status',
          componentId: markRaw(Energy),
          infoKey: 'energy'
        },
        {
          title: '充电设备',
          class: 'charge-analysis',
          componentId: markRaw(Charge),
          infoKey: 'charge'
        },
        {
          title: '光伏设备',
          class: 'work-order',
          componentId: markRaw(Pv),
          infoKey: 'pv'
        },
        {
          title: '告警信息',
          class: 'alarm-stats',
          componentId: markRaw(Alarm),
          infoKey: 'alarm'
        }
      ],

      sysName: '',
      user: JSON.parse(localStorage.getItem('user')) || {}
    }
  },
  computed: {
    leftList() {
      return {} //this.list.filter((_, index) => index % 2 === 0).slice(0, 3) // 左列取前3个偶数索引
    },
    rightList() {
      return {} //this.list.filter((_, index) => index % 2 !== 0).slice(0, 3) // 右列取前3个奇数索引
    }
  },
  beforeUnmount() {
    if (this.refreshInterval) {
      clearInterval(this.refreshInterval)
      this.refreshInterval = null
    }
  },
  async mounted() {
    await this.getStationList()
    await this.loadAllData()
    this.refreshInterval = setInterval(async () => {
      await this.loadAllData()
    }, 30000) //30s刷新一次

  },

  methods: {
    async loadAllData() {
      await Promise.all([
        this.queryStatTotal(),
        this.queryStatTotal(this.selectStationId),
        // this.getOperTotalList(),
        this.getStatDayList(),
        this.getStatDayList(this.selectStationId),
        // this.getStatDayList(1),
        // this.getStatDayList(2),
        // this.getStatDayList(3)
      ]).then((r) => {
        // if (
        //   this.compData.energy &&
        //   this.compData.charge &&
        //   this.compData.pv
        // ) {
        //   const newArr = this.mergedArray(
        //     this.compData.energy,
        //     this.compData.charge,
        //     this.compData.pv
        //   )
        //   this.compData.alarm = newArr
        // }
      })
    },
    getCurrentStation(e) {
      this.stationId = e
    },
    // 查询系统的场站列表
    async getStationList() {
      try {
        const res = await getReq('/queryStationList', { page: 0, page_size: 100 })
        if (res.errcode === 0) {
          // 设置场站下拉列表，默认选中第一项
          this.stationList = res.data
          this.selectStationId = this.stationList[0]['station_id']
        } else {
          throw res
        }
      } catch (error) {
        this.stationList = []
        this.selectStationId = ''
      }
    },
    // 查询系统累计统计信息, 不传参数 curStationId 时查询所有场站数据
    async queryStatTotal(curStationId) {
            
      try {
        const res = await getReq('/queryStatTotal', { station_id: curStationId })
        if (res.errcode === 0) {
          // this.compData.total = res.data
          // const { income_charge: incomeCharge, income_elect: incomeElect } =
          //   this.compData.total
          // this.compData.total.incomeTotal = +incomeCharge + +incomeElect
          // this.compData.total.runDays = getRunDays(res.data.launch_date)
          if (curStationId === undefined) {
            this.compData.total = res.data
            this.compData.total.runDays = getRunDays(res.data.launch_date)
          } else {
            this.compDataStation.totalStation = res.data
            this.compDataStation.totalStation.runDays = getRunDays(res.data.launch_date)
          }
        } else {
          throw res
        }
      } catch (error) {
        this.compData.total = {}
        this.compData.total.incomeTotal = 0
      }
    },
    // 运行分析  联调
    async getOperTotalList() {
      try {
        const res = await getReq('/queryStatStation', {})
        if (res.errcode === 0) {
          this.compData.operationTotal = res.data
        } else {
          throw res
        }
      } catch (error) {
        this.compData.operationTotal = []
      }
    },


    // 查询近7日的统计信息，
    async getStatDayList(curStationId) {
      try {
        if (curStationId === '') {
          return
        }
        // station_id: 场站ID
        // category: 类别： 1：储能设备,2:充电设备,3:光伏设备
        // start_date：开始日期，格式：yyyy-mm-dd
        // end_date：结束日期，格式：yyyy-mm-dd
        let query = {
          //station_id: this.stationId,
          // category,
          start_date: getDateDaysAgo(7 - 1),
          end_date: getDateDaysAgo(0)
        }
        if (curStationId) {
          query.station_id = curStationId
        }
        //const arr = { 1: 'energy', 2: 'charge', 3: 'pv' }
        const res = await getReq('/queryStatDayList', query)
        if (res.errcode === 0) {
          if (curStationId) {
            this.compDataStation.energy
              = this.compDataStation.charge
              = this.compDataStation.pv
              = this.compDataStation.stateGrid
              = res.data
          } else {
            this.compData.energy
              = this.compData.pv
              = this.compData.stateGrid
              = this.compData.charge
              = res.data
          }
          // this.list.forEach((item) => {
          //   //this.compData[arr[category]] = res.data
          //   alert(JSON.stringify(item))
          //   return
          // })
        } else {
          throw res
        }
      } catch (error) {
        console.log(error)
      }
    },
    // 整合三个数组
    mergedArray(arr1, arr2, arr3) {
      const newArr = []
      arr1.forEach((item1, index) => {
        // 获取对应索引的 arr2 和 arr3 的对象
        const item2 = arr2[index] || {}
        const item3 = arr3[index] || {}

        // 返回整合后的对象
        newArr.push({
          storage_num_err: item1.storage_num_err || '',
          solar_num_err: item2.solar_num_err || '',
          charge_num_err: item3.charge_num_err || '',
          dt: item1.dt
        })
      })
      return newArr
    },
    getStationChange() {
      this.queryStatTotal(this.selectStationId),
      this.getStatDayList(this.selectStationId)
    }
  }
}
</script>

<style scoped lang="scss">
.Home {
  color: #fff;
  height: 100%;
  padding: 10px;
  display: flex;
  justify-content: space-between;
}

.tianditu {
  width: 44%;
  height: 100%;
  margin: 0px 15px;
}

.content-left,
.content-right {
  height: 100%;
  width: 28%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
}

.grid-item {
  box-sizing: border-box;
  width: 100%;
  height: calc(25% - 10px);
  z-index: 20;

  .tool {
    background: linear-gradient(180deg, rgba(0, 10, 6, 0) 0%, rgba(0, 76, 112, 1) 100%);
    border-bottom: 2px solid transparent;
    border-image: linear-gradient(90deg, rgba(3, 220, 255, 1) 0%, rgba(0, 19, 13, 0) 100%) 0 0 2 0;

    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 32px;

    .linear-text {
      background: linear-gradient(180deg, rgba(255, 255, 255, 1) 0%, rgba(40, 235, 231, 1) 100%);
      color: transparent;
      -webkit-background-clip: text;
      background-clip: text;
      font-size: 16px;
      font-weight: 400;
      margin-left: 6px;
    }

    .text_right {
      display: flex;
      font-size: 11px;

      div {
        margin-right: 6px;
      }

      .mark {
        margin: 0px 2px;
        font-weight: bold;
        color: #43cf7c;
        font-size: 14px;
      }
    }
  }

  .title {
    display: flex;

    i {
      margin-left: 10px;
    }

    .text {
      margin-left: 20px;
      font-size: 16px;
      font-weight: 700;
      background: linear-gradient(90deg,
          rgba(0, 186, 173, 0.15) 0%,
          rgba(61, 254, 250, 0.15) 49.2%,
          rgba(61, 254, 250, 0) 100%);
      -webkit-background-clip: text;
      display: inline-block;
      background-clip: text;
      color: transparent;
    }
  }
}
</style>
