<template>
  <div class="order-detail-page">
    <ElCard shadow="never">
      <!-- 页面头部 -->
      <div class="detail-header">
        <ElButton @click="handleBack">
          <template #icon>
            <ElIcon><ArrowLeft /></ElIcon>
          </template>
          返回
        </ElButton>
        <h2 class="detail-title">订单详情</h2>
      </div>

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

      <!-- 订单项列表 -->
      <div
        v-if="detailData && detailData.items && detailData.items.length > 0"
        class="order-items-section"
      >
        <h3 class="section-title">订单项列表</h3>
        <ElTable :data="detailData.items" border style="margin-top: 10px">
          <ElTableColumn prop="package_name" label="套餐名称" min-width="150" />
          <ElTableColumn prop="quantity" label="数量" width="100" />
          <ElTableColumn prop="unit_price" label="单价" width="120">
            <template #default="{ row }">
              {{ formatCurrency(row.unit_price) }}
            </template>
          </ElTableColumn>
          <ElTableColumn prop="amount" label="金额" width="120">
            <template #default="{ row }">
              {{ formatCurrency(row.amount) }}
            </template>
          </ElTableColumn>
        </ElTable>
      </div>

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

<script setup lang="ts">
  import { ref, onMounted, computed } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import { ElCard, ElButton, ElIcon, ElMessage, ElTable, ElTableColumn, 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 { OrderService } from '@/api/modules'
  import type { Order } from '@/types/api'
  import { formatDateTime } from '@/utils/business/format'

  defineOptions({ name: 'OrderDetail' })

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

  const loading = ref(false)
  const detailData = ref<Order | null>(null)

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

  // 获取订单类型文本
  const getOrderTypeText = (type: string): string => {
    return type === 'single_card' ? '单卡购买' : '设备购买'
  }

  // 获取买家类型文本
  const getBuyerTypeText = (type: string): string => {
    return type === 'personal' ? '个人客户' : '代理商'
  }

  // 获取支付方式文本
  const getPaymentMethodText = (method: string): string => {
    const methodMap: Record<string, string> = {
      wallet: '钱包支付',
      wechat: '微信支付',
      alipay: '支付宝支付'
    }
    return methodMap[method] || method
  }

  // 获取佣金状态文本
  const getCommissionStatusText = (status: number): string => {
    const statusMap: Record<number, string> = {
      0: '不适用',
      1: '待结算',
      2: '已结算'
    }
    return statusMap[status] || '-'
  }

  // 获取订单角色文本
  const getPurchaseRoleText = (role: string): string => {
    const roleMap: Record<string, string> = {
      self_purchase: '自己购买',
      purchased_by_parent: '上级代理购买',
      purchased_by_platform: '平台代购',
      purchase_for_subordinate: '给下级购买'
    }
    return roleMap[role] || role
  }

  // 详情页配置
  const detailSections: DetailSection[] = [
    {
      title: '基本信息',
      fields: [
        { label: '订单号', prop: 'order_no' },
        {
          label: '订单类型',
          formatter: (_, data) => getOrderTypeText(data.order_type)
        },
        {
          label: '支付状态',
          formatter: (_, data) => data.payment_status_text || '-'
        },
        {
          label: '订单金额',
          prop: 'total_amount',
          formatter: (value) => formatCurrency(value)
        },
        {
          label: '实付金额',
          prop: 'actual_paid_amount',
          formatter: (value) =>
            value !== undefined && value !== null ? formatCurrency(value) : '-'
        },
        {
          label: 'IoT卡ID',
          prop: 'iot_card_id',
          formatter: (value) => value || '-'
        },
        {
          label: '买家类型',
          formatter: (_, data) => (data.buyer_type ? getBuyerTypeText(data.buyer_type) : '-')
        },
        {
          label: '买家ID',
          prop: 'buyer_id',
          formatter: (value) => value || '-'
        },
        {
          label: '订单渠道',
          formatter: (_, data) =>
            data.purchase_role ? getPurchaseRoleText(data.purchase_role) : '-'
        },
        {
          label: '购买备注',
          prop: 'purchase_remark',
          formatter: (value) => value || '-'
        },
        {
          label: '是否上级代购',
          formatter: (_, data) => (data.is_purchased_by_parent ? '是' : '否')
        },
        {
          label: '操作者ID',
          prop: 'operator_id',
          formatter: (value) => value || '-'
        },
        {
          label: '操作者类型',
          prop: 'operator_type',
          formatter: (value) => value || '-'
        },
        {
          label: '操作者名称',
          prop: 'operator_name',
          formatter: (value) => value || '-'
        },
        {
          label: '是否超时',
          formatter: (_, data) => {
            if (data.is_expired === undefined || data.is_expired === null) return '-'
            return data.is_expired ? '是' : '否'
          }
        },
        {
          label: '超时时间',
          prop: 'expires_at',
          formatter: (value) => (value ? formatDateTime(value) : '-')
        },
        {
          label: '佣金状态',
          formatter: (_, data) => getCommissionStatusText(data.commission_status)
        },
        {
          label: '佣金配置版本',
          prop: 'commission_config_version'
        },
        {
          label: '创建时间',
          prop: 'created_at',
          formatter: (value) => formatDateTime(value)
        },
        {
          label: '更新时间',
          prop: 'updated_at',
          formatter: (value) => formatDateTime(value)
        }
      ]
    }
  ]

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

  // 获取详情数据
  const fetchDetail = async () => {
    const id = Number(route.params.id)
    if (!id) {
      ElMessage.error('缺少ID参数')
      return
    }

    loading.value = true
    try {
      const res = await OrderService.getOrderById(id)
      if (res.code === 0) {
        detailData.value = res.data
      }
    } catch (error) {
      console.error(error)
      console.log('获取订单详情失败')
    } finally {
      loading.value = false
    }
  }

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

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

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

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

  .order-items-section {
    padding-top: 20px;
    margin-top: 30px;
    border-top: 1px solid var(--el-border-color-lighter);

    .section-title {
      margin: 0 0 16px;
      font-size: 16px;
      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 20px;
    color: var(--el-text-color-secondary);

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