<template>
  <div>
    <el-row style="background: #fff" class="row-container" :gutter="15">
      <el-col :xs="24" :sm="24" :lg="5">
        <!--      站点信息-->
        <el-card
            shadow="always"
            class="common-card-container common-card-container-body-no-padding"
        >
          <div slot="header">
            <span class="card-title">站点信息</span>
            <div class="alarm-msg" v-if="tableData.length > 0" @click="toAlarm">
              <i class="el-icon-message-solid"></i> 设备告警
            </div>
          </div>
          <div
              style="box-sizing: border-box; height: 218px; padding: 20px 15px"
          >
            <!--            地址、运行时间-->
            <div class="site-info site-info-address">
              <div class="title">
                <i class="el-icon-location"></i>
              </div>
              <div class="value">
                <i v-if="isBaseInfoLoading" class="el-icon-loading"></i>
                <span v-else>{{ info.siteAddress || '-' }}</span>
              </div>
            </div>
            <div class="site-info">
              <div class="title">
                <i class="el-icon-date"></i>
              </div>
              <div class="value">
                <i v-if="isBaseInfoLoading" class="el-icon-loading"></i>
                <span v-else>{{ info.runningTime || '-' }}</span>
              </div>
            </div>
            <!--      装机功率、容量      -->
            <el-row :gutter="10" style="margin-top:20px;">
              <el-col
                  :span="12"
                  class="sjgl-col power-col"
              >
                <div class="sjgl-wrapper">
                  <div class="sjgl-title">装机功率(MW)</div>
                  <div class="sjgl-value">
                    <i v-if="isBaseInfoLoading" class="el-icon-loading"></i>
                    <span v-else>{{ info.installPower | formatNumber }}</span>
                  </div>
                </div>
              </el-col>
              <el-col
                  :span="12"
                  class="sjgl-col power-col"
              >
                <div class="sjgl-wrapper">
                  <div class="sjgl-title">装机容量(MW)</div>
                  <div class="sjgl-value">
                    <i v-if="isBaseInfoLoading" class="el-icon-loading"></i>
                    <span v-else>{{ info.installCapacity | formatNumber }}</span>
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </el-col>
      <!--      总累计运行数据-->
      <el-col :xs="24" :sm="24" :lg="19">
        <el-card
            shadow="always"
            class="common-card-container common-card-container-body-no-padding"
        >
          <div slot="header">
            <span class="card-title">总累计运行数据</span>
            <div class="total-count">
              <span class="title">总收入</span>
              <span class="value">
                <i v-if="isRunningInfoLoading" class="el-icon-loading"></i>
                <span v-else>{{ totalRevenueDisplayValue | formatNumber }}</span>
              </span>
              <span class="unit">元</span>
            </div>
          </div>
          <div
              style="box-sizing: border-box; height: 218px; padding: 20px 15px"
          >
            <el-row :gutter="10">
              <el-col
                  :span="6"
                  v-for="(item, index) in runningDataCards"
                  :key="index + 'sjglData'"
                  class="sjgl-col"
              >
                <div class="sjgl-wrapper">
                  <div class="sjgl-title">{{ item.title }}</div>
                  <div class="sjgl-value" :style="{color:item.color}">
                    <i v-if="item.loading" class="el-icon-loading"></i>
                    <span v-else>{{ item.value | formatNumber }}</span>
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="24" :lg="12">
        <week-chart ref="weekChart" :display-data="runningDisplayData"/>
      </el-col>
      <el-col :xs="24" :sm="24" :lg="12">
        <active-chart ref="activeChart" :display-data="runningDisplayData"/>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {getSingleSiteBaseInfo} from "@/api/ems/zddt";
import {getDzjkHomeView, getProjectDisplayData} from "@/api/ems/dzjk";
import WeekChart from "./WeekChart.vue";
import ActiveChart from "./ActiveChart.vue";
import AlarmTable from "./AlarmTable.vue";
import ClInfo from "./ClInfo.vue";
import getQuerySiteId from "@/mixins/ems/getQuerySiteId";
import intervalUpdate from "@/mixins/ems/intervalUpdate";

