<script setup lang="ts">
import dayjs from 'dayjs'
import { api } from '@/utils/request'
import { useFailedMessageStore, type FailedMessageRecord } from '@/stores/failed-message'
import type { FailedMessageDetail, FailedMessageDataType } from '@/types/api'
import {
  SearchOutlined,
  ReloadOutlined,
  EyeOutlined,
} from '@ant-design/icons-vue'

const store = useFailedMessageStore()

// Detail drawer
const drawerVisible = ref(false)
const drawerLoading = ref(false)
const detail = ref<FailedMessageDetail | null>(null)
let detailRequestId = 0

const dataTypeColorMap: Record<FailedMessageDataType, string> = {
  order: 'blue',
  product: 'green',
  refund: 'orange',
  inventory: 'purple',
}

const dataTypeLabelMap: Record<FailedMessageDataType, string> = {
  order: '订单',
  product: '产品',
  refund: '退款',
  inventory: '库存',
}

const dataTypeOptions = Object.entries(dataTypeLabelMap).map(([value, label]) => ({
  label,
  value: value as FailedMessageDataType,
}))

const columns = [
  { title: 'ID', dataIndex: 'id', width: 80, fixed: 'left' as const },
  { title: '数据类型', key: 'data_type', width: 100 },
  { title: '平台', key: 'platform', width: 100 },
  { title: '错误类型', dataIndex: 'error_type', width: 200, ellipsis: true },
  { title: '错误信息', key: 'error_message', width: 260 },
  { title: '重试次数', dataIndex: 'retry_count', width: 90 },
  { title: '失败时间', key: 'failed_at', width: 160 },
  { title: '操作', key: 'action', width: 100, fixed: 'right' as const },
]

// RangePicker dayjs 桥接
const failedAtRange = computed({
  get: () => {
    if (!store.filters.failed_at_range) return undefined
    return store.filters.failed_at_range.map((d) => dayjs(d)) as [dayjs.Dayjs, dayjs.Dayjs]
  },
  set: (val) => {
    store.filters.failed_at_range = val
      ? [val[0].format('YYYY-MM-DD'), val[1].format('YYYY-MM-DD')]
      : null
  },
})

onMounted(() => {
  store.loadLookups()
  store.fetchMessages()
})

function handleSearch() {
  store.pagination.page = 1
  store.fetchMessages()
}

function handleReset() {
  store.resetFilters()
  store.fetchMessages()
}

function handlePageChange(page: number, pageSize: number) {
  store.pagination.page = page
  store.pagination.per_page = pageSize
  store.fetchMessages()
}

function formatTime(time: string | null) {
  if (!time) return '-'
  return time.replace('T', ' ').substring(0, 16)
}

async function handleViewDetail(record: { id: number }) {
  const currentRequestId = ++detailRequestId
  drawerVisible.value = true
  drawerLoading.value = true
  detail.value = null

  try {
    const data = await api.get<FailedMessageDetail>(`/api/v1/failed-messages/${record.id}`)
    if (currentRequestId !== detailRequestId) return
    detail.value = data
  } catch {
    if (currentRequestId !== detailRequestId) return
    message.error('获取失败消息详情失败')
  } finally {
    if (currentRequestId === detailRequestId) {
      drawerLoading.value = false
    }
  }
}
</script>

