<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">
            <span class="linear-text">{{ item.title }}</span>
          </div>
        </div>
      <component :is="item.componentId" :prop-key="item.infoKey" 
        :prop-data="compData[item.infoKey]"
        :props-info="modalInfo[item.infoKey]" 
        :props-total="['prefab', 'envTotal'].includes(item.infoKey)
            ? item.infoKey == 'prefab'
              ? modalInfo.prefabTotal
              : modalInfo.envInfoTotal
            : modalInfo.allTotal
          "></component>
      </div>
    </div>
    <div class="content-right">
      <div v-for="item in listRight" :key="item.componentId" :class="`grid-item ${item.class}`">
        <div class="tool">
          <div class="title">
            <span class="linear-text">{{ item.title }}</span>
          </div>
        </div>
        <component
          :is="item.componentId"
          :props-total="modalInfo.allTotal"
          :props-info="modalInfo[item.infoKey]"
        ></component>
      </div>
    </div>
  </div>
</template>

<script>
import PrefabCabin from '@/components/Home/Modal/PrefabCabin.vue'
import OperationalInfo from '@/components/Home/Modal/OperationalInfo.vue'
import StatisticalInfo from '@/components/Home/Modal/StatisticalInfo.vue'
import Revenue from '@/components/Home/Modal/Revenue.vue'
import Utilization from '@/components/Home/Modal/Utilization.vue'
// import DisCharge from '@/components/Home/Modal/DisCharge.vue'
import { getReq, postReq } from '@/request/api'
import { getRunDays, getDateDaysAgo } from '@/utils/dealWithData'
import EnvInfo from './Modal/EnvInfo.vue'
import { markRaw } from 'vue';
import StationVoltage from '@/components/Home/Modal/StationVoltage.vue'
import StationCurrent from '@/components/Home/Modal/StationCurrent.vue'
import StationPower from '@/components/Home/Modal/StationPower.vue'
export default {
  name: 'Home',
  components: {},
  props: {
    stationId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      refreshInterval:null,

      modalInfo: {},
      compData: {},

      listLeft: [
        { title: '场站信息', class: '', componentId: markRaw( PrefabCabin), infoKey: 'prefab' },
        { title: '储能运行信息', class: 'operation-status', componentId: markRaw(OperationalInfo), infoKey: 'storage' },
        { title: '充电运行信息', class: 'operation-status', componentId: markRaw(OperationalInfo), infoKey: 'charge' },
        { title: '光伏运行信息', class: 'operation-status', componentId: markRaw(OperationalInfo), infoKey: 'pv' },
        { title: '电网侧运行信息', class: 'operation-status', componentId: markRaw(OperationalInfo), infoKey: 'grid' },
        { title: '环境信息', class: 'envInfo', componentId:markRaw( EnvInfo), infoKey: 'envTotal' }
      ],

      listRight: [
        { title: '今日电压曲线', class: 'stats-cards', componentId:markRaw(StationVoltage), infoKey: 'voltage' },
        { title: '今日电流曲线', class: 'revenue', componentId:markRaw(StationCurrent), infoKey: 'current' },
        { title: '今日功率曲线', class: '', componentId:markRaw(StationPower), infoKey: 'power' },
      ],

      // list: [
      //   {
      //     title: '场站信息',
      //     class: '',
      //     componentId: markRaw( PrefabCabin),
      //     infoKey: 'prefab'
      //   },
      //   {
      //     title: '储能充放电量',
      //     class: 'stats-cards',
      //     componentId:markRaw( DisCharge),
      //     infoKey: 'energy'
      //   },
      //   {
      //     title: '运行信息',
      //     class: 'operation-status',
      //     componentId:markRaw( OperationalInfo),
      //     infoKey: 'envTotal'
      //   },
      //   {
      //     title: '场站收益情况',
      //     class: 'revenue',
      //     componentId:markRaw( Revenue),
      //     infoKey: 'energy'
      //   },

      //   {
      //     title: '统计信息',
      //     class: 'statistical',
      //     componentId:markRaw( StatisticalInfo),
      //     infoKey: ''
      //   },
      //   {
      //     title: '设备利用率',
      //     class: '',
      //     componentId:markRaw( Utilization),
      //     infoKey: 'energy'
      //   },
      //   {
      //     title: '环境信息',
      //     class: 'envInfo',
      //     componentId:markRaw( EnvInfo),
      //     infoKey: 'envTotal'
      //   }
      // ],
      sysName: '',
      user: JSON.parse(localStorage.getItem('permission')) || {}
    }
  },
  computed: {
    // leftList() {
    //   return this.list.filter((_, index) => index % 2 === 0).slice(0, 4) // 左列取前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.getStatTotalList(),
        this.queryStationInfo(),
        this.queryStationData(),
        this.getStatDayList(1),
        this.getStatDayList(2),
        this.getStatDayList(3),
      ])
    },
    // 查询系统累计统计信息
    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.compData.prefab = { stats: res.data }
          // this.compData.prefab.run_days = getRunDays(res.data.launch_date)
          // this.modalInfo.allTotal = res.data
          // this.modalInfo.allTotal.run_days = getRunDays(res.data.launch_date)
          // const { income_charge: incomeCharge, income_elect: incomeElect } = this.modalInfo.allTotal
          // this.modalInfo.allTotal.incomeTotal = +incomeCharge + +incomeElect
        } else {
          throw res
        }
      } catch (error) {
        this.modalInfo.allTotal = {}
      }
    },
    // 查询场站实时数据
    async queryStationData() {
      try {
        const res = await getReq('/queryStationData', { station_id: this.stationId })
        if (res.errcode === 0) {
          // this.compData.prefab = { data: res.data }
          this.compData.storage = res.data['storage']
          this.compData.charge = res.data['charge']
          this.compData.pv = res.data['pv']
          this.compData.grid = res.data['grid']
        } else {
          throw res
        }
      } catch (error) {
        this.compData.storage = this.compData.charge = this.compData.pv = this.compData.grid = {}
      }
    },
    // 查询场站信息
    async queryStationInfo() {
      try {
        const res = await getReq('/queryStationInfo', { station_id: this.stationId })
        if (res.errcode === 0) {
          this.compData.prefab = { info: res.data }
          this.compData.prefab.info.run_days = getRunDays(res.data.launch_date)
        } else {
          throw res
        }
      } catch (error) {
        this.compData.prefab = { info: {}}
      }
    },
    // 查询场站日统计信息
    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 res = await getReq('/queryStatDayList', query)
        const res = await getReq('/queryStationTodayU', query)
        if (res.errcode === 0) {
          if (category === 1) {
            this.modalInfo.voltage = [{ index: 0, data: res.data.U }] 
            this.modalInfo.current = [{ index: 0, data: res.data.I }] 
            this.modalInfo.power = [{ index: 0, data: res.data.P }] 
          }
          else if (category === 2){
            this.modalInfo.voltage = [{ index: 1, data: res.data.U }] 
            this.modalInfo.current = [{ index: 1, data: res.data.I }] 
            this.modalInfo.power = [{ index: 1, data: res.data.P }] 
          }
          else if (category === 3){
            this.modalInfo.voltage = [{ index: 2, data: res.data.U }] 
            this.modalInfo.current = [{ index: 2, data: res.data.I }] 
            this.modalInfo.power = [{ index: 2, data: res.data.P }] 
          }
        } else {
          throw res
        }
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

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

.content-left,
.content-right {
  height: 100%;
  width: 520px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
}

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

  &:nth-child(2n) {
    // height:calc(33% - 10px)!important;
  }
  .tool {
    background: url('@/assets/home/modal-header-bg.png');
    background-size: contain;
    background-repeat: no-repeat;
    background-position: center;

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

    .linear-text {
      margin-bottom: 7px;
      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: 18px;
      font-weight: 1000;
      margin-left: 28px;
    }

    .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: 1000;
      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;
    }
  }
}
.operation-status {
  height: calc(15% - 10px);
}
.statistical {
  height: calc(18% - 10px);
}
.envInfo {
  height: calc(15% - 10px);
}
</style>
