<script setup lang="ts">
import { ReloadOutlined } from '@ant-design/icons-vue'
import { useMqStatusStore } from '@/stores/mq-status'
import type { MqQueueInfo, MqQueueStatusEnum, MqQueueType } from '@/types/api'

const store = useMqStatusStore()

const statusTagMap: Record<MqQueueStatusEnum, { text: string; color: string }> = {
  high_load: { text: '高负载', color: 'red' },
  processing: { text: '处理中', color: 'orange' },
  active: { text: '活跃', color: 'green' },
  empty: { text: '空闲', color: 'default' },
  error: { text: '异常', color: 'red' },
}

const queueTypeOptions = [
  { label: '全部', value: '' },
  { label: 'Orders', value: 'orders' },
  { label: 'Products', value: 'products' },
  { label: 'Refunds', value: 'refunds' },
  { label: 'Inventory', value: 'inventory' },
]

const queueColumns = [
  { title: '队列名称', dataIndex: 'queue', key: 'queue' },
  { title: '消息数', dataIndex: 'messages', key: 'messages' },
  { title: '消费者数', dataIndex: 'consumers', key: 'consumers' },
  { title: '状态', key: 'status' },
]

const filterValue = computed({
  get: () => store.queueType ?? '',
  set: (val: string) => {
    store.queueType = val === '' ? undefined : (val as MqQueueType)
  },
})

const showErrorQueue = computed(() => {
  if (!store.statusData) return false
  return !Array.isArray(store.statusData.error_queue)
})

const errorQueueRows = computed<MqQueueInfo[]>(() => {
  if (!store.statusData || Array.isArray(store.statusData.error_queue)) return []
  return [store.statusData.error_queue]
})

function formatValue(val: number | string): string {
  return typeof val === 'number' ? String(val) : val
}

function handleFilterChange() {
  store.fetchStatus()
}

function handleRefresh() {
  store.fetchStatus()
}

onMounted(() => {
  store.fetchStatus()
})
</script>

<template>
  <div>
    <!-- 标题行 -->
    <div class="flex items-center justify-between mb-4">
      <h2 class="text-xl font-semibold m-0">消息队列状态</h2>
      <a-space>
        <a-select
          v-model:value="filterValue"
          :options="queueTypeOptions"
          style="width: 160px"
          @change="handleFilterChange"
        />
        <a-button type="primary" @click="handleRefresh">
          <template #icon><ReloadOutlined /></template>
          刷新
        </a-button>
      </a-space>
    </div>

    <!-- 错误提示 -->
    <a-alert
      v-if="store.errorMessage"
      type="error"
      :message="store.errorMessage"
      show-icon
      class="mb-4"
    />

    <a-spin :spinning="store.loading">
      <template v-if="store.statusData">
        <!-- 统计卡片 -->
        <a-row :gutter="16" class="mb-4">
          <a-col :span="8">
            <a-card>
              <a-statistic
                title="总消息数"
                :value="store.statusData.summary.total_messages"
              />
            </a-card>
          </a-col>
          <a-col :span="8">
            <a-card>
              <a-statistic
                title="总消费者数"
                :value="store.statusData.summary.total_consumers"
              />
            </a-card>
          </a-col>
          <a-col :span="8">
            <a-card>
              <a-statistic
                title="队列健康"
                :value="`${store.healthySummary.healthy}/${store.healthySummary.total}`"
              />
            </a-card>
          </a-col>
        </a-row>

        <!-- 业务队列 -->
        <a-card title="业务队列" class="mb-4">
          <a-table
            :columns="queueColumns"
            :data-source="store.statusData.business_queues"
            :pagination="false"
            row-key="queue"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'messages'">
                {{ formatValue((record as MqQueueInfo).messages) }}
              </template>
              <template v-else-if="column.key === 'consumers'">
                {{ formatValue((record as MqQueueInfo).consumers) }}
              </template>
              <template v-else-if="column.key === 'status'">
                <a-tag :color="statusTagMap[(record as MqQueueInfo).status]?.color || 'default'">
                  {{ statusTagMap[(record as MqQueueInfo).status]?.text || (record as MqQueueInfo).status }}
                </a-tag>
              </template>
            </template>
          </a-table>
        </a-card>

        <!-- 重试队列 -->
        <a-card title="重试队列" class="mb-4">
          <a-table
            :columns="queueColumns"
            :data-source="store.statusData.retry_queues"
            :pagination="false"
            row-key="queue"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'messages'">
                {{ formatValue((record as MqQueueInfo).messages) }}
              </template>
              <template v-else-if="column.key === 'consumers'">
                {{ formatValue((record as MqQueueInfo).consumers) }}
              </template>
              <template v-else-if="column.key === 'status'">
                <a-tag :color="statusTagMap[(record as MqQueueInfo).status]?.color || 'default'">
                  {{ statusTagMap[(record as MqQueueInfo).status]?.text || (record as MqQueueInfo).status }}
                </a-tag>
              </template>
            </template>
          </a-table>
        </a-card>

        <!-- 错误队列（仅未筛选时显示） -->
        <a-card v-if="showErrorQueue" title="错误队列" class="mb-4">
          <a-table
            :columns="queueColumns"
            :data-source="errorQueueRows"
            :pagination="false"
            row-key="queue"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'messages'">
                <span
                  :class="{ 'text-red-500 font-bold': typeof (record as MqQueueInfo).messages === 'number' && Number((record as MqQueueInfo).messages) > 0 }"
                >
                  {{ formatValue((record as MqQueueInfo).messages) }}
                </span>
              </template>
              <template v-else-if="column.key === 'consumers'">
                {{ formatValue((record as MqQueueInfo).consumers) }}
              </template>
              <template v-else-if="column.key === 'status'">
                <a-tag :color="statusTagMap[(record as MqQueueInfo).status]?.color || 'default'">
                  {{ statusTagMap[(record as MqQueueInfo).status]?.text || (record as MqQueueInfo).status }}
                </a-tag>
              </template>
            </template>
          </a-table>
        </a-card>

        <!-- 最后更新时间 -->
        <div class="text-gray-400 text-sm text-right">
          最后更新: {{ store.statusData.fetched_at }}
        </div>
      </template>
    </a-spin>
  </div>
</template>