<template>
  <div>
    <h2 class="text-xl font-semibold mb-4">失败消息管理</h2>

    <!-- Filter area -->
    <a-card class="mb-4">
      <a-form layout="inline" @submit.prevent="handleSearch">
        <a-form-item label="数据类型">
          <a-select
            v-model:value="store.filters.data_type"
            placeholder="全部类型"
            allow-clear
            style="width: 120px"
          >
            <a-select-option v-for="opt in dataTypeOptions" :key="opt.value" :value="opt.value">
              {{ opt.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="平台">
          <a-select
            v-model:value="store.filters.platform_id"
            placeholder="全部平台"
            allow-clear
            style="width: 140px"
          >
            <a-select-option v-for="p in store.platforms" :key="p.id" :value="p.id">
              {{ store.platformMap.get(p.id) || `平台 #${p.id}` }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="失败时间">
          <a-range-picker v-model:value="failedAtRange" format="YYYY-MM-DD" />
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" html-type="submit">
              <template #icon><SearchOutlined /></template>
              搜索
            </a-button>
            <a-button @click="handleReset">
              <template #icon><ReloadOutlined /></template>
              重置
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- Table -->
    <a-card>
      <a-table
        :columns="columns"
        :data-source="store.messages"
        :loading="store.loading"
        :pagination="false"
        :scroll="{ x: 1200 }"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'data_type'">
            <a-tag :color="dataTypeColorMap[record.data_type as FailedMessageDataType] || 'default'">
              {{ dataTypeLabelMap[record.data_type as FailedMessageDataType] || record.data_type }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'platform'">
            {{ store.platformMap.get(record.platform_id) || record.platform }}
          </template>
          <template v-else-if="column.key === 'error_message'">
            <a-tooltip :title="record.error_message">
              <span class="inline-block max-w-[240px] truncate align-bottom">
                {{ record.error_message }}
              </span>
            </a-tooltip>
          </template>
          <template v-else-if="column.key === 'failed_at'">
            {{ formatTime(record.failed_at) }}
          </template>
          <template v-else-if="column.key === 'action'">
            <a-button
              type="link"
              size="small"
              @click="handleViewDetail(record as FailedMessageRecord)"
            >
              <template #icon><EyeOutlined /></template>
              查看
            </a-button>
          </template>
        </template>
      </a-table>

      <div class="mt-4 flex justify-end">
        <a-pagination
          :current="store.pagination.page"
          :page-size="store.pagination.per_page"
          :total="store.pagination.total"
          show-size-changer
          show-quick-jumper
          :show-total="(total: number) => `共 ${total} 条`"
          @change="handlePageChange"
        />
      </div>
    </a-card>

    <!-- Detail drawer -->
    <a-drawer
      title="失败消息详情"
      :open="drawerVisible"
      :width="720"
      @close="drawerVisible = false"
    >
      <a-spin :spinning="drawerLoading">
        <template v-if="detail">
          <!-- 基本信息 -->
          <a-descriptions title="基本信息" :column="2" bordered class="mb-4">
            <a-descriptions-item label="错误 ID">{{ detail.error_id }}</a-descriptions-item>
            <a-descriptions-item label="数据类型">
              <a-tag :color="dataTypeColorMap[detail.data_type] || 'default'">
                {{ dataTypeLabelMap[detail.data_type] || detail.data_type }}
              </a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="平台">
              {{ store.platformMap.get(detail.platform_id) || detail.platform }}
            </a-descriptions-item>
            <a-descriptions-item label="重试次数">{{ detail.retry_count }}</a-descriptions-item>
            <a-descriptions-item label="失败时间">
              {{ formatTime(detail.failed_at) }}
            </a-descriptions-item>
            <a-descriptions-item label="消息 ID">{{ detail.message_id }}</a-descriptions-item>
          </a-descriptions>

          <!-- 错误信息 -->
          <a-descriptions title="错误信息" :column="1" bordered class="mb-4">
            <a-descriptions-item label="错误类型">{{ detail.error_type }}</a-descriptions-item>
            <a-descriptions-item label="错误码">
              {{ detail.error_code || '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="错误信息">{{ detail.error_message }}</a-descriptions-item>
          </a-descriptions>

          <!-- 错误堆栈 -->
          <h3 class="text-base font-medium mb-2">错误堆栈</h3>
          <pre
            v-if="detail.error_trace"
            class="m-0 p-3 text-xs max-h-80 overflow-auto bg-gray-50 rounded border mb-4"
          >{{ detail.error_trace }}</pre>
          <p v-else class="text-gray-400 mb-4">暂无堆栈信息</p>

          <!-- 原始消息 -->
          <h3 class="text-base font-medium mb-2">原始消息</h3>
          <pre
            v-if="detail.original_message"
            class="m-0 p-3 text-xs max-h-80 overflow-auto bg-gray-50 rounded border"
          >{{ JSON.stringify(detail.original_message, null, 2) }}</pre>
          <p v-else class="text-gray-400">暂无消息数据</p>
        </template>
      </a-spin>
    </a-drawer>
  </div>
</template>
