<template>
  <div class="container">
    <search-table
      :form-model="formModel"
      :form-items="formItems"
      :data="tableData"
      :columns="columns"
      :loading="loading"
      :pagination="clientPagination"
      title="Trap 字典"
      search-button-text="查询"
      reset-button-text="重置"
      :show-download="false"
      @update:form-model="handleFormModelUpdate"
      @search="handleSearch"
      @reset="handleReset"
      @page-change="handlePageChange"
      @page-size-change="handlePageSizeChange"
      @refresh="fetchList"
    >
      <template #toolbar-left>
        <a-button type="primary" @click="openCreate">
          <template #icon><icon-plus /></template>
          新建条目
        </a-button>
      </template>
      <template #enabled="{ record }">
        <a-tag :color="record.enabled ? 'green' : 'red'">{{ record.enabled ? '启用' : '禁用' }}</a-tag>
      </template>
      <template #severity_code="{ record }">
        <a-tag :color="severityColor(record.severity_code)">{{ severityLabel(record.severity_code) }}</a-tag>
      </template>
      <template #operations="{ record }">
        <a-space>
          <a-button type="text" size="small" @click="openEdit(record)">编辑</a-button>
          <a-button type="text" size="small" status="danger" @click="handleDelete(record)">删除</a-button>
        </a-space>
      </template>
    </search-table>

    <a-modal
      v-model:visible="modalVisible"
      :title="editingId ? `编辑字典 #${editingId}` : '新建 Trap 字典条目'"
      width="640px"
      :confirm-loading="submitting"
      @ok="submitForm"
      @cancel="modalVisible = false"
    >
      <a-form ref="formRef" :model="formData" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="vendor" label="厂商">
              <a-input v-model="formData.vendor" placeholder="H3C / Huawei / Cisco" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="oid" label="精确 OID">
              <a-input v-model="formData.oid" placeholder="可选，优先于 OID 前缀" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item field="oid_prefix" label="OID 前缀" :rules="[{ required: true, message: '必填' }]">
          <a-input v-model="formData.oid_prefix" placeholder="唯一前缀" />
        </a-form-item>
        <a-form-item field="name" label="名称">
          <a-input v-model="formData.name" placeholder="字典名称" />
        </a-form-item>
        <a-form-item field="title" label="标题" :rules="[{ required: true, message: '必填' }]">
          <a-input v-model="formData.title" />
        </a-form-item>
        <a-form-item field="description" label="描述">
          <a-textarea v-model="formData.description" :rows="3" />
        </a-form-item>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="severity_code" label="严重级别代码">
              <a-select
                v-model="formData.severity_code"
                placeholder="请选择告警级别"
                :loading="severityLoading"
                allow-search
                :filter-option="false"
                @search="handleSeveritySearch"
              >
                <a-option v-for="item in severityOptions" :key="item.code" :value="item.code">
                  {{ item.name }}
                </a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="enabled" label="启用">
              <a-switch v-model="formData.enabled" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item field="recovery_message" label="恢复说明">
          <a-textarea v-model="formData.recovery_message" :rows="2" />
        </a-form-item>
        <a-form-item field="severity_mapping_json" label="级别映射 JSON">
          <a-textarea v-model="formData.severity_mapping_json" :rows="2" placeholder='{"down":"major","up":"info"}' />
        </a-form-item>
        <a-form-item field="parse_expression" label="解析表达式">
          <a-textarea v-model="formData.parse_expression" :rows="2" placeholder="用于提取 varbind 中的接口、状态等字段" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { computed, reactive, ref } from 'vue'
import { Message, Modal } from '@arco-design/web-vue'
import { IconPlus } from '@arco-design/web-vue/es/icon'
import { fetchSeverityOptions, type AlertSeverity } from '@/api/ops/alertTemplate'
import type { FormItem } from '@/components/search-form/types'
import SearchTable from '@/components/search-table/index.vue'
import type { TableColumnData } from '@arco-design/web-vue/es/table/interface'
import type { FormInstance } from '@arco-design/web-vue'
import {
  createTrapDictionary,
  deleteTrapDictionary,
  fetchTrapDictionary,
  unwrapLogsPayload,
  updateTrapDictionary,
  type TrapDictionaryEntry,
} from '@/api/ops/logs'

