<template>
  <el-dialog
    title="项目分析"
    :visible.sync="visibleProxy"
    width="88%"
    top="2vh"
    append-to-body
    custom-class="project-analysis-dialog"
    @close="handleDialogClosed"
  >
    <div class="project-analysis-dialog__body">
      <div class="project-analysis-header">
        <div class="project-analysis-header__main">
          <div class="project-analysis-header__title-group">
            <div class="project-analysis-header__eyebrow">结果总览</div>
            <div class="project-analysis-header__title">项目分析详情</div>
          </div>
          <div
            v-if='dialogData.sourceSummary.showCurrentModel && source === "riskModelPeople"'
            class="project-analysis-header__meta"
          >
            <span class="project-analysis-header__meta-label">当前命中模型</span>
            <span class="project-analysis-header__meta-value">
              {{ dialogData.sourceSummary.currentModelValue }}
            </span>
          </div>
        </div>
      </div>
      <div v-loading="detailLoading" class="project-analysis-workspace">
        <project-analysis-sidebar
          class="project-analysis-layout__sidebar"
          :sidebar-data="dialogData.sidebar"
        />
        <div class="project-analysis-layout__main">
          <el-alert
            v-if="detailError"
            :closable="false"
            class="project-analysis-layout__alert"
            type="error"
            show-icon
            :title="detailError"
          >
            <template slot="default">
              <el-button type="text" size="mini" @click="handleRetryDetail">重试</el-button>
            </template>
          </el-alert>
          <el-tabs v-model="activeTab" class="project-analysis-tabs" stretch @tab-click="handleTabChange">
            <el-tab-pane label="异常明细" name="abnormalDetail">
              <project-analysis-abnormal-tab
                :detail-data="dialogData.abnormalDetail"
                :person="person"
                :project-id="projectId"
                @evidence-confirm="$emit('evidence-confirm', $event)"
              />
            </el-tab-pane>
            <el-tab-pane label="资产分析" name="assetAnalysis">
              <project-analysis-placeholder-tab :tab-data="getTabData('assetAnalysis')" />
            </el-tab-pane>
            <el-tab-pane label="征信摘要" name="creditSummary">
              <project-analysis-placeholder-tab :tab-data="getTabData('creditSummary')" />
            </el-tab-pane>
            <el-tab-pane label="关系图谱" name="relationshipGraph">
              <project-analysis-fund-flow-tab
                v-if="activeTab === 'relationshipGraph'"
                ref="relationshipGraphTab"
                :project-id="projectId"
                :person="person"
                :model-summary="modelSummary"
                initial-graph-tab="relation"
                :graph-tabs="['relation']"
              />
            </el-tab-pane>
            <el-tab-pane label="资金流向" name="fundFlow">
              <project-analysis-fund-flow-tab
                v-if="activeTab === 'fundFlow'"
                ref="fundFlowTab"
                :project-id="projectId"
                :person="person"
                :model-summary="modelSummary"
              />
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import { getOverviewPersonAnalysisDetail } from "@/api/ccdi/projectOverview";
import ProjectAnalysisAbnormalTab from "./ProjectAnalysisAbnormalTab";
import ProjectAnalysisFundFlowTab from "./ProjectAnalysisFundFlowTab";
import ProjectAnalysisPlaceholderTab from "./ProjectAnalysisPlaceholderTab";
import ProjectAnalysisSidebar from "./ProjectAnalysisSidebar";
import { buildProjectAnalysisDialogData } from "./preliminaryCheck.mock";

