<template>
  <div class="family-asset-liability-detail" v-loading="loading">
    <div class="detail-stack">
      <section class="detail-block">
        <div class="block-header section-header">
          <div class="block-title">总收入</div>
          <div class="section-summary-value">{{ formatWanAmount(totalIncome) }}</div>
        </div>
        <div class="detail-metric-list">
          <div class="detail-metric-item">
            <span class="metric-label">本人收入</span>
            <span class="metric-value">{{ formatWanAmount(incomeDetail.selfIncome) }}</span>
          </div>
          <div class="detail-metric-item">
            <span class="metric-label">配偶收入</span>
            <span class="metric-value">{{ formatWanAmount(incomeDetail.spouseIncome) }}</span>
          </div>
        </div>
      </section>

      <section class="detail-block">
        <div class="block-header section-header">
          <div class="block-title">总负债</div>
          <div class="section-summary-value">{{ formatAmount(totalDebt) }}</div>
        </div>
        <div v-if="debtGroups.length" class="summary-group-list">
          <div v-for="group in debtGroups" :key="group.key" class="summary-group-item">
            <div class="summary-group-main">
              <span class="summary-group-name">{{ group.label }}</span>
              <span class="summary-group-amount">{{ formatAmount(group.amount) }}</span>
            </div>
            <div class="summary-group-meta">
              <span class="summary-group-share-label">占比</span>
              <span class="summary-group-share">{{ formatPercent(group.amount, totalDebt) }}</span>
            </div>
          </div>
        </div>
        <div v-else class="empty-hint">暂无负债来源项</div>
      </section>

      <section class="detail-block">
        <div class="block-header section-header">
          <div class="block-title">总资产</div>
          <div class="section-summary-value">{{ formatWanAmount(totalAsset) }}</div>
        </div>
        <div v-if="assetGroups.length" class="summary-group-list">
          <div v-for="group in assetGroups" :key="group.key" class="summary-group-item">
            <div class="summary-group-main">
              <span class="summary-group-name">{{ group.label }}</span>
              <span class="summary-group-amount">{{ formatWanAmount(group.amount) }}</span>
            </div>
            <div class="summary-group-meta">
              <span class="summary-group-share-label">占比</span>
              <span class="summary-group-share">{{ formatPercent(group.amount, totalAsset) }}</span>
            </div>
          </div>
        </div>
        <div v-else class="empty-hint">暂无资产来源项</div>
      </section>

      <section class="detail-block">
        <div class="block-header section-header">
          <div class="block-title">关键指标</div>
          <div class="section-summary-value">3 项</div>
        </div>
        <div class="metric-grid">
          <div class="metric-card">
            <span class="metric-card-label">资产负债率</span>
            <span class="metric-card-value">{{ assetDebtRatio }}</span>
          </div>
          <div class="metric-card">
            <span class="metric-card-label">资产收入倍数</span>
            <span class="metric-card-value">{{ assetIncomeRatio }}</span>
          </div>
          <div class="metric-card">
            <span class="metric-card-label">负债/收入比</span>
            <span class="metric-card-value">{{ debtIncomeRatio }}</span>
          </div>
        </div>
      </section>

      <section class="detail-block">
        <div class="block-header section-header">
          <div class="block-title">详查结果</div>
          <div class="section-summary-value">{{ riskResult.name }}</div>
        </div>
        <div class="result-card" :class="[`result-card--${riskResult.type}`]">
          <div class="result-card-label">结论</div>
          <div class="result-card-value">
            <div v-for="line in riskResult.lines" :key="line" class="result-card-line">{{ line }}</div>
          </div>
        </div>
      </section>
    </div>
  </div>
</template>

<script>
import { parseTime } from "@/utils/ruoyi";