const loading = ref(false)
const tableData = ref<TrapDictionaryEntry[]>([])
const allRows = ref<TrapDictionaryEntry[]>([])
const formModel = ref({ keyword: '' })

function handleFormModelUpdate(v: Record<string, unknown>) {
  formModel.value = v as { keyword: string }
}
const modalVisible = ref(false)
const submitting = ref(false)
const editingId = ref<number | null>(null)
const formRef = ref<FormInstance>()

const emptyForm = (): TrapDictionaryEntry => ({
  oid_prefix: '',
  vendor: '',
  oid: '',
  name: '',
  title: '',
  description: '',
  severity_code: '',
  severity_mapping_json: '',
  parse_expression: '',
  recovery_message: '',
  enabled: true,
})

const formData = reactive<TrapDictionaryEntry>(emptyForm())

const severityOptions = ref<AlertSeverity[]>([])
const baseSeverityOptions = ref<AlertSeverity[]>([])
const severityLoading = ref(false)
let severitySearchTimer: ReturnType<typeof setTimeout> | null = null

async function loadSeverityOptions(keyword?: string) {
  severityLoading.value = true
  try {
    const res: any = await fetchSeverityOptions({
      keyword,
      enabled: 'true',
    })
    const list = Array.isArray(res?.details) ? res.details : res?.details?.data || res?.details?.list || res?.data || res

    const fetchedOptions = Array.isArray(list) ? list : []

    const isBaseLoad = !keyword || keyword.trim().length === 0
    if (isBaseLoad) {
      baseSeverityOptions.value = fetchedOptions
    }

    const selectedCode = formData.severity_code
    const selectedOptions = baseSeverityOptions.value.filter((s) => s.code === selectedCode)

    const mergedMap = new Map<string, AlertSeverity>()
    ;[...fetchedOptions, ...selectedOptions].forEach((item) => {
      if (item?.code) mergedMap.set(item.code, item)
    })
    severityOptions.value = Array.from(mergedMap.values())
  } catch (e: any) {
    console.error('加载告警级别失败:', e)
    severityOptions.value = []
  } finally {
    severityLoading.value = false
  }
}

function handleSeveritySearch(keyword: string) {
  if (severitySearchTimer) {
    clearTimeout(severitySearchTimer)
  }

  severitySearchTimer = setTimeout(() => {
    loadSeverityOptions(keyword)
  }, 300)
}

const clientPagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
})

const formItems = computed<FormItem[]>(() => [{ field: 'keyword', label: '关键词', type: 'input', placeholder: 'OID / 标题', span: 8 }])

const columns = computed<TableColumnData[]>(() => [
  { title: 'ID', dataIndex: 'id', width: 72 },
  { title: '厂商', dataIndex: 'vendor', width: 100, ellipsis: true, tooltip: true },
  { title: '精确 OID', dataIndex: 'oid', ellipsis: true, tooltip: true },
  { title: 'OID 前缀', dataIndex: 'oid_prefix', ellipsis: true, tooltip: true },
  { title: '名称', dataIndex: 'name', ellipsis: true, tooltip: true },
  { title: '标题', dataIndex: 'title', ellipsis: true, tooltip: true },
  { title: '级别', dataIndex: 'severity_code', slotName: 'severity_code', width: 110 },
  { title: '启用', dataIndex: 'enabled', slotName: 'enabled', width: 88 },
  { title: '描述', dataIndex: 'description', ellipsis: true, tooltip: true },
  { title: '操作', slotName: 'operations', width: 160, fixed: 'right' },
])

function severityMeta(code: string) {
  const key = (code || '').trim().toLowerCase()
  if (!key) return null
  return (
    severityOptions.value.find(
      (item) =>
        String(item.code || '')
          .trim()
          .toLowerCase() === key
    ) || null
  )
}

function severityLabel(code: string) {
  const meta = severityMeta(code)
  if (meta?.name) return meta.name
  const key = (code || '').toLowerCase()
  if (!key) return '-'
  if (['critical', 'fatal', 'emergency', 'emerg', 'alert'].includes(key)) return '严重'
  if (['error', 'err'].includes(key)) return '错误'
  if (['warning', 'warn'].includes(key)) return '警告'
  if (['notice', 'info', 'informational'].includes(key)) return '信息'
  if (['debug', 'trace'].includes(key)) return '调试'
  return code
}

