<template>
  <div class="preliminary-check-container">
    <div v-if="pageState === 'loading'" class="preliminary-check-state">
      <div class="state-card">
        <el-skeleton animated :rows="6" />
      </div>
    </div>

    <div v-else-if="pageState === 'empty'" class="preliminary-check-state">
      <div class="state-card">
        <el-empty description="暂无结果总览数据" />
      </div>
    </div>

    <div v-else class="preliminary-check-page">
      <section class="section-card risk-overview-card">
        <div class="section-header">
          <div>
            <div class="section-title">风险总览</div>
            <div class="section-subtitle">集中展示项目风险统计与命中人员总览</div>
          </div>
          <el-button
            size="mini"
            type="primary"
            plain
            icon="el-icon-download"
            :disabled="!projectId"
            @click="handleOverviewReportExport"
          >
            一键导出
          </el-button>
        </div>
        <overview-stats :summary="currentData.summary" />
        <risk-people-section
          :project-id="projectId"
          :section-data="currentData.riskPeople"
          :selected-model-codes="selectedModelCodes"
          @view-project-analysis="handleRiskPeopleProjectAnalysis"
        />
      </section>
      <risk-model-section
        :section-data="currentData.riskModels"
        @selection-change="handleRiskModelSelectionChange"
        @view-project-analysis="handleRiskModelProjectAnalysis"
      />
      <risk-detail-section
        :section-data="currentData.riskDetails"
        @evidence-confirm="$emit('evidence-confirm', $event)"
      />
    </div>
    <project-analysis-dialog
      :visible.sync="projectAnalysisDialogVisible"
      :project-id="projectId"
      :person="currentProjectAnalysisPerson"
      :source="projectAnalysisSource"
      :model-summary="projectAnalysisModelSummary"
      :project-name="projectInfo.projectName"
      @close="handleProjectAnalysisDialogClose"
      @evidence-confirm="$emit('evidence-confirm', $event)"
    />
  </div>
</template>

<script>
import {
  createOverviewLoadedData,
  mockOverviewData,
  mockOverviewStateData,
} from "./preliminaryCheck.mock";
import {
  getOverviewDashboard,
  getOverviewEmployeeCreditNegative,
  getOverviewRiskPeople,
  getOverviewRiskModelCards,
  getOverviewSuspiciousTransactions,
} from "@/api/ccdi/projectOverview";
import OverviewStats from "./OverviewStats";
import RiskPeopleSection from "./RiskPeopleSection";
import RiskModelSection from "./RiskModelSection";
import RiskDetailSection from "./RiskDetailSection";
import ProjectAnalysisDialog from "./ProjectAnalysisDialog";

