<script lang="ts" setup>
/**
 * 提现申请 ↔ 代付手续费 互通详情弹窗
 * 两边列表共用，按 source 拉取对应详情并展示完整关联信息
 */
import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { Spin, Tag } from 'ant-design-vue';

import { getChargeCashPayRecordDetailApi } from '#/views/finance/charge-cash-pay-record/api';
import { getWithdrawalApplicationInfo } from '#/views/finance/withdrawal/api';

defineOptions({
  name: 'WithdrawalRelationDetail',
});

const loading = ref(false);
/** 归一化后的展示数据 */
const view = ref<Record<string, any> | null>(null);

const [Modal, modalApi] = useVbenModal({
  footer: false,
  draggable: true,
  onOpenChange(isOpen) {
    if (isOpen) {
      loadDetail();
    } else {
      view.value = null;
    }
  },
});

const heroAmount = computed(() => {
  const v = view.value;
  if (!v) return '0.00';
  return formatMoney(v.true_cash ?? v.apply_cash ?? 0);
});

const checkStatusColor = computed(() => {
  const s = Number(view.value?.check_status ?? 0);
  if (s === 2) return 'success';
  if (s === 3 || s === 4) return 'error';
  return 'warning';
});

/**
 * 按入口源加载：apply 走提现详情，charge 走代付详情再归一化
 */
async function loadDetail() {
  const data = modalApi.getData<{
    id: number;
    source: 'apply' | 'charge';
  }>();
  if (!data?.id) return;
  loading.value = true;
  try {
    if (data.source === 'charge') {
      const res = await getChargeCashPayRecordDetailApi(data.id);
      view.value = normalizeFromCharge(res);
    } else {
      const res = await getWithdrawalApplicationInfo(data.id);
      view.value = normalizeFromApply(res);
    }
  } finally {
    loading.value = false;
  }
}

/** 从提现申请详情归一化 */
function normalizeFromApply(res: Record<string, any>) {
  const charge =
    res?.charge_cash_pay_record || res?.chargeCashPayRecord || null;
  return {
    order_no: res?.order_no,
    apply_id: res?.id,
    charge_id: charge?.id,
    apply_cash: res?.apply_cash,
    true_cash: res?.true_cash,
    display_charge_cash: res?.display_charge_cash ?? charge?.charge_cash ?? 0,
    check_status: res?.check_status,
    check_status_txt: res?.check_status_txt,
    check_result: res?.check_result,
    check_time: res?.check_time,
    apply_time: res?.apply_time,
    dakuan_status: res?.dakuan_status,
    dakuan_status_txt: res?.dakuan_status_txt,
    dakuan_time: res?.dakuan_time,
    user_type_txt: res?.user_type_txt,
    subject_name:
      res?.store?.name ||
      res?.supplier?.name ||
      res?.delivery_warehouse?.name ||
      res?.deliveryWarehouse?.name ||
      (Number(res?.user_type) === 2 ? '萧康云医' : '-'),
    charge_status: res?.charge_status ?? charge?.status,
    charge_status_txt: res?.charge_status_txt,
    charge_created_at: charge?.created_at,
  };
}

/** 从代付记录详情归一化 */
function normalizeFromCharge(res: Record<string, any>) {
  const apply = res?.cash_apply || res?.cashApply || null;
  return {
    order_no: res?.order_no,
    apply_id: res?.apply_id || apply?.id,
    charge_id: res?.id,
    apply_cash: res?.apply_cash ?? apply?.apply_cash,
    true_cash: res?.true_cash ?? apply?.true_cash,
    display_charge_cash: res?.charge_cash,
    check_status: res?.apply_check_status ?? apply?.check_status,
    check_status_txt: res?.apply_check_status_txt,
    check_result: apply?.check_result,
    check_time: apply?.check_time,
    apply_time: apply?.apply_time,
    dakuan_status: res?.apply_dakuan_status ?? apply?.dakuan_status,
    dakuan_status_txt: res?.apply_dakuan_status_txt,
    dakuan_time: apply?.dakuan_time,
    user_type_txt: res?.type_txt,
    subject_name: res?.subject_name || '-',
    charge_status: res?.status,
    charge_status_txt: res?.status_txt,
    charge_created_at: res?.created_at,
  };
}

function formatMoney(val: any) {
  const n = Number(val || 0);
  return Number.isFinite(n) ? n.toFixed(2) : '0.00';
}

function chargeTagColor(status: number) {
  if (status === 2) return 'success';
  if (status === 3) return 'default';
  return 'processing';
}
</script>

