<template>
  <div class="order-package-invalidate-task-detail-page">
    <ElCard shadow="never">
      <div class="detail-header">
        <ElButton @click="router.back()">返回</ElButton>
        <h2 class="detail-title">订单套餐作废任务详情</h2>
      </div>

      <DetailPage v-if="taskDetail" :sections="detailSections" :data="taskDetail" />

      <ElTable
        v-if="taskDetail?.failed_items?.length"
        :data="taskDetail.failed_items"
        border
        style="width: 100%; margin-top: 16px"
      >
        <ElTableColumn prop="line" label="行号" width="100" />
        <ElTableColumn prop="order_no" label="订单号" min-width="180" show-overflow-tooltip />
        <ElTableColumn prop="reason" label="失败原因" min-width="240" show-overflow-tooltip />
      </ElTable>
      <ElEmpty v-else-if="taskDetail" description="暂无失败明细" />
    </ElCard>

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

<script setup lang="ts">
  import { computed, h, onMounted, ref } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import { ElButton, ElCard, ElEmpty, ElMessage, ElTable, ElTableColumn, ElTag } from 'element-plus'
  import DetailPage from '@/components/common/DetailPage.vue'
  import type { DetailSection } from '@/components/common/DetailPage.vue'
  import { OrderPackageInvalidateTaskService } from '@/api/modules'
  import type {
    OrderPackageInvalidateTaskDetail,
    OrderPackageInvalidateTaskStatus
  } from '@/types/api'
  import { formatDateTime } from '@/utils/business/format'
  import { hasVoucherKeys, toVoucherKeyList } from '@/utils/business'
  import PaymentVoucherDialog from '@/components/business/PaymentVoucherDialog.vue'

  defineOptions({ name: 'OrderPackageInvalidateTaskDetail' })

  const route = useRoute()
  const router = useRouter()
  const taskDetail = ref<OrderPackageInvalidateTaskDetail | null>(null)
  const voucherPreviewKeys = ref<string[]>([])

  const getStatusType = (status: OrderPackageInvalidateTaskStatus) => {
    const statusMap: Record<number, 'info' | 'warning' | 'success' | 'danger'> = {
      1: 'info',
      2: 'warning',
      3: 'success',
      4: 'danger'
    }
    return statusMap[status] || 'info'
  }

  const getStatusName = (task: OrderPackageInvalidateTaskDetail) =>
    task.status_text || task.status_name || '-'

  const detailSections = computed<DetailSection[]>(() => [
    {
      title: '任务信息',
      columns: 2,
      fields: [
        { label: '任务编号', prop: 'task_no' },
        {
          label: '任务状态',
          render: (data: OrderPackageInvalidateTaskDetail) =>
            h(ElTag, { type: getStatusType(data.status) }, () => getStatusName(data))
        },
        { label: '文件名', prop: 'file_name', formatter: (value: string) => value || '-' },
        { label: '操作人', prop: 'creator_name', formatter: (value: string) => value || '-' },
        {
          label: '凭证附件',
          render: (data: OrderPackageInvalidateTaskDetail) =>
            hasVoucherKeys(data.voucher_keys)
              ? h(
                  ElButton,
                  {
                    link: true,
                    type: 'primary',
                    onClick: () => (voucherPreviewKeys.value = toVoucherKeyList(data.voucher_keys))
                  },
                  () => '查看凭证'
                )
              : h('span', '-')
        },
        {
          label: '运营备注',
          prop: 'remark',
          formatter: (value: string) => value || '-',
          fullWidth: true
        },
        {
          label: '错误信息',
          prop: 'error_message',
          formatter: (value: string) => value || '-',
          fullWidth: true
        },
        {
          label: '创建时间',
          prop: 'created_at',
          formatter: (value: string) => formatDateTime(value)
        },
        {
          label: '开始时间',
          prop: 'started_at',
          formatter: (value: string) => (value ? formatDateTime(value) : '-')
        },
        {
          label: '完成时间',
          prop: 'completed_at',
          formatter: (value: string) => (value ? formatDateTime(value) : '-')
        }
      ]
    },
    {
      title: '统计信息',
      columns: 2,
      fields: [
        { label: '总数', prop: 'total_count' },
        { label: '成功数', prop: 'success_count' },
        { label: '失败数', prop: 'fail_count' },
        { label: '跳过数', prop: 'skip_count', formatter: (value: number) => String(value ?? 0) }
      ]
    }
  ])

  const getTaskDetail = async () => {
    const taskId = Number(route.query.id)
    if (!taskId) {
      ElMessage.error('任务ID无效')
      return
    }
    const res = await OrderPackageInvalidateTaskService.getTaskDetail(taskId)
    if (res.code === 0) {
      taskDetail.value = res.data
    }
  }

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

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

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

    .detail-title {
      min-width: 0;
      margin: 0;
      overflow: hidden;
      font-size: 20px;
      font-weight: 600;
      color: var(--el-text-color-primary);
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
</style>