function severityColor(code: string) {
  const meta = severityMeta(code)
  return meta?.color || 'arcoblue'
}

function applyFilter(list: TrapDictionaryEntry[]) {
  const kw = formModel.value.keyword?.trim()
  if (!kw) return list
  return list.filter(
    (r) =>
      r.oid_prefix?.includes(kw) ||
      r.oid?.includes(kw) ||
      r.vendor?.includes(kw) ||
      r.name?.includes(kw) ||
      r.title?.includes(kw) ||
      r.description?.includes(kw)
  )
}

function slicePage(list: TrapDictionaryEntry[]) {
  const start = (clientPagination.current - 1) * clientPagination.pageSize
  tableData.value = list.slice(start, start + clientPagination.pageSize)
}

async function fetchList() {
  loading.value = true
  try {
    const res: any = await fetchTrapDictionary()
    const payload = unwrapLogsPayload(res)
    const items = (payload?.items ?? []) as TrapDictionaryEntry[]
    allRows.value = items
    const filtered = applyFilter(items)
    clientPagination.total = filtered.length
    slicePage(filtered)
    if (typeof res.code === 'number' && res.code !== 0) {
      Message.error(res.message || res.msg || '加载失败')
    }
  } catch (e: any) {
    Message.error(e?.message || '加载失败')
    allRows.value = []
    tableData.value = []
    clientPagination.total = 0
  } finally {
    loading.value = false
  }
}

function handleSearch() {
  clientPagination.current = 1
  const filtered = applyFilter(allRows.value)
  clientPagination.total = filtered.length
  slicePage(filtered)
}

function handleReset() {
  formModel.value = { keyword: '' }
  clientPagination.current = 1
  const filtered = applyFilter(allRows.value)
  clientPagination.total = filtered.length
  slicePage(filtered)
}

function handlePageChange(c: number) {
  clientPagination.current = c
  slicePage(applyFilter(allRows.value))
}

function handlePageSizeChange(size: number) {
  clientPagination.pageSize = size
  clientPagination.current = 1
  slicePage(applyFilter(allRows.value))
}

function openCreate() {
  editingId.value = null
  Object.assign(formData, emptyForm())
  modalVisible.value = true
}

function openEdit(row: TrapDictionaryEntry) {
  if (!row.id) return
  editingId.value = row.id
  Object.assign(formData, {
    vendor: row.vendor ?? '',
    oid: row.oid ?? '',
    oid_prefix: row.oid_prefix,
    name: row.name ?? '',
    title: row.title,
    description: row.description ?? '',
    severity_code: row.severity_code ?? '',
    severity_mapping_json: row.severity_mapping_json ?? '',
    parse_expression: row.parse_expression ?? '',
    recovery_message: row.recovery_message ?? '',
    enabled: row.enabled,
  })
  modalVisible.value = true
}

async function submitForm() {
  const err = await formRef.value?.validate()
  if (err) return
  submitting.value = true
  try {
    if (editingId.value != null) {
      const res: any = await updateTrapDictionary(editingId.value, { ...formData })
      if (typeof res.code === 'number' && res.code !== 0) {
        Message.error(res.message || res.msg || '保存失败')
        return
      }
      Message.success('已保存')
    } else {
      const res: any = await createTrapDictionary({ ...formData })
      if (typeof res.code === 'number' && res.code !== 0) {
        Message.error(res.message || res.msg || '创建失败')
        return
      }
      Message.success('已创建')
    }
    modalVisible.value = false
    await fetchList()
  } catch (e: any) {
    Message.error(e?.message || '请求失败')
  } finally {
    submitting.value = false
  }
}

function handleDelete(row: TrapDictionaryEntry) {
  if (!row.id) return
  Modal.confirm({
    title: '确认删除',
    content: `删除 OID 前缀「${row.oid_prefix}」？`,
    onOk: async () => {
      try {
        const res: any = await deleteTrapDictionary(row.id!)
        if (typeof res.code === 'number' && res.code !== 0) {
          Message.error(res.message || res.msg || '删除失败')
          return
        }
        Message.success('已删除')
        await fetchList()
      } catch (e: any) {
        Message.error(e?.message || '删除失败')
      }
    },
  })
}

fetchList()
loadSeverityOptions()
</script>

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

<style scoped lang="less">
.container {
  padding: 16px;
}
</style>
