<template>
  <div class="records-page">
    <div class="records-header">
      <div>
        <h2 class="ops-page-title">检测记录</h2>
        <div class="records-header__meta">全局检测审计与命中证据搜索</div>
      </div>
      <a-button :loading="loading" @click="reload">
        <template #icon><ReloadOutlined /></template>
        刷新
      </a-button>
    </div>

    <div class="ops-card">
      <div class="ops-toolbar records-toolbar">
        <a-input-number
          v-model:value="filter.tenant_id"
          class="number-filter"
          :min="1"
          placeholder="租户 ID"
        />
        <a-input-number
          v-model:value="filter.article_id"
          class="number-filter"
          :min="1"
          placeholder="文章 ID"
        />
        <a-select
          v-model:value="filter.decision"
          class="decision-filter"
          :options="decisionOptions"
          allow-clear
          placeholder="判定"
        />
        <a-button @click="onFilter">查询</a-button>
      </div>

      <a-table
        :columns="columns"
        :data-source="rows"
        :loading="loading"
        :pagination="pagination"
        row-key="record_id"
        @change="onTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'record'">
            <div class="primary-cell">
              <strong>记录 #{{ record.record_id }}</strong>
              <span>文章 #{{ record.article_id || '--' }} · 版本 #{{ record.article_version_id || '--' }}</span>
            </div>
          </template>
          <template v-else-if="column.key === 'decision'">
            <a-tag :color="decisionColor(record.decision)">
              {{ decisionLabel(record.decision) }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'level'">
            <a-tag :color="levelColor(record.highest_level)">
              {{ levelLabel(record.highest_level) }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'mode'">
            <a-tag :color="modeColor(record.enforcement_mode)">
              {{ modeLabel(record.enforcement_mode) }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'violations'">
            <a-space wrap>
              <a-tag
                v-for="violation in record.violations.slice(0, 3)"
                :key="`${record.record_id}-${violation.id}-${violation.matched_text}`"
                :color="levelColor(violation.level)"
              >
                {{ violation.matched_text }}
              </a-tag>
              <a-tag v-if="record.violations.length > 3">+{{ record.violations.length - 3 }}</a-tag>
              <span v-if="record.violations.length === 0" class="muted-text">无命中</span>
            </a-space>
          </template>
          <template v-else-if="column.key === 'manual'">
            <a-tag :color="reviewStatusColor(record.manual_review_status)">
              {{ reviewStatusLabel(record.manual_review_status) }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'checked_at'">
            {{ formatDate(record.checked_at) }}
          </template>
          <template v-else-if="column.key === 'duration'">
            {{ record.duration_ms }}ms
          </template>
        </template>
      </a-table>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { ComplianceCheckResult } from '@geo/shared-types'
import { ReloadOutlined } from '@ant-design/icons-vue'
import type { TableColumnsType, TablePaginationConfig } from 'ant-design-vue'
import dayjs from 'dayjs'
import { computed, onMounted, reactive, ref } from 'vue'

import {
  decisionColor,
  decisionLabel,
  levelColor,
  levelLabel,
  modeColor,
  modeLabel,
  reviewStatusColor,
  reviewStatusLabel,
} from '@/lib/compliance-display'
import { complianceApi } from '@/lib/compliance'
import { showOpsError } from '@/lib/errors'

const rows = ref<ComplianceCheckResult[]>([])
const loading = ref(false)
const page = ref(1)
const pageSize = ref(50)
const total = ref(0)
const filter = reactive({
  tenant_id: null as number | null,
  article_id: null as number | null,
  decision: undefined as string | undefined,
})

const decisionOptions = [
  { label: '通过', value: 'pass' },
  { label: '待确认', value: 'needs_ack' },
  { label: '阻断', value: 'block' },
]

const columns: TableColumnsType<ComplianceCheckResult> = [
  { title: '记录', key: 'record', width: 230 },
  { title: '判定', key: 'decision', width: 100 },
  { title: '最高等级', key: 'level', width: 110 },
  { title: '模式', key: 'mode', width: 120 },
  { title: '命中', key: 'violations' },
  { title: '人工审阅', key: 'manual', width: 120 },
  { title: '耗时', key: 'duration', width: 90 },
  { title: '检测时间', key: 'checked_at', width: 170 },
]

const pagination = computed<TablePaginationConfig>(() => ({
  current: page.value,
  pageSize: pageSize.value,
  total: total.value,
  showSizeChanger: true,
  pageSizeOptions: ['20', '50', '100'],
}))

async function reload() {
  loading.value = true
  try {
    const result = await complianceApi.records({
      tenant_id: filter.tenant_id ?? undefined,
      article_id: filter.article_id ?? undefined,
      decision: filter.decision,
      page: page.value,
      page_size: pageSize.value,
    })
    rows.value = result.items
    total.value = result.total
  } catch (error) {
    showError(error)
  } finally {
    loading.value = false
  }
}

function onFilter() {
  page.value = 1
  void reload()
}

function onTableChange(pag: TablePaginationConfig) {
  page.value = pag.current ?? 1
  pageSize.value = pag.pageSize ?? 50
  void reload()
}

function formatDate(value: string): string {
  return dayjs(value).format('YYYY-MM-DD HH:mm')
}

function showError(error: unknown) {
  showOpsError(error)
}

onMounted(() => {
  void reload()
})
</script>

<style scoped>
.records-page {
  display: flex;
  flex-direction: column;
  gap: 18px;
}

.records-header {
  display: flex;
  justify-content: space-between;
  gap: 16px;
  align-items: flex-start;
}

.records-header__meta {
  color: #64748b;
  font-size: 13px;
}

.number-filter {
  width: 140px;
}

.decision-filter {
  width: 140px;
}

.primary-cell {
  display: flex;
  flex-direction: column;
  gap: 3px;
}

.primary-cell span,
.muted-text {
  color: #94a3b8;
  font-size: 12px;
}
</style>
