<template>
  <section class="family-asset-liability-section">
    <div class="section-card">
      <div class="block-header">
        <div>
          <div class="block-title">{{ title }}</div>
          <div class="block-subtitle">{{ subtitle }}</div>
        </div>
      </div>

      <el-table
        ref="familyTable"
        v-loading="loading"
        :data="rows"
        class="family-table"
        row-key="staffIdCard"
        :expand-row-keys="expandedRowKeys"
      >
        <template slot="empty">
          <el-empty :image-size="80" description="暂无员工家庭资产负债核查数据" />
        </template>
        <el-table-column type="expand" width="1" class-name="family-expand-column">
          <template slot-scope="scope">
            <div class="family-detail-wrapper">
              <div class="family-detail-toolbar">
                <span class="family-detail-title">资产详情</span>
                <el-button
                  class="evidence-corner-btn"
                  size="mini"
                  plain
                  :disabled="Boolean(detailLoadingMap[scope.row.staffIdCard]) || !buildAssetEvidenceFingerprint(scope.row)"
                  @click="handleAddEvidence(scope.row)"
                >
                  加入证据库
                </el-button>
              </div>
              <family-asset-liability-detail
                :detail="detailCache[scope.row.staffIdCard]"
                :loading="Boolean(detailLoadingMap[scope.row.staffIdCard])"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="staffName" label="姓名" min-width="100" />
        <el-table-column prop="staffIdCard" label="身份证号" min-width="180" />
        <el-table-column prop="deptName" label="所属部门" min-width="140" />
        <el-table-column label="家庭总年收入" min-width="140">
          <template slot-scope="scope">
            <span>{{ formatWanAmount(scope.row.totalIncome) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="家庭总负债" min-width="140">
          <template slot-scope="scope">
            <span>{{ formatAmount(scope.row.totalDebt) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="家庭总资产" min-width="140">
          <template slot-scope="scope">
            <span>{{ formatWanAmount(scope.row.totalAsset) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="风险情况" min-width="120">
          <template slot-scope="scope">
            <el-tag size="mini" effect="plain" :type="resolveRiskTagType(scope.row.riskLevelCode)">
              {{ scope.row.riskLevelName || "-" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" align="right">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="handleToggleDetail(scope.row)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </section>
</template>

<script>
import { getFamilyAssetLiabilityDetail } from "@/api/ccdi/projectSpecialCheck";
import { buildAssetEvidenceFingerprint, buildAssetEvidenceSnapshot } from "@/utils/ccdiEvidence";
import FamilyAssetLiabilityDetail from "./FamilyAssetLiabilityDetail";

export default {
  name: "FamilyAssetLiabilitySection",
  components: {
    FamilyAssetLiabilityDetail,
  },
  props: {
    rows: {
      type: Array,
      default: () => [],
    },
    loading: {
      type: Boolean,
      default: false,
    },
    projectId: {
      type: [String, Number],
      default: null,
    },
    title: {
      type: String,
      default: "员工家庭资产负债专项核查",
    },
    subtitle: {
      type: String,
      default: "展示项目内员工家庭收入、资产、负债与风险情况",
    },
  },
  data() {
    return {
      expandedStaffIdCard: "",
      detailCache: {},
      detailLoadingMap: {},
    };
  },
  computed: {
    expandedRowKeys() {
      return this.expandedStaffIdCard ? [this.expandedStaffIdCard] : [];
    },
  },
  watch: {
    projectId() {
      this.resetDetailState();
    },
  },
  methods: {
    buildAssetEvidenceFingerprint,
    resolveRiskTagType(riskLevelCode) {
      const riskTagTypeMap = {
        NORMAL: "success",
        RISK: "warning",
        HIGH: "danger",
        MISSING_INFO: "info",
      };
      return riskTagTypeMap[riskLevelCode] || "info";
    },
    formatAmount(value) {
      const amount = Number(value || 0);
      return `${amount.toLocaleString("zh-CN", {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      })} 元`;
    },
    formatWanAmount(value) {
      const amount = Number(value || 0);
      if (!Number.isFinite(amount)) {
        return "-";
      }
      return `${(amount / 10000).toLocaleString("zh-CN", {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      })} 万元`;
    },
    async handleToggleDetail(row) {
      if (!row || !row.staffIdCard) {
        return;
      }

      if (this.expandedStaffIdCard === row.staffIdCard) {
        this.expandedStaffIdCard = "";
        return;
      }

      this.expandedStaffIdCard = row.staffIdCard;
      if (!this.detailCache[row.staffIdCard]) {
        await this.loadFamilyDetail(row);
      }
    },
    async loadFamilyDetail(row) {
      const staffIdCard = row.staffIdCard;
      this.$set(this.detailLoadingMap, staffIdCard, true);
      try {
        const response = await getFamilyAssetLiabilityDetail(this.projectId, staffIdCard);
        const detail = (response && response.data) || {};
        this.$set(this.detailCache, staffIdCard, detail);
      } catch (error) {
        this.$set(this.detailCache, staffIdCard, null);
        console.error("加载员工家庭资产负债详情失败", error);
      } finally {
        this.$set(this.detailLoadingMap, staffIdCard, false);
      }
    },
    resetDetailState() {
      this.expandedStaffIdCard = "";
      this.detailCache = {};
      this.detailLoadingMap = {};
    },
    handleAddEvidence(row) {
      if (!row || !row.staffIdCard) {
        return;
      }
      const sourceRecordId = buildAssetEvidenceFingerprint(row);
      if (!sourceRecordId) {
        this.$message.warning("缺少人员身份证或资产字段，暂不能加入证据库");
        return;
      }
      const detail = this.detailCache[row.staffIdCard] || {};
      const summary = detail.summary || {};
      const evidenceSummary = `${row.staffName}家庭资产负债核查：家庭总年收入${this.formatWanAmount(row.totalIncome)}，家庭总负债${this.formatAmount(row.totalDebt)}，家庭总资产${this.formatWanAmount(row.totalAsset)}，风险情况${row.riskLevelName || "-" }。`;
      this.$emit("evidence-confirm", {
        evidenceType: "ASSET",
        relatedPersonName: row.staffName || "关联人员",
        relatedPersonId: row.staffIdCard || "",
        evidenceTitle: `${row.staffName || "关联人员"} / 家庭资产负债核查`,
        evidenceSummary,
        sourceType: "ASSET_DETAIL",
        sourceRecordId,
        sourcePage: "资产详情",
        snapshotJson: JSON.stringify(buildAssetEvidenceSnapshot(row, detail, summary)),
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.family-asset-liability-section {
  margin-bottom: 16px;
}

.section-card {
  padding: 20px;
  border-radius: 0;
  background: #fff;
  box-shadow: 0 8px 24px rgba(15, 23, 42, 0.06);
}

.block-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 14px;
}

.block-title {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
}

.block-subtitle {
  margin-top: 4px;
  font-size: 12px;
  color: #94a3b8;
}

.family-table {
  border-radius: 12px;
  overflow: hidden;
}

.family-detail-wrapper {
  padding: 12px 0;
}

.family-detail-toolbar {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 10px;
  margin-bottom: 10px;
}

.family-detail-title {
  margin-right: auto;
  color: #64748b;
  font-size: 13px;
  font-weight: 600;
}

.evidence-corner-btn {
  padding: 4px 9px;
  font-size: 12px;
  color: #5b7fb8;
  border-color: #d6e4f7;
  background: #f8fbff;

  &:hover {
    color: #2474e8;
    border-color: #9fc3ff;
    background: #edf5ff;
  }
}

:deep(.family-table th) {
  background: #f8fafc;
  color: #64748b;
}

::v-deep .family-expand-column .cell,
::v-deep .family-expand-column .el-table__expand-icon {
  display: none;
}
</style>