export default {
  name: "DzjkSbjkHome",
  components: {WeekChart, ActiveChart, AlarmTable, ClInfo},
  mixins: [getQuerySiteId, intervalUpdate],
  data() {
    return {
      loading: false,
      baseInfoLoading: false,
      runningInfoLoading: false,
      runningUpdateSpinning: false,
      runningUpdateTimer: null,
      fallbackSjglData: [
        {
          title: "今日充电量（kWh）",
          attr: "dayChargedCap",
          color: '#4472c4'
        },
        {
          title: "今日放电量（kWh）",
          attr: "dayDisChargedCap",
          color: '#70ad47'
        },
        {
          title: "总充电量（kWh）",
          attr: "totalChargedCap",
          color: '#4472c4'
        },
        {
          title: "今日实时收入（元）",
          attr: "dayRevenue",
          color: '#f67438'
        },
        {
          title: "昨日充电量（kWh）",
          attr: "yesterdayChargedCap",
          color: '#4472c4'
        },
        {
          title: "昨日放电量（kWh）",
          attr: "yesterdayDisChargedCap",
          color: '#70ad47'
        },
        {
          title: "总放电量（kWh）",
          attr: "totalDischargedCap",
          color: '#70ad47'
        },
        {
          title: "昨日实时收入（元）",
          attr: "yesterdayRevenue",
          color: '#f67438'
        },
      ],
      info: {}, //基本信息
      runningInfo: {}, //总累计运行数据+报警表格
      runningDisplayData: [], //单站监控项目配置展示数据
    };
  },
  computed: {
    isBaseInfoLoading() {
      return false;
    },
    isRunningInfoLoading() {
      const state = this.$data || {};
      return !!(state.runningInfoLoading || state.runningUpdateSpinning || state.loading);
    },
    tableData() {
      return this.runningInfo?.siteMonitorHomeAlarmVo || [];
    },
    totalRunningSectionData() {
      return (this.runningDisplayData || []).filter(item => item.sectionName === "总累计运行数据");
    },
    totalRevenueDisplayItem() {
      const sectionData = this.totalRunningSectionData || [];
      const byFieldCode = sectionData.find(item => item.fieldCode === "totalRevenue");
      if (byFieldCode) {
        return byFieldCode;
      }
      return sectionData.find(item => item.fieldName === "总收入");
    },
    totalRevenueDisplayValue() {
      return this.totalRevenueDisplayItem ? this.totalRevenueDisplayItem.fieldValue : this.runningInfo.totalRevenue;
    },
    runningDataCards() {
      const sectionData = this.totalRunningSectionData || [];
      if (sectionData.length > 0) {
        const revenueFieldCode = this.totalRevenueDisplayItem ? this.totalRevenueDisplayItem.fieldCode : "";
        return sectionData
            .filter(item => item.fieldCode !== revenueFieldCode)
            .map((item, index) => ({
              title: item.fieldName,
              value: item.fieldValue,
              color: this.getCardColor(index),
              loading: this.isRunningInfoLoading,
            }));
      }
      return this.fallbackSjglData.map(item => ({
        title: item.title,
        value: this.runningInfo[item.attr],
        color: item.color,
        loading: this.isRunningInfoLoading,
      }));
    },
  },
  beforeDestroy() {
    if (this.runningUpdateTimer) {
      clearTimeout(this.runningUpdateTimer);
      this.runningUpdateTimer = null;
    }
  },
  methods: {
    setBaseInfoLoading(loading) {
      if (Object.prototype.hasOwnProperty.call(this.$data, "baseInfoLoading")) {
        this.baseInfoLoading = loading;
        return;
      }
      this.$set(this.$data, "baseInfoLoading", loading);
    },
    setRunningInfoLoading(loading) {
      if (Object.prototype.hasOwnProperty.call(this.$data, "runningInfoLoading")) {
        this.runningInfoLoading = loading;
        return;
      }
      this.$set(this.$data, "runningInfoLoading", loading);
    },
    getCardColor(index) {
      const colors = ['#4472c4', '#70ad47', '#4472c4', '#f67438', '#4472c4', '#70ad47', '#70ad47', '#f67438'];
      return colors[index % colors.length];
    },
    toAlarm() {
      this.$router.push({path: "/dzjk/gzgj", query: this.$route.query});
    },
    getBaseInfo() {
      return getSingleSiteBaseInfo(this.siteId).then((response) => {
        this.info = response?.data || {};
      });
    },
    getRunningInfo() {
      const hasOldData = Object.keys(this.runningInfo || {}).length > 0 || (this.runningDisplayData || []).length > 0;
      if (!hasOldData) {
        this.setRunningInfoLoading(true);
      }
      return Promise.all([
        getDzjkHomeView(this.siteId),
        getProjectDisplayData(this.siteId),
      ]).then(([homeResponse, displayResponse]) => {
        const nextRunningInfo = homeResponse?.data || {};
        const nextRunningDisplayData = displayResponse?.data || [];
        const changed = hasOldData && this.hasTotalRunningChanged(nextRunningInfo, nextRunningDisplayData);
        this.runningInfo = nextRunningInfo;
        this.runningDisplayData = nextRunningDisplayData;
        if (changed) {
          this.triggerRunningUpdateSpinner();
        }
      }).finally(() => {
        if (!hasOldData) {
          this.setRunningInfoLoading(false);
        }
      });
    },
    triggerRunningUpdateSpinner() {
      if (this.runningUpdateTimer) {
        clearTimeout(this.runningUpdateTimer);
      }
      this.runningUpdateSpinning = true;
      this.runningUpdateTimer = setTimeout(() => {
        this.runningUpdateSpinning = false;
        this.runningUpdateTimer = null;
      }, 800);
    },
    hasTotalRunningChanged(nextRunningInfo, nextRunningDisplayData) {
      const oldSnapshot = this.getTotalRunningSnapshot(this.runningInfo, this.runningDisplayData);
      const newSnapshot = this.getTotalRunningSnapshot(nextRunningInfo, nextRunningDisplayData);
      return JSON.stringify(oldSnapshot) !== JSON.stringify(newSnapshot);
    },
    getTotalRunningSnapshot(runningInfo, runningDisplayData) {
      const snapshot = {};
      const sectionData = (runningDisplayData || []).filter(item => item.sectionName === "总累计运行数据");
      if (sectionData.length > 0) {
        sectionData.forEach(item => {
          const key = item.fieldCode || item.fieldName;
          if (!key) return;
          snapshot[`cfg:${key}`] = this.normalizeRunningCompareValue(item.fieldValue);
        });
        return snapshot;
      }
      this.fallbackSjglData.forEach(item => {
        snapshot[`fallback:${item.attr}`] = this.normalizeRunningCompareValue(runningInfo?.[item.attr]);
      });
      snapshot["fallback:totalRevenue"] = this.normalizeRunningCompareValue(runningInfo?.totalRevenue);
      return snapshot;
    },
    normalizeRunningCompareValue(value) {
      if (value === null || value === undefined) return "";
      if (typeof value === "number") return Number.isNaN(value) ? "" : value;
      const text = String(value).trim();
      if (text === "") return "";
      const num = Number(text);
      return Number.isNaN(num) ? text : num;
    },
    init() {
      // 功率曲线
      this.$refs.activeChart.init(this.siteId);
      // 一周冲放曲线
      this.$refs.weekChart.init(this.siteId);
      // 静态信息  this.getBaseInfo()
      // 总累计运行数据+故障告警 this.getRunningInfo()
      Promise.all([this.getBaseInfo(), this.getRunningInfo()]);
      // 一分钟循环一次总累计运行数据
      this.updateInterval(this.getRunningInfo);
    },
  },
};
</script>

