<template>
  <div class="agent-recharge-detail-page">
    <ElCard shadow="never">
      <!-- 页面头部 -->
      <div class="detail-header">
        <ElButton @click="handleBack">
          <template #icon>
            <ElIcon><ArrowLeft /></ElIcon>
          </template>
          返回
        </ElButton>
        <h2 class="detail-title">{{ pageTitle }}</h2>
      </div>

      <!-- 详情内容 -->
      <DetailPage v-if="detailData" :sections="detailSections" :data="detailData" />

      <!-- 加载中 -->
      <div v-if="loading" class="loading-container">
        <ElIcon class="is-loading"><Loading /></ElIcon>
        <span>加载中...</span>
      </div>
    </ElCard>

    <PaymentVoucherDialog
      :file-keys="paymentVoucherFileKeys"
      @close="paymentVoucherFileKeys = []"
    />
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, computed, h } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import { ElCard, ElButton, ElIcon, ElMessage, ElTag } from 'element-plus'
  import { ArrowLeft, Loading } from '@element-plus/icons-vue'
  import DetailPage from '@/components/common/DetailPage.vue'
  import type { DetailSection } from '@/components/common/DetailPage.vue'
  import { AgentRechargeService } from '@/api/modules'
  import type { AgentRecharge, AgentRechargeStatus, AgentRechargePaymentMethod } from '@/types/api'
  import { formatDateTime } from '@/utils/business/format'
  import { hasVoucherKeys, toVoucherKeyList } from '@/utils/business'
  import PaymentVoucherDialog from '@/components/business/PaymentVoucherDialog.vue'
  import { formatRejectionReason } from './agentRechargeDisplay'

  defineOptions({ name: 'AgentRechargeDetail' })

  const route = useRoute()
  const router = useRouter()

  const loading = ref(false)
  const detailData = ref<AgentRecharge | null>(null)
  const paymentVoucherFileKeys = ref<string[]>([])

  const pageTitle = computed(() => `充值订单详情`)

  // 格式化货币 - 将分转换为元
  const formatCurrency = (amount: number): string => {
    return `¥${(amount / 100).toFixed(2)}`
  }

  // 获取状态标签类型
  const getStatusType = (
    status: AgentRechargeStatus
  ): 'warning' | 'success' | 'info' | 'danger' => {
    const statusMap: Record<AgentRechargeStatus, 'warning' | 'success' | 'info' | 'danger'> = {
      1: 'warning', // 待支付
      2: 'success', // 已支付
      3: 'success', // 已完成
      4: 'info', // 已关闭
      5: 'danger' // 已退款
    }
    return statusMap[status] || 'info'
  }

  // 获取状态文本（优先使用 status_name，否则使用本地映射）
  const getStatusText = (status: AgentRechargeStatus, statusName?: string): string => {
    if (statusName) return statusName
    const statusMap: Record<AgentRechargeStatus, string> = {
      1: '待支付',
      2: '已支付',
      3: '已完成',
      4: '已关闭',
      5: '已退款'
    }
    return statusMap[status] || '-'
  }

  // 获取支付方式文本
  const getPaymentMethodText = (method: AgentRechargePaymentMethod): string => {
    const methodMap: Record<AgentRechargePaymentMethod, string> = {
      wechat: '微信在线支付',
      offline: '线下转账'
    }
    return methodMap[method] || method
  }

  // 详情配置
  const detailSections = computed((): DetailSection[] => [
    {
      title: '订单信息',
      fields: [
        { label: '充值单号', prop: 'recharge_no' },
        { label: '店铺名称', prop: 'shop_name' },
        {
          label: '充值金额',
          formatter: (_, data) => formatCurrency(data.amount)
        },
        {
          label: '状态',
          render: (data) =>
            h(ElTag, { type: getStatusType(data.status) }, () =>
              getStatusText(data.status, data.status_name)
            )
        },
        {
          label: '驳回原因',
          prop: 'rejection_reason',
          formatter: (value) => formatRejectionReason(value),
          fullWidth: true
        }
      ]
    },
    {
      title: '支付信息',
      fields: [
        {
          label: '支付方式',
          formatter: (_, data) => getPaymentMethodText(data.payment_method)
        },
        {
          label: '支付通道',
          prop: 'payment_channel',
          formatter: (value) => value || '-'
        },
        {
          label: '第三方支付流水号',
          prop: 'payment_transaction_id',
          formatter: (value) => value || '-',
          fullWidth: true
        },
        {
          label: '支付凭证',
          fullWidth: true,
          render: (data) =>
            hasVoucherKeys(data.payment_voucher_key)
              ? h(
                  ElButton,
                  {
                    type: 'primary',
                    link: true,
                    onClick: () => {
                      paymentVoucherFileKeys.value = toVoucherKeyList(data.payment_voucher_key)
                    }
                  },
                  () => '查看支付凭证'
                )
              : h('span', '-')
        },
        {
          label: '运营备注',
          prop: 'remark',
          formatter: (value) => value || '-',
          fullWidth: true
        }
      ]
    },
    {
      title: '时间信息',
      fields: [
        {
          label: '创建时间',
          prop: 'created_at',
          formatter: (value) => formatDateTime(value)
        },
        {
          label: '支付时间',
          prop: 'paid_at',
          formatter: (value) => (value ? formatDateTime(value) : '-')
        },
        {
          label: '完成时间',
          prop: 'completed_at',
          formatter: (value) => (value ? formatDateTime(value) : '-')
        },
        {
          label: '更新时间',
          prop: 'updated_at',
          formatter: (value) => formatDateTime(value)
        }
      ]
    }
  ])

  // 加载详情数据
  const loadDetailData = async () => {
    loading.value = true
    try {
      const res = await AgentRechargeService.getAgentRechargeById(Number(route.params.id))
      if (res.code === 0) {
        detailData.value = res.data
      } else {
        ElMessage.error(res.msg || '加载失败')
      }
    } catch (error) {
      console.error(error)
      console.log('加载失败')
    } finally {
      loading.value = false
    }
  }

  // 返回上一页
  const handleBack = () => {
    router.back()
  }

  onMounted(() => {
    loadDetailData()
  })
</script>

<style scoped lang="scss">
  .agent-recharge-detail-page {
    padding: 20px;

    .detail-header {
      display: flex;
      gap: 16px;
      align-items: center;
      margin-bottom: 24px;

      .detail-title {
        margin: 0;
        font-size: 20px;
        font-weight: 600;
        color: var(--el-text-color-primary);
      }
    }

    .loading-container {
      display: flex;
      flex-direction: column;
      gap: 12px;
      align-items: center;
      justify-content: center;
      padding: 60px 0;
      color: var(--el-text-color-secondary);

      .el-icon {
        font-size: 32px;
      }
    }
  }
</style>