<template>
  <Modal class="w-[640px]" title="提现与代付详情">
    <Spin :spinning="loading">
      <div v-if="view" class="relation-detail">
        <div class="hero">
          <div class="hero-label">打款金额（元）</div>
          <div class="hero-amount">{{ heroAmount }}</div>
          <div class="hero-tags">
            <Tag :color="checkStatusColor">
              {{ view.check_status_txt || '未知审核状态' }}
            </Tag>
            <Tag :color="chargeTagColor(Number(view.charge_status || 0))">
              手续费{{ view.charge_status_txt || '无记录' }}
            </Tag>
          </div>
        </div>

        <div class="section">
          <div class="section-title">提现申请</div>
          <div class="rows">
            <div class="row">
              <span class="label">订单号</span>
              <span class="value mono">{{ view.order_no || '-' }}</span>
            </div>
            <div class="row">
              <span class="label">申请主体</span>
              <span class="value">
                {{ view.user_type_txt || '-' }} · {{ view.subject_name || '-' }}
              </span>
            </div>
            <div class="row">
              <span class="label">申请金额</span>
              <span class="value">¥{{ formatMoney(view.apply_cash) }}</span>
            </div>
            <div class="row">
              <span class="label">打款金额</span>
              <span class="value">¥{{ formatMoney(view.true_cash) }}</span>
            </div>
            <div class="row">
              <span class="label">申请时间</span>
              <span class="value">{{ view.apply_time || '-' }}</span>
            </div>
            <div class="row">
              <span class="label">打款状态</span>
              <span class="value">{{ view.dakuan_status_txt || '-' }}</span>
            </div>
            <div v-if="view.dakuan_time" class="row">
              <span class="label">打款时间</span>
              <span class="value">{{ view.dakuan_time }}</span>
            </div>
            <div v-if="view.check_result" class="row">
              <span class="label">审核说明</span>
              <span
                class="value"
                :class="{ danger: Number(view.check_status) === 3 }"
              >
                {{ view.check_result }}
              </span>
            </div>
          </div>
        </div>

        <div class="section section--fee">
          <div class="section-title">代付手续费</div>
          <div class="rows">
            <div class="row">
              <span class="label">手续费金额</span>
              <span class="value fee">
                ¥{{ formatMoney(view.display_charge_cash) }}
              </span>
            </div>
            <div class="row">
              <span class="label">代付状态</span>
              <span class="value">{{ view.charge_status_txt || '无关联记录' }}</span>
            </div>
            <div class="row">
              <span class="label">记录时间</span>
              <span class="value">{{ view.charge_created_at || '-' }}</span>
            </div>
            <div class="row">
              <span class="label">代付记录ID</span>
              <span class="value">{{ view.charge_id || '-' }}</span>
            </div>
          </div>
        </div>
      </div>
      <div v-else-if="!loading" class="empty">暂无详情</div>
    </Spin>
  </Modal>
</template>

<style scoped lang="scss">
.relation-detail {
  padding: 4px 4px 8px;
}

.hero {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px 12px;
  border-radius: 12px;
  background: hsl(var(--muted) / 0.35);
}

.hero-label {
  margin-bottom: 6px;
  font-size: 13px;
  color: hsl(var(--muted-foreground));
}

.hero-amount {
  margin-bottom: 10px;
  font-family: 'DIN Alternate', ui-monospace, SFMono-Regular, Menlo, monospace;
  font-size: 32px;
  font-weight: 700;
  color: hsl(var(--foreground));
  line-height: 1.1;
}

.hero-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  justify-content: center;
}

.section {
  margin-bottom: 14px;
  padding: 12px 14px;
  border: 1px solid hsl(var(--border));
  border-radius: 10px;
  background: hsl(var(--card, var(--background)));
}

.section--fee {
  border-color: hsl(var(--primary) / 0.3);
  background: hsl(var(--primary) / 0.06);
}

.section-title {
  margin-bottom: 10px;
  font-size: 13px;
  font-weight: 600;
  color: hsl(var(--foreground));
}

.rows {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.row {
  display: flex;
  justify-content: space-between;
  gap: 12px;
  font-size: 13px;
  line-height: 1.4;
}

.label {
  flex-shrink: 0;
  color: hsl(var(--muted-foreground));
}

.value {
  text-align: right;
  color: hsl(var(--foreground));
  word-break: break-all;
}

.value.mono {
  font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
}

.value.fee {
  font-weight: 600;
  color: hsl(var(--primary));
}

.value.danger {
  color: hsl(var(--destructive, 0 84% 60%));
}

.empty {
  padding: 32px 0;
  text-align: center;
  color: hsl(var(--muted-foreground));
}
</style>