export default {
  name: "PreliminaryCheck",
  components: {
    OverviewStats,
    RiskPeopleSection,
    RiskModelSection,
    RiskDetailSection,
    ProjectAnalysisDialog,
  },
  props: {
    projectId: {
      type: [String, Number],
      default: null,
    },
    projectInfo: {
      type: Object,
      default: () => ({
        projectName: "",
        updateTime: "",
        projectStatus: "0",
      }),
    },
  },
  data() {
    return {
      pageState: "loading",
      selectedModelCodes: [],
      mockData: mockOverviewData,
      stateDataMap: mockOverviewStateData,
      realData: mockOverviewData,
      projectAnalysisDialogVisible: false,
      currentProjectAnalysisPerson: null,
      projectAnalysisSource: "riskPeople",
      projectAnalysisModelSummary: {
        modelCount: 0,
        currentModel: "-",
        riskTags: [],
      },
    };
  },
  computed: {
    currentData() {
      if (this.pageState === "loaded") {
        return this.realData;
      }
      return this.stateDataMap[this.pageState] || this.realData;
    },
  },
  watch: {
    projectId(newVal) {
      if (newVal) {
        this.loadOverviewData();
        return;
      }
      this.realData = this.stateDataMap.empty;
      this.pageState = "empty";
      this.selectedModelCodes = [];
      this.resetProjectAnalysisDialog();
    },
  },
  created() {
    if (this.projectId) {
      this.loadOverviewData();
      return;
    }
    this.realData = this.stateDataMap.empty;
    this.pageState = "empty";
    this.resetProjectAnalysisDialog();
  },
  methods: {
    handleRiskModelSelectionChange(modelCodes) {
      this.selectedModelCodes = Array.isArray(modelCodes) ? [...modelCodes] : [];
    },
    handleRiskPeopleProjectAnalysis(row) {
      this.openProjectAnalysisDialog("riskPeople", row);
    },
    handleRiskModelProjectAnalysis(row) {
      this.openProjectAnalysisDialog("riskModelPeople", row);
    },
    openProjectAnalysisDialog(source, person) {
      this.projectAnalysisSource = source || "riskPeople";
      this.currentProjectAnalysisPerson = person || null;
      this.projectAnalysisModelSummary = this.buildProjectAnalysisModelSummary(
        this.projectAnalysisSource,
        this.currentProjectAnalysisPerson
      );
      this.projectAnalysisDialogVisible = true;
    },
    handleProjectAnalysisDialogClose() {
      this.projectAnalysisDialogVisible = false;
      this.resetProjectAnalysisDialog();
    },
    resetProjectAnalysisDialog() {
      this.projectAnalysisDialogVisible = false;
      this.currentProjectAnalysisPerson = null;
      this.projectAnalysisSource = "riskPeople";
      this.projectAnalysisModelSummary = {
        modelCount: 0,
        currentModel: "-",
        riskTags: [],
      };
    },
    buildProjectAnalysisModelSummary(source, person) {
      const safePerson = person || {};
      const riskTags = Array.isArray(safePerson.riskPointTagList)
        ? safePerson.riskPointTagList
        : Array.isArray(safePerson.hitTagList)
          ? safePerson.hitTagList
          : [];

      return {
        staffIdCard: safePerson.idNo || safePerson.staffIdCard || "",
        modelCount: safePerson.modelCount || (Array.isArray(safePerson.modelNames) ? safePerson.modelNames.length : 0),
        currentModel: source === "riskModelPeople"
          ? (Array.isArray(safePerson.modelNames) && safePerson.modelNames.length
            ? safePerson.modelNames.join("、")
            : safePerson.modelName || "-")
          : ((riskTags[0] && riskTags[0].modelName) || "-"),
        riskTags,
      };
    },
    handleOverviewReportExport() {
      if (!this.projectId) {
        return;
      }
      this.download(
        "ccdi/project/overview/report/export",
        {
          projectId: this.projectId,
        },
        `初核结果报告_${this.projectId}_${new Date().getTime()}.pdf`
      );
    },
    async loadOverviewData() {
      if (!this.projectId) {
        this.realData = this.stateDataMap.empty;
        this.pageState = "empty";
        this.selectedModelCodes = [];
        this.resetProjectAnalysisDialog();
        return;
      }

      this.pageState = "loading";
      this.selectedModelCodes = [];
      this.resetProjectAnalysisDialog();
      try {
        const [dashboardRes, riskPeopleRes, riskModelCardsRes, suspiciousRes, creditNegativeRes] = await Promise.all([
          getOverviewDashboard(this.projectId),
          getOverviewRiskPeople({
            projectId: this.projectId,
            pageNum: 1,
            pageSize: 5,
          }),
          getOverviewRiskModelCards(this.projectId),
          getOverviewSuspiciousTransactions({
            projectId: this.projectId,
            suspiciousType: "ALL",
            pageNum: 1,
            pageSize: 5,
          }),
          getOverviewEmployeeCreditNegative({
            projectId: this.projectId,
            pageNum: 1,
            pageSize: 5,
          }),
        ]);
        const dashboardData = (dashboardRes && dashboardRes.data) || {};
        const riskPeopleData = (riskPeopleRes && riskPeopleRes.data) || {};
        const riskModelCardsData = (riskModelCardsRes && riskModelCardsRes.data) || {};
        const suspiciousData = (suspiciousRes && suspiciousRes.data) || {};
        const creditNegativeData = (creditNegativeRes && creditNegativeRes.data) || {};

        this.realData = createOverviewLoadedData({
          projectId: this.projectId,
          dashboardData,
          riskPeopleData,
          riskModelCardsData,
          suspiciousData,
          creditNegativeData,
        });

        const hasOverviewData = Boolean(
          (Array.isArray(dashboardData.stats) && dashboardData.stats.length) ||
          (Array.isArray(riskPeopleData.rows) && riskPeopleData.rows.length) ||
          (Array.isArray(riskModelCardsData.cardList) && riskModelCardsData.cardList.length)
        );

        this.pageState = hasOverviewData ? "loaded" : "empty";
      } catch (error) {
        this.realData = this.stateDataMap.empty;
        this.pageState = "empty";
        this.selectedModelCodes = [];
        this.resetProjectAnalysisDialog();
        console.error("加载结果总览失败", error);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.preliminary-check-container {
  min-height: 400px;
  padding: 0 0 24px;
}

.preliminary-check-state {
  min-height: 400px;
}

.state-card {
  padding: 32px 24px;
  border-radius: 14px;
  background: #fff;
  border: 1px solid var(--ccdi-border);
  box-shadow: var(--ccdi-shadow);
}

.preliminary-check-page {
  min-height: 400px;
}

.section-card {
  padding: 20px;
  border-radius: 14px;
  background: #fff;
  border: 1px solid var(--ccdi-border);
  box-shadow: var(--ccdi-shadow);
}

.risk-overview-card {
  margin-bottom: 16px;
  padding: 24px 20px 20px;
}

.section-header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 16px;
  margin-bottom: 18px;
  padding-left: 12px;
  border-left: 4px solid var(--ccdi-primary);
}

.section-title {
  font-size: 20px;
  line-height: 28px;
  font-weight: 700;
  color: var(--ccdi-text-primary);
}

.section-subtitle {
  margin-top: 6px;
  font-size: 12px;
  color: var(--ccdi-text-muted);
}
</style>
