<template>
  <div class="collection-health-page">
    <a-row :gutter="16" class="summary-row">
      <a-col :xs="12" :lg="6">
        <a-card :bordered="false" class="summary-card">
          <div class="summary-label">筛选结果任务</div>
          <div class="summary-value">{{ pagination.total }}</div>
        </a-card>
      </a-col>
      <a-col :xs="12" :lg="6">
        <a-card :bordered="false" class="summary-card">
          <div class="summary-label">当前页正常</div>
          <div class="summary-value success">{{ okCount }}</div>
        </a-card>
      </a-col>
      <a-col :xs="12" :lg="6">
        <a-card :bordered="false" class="summary-card">
          <div class="summary-label">当前页失败</div>
          <div class="summary-value danger">{{ failedCount }}</div>
        </a-card>
      </a-col>
      <a-col :xs="12" :lg="6">
        <a-card :bordered="false" class="summary-card">
          <div class="summary-label">当前页未知</div>
          <div class="summary-value muted">{{ unknownCount }}</div>
        </a-card>
      </a-col>
    </a-row>

    <a-card :bordered="false" title="采集健康度">
      <template #extra>
        <a-button type="primary" @click="fetchData">
          <template #icon><icon-refresh /></template>
          刷新
        </a-button>
      </template>

      <a-form :model="filters" layout="inline" class="filter-form">
        <a-form-item field="keyword" label="关键字">
          <a-input v-model="filters.keyword" allow-clear placeholder="UID / 标识 / 错误" />
        </a-form-item>
        <a-form-item field="resource_category" label="资源分类">
          <a-select v-model="filters.resource_category" allow-clear placeholder="全部">
            <a-option value="host">主机</a-option>
            <a-option value="database">数据库</a-option>
            <a-option value="middleware">中间件</a-option>
            <a-option value="network">网络</a-option>
            <a-option value="url">URL</a-option>
            <a-option value="security">安全</a-option>
            <a-option value="storage">存储</a-option>
            <a-option value="room_device">机房设备</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="status" label="状态">
          <a-select v-model="filters.status" allow-clear placeholder="全部">
            <a-option value="ok">正常</a-option>
            <a-option value="failed">失败</a-option>
            <a-option value="unknown">未知</a-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button @click="resetFilters">重置</a-button>
            <a-button type="primary" @click="handleSearch">
              <template #icon><icon-search /></template>
              查询
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>

      <a-table
        row-key="id"
        :loading="loading"
        :data="rows"
        :columns="columns"
        :pagination="pagination"
        @page-change="handlePageChange"
        @page-size-change="handlePageSizeChange"
      >
        <template #resource_uid="{ record }">
          <a-typography-text copyable>{{ record.resource_uid }}</a-typography-text>
        </template>
        <template #last_status="{ record }">
          <a-tag :color="statusColor(record.last_status)">{{ statusText(record.last_status) }}</a-tag>
        </template>
        <template #schedule_interval="{ record }">{{ record.schedule_interval }}s</template>
        <template #last_sample_time="{ record }">{{ formatTime(record.last_sample_time) }}</template>
        <template #last_error="{ record }">
          <span class="error-text">{{ record.last_error || '-' }}</span>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { Message } from '@arco-design/web-vue'
import { IconRefresh, IconSearch } from '@arco-design/web-vue/es/icon'
import type { TableColumnData } from '@arco-design/web-vue/es/table/interface'
import { fetchCollectionStatus, type ControlCollectionStatus } from '@/api/ops/dcControl'

const loading = ref(false)
const rows = ref<ControlCollectionStatus[]>([])

const filters = reactive({
  keyword: '',
  resource_category: undefined as string | undefined,
  status: undefined as string | undefined,
})

const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
  showTotal: true,
  showPageSize: true,
})

const columns: TableColumnData[] = [
  { title: '资源 UID', dataIndex: 'resource_uid', slotName: 'resource_uid', width: 230 },
  { title: '分类', dataIndex: 'resource_category', width: 110 },
  { title: '服务标识', dataIndex: 'service_identity', width: 180, ellipsis: true, tooltip: true },
  { title: '采集方式', dataIndex: 'collect_method', width: 110 },
  { title: '周期', dataIndex: 'schedule_interval', slotName: 'schedule_interval', width: 90 },
  { title: '状态', dataIndex: 'last_status', slotName: 'last_status', width: 100 },
  { title: '最近样本', dataIndex: 'last_sample_time', slotName: 'last_sample_time', width: 180 },
  { title: '最近错误', dataIndex: 'last_error', slotName: 'last_error', ellipsis: true, tooltip: true },
  { title: 'Trace ID', dataIndex: 'trace_id', width: 180, ellipsis: true, tooltip: true },
]

const okCount = computed(() => rows.value.filter((item) => item.last_status === 'ok').length)
const failedCount = computed(() => rows.value.filter((item) => item.last_status === 'failed').length)
const unknownCount = computed(() => rows.value.filter((item) => !['ok', 'failed'].includes(item.last_status)).length)

const statusColor = (status?: string) => {
  if (status === 'ok') return 'green'
  if (status === 'failed') return 'red'
  return 'gray'
}

const statusText = (status?: string) => {
  if (status === 'ok') return '正常'
  if (status === 'failed') return '失败'
  return '未知'
}

const formatTime = (value?: string) => {
  if (!value) return '-'
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) return value
  return date.toLocaleString()
}

const fetchData = async () => {
  loading.value = true
  try {
    const response = await fetchCollectionStatus({
      page: pagination.current,
      size: pagination.pageSize,
      keyword: filters.keyword,
      resource_category: filters.resource_category,
      status: filters.status,
    })
    rows.value = response.details?.data || []
    pagination.total = response.details?.total || 0
  } catch (error) {
    console.error('获取采集健康度失败:', error)
    Message.error('获取采集健康度失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.current = 1
  fetchData()
}

const resetFilters = () => {
  filters.keyword = ''
  filters.resource_category = undefined
  filters.status = undefined
  handleSearch()
}

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

const handlePageSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize
  pagination.current = 1
  fetchData()
}

onMounted(fetchData)
</script>

<script lang="ts">
export default {
  name: 'CollectionHealth',
}
</script>

<style scoped lang="less">
.collection-health-page {
  padding: 16px;
}

.summary-row,
.filter-form {
  margin-bottom: 16px;
}

.summary-card {
  height: 100%;
}

.summary-label {
  color: var(--color-text-3);
  font-size: 13px;
  margin-bottom: 8px;
}

.summary-value {
  color: var(--color-text-1);
  font-size: 24px;
  font-weight: 600;
  line-height: 1.2;
}

.summary-value.success {
  color: rgb(var(--green-6));
}

.summary-value.danger {
  color: rgb(var(--red-6));
}

.summary-value.muted {
  color: var(--color-text-3);
}

.error-text {
  color: var(--color-text-2);
}
</style>
