<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 #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-form-item field="name" label="名称" :rules="[{ required: true, message: '必填' }]">
          <a-input v-model="formData.name" />
        </a-form-item>
        <a-form-item field="enabled" label="启用">
          <a-switch v-model="formData.enabled" />
        </a-form-item>
        <a-form-item field="source_ip_cidr" label="源 IP / CIDR">
          <a-input v-model="formData.source_ip_cidr" placeholder="如 192.168.1.0/24" />
        </a-form-item>
        <a-form-item field="oid_prefix" label="OID 前缀">
          <a-input v-model="formData.oid_prefix" />
        </a-form-item>
        <a-form-item field="interface_hint" label="接口提示">
          <a-input v-model="formData.interface_hint" />
        </a-form-item>
        <a-form-item field="time_windows_json" label="时间窗 JSON" extra="后端约定的 JSON 字符串，可为空">
          <a-textarea v-model="formData.time_windows_json" :rows="4" placeholder="{}" />
        </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 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 {
  createTrapSuppression,
  deleteTrapSuppression,
  fetchTrapSuppressions,
  unwrapLogsPayload,
  updateTrapSuppression,
  type TrapShield,
} from '@/api/ops/logs'

const loading = ref(false)
const tableData = ref<TrapShield[]>([])
const allRows = ref<TrapShield[]>([])
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 = (): TrapShield => ({
  name: '',
  enabled: true,
  source_ip_cidr: '',
  oid_prefix: '',
  interface_hint: '',
  time_windows_json: '',
})

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

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

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

const columns = computed<TableColumnData[]>(() => [
  { title: 'ID', dataIndex: 'id', width: 72 },
  { title: '名称', dataIndex: 'name', ellipsis: true, tooltip: true },
  { title: '启用', dataIndex: 'enabled', slotName: 'enabled', width: 88 },
  { title: '源 IP/CIDR', dataIndex: 'source_ip_cidr', ellipsis: true, tooltip: true },
  { title: 'OID 前缀', dataIndex: 'oid_prefix', ellipsis: true, tooltip: true },
  { title: '接口提示', dataIndex: 'interface_hint', ellipsis: true, tooltip: true },
  { title: '操作', slotName: 'operations', width: 160, fixed: 'right' },
])

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

function slicePage(list: TrapShield[]) {
  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 fetchTrapSuppressions()
    const payload = unwrapLogsPayload(res)
    const items = (payload?.items ?? []) as TrapShield[]
    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: TrapShield) {
  if (!row.id) return
  editingId.value = row.id
  Object.assign(formData, {
    name: row.name,
    enabled: row.enabled,
    source_ip_cidr: row.source_ip_cidr ?? '',
    oid_prefix: row.oid_prefix ?? '',
    interface_hint: row.interface_hint ?? '',
    time_windows_json: row.time_windows_json ?? '',
  })
  modalVisible.value = true
}

async function submitForm() {
  const err = await formRef.value?.validate()
  if (err) return
  const tw = formData.time_windows_json?.trim()
  if (tw) {
    try {
      JSON.parse(tw)
    } catch {
      Message.warning('时间窗 JSON 格式无效')
      return
    }
  }
  submitting.value = true
  try {
    if (editingId.value != null) {
      const res: any = await updateTrapSuppression(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 createTrapSuppression({ ...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: TrapShield) {
  if (!row.id) return
  Modal.confirm({
    title: '确认删除',
    content: `删除「${row.name}」？`,
    onOk: async () => {
      try {
        const res: any = await deleteTrapSuppression(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()
</script>

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

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