<template>
  <div class="exchange-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="exchangeDetail" :sections="detailSections" :data="exchangeDetail" />

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

<script setup lang="ts">
  import { h } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import { ExchangeService } from '@/api/modules'
  import type { ExchangeResponse } from '@/api/modules/exchange'
  import { ElTag, ElCard, ElButton, ElIcon } from 'element-plus'
  import type { TagProps } from 'element-plus'
  import { ArrowLeft, Loading } from '@element-plus/icons-vue'
  import { formatDateTime } from '@/utils/business/format'
  import DetailPage from '@/components/common/DetailPage.vue'
  import type { DetailSection } from '@/components/common/DetailPage.vue'

  defineOptions({ name: 'ExchangeDetail' })

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

  const loading = ref(false)
  const exchangeDetail = ref<ExchangeResponse | null>(null)
  const exchangeId = ref<number>(0)

  const formatExchangeShopName = (shopName?: string | null, shopId?: number | null) => {
    if (shopName) return shopName
    if (shopId === null || shopId === 0) return '平台'
    return '--'
  }

  const getStatusType = (status: number): TagProps['type'] => {
    const types: Record<number, TagProps['type']> = {
      1: 'warning',
      2: 'info',
      3: 'primary',
      4: 'success',
      5: 'danger'
    }
    return types[status] || 'info'
  }

  // 根据流程类型动态生成详情页配置
  const detailSections = computed<DetailSection[]>(() => {
    if (!exchangeDetail.value) return []

    const flowType = exchangeDetail.value.flow_type || 'shipping' // 历史数据兼容
    const sections: DetailSection[] = []

    // 基本信息
    sections.push({
      title: '基本信息',
      fields: [
        { label: '换货单号', prop: 'exchange_no' },
        {
          label: '状态',
          render: (data) => h(ElTag, { type: getStatusType(data.status) }, () => data.status_text)
        },
        {
          label: '流程类型',
          formatter: (_, data) =>
            data.flow_type_name || (flowType === 'direct' ? '直接换货' : '物流换货')
        },
        {
          label: '换货原因',
          prop: 'exchange_reason',
          fullWidth: true
        },
        {
          label: '旧资产类型',
          formatter: (_, data) => (data.old_asset_type === 'iot_card' ? 'IoT卡' : '设备')
        },
        { label: '旧资产标识符', prop: 'old_asset_identifier' },
        {
          label: '新资产类型',
          formatter: (_, data) =>
            data.new_asset_type ? (data.new_asset_type === 'iot_card' ? 'IoT卡' : '设备') : '--'
        },
        {
          label: '新资产标识符',
          formatter: (value) => value || '--',
          prop: 'new_asset_identifier'
        },
        {
          label: '继承归属店铺',
          formatter: (_, data) =>
            formatExchangeShopName(data.inherited_shop_name, data.inherited_shop_id)
        }
      ]
    })

    // 收货信息（仅物流换货显示）
    if (flowType === 'shipping') {
      sections.push({
        title: '收货信息',
        fields: [
          {
            label: '收货人姓名',
            formatter: (value) => value || '--',
            prop: 'recipient_name'
          },
          {
            label: '收货人电话',
            formatter: (value) => value || '--',
            prop: 'recipient_phone'
          },
          {
            label: '收货地址',
            formatter: (value) => value || '--',
            prop: 'recipient_address',
            fullWidth: true
          }
        ]
      })

      // 物流信息（仅物流换货显示）
      sections.push({
        title: '物流信息',
        fields: [
          {
            label: '快递公司',
            formatter: (value) => value || '--',
            prop: 'express_company'
          },
          {
            label: '快递单号',
            formatter: (value) => value || '--',
            prop: 'express_no'
          },
          {
            label: '发货时间',
            formatter: (value) => (value ? formatDateTime(value) : '--'),
            prop: 'shipped_at'
          }
        ]
      })
    }

    // 其他信息
    sections.push({
      title: '其他信息',
      fields: [
        {
          label: '备注',
          formatter: (value) => value || '--',
          prop: 'remark',
          fullWidth: true
        },
        {
          label: '完成时间',
          formatter: (value) => (value ? formatDateTime(value) : '--'),
          prop: 'completed_at'
        },
        {
          label: '创建时间',
          formatter: (value) => formatDateTime(value),
          prop: 'created_at'
        },
        {
          label: '更新时间',
          formatter: (value) => formatDateTime(value),
          prop: 'updated_at'
        }
      ]
    })

    return sections
  })

  // 加载换货单详情
  const loadExchangeDetail = async () => {
    loading.value = true
    try {
      const res = await ExchangeService.getExchangeDetail(exchangeId.value)
      if (res.code === 0 && res.data) {
        exchangeDetail.value = res.data
      }
    } catch (error) {
      console.error('加载换货单详情失败:', error)
    } finally {
      loading.value = false
    }
  }

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

  // 初始化
  onMounted(() => {
    exchangeId.value = Number(route.params.id)
    if (exchangeId.value) {
      loadExchangeDetail()
    }
  })
</script>

<style lang="scss" scoped>
  .exchange-detail-page {
    height: 100%;
    padding: 20px;

    .detail-header {
      display: flex;
      align-items: center;
      margin-bottom: 20px;

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

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

      .el-icon {
        margin-bottom: 8px;
        font-size: 40px;
      }
    }
  }
</style>
