<template>
  <div class="conflicts-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 #status="{ record }">
        <a-tag :color="record.status === 'resolved' ? 'green' : 'red'" bordered>
          {{ record.status === 'resolved' ? '已解决' : '未解决' }}
        </a-tag>
      </template>

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

      <template #resolved_at="{ record }">
        {{ record.resolved_at ? formatDateTime(record.resolved_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="MAC地址1">{{ currentDetail?.mac_address_1 }}</a-descriptions-item>
        <a-descriptions-item label="主机名1">{{ currentDetail?.hostname_1 }}</a-descriptions-item>
        <a-descriptions-item label="MAC地址2">{{ currentDetail?.mac_address_2 }}</a-descriptions-item>
        <a-descriptions-item label="主机名2">{{ currentDetail?.hostname_2 }}</a-descriptions-item>
        <a-descriptions-item label="发现时间">{{ formatDateTime(currentDetail?.detected_at) }}</a-descriptions-item>
        <a-descriptions-item label="解决时间">
          {{ currentDetail?.resolved_at ? formatDateTime(currentDetail?.resolved_at) : '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="状态">
          <a-tag :color="currentDetail?.status === 'resolved' ? 'green' : 'red'" bordered>
            {{ currentDetail?.status === 'resolved' ? '已解决' : '未解决' }}
          </a-tag>
        </a-descriptions-item>
      </a-descriptions>
      <div v-if="currentDetail?.evidence_json" class="evidence-section">
        <div class="evidence-title">证据信息</div>
        <pre class="evidence-content">{{ formatJson(currentDetail?.evidence_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 { fetchIPConflictList, fetchIPSubnetList, type IPConflictItem, type IPConflictListParams, 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<IPConflictItem[]>([])
const subnets = ref<IPSubnetItem[]>([])
const showDetailDialog = ref(false)
const currentDetail = ref<IPConflictItem | null>(null)

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

interface ConflictSearchForm {
  keyword: string
  subnet_id: number | ''
  status: string
}

const formModel = reactive<ConflictSearchForm>({
  keyword: '',
  subnet_id: '',
  status: '',
})

const formItems = computed<FormItem[]>(() => [
  {
    field: 'keyword',
    label: '关键词',
    type: 'input',
    placeholder: '请输入IP地址',
    span: 8,
  },
  {
    field: 'subnet_id',
    label: '子网',
    type: 'select',
    placeholder: '全部子网',
    options: subnets.value.map((s) => ({ label: `${s.name} (${s.cidr})`, value: s.id })),
    span: 8,
  },
  {
    field: 'status',
    label: '状态',
    type: 'select',
    placeholder: '全部状态',
    options: [
      { label: '未解决', value: 'unresolved' },
      { label: '已解决', value: 'resolved' },
    ],
    span: 8,
  },
])

const columns: TableColumnData[] = [
  { title: 'IP地址', dataIndex: 'ip_address', width: 150 },
  { title: 'MAC地址1', dataIndex: 'mac_address_1', width: 180 },
  { title: '主机名1', dataIndex: 'hostname_1', width: 150 },
  { title: 'MAC地址2', dataIndex: 'mac_address_2', width: 180 },
  { title: '主机名2', dataIndex: 'hostname_2', width: 150 },
  { title: '所属子网', dataIndex: 'subnet_name', width: 150 },
  { title: '发现时间', dataIndex: 'detected_at', slotName: 'detected_at', width: 180 },
  { title: '解决时间', dataIndex: 'resolved_at', slotName: 'resolved_at', width: 180 },
  { title: '状态', dataIndex: 'status', slotName: 'status', width: 100, align: 'center' },
  { 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 || []
    }
  } catch (error) {
    console.error('Failed to load subnets:', error)
  }
}

const loadData = async () => {
  loading.value = true
  try {
    const params: IPConflictListParams = {
      page: pagination.current,
      size: pagination.pageSize,
      keyword: formModel.keyword,
      subnet_id: formModel.subnet_id || undefined,
      status: formModel.status,
    }

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

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

const handleFormModelUpdate = (model: Record<string, unknown>) => {
  Object.assign(formModel, model)
}

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

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

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

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

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

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">
.evidence-section {
  margin-top: 16px;
}

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

.evidence-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>