export default {
  name: "FamilyAssetLiabilityDetail",
  props: {
    detail: {
      type: Object,
      default: () => ({}),
    },
    loading: {
      type: Boolean,
      default: false,
    },
  },
  computed: {
    incomeDetail() {
      return this.detail && this.detail.incomeDetail
        ? this.detail.incomeDetail
        : {
            selfIncome: 0,
            spouseIncome: 0,
            employmentYears: null,
            totalIncome: 0,
            explainableIncome: 0,
          };
    },
    summary() {
      return this.detail && this.detail.summary
        ? this.detail.summary
        : {
            totalIncome: 0,
            totalAsset: 0,
            totalDebt: 0,
            riskLevelCode: "MISSING_INFO",
            riskLevelName: "缺少信息",
          };
    },
    assetDetail() {
      return this.detail && this.detail.assetDetail
        ? this.detail.assetDetail
        : {
            missingSelfAssetInfo: false,
            selfTotalAsset: 0,
            spouseTotalAsset: 0,
            totalAsset: 0,
            items: [],
          };
    },
    debtDetail() {
      return this.detail && this.detail.debtDetail
        ? this.detail.debtDetail
        : {
            missingSelfDebtInfo: false,
            selfTotalDebt: 0,
            spouseTotalDebt: 0,
            totalDebt: 0,
            items: [],
          };
    },
    totalIncome() {
      return this.resolveAmount(this.summary.totalIncome, this.incomeDetail.totalIncome);
    },
    totalAsset() {
      return this.resolveAmount(this.summary.totalAsset, this.assetDetail.totalAsset);
    },
    totalDebt() {
      return this.resolveAmount(this.summary.totalDebt, this.debtDetail.totalDebt);
    },
    employmentYears() {
      const target = this.summary.employmentYears !== undefined && this.summary.employmentYears !== null
        ? this.summary.employmentYears
        : this.incomeDetail.employmentYears;
      return target === undefined || target === null || target === "" ? null : Number(target);
    },
    explainableIncome() {
      return this.resolveAmount(this.summary.explainableIncome, this.incomeDetail.explainableIncome);
    },
    assetItems() {
      return Array.isArray(this.assetDetail.items) ? this.assetDetail.items : [];
    },
    debtItems() {
      return Array.isArray(this.debtDetail.items) ? this.debtDetail.items : [];
    },
    assetGroups() {
      return this.buildAmountGroups(this.assetItems, "currentValue", this.resolveAssetGroupLabel, this.totalAsset);
    },
    debtGroups() {
      return this.buildAmountGroups(this.debtItems, "principalBalance", this.resolveDebtGroupLabel, this.totalDebt);
    },
    // 净资产 = 总资产 - 总负债
    netAsset() {
      return this.totalAsset - this.totalDebt;
    },
    // 资产负债率 = totalDebt / totalAsset
    assetDebtRatio() {
      return this.formatMetricValue(this.totalDebt / this.totalAsset, {
        denominator: this.totalAsset,
        suffix: "%",
        isPercent: true,
      });
    },
    // 资产收入倍数 = totalAsset / explainableIncome
    assetIncomeRatio() {
      const ratio = this.resolveRatio(this.summary.assetIncomeRatio, this.totalAsset, this.explainableIncome);
      return this.formatRatio(ratio);
    },
    // 负债/收入比 = totalDebt / totalIncome
    debtIncomeRatio() {
      return this.formatMetricValue(this.totalDebt / this.totalIncome, {
        denominator: this.totalIncome,
        suffix: "倍",
      });
    },
    riskResult() {
      const riskResultMap = {
        NORMAL: {
          name: this.summary.riskLevelName || "正常",
          lines: this.buildResultLines(),
          type: "success",
        },
        RISK: {
          name: this.summary.riskLevelName || "关注",
          lines: this.buildResultLines(),
          type: "warning",
        },
        HIGH: {
          name: this.summary.riskLevelName || "高关注",
          lines: this.buildResultLines(),
          type: "danger",
        },
        MISSING_INFO: {
          name: this.summary.riskLevelName || "缺少信息",
          lines: [this.buildMissingInfoLine()],
          type: "info",
        },
      };
      return riskResultMap[this.summary.riskLevelCode] || riskResultMap.MISSING_INFO;
    },
  },
  methods: {
    resolveAmount(...values) {
      const target = values.find((value) => value !== undefined && value !== null && value !== "");
      return Number(target || 0);
    },
    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,
      })} 万元`;
    },
    buildResultLines() {
      return [
        `家庭总资产：${this.formatWanAmount(this.totalAsset)}`,
        `可解释收入：本人年收入 ${this.formatWanAmount(this.incomeDetail.selfIncome)} × 入职年限 ${this.employmentYears || "-"} 年 + 配偶年收入 ${this.formatWanAmount(this.incomeDetail.spouseIncome)} + 家庭总负债 ${this.formatWanAmount(this.totalDebt)} = ${this.formatWanAmount(this.explainableIncome)}`,
        `资产收入倍数：${this.formatRatio(this.resolveRatio(this.summary.assetIncomeRatio, this.totalAsset, this.explainableIncome))}`,
      ];
    },
    buildMissingInfoLine() {
      const missing = [];
      if (this.resolveAmount(this.incomeDetail.selfIncome) <= 0) {
        missing.push("收入");
      }
      if (this.resolveAmount(this.totalAsset) <= 0) {
        missing.push("资产");
      }
      if (!this.employmentYears) {
        missing.push("入职时间");
      }
      return missing.length === 1
        ? `缺少${missing[0]}，暂无法判断。`
        : "关键信息不完整，暂无法判断。";
    },
    resolveRatio(preferred, numerator, denominator) {
      if (preferred !== undefined && preferred !== null && preferred !== "") {
        const ratio = Number(preferred);
        return Number.isFinite(ratio) ? ratio : null;
      }
      const divisor = Number(denominator || 0);
      if (!divisor) {
        return null;
      }
      const ratio = Number(numerator || 0) / divisor;
      return Number.isFinite(ratio) ? ratio : null;
    },
    formatRatio(value) {
      if (value === null || value === undefined || !Number.isFinite(Number(value))) {
        return "-";
      }
      return Number(value).toFixed(2);
    },
    buildAmountGroups(items, amountField, resolveLabel, totalAmount) {
      const groupMap = items.reduce((result, item, index) => {
        const label = resolveLabel(item);
        const key = `${label}-${index}`;
        if (!result[label]) {
          result[label] = {
            key,
            label,
            amount: 0,
          };
        }
        result[label].amount += Number(item[amountField] || 0);
        return result;
      }, {});

      return Object.values(groupMap)
        .map((group) => ({
          ...group,
          share: this.formatPercent(group.amount, totalAmount),
        }))
        .sort((left, right) => right.amount - left.amount);
    },
    resolveAssetGroupLabel(item) {
      return item.assetName || [item.assetMainType, item.assetSubType].filter(Boolean).join(" / ") || "未分类资产";
    },
    resolveDebtGroupLabel(item) {
      return item.debtName || [item.debtMainType, item.debtSubType].filter(Boolean).join(" / ") || "未分类负债";
    },
    formatPercent(numerator, denominator) {
      if (!denominator) {
        return "-";
      }
      return `${((Number(numerator || 0) / Number(denominator)) * 100).toFixed(2)}%`;
    },
    formatMetricValue(value, options = {}) {
      const { denominator, suffix, isPercent } = options;
      // 分母为 0 时显示 -
      if (!denominator) {
        return "-";
      }
      if (isPercent) {
        return `${(Number(value || 0) * 100).toFixed(2)}${suffix}`;
      }
      return `${Number(value || 0).toFixed(2)}${suffix}`;
    },
    formatDetailDateTime(value) {
      if (!value) {
        return "-";
      }
      const formatted = parseTime(value, "{y}-{m}-{d} {h}:{i}:{s}");
      if (!formatted) {
        return "-";
      }
      const hasTime = !formatted.endsWith(" 00:00:00");
      return parseTime(value, hasTime ? "{y}-{m}-{d} {h}:{i}:{s}" : "{y}-{m}-{d}") || "-";
    },
  },
};
</script>

<style lang="scss" scoped>
.family-asset-liability-detail {
  padding: 8px 0 4px;
}

.detail-stack {
  display: grid;
  gap: 12px;
}

.detail-block {
  padding: 16px;
  background: #f8fafc;
  border: 1px solid #e2e8f0;
  border-radius: 12px;
  min-width: 0;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 16px;
  margin-bottom: 12px;
}

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

.section-summary-value {
  flex-shrink: 0;
  font-size: 18px;
  font-weight: 700;
  color: #111827;
}

.detail-metric-list {
  display: grid;
  gap: 8px;
}

.detail-metric-item {
  display: flex;
  justify-content: space-between;
  gap: 16px;
  font-size: 13px;
  color: #475569;
}

.metric-value {
  font-weight: 600;
  color: #111827;
}

.summary-group-list {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 12px;
}

.summary-group-item {
  padding: 12px 14px;
  background: #ffffff;
  border: 1px solid #e2e8f0;
  border-radius: 10px;
}

.summary-group-main,
.summary-group-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 12px;
}

.summary-group-meta {
  margin-top: 8px;
}

.summary-group-name,
.summary-group-share-label {
  font-size: 13px;
  color: #475569;
}

.summary-group-amount,
.summary-group-share {
  font-size: 13px;
  font-weight: 600;
  color: #111827;
}

.metric-grid {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: 12px;
}

.metric-card {
  padding: 12px 14px;
  background: #ffffff;
  border: 1px solid #e2e8f0;
  border-radius: 10px;
}

.metric-card-label {
  display: block;
  font-size: 13px;
  color: #64748b;
}

.metric-card-value {
  display: block;
  margin-top: 8px;
  font-size: 18px;
  font-weight: 700;
  color: #111827;
}

.result-card {
  padding: 14px 16px;
  border-radius: 10px;
  border: 1px solid #dbeafe;
  background: #eff6ff;
}

.result-card--success {
  border-color: #bbf7d0;
  background: #f0fdf4;
}

.result-card--warning {
  border-color: #fde68a;
  background: #fffbeb;
}

.result-card--danger {
  border-color: #fecaca;
  background: #fef2f2;
}

.result-card--info {
  border-color: #cbd5e1;
  background: #f8fafc;
}

.result-card-label {
  font-size: 12px;
  color: #64748b;
}

.result-card-value {
  margin-top: 6px;
  font-size: 14px;
  font-weight: 600;
  color: #111827;
}

.result-card-line {
  line-height: 1.7;
  word-break: break-word;
}

.empty-hint {
  font-size: 13px;
  color: #94a3b8;
}

@media (max-width: 1200px) {
  .summary-group-list,
  .metric-grid {
    grid-template-columns: 1fr;
  }
}
</style>
