<template>
  <ElDialog v-model="visible" title="往期订单" width="60%" destroy-on-close>
    <div v-if="loading" style="padding: 40px 0; text-align: center">
      <ElIcon class="is-loading" :size="40"><Loading /></ElIcon>
    </div>
    <div v-else-if="data">
      <!-- 当前代订单 -->
      <div class="generation-section">
        <h3 style="margin-bottom: 16px"> 当前代 ({{ data.current_generation.identifier }}) </h3>
        <ElTable :data="data.current_generation.items" border>
          <ElTableColumn prop="order_no" label="订单号" width="200" />
          <ElTableColumn prop="order_type" label="订单类型" width="120" />
          <ElTableColumn prop="payment_status_text" label="支付状态" width="100">
            <template #default="{ row }">
              <ElTag :type="getPaymentStatusType(row.payment_status)">
                {{ row.payment_status_text }}
              </ElTag>
            </template>
          </ElTableColumn>
          <ElTableColumn prop="total_amount" label="总金额" width="120">
            <template #default="{ row }"> ¥{{ (row.total_amount / 100).toFixed(2) }} </template>
          </ElTableColumn>
          <ElTableColumn prop="payment_method" label="支付方式" width="120" />
          <ElTableColumn prop="paid_at" label="支付时间" width="180">
            <template #default="{ row }">
              {{ row.paid_at ? formatDateTime(row.paid_at) : '-' }}
            </template>
          </ElTableColumn>
          <ElTableColumn label="订单项" min-width="200">
            <template #default="{ row }">
              <div v-for="(item, idx) in row.items" :key="idx" style="margin-bottom: 4px">
                {{ item.package_name }} × {{ item.quantity }}
              </div>
            </template>
          </ElTableColumn>
          <ElTableColumn prop="created_at" label="创建时间" width="180">
            <template #default="{ row }">
              {{ formatDateTime(row.created_at) }}
            </template>
          </ElTableColumn>
        </ElTable>

        <!-- 分页 -->
        <div style="margin-top: 16px; text-align: right">
          <ElPagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.page_size"
            :total="data.current_generation.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handlePageSizeChange"
            @current-change="handlePageChange"
          />
        </div>
      </div>

      <!-- 前代订单 -->
      <div
        v-if="data.previous_generations && data.previous_generations.length > 0"
        style="margin-top: 32px"
      >
        <div
          v-for="gen in data.previous_generations"
          :key="gen.generation"
          class="generation-section"
          style="margin-bottom: 24px"
        >
          <h3 style="margin-bottom: 16px">
            第{{ gen.generation }}代 ({{ gen.identifier }})
            <span v-if="gen.exchange_no" style="margin-left: 12px; font-size: 14px; color: #909399">
              换货单号: {{ gen.exchange_no }}
            </span>
            <span
              v-if="gen.exchanged_at"
              style="margin-left: 12px; font-size: 14px; color: #909399"
            >
              换货时间: {{ formatDateTime(gen.exchanged_at) }}
            </span>
          </h3>
          <ElTable :data="gen.items" border>
            <ElTableColumn prop="order_no" label="订单号" width="200" />
            <ElTableColumn prop="order_type" label="订单类型" width="120" />
            <ElTableColumn prop="payment_status_text" label="支付状态" width="100">
              <template #default="{ row }">
                <ElTag :type="getPaymentStatusType(row.payment_status)">
                  {{ row.payment_status_text }}
                </ElTag>
              </template>
            </ElTableColumn>
            <ElTableColumn prop="total_amount" label="总金额" width="120">
              <template #default="{ row }"> ¥{{ (row.total_amount / 100).toFixed(2) }} </template>
            </ElTableColumn>
            <ElTableColumn prop="payment_method" label="支付方式" width="120" />
            <ElTableColumn prop="paid_at" label="支付时间" width="180">
              <template #default="{ row }">
                {{ row.paid_at ? formatDateTime(row.paid_at) : '-' }}
              </template>
            </ElTableColumn>
            <ElTableColumn label="订单项" min-width="200">
              <template #default="{ row }">
                <div v-for="(item, idx) in row.items" :key="idx" style="margin-bottom: 4px">
                  {{ item.package_name }} × {{ item.quantity }}
                </div>
              </template>
            </ElTableColumn>
            <ElTableColumn prop="created_at" label="创建时间" width="180">
              <template #default="{ row }">
                {{ formatDateTime(row.created_at) }}
              </template>
            </ElTableColumn>
          </ElTable>
        </div>

        <ElAlert v-if="data.truncated" type="warning" :closable="false" style="margin-top: 16px">
          换货链超过10代，仅显示最近10代的订单记录
        </ElAlert>
      </div>
    </div>
    <div v-else style="padding: 40px 0; text-align: center">
      <ElEmpty description="暂无订单数据" />
    </div>
  </ElDialog>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, watch } from 'vue'
  import {
    ElDialog,
    ElTable,
    ElTableColumn,
    ElTag,
    ElPagination,
    ElAlert,
    ElEmpty,
    ElIcon,
    ElMessage
  } from 'element-plus'
  import { Loading } from '@element-plus/icons-vue'
  import { AssetService } from '@/api/modules'
  import { formatDateTime } from '@/utils/business/format'

  interface Props {
    modelValue: boolean
    assetIdentifier?: string
    assetType?: 'card' | 'device'
  }

  interface Emits {
    (e: 'update:modelValue', value: boolean): void
  }

  const props = defineProps<Props>()
  const emit = defineEmits<Emits>()

  const loading = ref(false)
  const data = ref<any>(null)

  const pagination = reactive({
    page: 1,
    page_size: 20
  })

  const visible = computed({
    get: () => props.modelValue,
    set: (value) => emit('update:modelValue', value)
  })

  // 监听对话框打开，加载数据
  watch(visible, async (newVal) => {
    if (newVal && props.assetIdentifier) {
      pagination.page = 1
      pagination.page_size = 20
      await loadOrderHistory()
    } else if (!newVal) {
      // 关闭时重置数据
      data.value = null
    }
  })

  const loadOrderHistory = async () => {
    if (!props.assetIdentifier) return

    try {
      loading.value = true

      const response = await AssetService.getAssetOrders(props.assetIdentifier, {
        page: pagination.page,
        page_size: pagination.page_size,
        include_previous: true // 包含换货前代的订单
      })

      if (response.code === 0 && response.data) {
        data.value = response.data
      }
    } catch (error: any) {
      console.error('加载往期订单失败:', error)
      console.log(error?.message || '加载往期订单失败')
    } finally {
      loading.value = false
    }
  }

  const handlePageSizeChange = (size: number) => {
    pagination.page_size = size
    loadOrderHistory()
  }

  const handlePageChange = (page: number) => {
    pagination.page = page
    loadOrderHistory()
  }

  const getPaymentStatusType = (status: number): 'success' | 'warning' | 'danger' | 'info' => {
    const statusMap: Record<number, 'success' | 'warning' | 'danger' | 'info'> = {
      1: 'warning', // 待支付
      2: 'success', // 已支付
      3: 'danger', // 已取消
      4: 'info' // 已关闭
    }
    return statusMap[status] || 'info'
  }
</script>

<style lang="scss" scoped>
  .generation-section {
    h3 {
      font-size: 16px;
      font-weight: 600;
      color: var(--el-text-color-primary);
    }
  }
</style>
