<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">
        <ElCard style="margin-top: 20px" shadow="never">
          <div class="order-items-section">
            <h3 class="section-title">订单列表</h3>
            <ElTable :data="detailData.items" border>
              <ElTableColumn prop="package_name" label="套餐名称" />
              <ElTableColumn prop="package_type" label="套餐类型">
                <template #default="{ row }">
                  {{
                    row.package_type === 'formal'
                      ? '正式套餐'
                      : row.package_type === 'addon'
                        ? '加油包'
                        : '-'
                  }}
                </template>
              </ElTableColumn>
              <ElTableColumn prop="quantity" label="数量" />
              <ElTableColumn prop="unit_price" label="单价">
                <template #default="{ row }">
                  {{ formatCurrency(row.unit_price) }}
                </template>
              </ElTableColumn>
              <ElTableColumn prop="amount" label="金额">
                <template #default="{ row }">
                  {{ formatCurrency(row.amount) }}
                </template>
              </ElTableColumn>
            </ElTable>
          </div>
        </ElCard>
      </div>

      <!-- 加载中 -->
      <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 { h, onMounted, ref, computed } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import { ElButton, ElCard, ElIcon, ElMessage, ElTable, ElTableColumn } from 'element-plus'
  import { ArrowLeft, Loading } from '@element-plus/icons-vue'
  import DetailPage from '@/components/common/DetailPage.vue'
  import type { DetailField, DetailSection } from '@/components/common/DetailPage.vue'
  import { OrderService } from '@/api/modules'
  import type {
    Order,
    OrderCommissionResult,
    OrderCommissionStatus,
    OrderOperatorType
  } from '@/types/api'
  import { useAuth } from '@/composables/useAuth'
  import { useUserStore } from '@/store/modules/user'
  import { formatDateTime } from '@/utils/business/format'
  import { hasVoucherKeys, toVoucherKeyList } from '@/utils/business'
  import PaymentVoucherDialog from '@/components/business/PaymentVoucherDialog.vue'

  defineOptions({ name: 'OrderDetail' })

  const route = useRoute()
  const router = useRouter()
  const { hasAuth } = useAuth()
  const userStore = useUserStore()

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

  // 格式化货币 - 将分转换为元
  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 getOperatorTypeText = (type?: OrderOperatorType): string => {
    if (!type) return '-'
    const typeMap: Record<OrderOperatorType, string> = {
      platform: '平台',
      agent: '代理',
      enterprise: '企业',
      personal_customer: '个人客户'
    }
    return typeMap[type] || type
  }

  // 获取佣金流程状态文本
  const getCommissionStatusText = (status?: OrderCommissionStatus, statusName?: string): string => {
    if (statusName) return statusName
    if (status === undefined) return '-'

    const statusMap: Record<OrderCommissionStatus, string> = {
      1: '待计算',
      2: '已完成',
      3: '待人工处理'
    }
    return statusMap[status] || '-'
  }

  // 获取佣金业务结果文本
  const getCommissionResultText = (result?: OrderCommissionResult, resultName?: string): string => {
    if (resultName) return resultName
    if (result === undefined) return '-'

    const resultMap: Record<OrderCommissionResult, string> = {
      0: '未知',
      1: '有佣金',
      2: '无佣金',
      3: '链路异常'
    }
    return resultMap[result] || '-'
  }

  // 获取订单角色文本
  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 canViewActualPaidAmount = computed(() => {
    const userType = userStore.info.user_type
    // 只有代理账号(3)和企业账号(4)不能看到实付金额
    return userType !== 3 && userType !== 4
  })

  // 详情页配置
  const detailSections = computed<DetailSection[]>(() => {
    const baseFields: DetailField[] = [
      { label: '订单号', prop: 'order_no' },
      {
        label: '订单类型',
        formatter: (_: any, data: any) => getOrderTypeText(data.order_type)
      },
      {
        label: '支付状态',
        formatter: (_: any, data: any) => data.payment_status_text || '-'
      },
      {
        label: '订单金额',
        prop: 'total_amount',
        formatter: (value: any) => formatCurrency(value)
      }
    ]

    // 只有非代理账号和非企业账号才能看到实付金额字段
    if (canViewActualPaidAmount.value) {
      baseFields.push({
        label: '实付金额',
        prop: 'actual_paid_amount',
        formatter: (value: any) =>
          value !== undefined && value !== null ? formatCurrency(value) : '-'
      })
    }

    baseFields.push(
      {
        label: '支付凭证',
        fullWidth: true,
        render: (data: any) => {
          if (
            !hasVoucherKeys(data.payment_voucher_key) ||
            !hasAuth('orders:view_payment_voucher')
          ) {
            return h('span', '-')
          }

          return h(
            ElButton,
            {
              type: 'primary',
              link: true,
              onClick: () => {
                paymentVoucherFileKeys.value = toVoucherKeyList(data.payment_voucher_key)
              }
            },
            () => '查看支付凭证'
          )
        }
      },
      {
        label: '买家类型',
        formatter: (_, data) => (data.buyer_type ? getBuyerTypeText(data.buyer_type) : '-')
      },
      {
        label: '买家手机号',
        prop: 'buyer_phone',
        formatter: (value) => value || '-'
      },
      {
        label: '买家昵称',
        prop: 'buyer_nickname',
        formatter: (value) => value || '-'
      },
      {
        label: '订单渠道',
        formatter: (_, data) => (data.purchase_role ? getPurchaseRoleText(data.purchase_role) : '-')
      },
      {
        label: '购买备注',
        prop: 'purchase_remark',
        formatter: (value) => value || '-'
      },
      {
        label: '支付时间',
        prop: 'paid_at',
        formatter: (value) => (value ? formatDateTime(value) : '-')
      },
      {
        label: '是否上级代购',
        formatter: (_, data) => (data.is_purchased_by_parent ? '是' : '否')
      },
      {
        label: 'ICCID/VirtualNo',
        prop: 'asset_identifier',
        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: '创建时间',
        prop: 'created_at',
        formatter: (value) => formatDateTime(value)
      },
      {
        label: '更新时间',
        prop: 'updated_at',
        formatter: (value) => formatDateTime(value)
      }
    )

    return [
      {
        title: '基本信息',
        fields: baseFields
      },
      {
        title: '操作者信息',
        fields: [
          {
            label: '操作者类型',
            prop: 'operator_type',
            formatter: (value) => getOperatorTypeText(value)
          },
          {
            label: '操作者名称',
            prop: 'operator_name',
            formatter: (value) => value || '-'
          }
        ]
      },
      {
        title: '业务归属信息',
        fields: [
          {
            label: '销售店铺名称',
            prop: 'seller_shop_name',
            formatter: (value) => value || '-'
          }
        ]
      },
      {
        title: '佣金信息',
        fields: [
          {
            label: '流程状态',
            formatter: (_, data) =>
              getCommissionStatusText(data.commission_status, data.commission_status_name)
          },
          {
            label: '业务结果',
            formatter: (_, data) =>
              getCommissionResultText(data.commission_result, data.commission_result_name)
          },
          {
            label: '佣金配置版本',
            prop: 'commission_config_version'
          }
        ]
      }
    ]
  })

  // 返回上一页
  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 {
    .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>
