<template>
  <div class="anomalies-tab">
    <search-table
      :form-model="formModel"
      :form-items="formItems"
      :data="tableData"
      :columns="columns"
      :loading="loading"
      :pagination="pagination"
      title="IP异常记录"
      search-button-text="查询"
      reset-button-text="重置"
      @update:form-model="handleFormModelUpdate"
      @search="handleSearch"
      @reset="handleReset"
      @page-change="handlePageChange"
      @refresh="handleRefresh"
    >
      <template #anomaly_type="{ record }">
        <a-tag :color="getAnomalyTypeColor(record.anomaly_type)" bordered>
          {{ getAnomalyTypeText(record.anomaly_type) }}
        </a-tag>
      </template>

      <template #status="{ record }">
        <a-tag :color="record.status === 'resolved' ? 'green' : 'orange'" bordered>
          {{ record.status === 'resolved' ? '已处理' : '待处理' }}
        </a-tag>
      </template>

      <template #detected_at="{ record }">
        {{ formatDateTime(record.detected_at) }}
      </template>

      <template #actions="{ record }">
        <a-button type="text" size="small" @click="handleDetail(record)">详情</a-button>
      </template>
    </search-table>

    <a-modal v-model:visible="showDetailDialog" title="异常详情" :width="700" :footer="false">
      <a-descriptions :column="2" bordered>
        <a-descriptions-item label="IP地址">{{ currentDetail?.ip_address }}</a-descriptions-item>
        <a-descriptions-item label="所属子网">{{ currentDetail?.subnet_name }}</a-descriptions-item>
        <a-descriptions-item label="异常类型">
          <a-tag :color="getAnomalyTypeColor(currentDetail?.anomaly_type)" bordered>
            {{ getAnomalyTypeText(currentDetail?.anomaly_type) }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="状态">
          <a-tag :color="currentDetail?.status === 'resolved' ? 'green' : 'orange'" bordered>
            {{ currentDetail?.status === 'resolved' ? '已处理' : '待处理' }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="发现时间">{{ formatDateTime(currentDetail?.detected_at) }}</a-descriptions-item>
        <a-descriptions-item label="备注">{{ currentDetail?.remark || '-' }}</a-descriptions-item>
      </a-descriptions>
      <div v-if="currentDetail?.detail_json" class="detail-section">
        <div class="detail-title">详细信息</div>
        <pre class="detail-content">{{ formatJson(currentDetail?.detail_json) }}</pre>
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue'
import SearchTable from '@/components/search-table/index.vue'
import {
  fetchIPAnomalyList,
  fetchIPSubnetList,
  type IPAnomalyItem,
  type IPAnomalyListParams,
  type IPSubnetItem,
} from '@/api/ops/ipam'
import type { FormItem } from '@/components/search-form/types'
import type { TableColumnData } from '@arco-design/web-vue/es/table/interface'

const loading = ref(false)
const tableData = ref<IPAnomalyItem[]>([])
const subnets = ref<IPSubnetItem[]>([])
const showDetailDialog = ref(false)
const currentDetail = ref<IPAnomalyItem | null>(null)

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

const formModel = reactive({
  keyword: '',
  subnet_id: '',
  anomaly_type: '',
  status: '',
})

const formItems = computed<FormItem[]>(() => [
  {
    field: 'keyword',
    label: '关键词',
    type: 'input',
    placeholder: '请输入IP地址',
    span: 6,
  },
  {
    field: 'subnet_id',
    label: '子网',
    type: 'select',
    placeholder: '全部子网',
    options: subnets.value.map((s) => ({ label: `${s.name} (${s.cidr})`, value: s.id })),
    span: 6,
  },
  {
    field: 'anomaly_type',
    label: '异常类型',
    type: 'select',
    placeholder: '全部类型',
    options: [
      { label: 'IP扫描异常', value: 'scan_anomaly' },
      { label: 'MAC地址变更', value: 'mac_change' },
      { label: '未知设备', value: 'unknown_device' },
      { label: 'IP地址泄漏', value: 'ip_leak' },
    ],
    span: 6,
  },
  {
    field: 'status',
    label: '状态',
    type: 'select',
    placeholder: '全部状态',
    options: [
      { label: '待处理', value: 'pending' },
      { label: '已处理', value: 'resolved' },
    ],
    span: 6,
  },
])

const columns: TableColumnData[] = [
  { title: 'IP地址', dataIndex: 'ip_address', width: 150 },
  { title: '异常类型', dataIndex: 'anomaly_type', slotName: 'anomaly_type', width: 120, align: 'center' },
  { title: '所属子网', dataIndex: 'subnet_name', width: 150 },
  { title: '发现时间', dataIndex: 'detected_at', slotName: 'detected_at', width: 180 },
  { title: '状态', dataIndex: 'status', slotName: 'status', width: 100, align: 'center' },
  { title: '备注', dataIndex: 'remark', width: 200 },
  { title: '操作', dataIndex: 'actions', slotName: 'actions', width: 80, fixed: 'right' },
]

const loadSubnets = async () => {
  try {
    const response = await fetchIPSubnetList({ size: 1000 })
    if (response && response.code === 0) {
      subnets.value = response.details?.data || response.data || []
    }
  } catch (error) {
    console.error('Failed to load subnets:', error)
  }
}

const loadData = async () => {
  loading.value = true
  try {
    const params: IPAnomalyListParams = {
      page: pagination.current,
      size: pagination.pageSize,
      ...formModel,
    }

    Object.keys(params).forEach((key) => {
      if (!params[key as keyof IPAnomalyListParams]) {
        delete params[key as keyof IPAnomalyListParams]
      }
    })

    const response = await fetchIPAnomalyList(params)
    if (response && response.code === 0) {
      tableData.value = response.details?.data || response.data || []
      pagination.total = response.details?.total || response.total || 0
    }
  } catch (error) {
    console.error('Failed to load anomalies:', error)
  } finally {
    loading.value = false
  }
}

const handleFormModelUpdate = (model: typeof formModel) => {
  Object.assign(formModel, model)
}

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

const handleReset = () => {
  Object.assign(formModel, {
    keyword: '',
    subnet_id: '',
    anomaly_type: '',
    status: '',
  })
  pagination.current = 1
  loadData()
}

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

const handleRefresh = () => {
  loadData()
}

const handleDetail = (record: IPAnomalyItem) => {
  currentDetail.value = record
  showDetailDialog.value = true
}

const getAnomalyTypeColor = (type?: string) => {
  const colorMap: Record<string, string> = {
    scan_anomaly: 'red',
    mac_change: 'orange',
    unknown_device: 'purple',
    ip_leak: 'arcoblue',
  }
  return colorMap[type || ''] || 'gray'
}

const getAnomalyTypeText = (type?: string) => {
  const textMap: Record<string, string> = {
    scan_anomaly: 'IP扫描异常',
    mac_change: 'MAC地址变更',
    unknown_device: '未知设备',
    ip_leak: 'IP地址泄漏',
  }
  return textMap[type || ''] || type || '-'
}

const formatDateTime = (datetime?: string) => {
  if (!datetime) return '-'
  return new Date(datetime).toLocaleString('zh-CN')
}

const formatJson = (jsonStr?: string) => {
  if (!jsonStr) return '{}'
  try {
    return JSON.stringify(JSON.parse(jsonStr), null, 2)
  } catch {
    return jsonStr
  }
}

onMounted(() => {
  loadSubnets()
  loadData()
})
</script>

<style scoped lang="less">
.detail-section {
  margin-top: 16px;
}

.detail-title {
  font-weight: 500;
  margin-bottom: 8px;
  color: var(--color-text-1);
}

.detail-content {
  background: var(--color-fill-1);
  padding: 12px;
  border-radius: 4px;
  font-size: 12px;
  max-height: 300px;
  overflow: auto;
  white-space: pre-wrap;
  word-break: break-all;
}
</style>
