<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__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>
          <button class="project-analysis-header__close" type="button" aria-label="关闭" @click="closeDialog">
            <i class="el-icon-close" />
          </button>
        </div>
      </div>
      <div
        v-loading="detailLoading"
        class="project-analysis-workspace"
        :class="{ 'project-analysis-workspace--sidebar-collapsed': sidebarCollapsed }"
      >
        <div class="project-analysis-layout__sidebar">
          <project-analysis-sidebar
            :sidebar-data="dialogData.sidebar"
            collapsible
            :collapsed="sidebarCollapsed"
            @toggle="toggleSidebar"
          />
        </div>
        <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"
                :can-operate="canOperate"
                @evidence-confirm="$emit('evidence-confirm', $event)"
                @risk-excluded="handleRiskExcluded"
              />
            </el-tab-pane>
            <el-tab-pane label="资产分析" name="assetAnalysis">
              <div class="project-analysis-tab-panel">
                <el-alert
                  v-if="assetError"
                  :closable="false"
                  class="project-analysis-layout__alert"
                  type="error"
                  show-icon
                  :title="assetError"
                >
                  <template slot="default">
                    <el-button type="text" size="mini" @click="fetchAssetDetailData">重试</el-button>
                  </template>
                </el-alert>
                <family-asset-liability-detail
                  v-else
                  :detail="assetDetail"
                  :loading="assetLoading"
                />
              </div>
            </el-tab-pane>
            <el-tab-pane label="征信详情" name="creditDetail">
              <div class="project-analysis-tab-panel">
                <el-alert
                  v-if="creditError"
                  :closable="false"
                  class="project-analysis-layout__alert"
                  type="error"
                  show-icon
                  :title="creditError"
                >
                  <template slot="default">
                    <el-button type="text" size="mini" @click="fetchCreditDetailData">重试</el-button>
                  </template>
                </el-alert>
                <credit-info-detail
                  v-else
                  :detail="creditDetail"
                  :loading="creditLoading"
                />
              </div>
            </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"
                :can-operate="canOperate"
                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"
                :can-operate="canOperate"
              />
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import { getCreditInfoDetail } from "@/api/ccdiCreditInfo";
import { getFamilyAssetLiabilityDetail } from "@/api/ccdi/projectSpecialCheck";
import { getOverviewPersonAnalysisDetail } from "@/api/ccdi/projectOverview";
import CreditInfoDetail from "@/views/ccdiCreditInfo/components/CreditInfoDetail.vue";
import { createEmptyCreditDetail, normalizeCreditDetail } from "@/views/ccdiCreditInfo/components/creditDetailViewModel.js";
import FamilyAssetLiabilityDetail from "./FamilyAssetLiabilityDetail";
import ProjectAnalysisAbnormalTab from "./ProjectAnalysisAbnormalTab";
import ProjectAnalysisFundFlowTab from "./ProjectAnalysisFundFlowTab";
import ProjectAnalysisSidebar from "./ProjectAnalysisSidebar";
import { buildProjectAnalysisDialogData } from "./preliminaryCheck.mock";