export default {
  name: "ProjectAnalysisDialog",
  components: {
    ProjectAnalysisAbnormalTab,
    ProjectAnalysisFundFlowTab,
    ProjectAnalysisPlaceholderTab,
    ProjectAnalysisSidebar,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    projectId: {
      type: [String, Number],
      default: null,
    },
    person: {
      type: Object,
      default: () => null,
    },
    source: {
      type: String,
      default: "riskPeople",
    },
    modelSummary: {
      type: Object,
      default: () => ({
        modelCount: 0,
        riskTags: [],
      }),
    },
    projectName: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      activeTab: "abnormalDetail",
      detailLoading: false,
      detailError: "",
      detailData: null,
    };
  },
  computed: {
    dialogData() {
      const mockData = buildProjectAnalysisDialogData({
        person: this.person,
        source: this.source,
        projectName: this.projectName,
      });
      return {
        ...mockData,
        sidebar: {
          ...mockData.sidebar,
          basicInfo: (this.detailData && this.detailData.basicInfo) || mockData.sidebar.basicInfo,
          modelSummary: {
            ...mockData.sidebar.modelSummary,
            ...(this.modelSummary || {}),
          },
        },
        abnormalDetail: (this.detailData && this.detailData.abnormalDetail) || mockData.abnormalDetail,
      };
    },
    visibleProxy: {
      get() {
        return this.visible;
      },
      set(value) {
        this.$emit("update:visible", value);
      },
    },
  },
  watch: {
    visible(value) {
      if (value) {
        this.resetDialogState();
        this.fetchDetailData();
      }
    },
  },
  methods: {
    resetDialogState() {
      this.activeTab = "abnormalDetail";
      this.detailLoading = false;
      this.detailError = "";
      this.detailData = null;
    },
    resolveStaffIdCard() {
      return (this.modelSummary && this.modelSummary.staffIdCard)
        || (this.person && (this.person.idNo || this.person.staffIdCard))
        || "";
    },
    async fetchDetailData() {
      const staffIdCard = this.resolveStaffIdCard();
      if (!this.projectId || !staffIdCard) {
        return;
      }
      this.detailLoading = true;
      this.detailError = "";
      try {
        const response = await getOverviewPersonAnalysisDetail({
          projectId: this.projectId,
          staffIdCard,
        });
        this.detailData = (response && response.data) || null;
      } catch (error) {
        this.detailError = "项目分析详情加载失败，请稍后重试";
        this.detailData = null;
        console.error("加载项目分析详情失败", error);
      } finally {
        this.detailLoading = false;
      }
    },
    handleRetryDetail() {
      this.fetchDetailData();
    },
    getTabData(tabKey) {
      return (
        this.dialogData.tabs.find((item) => item.key === tabKey) || {
          label: "",
          description: "",
        }
      );
    },
    handleDialogClosed() {
      this.resetDialogState();
      this.$emit("close");
    },
    handleTabChange() {
      this.$nextTick(() => {
        const tabRef = this.activeTab === "relationshipGraph"
          ? this.$refs.relationshipGraphTab
          : this.$refs.fundFlowTab;
        if (tabRef && tabRef.ensureGraphReady) {
          tabRef.ensureGraphReady();
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.project-analysis-dialog__body {
  display: flex;
  flex-direction: column;
  min-height: calc(92vh - 64px);
  border: 1px solid #dde3ec;
  background: #ffffff;
  overflow: hidden;
}

.project-analysis-header {
  padding: 28px 40px 24px;
  border-bottom: 1px solid #dde3ec;
  background: #ffffff;
}

.project-analysis-header__main {
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
  gap: 24px;
}

.project-analysis-header__title-group {
  min-width: 0;
}

.project-analysis-header__eyebrow {
  color: #65758d;
  font-size: 15px;
  font-weight: 700;
  line-height: 1;
}

.project-analysis-header__title {
  margin-top: 18px;
  color: #101a2b;
  font-size: 28px;
  font-weight: 700;
  line-height: 1;
}

.project-analysis-header__meta {
  display: inline-flex;
  align-items: center;
  gap: 10px;
  min-height: 34px;
  padding: 0 12px;
  border: 1px solid #bfd0e2;
  border-radius: 2px;
  background: #eef4f9;
}

.project-analysis-header__meta-label {
  color: #637187;
  font-size: 13px;
  font-weight: 600;
}

.project-analysis-header__meta-value {
  color: #245b8f;
  font-size: 13px;
  font-weight: 600;
}

.project-analysis-workspace {
  display: flex;
  align-items: flex-start;
  gap: 36px;
  min-height: 640px;
  max-height: calc(92vh - 150px);
  padding: 20px 40px 28px;
  overflow: auto;
  background: #ffffff;
}

.project-analysis-layout {
  display: flex;
  gap: 20px;
  min-height: 640px;
}

.project-analysis-layout__sidebar {
  flex: 0 0 34%;
  max-width: 460px;
}

.project-analysis-layout__main {
  flex: 1;
  min-width: 0;
  border-left: 1px solid #dde3ec;
  padding-left: 36px;
}

.project-analysis-layout__alert {
  margin-bottom: 20px;
}

.project-analysis-tabs {
  margin-top: -2px;
}
</style>

<style lang="scss">
.project-analysis-dialog {
  margin-top: 2vh !important;
  border-radius: 0;
  background: #f5f6f8;
  overflow: hidden;

  .el-dialog__header {
    display: none;
  }

  .el-dialog__body {
    padding: 0;
    background: #f5f6f8;
  }
}

.project-analysis-tabs {
  .el-tabs__header {
    margin: 0;
  }

  .el-tabs__nav-wrap::after {
    height: 1px;
    background: #dde3ec;
  }

  .el-tabs__item {
    height: 52px;
    padding: 0 24px !important;
    color: #2a374a;
    font-size: 16px;
    font-weight: 500;
    line-height: 52px;
  }

  .el-tabs__item.is-active {
    color: #245b8f;
    font-weight: 700;
  }

  .el-tabs__active-bar {
    height: 4px;
    background: #245b8f;
  }

  .el-tabs__content {
    padding-top: 20px;
  }
}
</style>
