<template>
  <div
    v-loading="loading"
    class="health-dashboard-page"
    element-loading-background="rgba(5, 14, 35, 0.75)"
  >
    <HealthHeader
      v-model="companyCode"
      :datatime.sync="datatime"
      @change="handleQueryChange"
    />

    <div class="health-page__body">
      <main class="dashboard-main">
        <div class="dashboard-top-row">
          <HealthScorePanel
            :distribution="scoreDistribution"
            :summary="scoreSummary"
            :total-score="totalScore"
          />

          <HealthSubsystemPanel :chart-data="subsystemData" />

          <HealthRankingPanel
            :healthy-list="healthyRankList"
            :risk-list="riskRankList"
          />
        </div>

        <section class="health-unit-grid">
          <HealthUnitCard
            v-for="unit in unitCards"
            :key="unit.engineId || unit.name"
            :unit="unit"
          />
        </section>
      </main>
    </div>
  </div>
</template>

<script>
import HealthHeader from "./components/health/HealthHeader.vue";
import HealthScorePanel from "./components/health/HealthScorePanel.vue";
import HealthSubsystemPanel from "./components/health/HealthSubsystemPanel.vue";
import HealthRankingPanel from "./components/health/HealthRankingPanel.vue";
import HealthUnitCard from "./components/health/HealthUnitCard.vue";
import { getHealthOverview } from "@/api/healthAnalyse";
import {
  getEmptyDashboard,
  mapHealthOverviewToDashboard,
} from "./utils/healthDashboardMapper";

export default {
  name: "HealthDashboard",
  components: {
    HealthHeader,
    HealthScorePanel,
    HealthSubsystemPanel,
    HealthRankingPanel,
    HealthUnitCard,
  },
  data() {
    const empty = getEmptyDashboard();
    return {
      companyCode: "",
      selectedField: null,
      datatime: "",
      loading: false,
      totalScore: empty.totalScore,
      scoreDistribution: empty.scoreDistribution,
      scoreSummary: empty.scoreSummary,
      subsystemData: empty.subsystemData,
      healthyRankList: empty.healthyRankList,
      riskRankList: empty.riskRankList,
      unitCards: empty.unitCards,
    };
  },
  mounted() {
    this.$nextTick(() => {
      window.dispatchEvent(new Event("resize"));
    });
  },
  methods: {
    handleQueryChange(data) {
      const fieldCode = data?.fieldCode || data?.codeNumber;
      if (!fieldCode) return;
      this.selectedField = data;
      this.companyCode = fieldCode;
      if (data.datatime !== undefined) {
        this.datatime = data.datatime;
      }
      this.fetchDashboard(fieldCode);
    },
    async fetchDashboard(fieldCode) {
      if (!fieldCode) return;
      this.loading = true;
      try {
        const params = { fieldCode };
        if (this.datatime) {
          params.datatime = this.datatime;
        }
        const res = await getHealthOverview(params);
        const mapped = mapHealthOverviewToDashboard(res.data || {});
        this.applyDashboard(mapped);
      } catch (error) {
        console.error("加载健康概览失败:", error);
        const empty = getEmptyDashboard();
        this.applyDashboard(empty);
      } finally {
        this.loading = false;
        this.$nextTick(() => {
          window.dispatchEvent(new Event("resize"));
        });
      }
    },
    applyDashboard(mapped) {
      this.totalScore = mapped.totalScore;
      this.scoreDistribution = mapped.scoreDistribution;
      this.scoreSummary = mapped.scoreSummary;
      this.subsystemData = mapped.subsystemData;
      this.healthyRankList = mapped.healthyRankList;
      this.riskRankList = mapped.riskRankList;
      this.unitCards = mapped.unitCards;
    },
  },
};
</script>

<style lang="scss">
@import "./components/health/health-dashboard.scss";

.health-dashboard-page {
  .dashboard-top-row {
    display: grid;
    grid-template-columns: 1fr;
    gap: 24px;
    min-width: 0;
  }

  @media (min-width: 900px) {
    .dashboard-top-row {
      grid-template-columns: repeat(2, minmax(0, 1fr));
    }

    .dashboard-top-row > :last-child {
      grid-column: span 2;
    }
  }

  @media (min-width: 1280px) {
    .dashboard-top-row {
      grid-template-columns: repeat(3, minmax(0, 1fr));
    }

    .dashboard-top-row > :last-child {
      grid-column: auto;
    }
  }

  .health-unit-grid {
    display: grid;
    grid-template-columns: repeat(1, minmax(0, 1fr));
    gap: 16px;
    min-width: 0;
  }

  @media (min-width: 768px) {
    .health-unit-grid {
      grid-template-columns: repeat(2, minmax(0, 1fr));
    }
  }

  @media (min-width: 1024px) {
    .health-unit-grid {
      grid-template-columns: repeat(3, minmax(0, 1fr));
    }
  }

  @media (min-width: 1280px) {
    .health-unit-grid {
      grid-template-columns: repeat(5, minmax(0, 1fr));
    }
  }
}
</style>