export default {
  name: "ProjectAnalysisDialog",
  components: {
    CreditInfoDetail,
    FamilyAssetLiabilityDetail,
    ProjectAnalysisAbnormalTab,
    ProjectAnalysisFundFlowTab,
    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: "",
    },
    canOperate: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      activeTab: "abnormalDetail",
      sidebarCollapsed: false,
      detailLoading: false,
      detailError: "",
      detailData: null,
      assetLoading: false,
      assetError: "",
      assetDetail: null,
      assetLoaded: false,
      creditLoading: false,
      creditError: "",
      creditDetail: createEmptyCreditDetail(),
      creditLoaded: false,
    };
  },
  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) || { groups: [] },
      };
    },
    visibleProxy: {
      get() {
        return this.visible;
      },
      set(value) {
        this.$emit("update:visible", value);
      },
    },
  },
  watch: {
    visible(value) {
      if (value) {
        this.resetDialogState();
        this.fetchDetailData();
      }
    },
    projectId() {
      this.resetAssetDetailState();
      this.resetCreditDetailState();
    },
    person() {
      this.resetAssetDetailState();
      this.resetCreditDetailState();
    },
  },
  methods: {
    resetDialogState() {
      this.activeTab = "abnormalDetail";
      this.sidebarCollapsed = false;
      this.detailLoading = false;
      this.detailError = "";
      this.detailData = null;
      this.resetAssetDetailState();
      this.resetCreditDetailState();
    },
    resetAssetDetailState() {
      this.assetLoading = false;
      this.assetError = "";
      this.assetDetail = null;
      this.assetLoaded = false;
    },
    resetCreditDetailState() {
      this.creditLoading = false;
      this.creditError = "";
      this.creditDetail = createEmptyCreditDetail();
      this.creditLoaded = false;
    },
    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();
    },
    async handleRiskExcluded(payload) {
      await this.fetchDetailData();
      this.$emit("risk-excluded", payload);
    },
    async fetchAssetDetailData() {
      if (this.assetLoaded || this.assetLoading) {
        return;
      }
      const staffIdCard = this.resolveStaffIdCard();
      if (!this.projectId || !staffIdCard) {
        this.assetError = "缺少项目或人员身份证号，无法加载资产详情";
        return;
      }
      this.assetLoading = true;
      this.assetError = "";
      try {
        const response = await getFamilyAssetLiabilityDetail(this.projectId, staffIdCard);
        this.assetDetail = (response && response.data) || {};
        this.assetLoaded = true;
      } catch (error) {
        this.assetDetail = null;
        this.assetLoaded = false;
        this.assetError = "资产详情加载失败，请稍后重试";
        console.error("加载资产详情失败", error);
      } finally {
        this.assetLoading = false;
      }
    },
    async fetchCreditDetailData() {
      if (this.creditLoaded || this.creditLoading) {
        return;
      }
      const staffIdCard = this.resolveStaffIdCard();
      if (!staffIdCard) {
        this.creditError = "缺少人员身份证号，无法加载征信详情";
        return;
      }
      this.creditLoading = true;
      this.creditError = "";
      try {
        const response = await getCreditInfoDetail(staffIdCard);
        const data = (response && response.data) || {};
        this.creditDetail = normalizeCreditDetail(data);
        this.creditLoaded = true;
      } catch (error) {
        this.creditDetail = createEmptyCreditDetail();
        this.creditLoaded = false;
        this.creditError = "征信详情加载失败，请稍后重试";
        console.error("加载征信详情失败", error);
      } finally {
        this.creditLoading = false;
      }
    },
    getTabData(tabKey) {
      return (
        this.dialogData.tabs.find((item) => item.key === tabKey) || {
          label: "",
          description: "",
        }
      );
    },
    handleDialogClosed() {
      this.resetDialogState();
      this.$emit("close");
    },
    closeDialog() {
      this.visibleProxy = false;
    },
    toggleSidebar() {
      this.sidebarCollapsed = !this.sidebarCollapsed;
      this.$nextTick(() => {
        const tabRef = this.activeTab === "relationshipGraph"
          ? this.$refs.relationshipGraphTab
          : this.$refs.fundFlowTab;
        if (tabRef && tabRef.ensureGraphReady) {
          tabRef.ensureGraphReady();
        }
      });
    },
    handleTabChange() {
      if (this.activeTab === "assetAnalysis") {
        this.fetchAssetDetailData();
      }
      if (this.activeTab === "creditDetail") {
        this.fetchCreditDetailData();
      }
      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);
  background: #f5f7fb;
  overflow: hidden;
}

.project-analysis-header {
  padding: 14px 24px;
  border-bottom: 1px solid #dbe4ef;
  background: #ffffff;
}

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

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

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

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

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

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

.project-analysis-header__close {
  flex: 0 0 auto;
  width: 34px;
  height: 34px;
  border: none;
  border-radius: 6px;
  background: transparent;
  color: #8d99aa;
  font-size: 18px;
  line-height: 34px;
  text-align: center;
  cursor: pointer;
}

.project-analysis-header__close:hover {
  background: #f2f5f8;
  color: #245b8f;
}

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

.project-analysis-workspace--sidebar-collapsed {
  gap: 0;
}

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

.project-analysis-layout__sidebar {
  position: sticky;
  top: 0;
  flex: 0 0 286px;
  max-width: 286px;
  background: #ffffff;
}

.project-analysis-workspace--sidebar-collapsed .project-analysis-layout__sidebar {
  flex-basis: 46px;
  max-width: 46px;
}

.project-analysis-layout__main {
  flex: 1;
  min-width: 0;
  margin-left: 24px;
  border: 1px solid #dbe4ef;
  border-radius: 6px;
  background: #ffffff;
  overflow: hidden;
}

.project-analysis-workspace--sidebar-collapsed .project-analysis-layout__main {
  margin-left: 18px;
}

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

.project-analysis-tabs {
  margin-top: 0;
}

@media (max-width: 1100px) {
  .project-analysis-workspace {
    flex-direction: column;
  }

  .project-analysis-layout__sidebar {
    position: static;
    flex: none;
    max-width: none;
    width: 100%;
  }

  .project-analysis-layout__main {
    width: 100%;
    margin-top: 16px;
    margin-left: 0;
  }
}
</style>

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

  .el-dialog__header {
    display: none;
  }

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

.project-analysis-tabs {
  .el-tabs__header {
    margin: 0;
    padding: 0 20px;
    border-bottom: 1px solid #dbe4ef;
    background: #ffffff;
  }

  .el-tabs__nav-wrap::after {
    display: none;
  }

  .el-tabs__item {
    height: 46px;
    padding: 0 22px !important;
    color: #2a374a;
    font-size: 14px;
    font-weight: 500;
    line-height: 46px;
  }

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

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

  .el-tabs__content {
    padding: 20px;
    background: #ffffff;
  }
}
</style>