<style scoped lang="scss">
//设备告警
.alarm-msg {
  background: #ff4949;
  padding: 2px 5px;
  font-size: 10px;
  font-weight: bolder;
  border-radius: 3px;
  line-height: 20px;
  cursor: pointer;
  color: #fff;
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
}

//基本信息-地址 运行️时间
.site-info {
  display: flex;
  font-size: 12px;
  line-height: 20px;
  margin-bottom: 10px;
  align-items: center;

  &.site-info-address {
    height: 40px;
  }

  .title {
    color: #1791ff;
    font-size: 18px;
    line-height: 20px;
    margin-right: 7px;
  }

  .value {
    color: #000;
    font-size: 12px;
    max-height: 40px;
    overflow: hidden;
  }
}

//总收入
.total-count {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 12px;
  font-weight: bolder;
  color: #333;
  line-height: 14px;

  .unit {
    font-style: italic;
  }

  .value {
    font-size: 22px;
    font-weight: bolder;
    color: #ed2f1d;
    font-style: italic;
    padding: 0 5px;
  }
}

.row-container {
  & > .el-col {
    margin-bottom: 20px;
  }
}

//数据概览
.sjgl-col {
  .sjgl-wrapper {
    text-align: left;
    padding: 15px 20px;
    background-color: #f2f7fb;
  }

  &.power-col {
    .sjgl-wrapper {
      padding: 10px;

      .sjgl-value {
        color: #c44444;
      }
    }
  }

  &:nth-child(4),
  &:nth-child(2),
  &:nth-child(3),
  &:nth-child(4) {
    margin-bottom: 10px;
  }

  .sjgl-title {
    color: #717171;
    line-height: 14px;
    font-weight: bold;
  }

  .sjgl-value {
    color: rgba(51, 51, 51, 1);
    font-size: 22px;
    line-height: 26px;
    font-weight: bolder;
    font-style: italic;
    margin-top: 14px;
    width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
</style>

<style lang="scss">
.home-normal-info {
  font-size: 12px;

  .el-descriptions-item__container {
    .el-descriptions-item__label {
      color: #666666;
    }

    .el-descriptions-item__content {
      color: #333333;
    }
  }
}
</style>
