<template>
  <div class="Home">
    <div class="content-left">
      <div v-for="item in leftList" :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"
          :info-key="item.infoKey"
          :device-info="deviceInfo[item.infoKey]"
          :total="item.infoKey === 'onLineTotal' ? deviceInfo.onLine : deviceInfo.allTotal"
        ></component>
      </div>
    </div>
    <div class="tianditu">
      <Map @changeStation="getCurrentStation"></Map>
    </div>
    <div class="content-right">
      <div v-for="item in rightList" :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"
          :device-info="deviceInfo[item.infoKey]"
          :total="item.infoKey === 'onLineTotal' ? deviceInfo.onLine : deviceInfo.allTotal"
        ></component>
      </div>
    </div>
  </div>
</template>

<script>
import onLine from '@/components/Home/onLine.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 { 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,
      deviceInfo: {},
      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.loadAllData()
    this.refreshInterval=setInterval(async()=>{
      await this.loadAllData()
    },30000) //30s刷新一次
   
  },

  methods: {
    async loadAllData(){
      await Promise.all([
        this.getOnLineList(),
        this.getStatTotalList(),
        this.getOperTotalList(),
        this.getStatDayList(1),
        this.getStatDayList(2),
        this.getStatDayList(3)
      ]).then((r) => {
        if (
          this.deviceInfo.energy &&
        this.deviceInfo.charge &&
        this.deviceInfo.pv
        ) {
          const newArr = this.mergedArray(
            this.deviceInfo.energy,
            this.deviceInfo.charge,
            this.deviceInfo.pv
          )
          this.deviceInfo.alarm = newArr
        }
      })
    },
    getCurrentStation(e) {
      this.stationId = e
    },
    // 查询系统统计信息
    async getOnLineList() {
      try {
        // token: 用户TOKEN
        const res = await getReq('/queryStatSystem')
        if (res.errcode === 0) {
          this.deviceInfo.onLine = JSON.parse(JSON.stringify(res.data))
          this.deviceInfo.onLine.runDays = getRunDays(res.data.launch_date)
        } else {
          throw res
        }
      } catch (error) {
        this.deviceInfo.onLine = {}
      }
    },

    // 查询系统累计统计信息
    async getStatTotalList() {
      try {
        // token: 用户TOKEN
        // date:日期
        // station_id:场站ID，为0或不传查询所有场站总计
        // category:类别，1:储能设备,2:充电设备,3:光伏设备,为0或不传查询所有类别总计
        const query = {
          date: getDateDaysAgo(0),
          station_id: this.stationId,
          category: 0
        }
        const res = await getReq('/queryStatTotal', query)
        if (res.errcode === 0) {
          this.deviceInfo.allTotal = res.data
          const { income_charge: incomeCharge, income_elect: incomeElect } =
            this.deviceInfo.allTotal
          this.deviceInfo.allTotal.incomeTotal = +incomeCharge + +incomeElect
        } else {
          throw res
        }
      } catch (error) {
        this.deviceInfo.allTotal = {}
        this.deviceInfo.allTotal.incomeTotal = 0
      }
    },
    // 运行分析  联调
    async getOperTotalList() {
      try {
        const res = await getReq('/queryStatStation', {})
        if (res.errcode === 0) {
          this.deviceInfo.operationTotal = res.data
        } else {
          throw res
        }
      } catch (error) {
        this.deviceInfo.operationTotal = [ ]
      }
    },

    // 示例：获取7天前的日期
    // 查询场站日统计信息
    async getStatDayList(category) {
      try {
        // station_id: 场站ID
        // category: 类别： 1：储能设备,2:充电设备,3:光伏设备
        // start_date：开始日期，格式：yyyy-mm-dd
        // end_date：结束日期，格式：yyyy-mm-dd
        const query = {
          station_id: this.stationId,
          category,
          start_date: getDateDaysAgo(7 - 1),
          end_date: getDateDaysAgo(0)
        }
        const arr = { 1: 'energy', 2: 'charge', 3: 'pv' }
        const res = await getReq('/queryStatDayList', query)
        if (res.errcode === 0) {
          this.list.forEach((item) => {
            this.deviceInfo[arr[category]] = res.data
          })
        } 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
    }
  }
}
</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: space-between;
}

.grid-item {
  box-sizing: border-box;
  width: 100%;
  height: calc(33% - 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: 45px;

    .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>
