<template>
  <div class="container">
    <search-table
      :form-model="formModel"
      :form-items="formItems"
      :data="tableData"
      :columns="columns"
      :loading="loading"
      :pagination="pagination"
      title="网络设备数据采集管理"
      search-button-text="查询"
      reset-button-text="重置"
      @update:form-model="handleFormModelUpdate"
      @search="handleSearch"
      @reset="handleReset"
      @page-change="handlePageChange"
      @refresh="handleRefresh"
    >
      <template #toolbar-left>
        <a-space>
          <a-button type="primary" @click="handleAdd">
            <template #icon><icon-plus /></template>
            新增设备
          </a-button>
          <a-button type="outline" @click="handleRefresh">
            <template #icon><icon-refresh /></template>
            刷新状态
          </a-button>
        </a-space>
      </template>
      <template #category="{ record }">
        <a-tag color="arcoblue">{{ formatDeviceCategory(record.category) }}</a-tag>
      </template>
      <template #host_port="{ record }">{{ record.host || '-' }}:{{ record.port || '-' }}</template>
      <template #protocol="{ record }">
        <a-space>
          <a-tag color="purple">{{ String(record.protocol || '-').toUpperCase() }}</a-tag>
          <a-tag v-if="record.protocol === 'snmp'" color="orangered">{{ String(record.snmp_version || '-').toUpperCase() }}</a-tag>
        </a-space>
      </template>
      <template #interval="{ record }">{{ record.interval || 0 }} 秒</template>
      <template #enabled="{ record }">
        <a-tag :color="record.enabled ? 'green' : 'gray'">{{ record.enabled ? '已启用' : '已停用' }}</a-tag>
      </template>
      <template #status="{ record }">
        <a-tooltip :content="statusHint(record.status)">
          <a-tag :color="getStatusColor(record.status)">{{ getStatusText(record.status) }}</a-tag>
        </a-tooltip>
      </template>
      <template #response_time="{ record }">
        <span :style="{ color: getResponseTimeColor(record.response_time) }">{{ formatResponseTime(record.response_time) }}</span>
      </template>
      <template #last_check_time="{ record }">{{ formatTime(record.last_check_time) }}</template>
      <template #tags="{ record }">
        <a-tag v-for="(tag, idx) in parseTags(record.tags)" :key="idx" style="margin-right: 4px">{{ tag }}</a-tag>
        <span v-if="!parseTags(record.tags).length">-</span>
      </template>
      <template #actions="{ record }">
        <a-space>
          <a-dropdown trigger="hover">
            <a-button type="primary" size="small">
              管理
              <icon-down />
            </a-button>
            <template #content>
              <a-doption @click="handleDetail(record)">
                <template #icon>
                  <icon-eye />
                </template>
                详情
              </a-doption>
              <a-doption @click="handleEdit(record)">
                <template #icon>
                  <icon-edit />
                </template>
                编辑
              </a-doption>
              <a-doption @click="handleDelete(record)" style="color: rgb(var(--danger-6))">
                <template #icon>
                  <icon-delete />
                </template>
                删除
              </a-doption>
            </template>
          </a-dropdown>
        </a-space>
      </template>
    </search-table>

    <FormDialog v-model:visible="formDialogVisible" :record="currentRecord" @success="handleFormSuccess" />
    <a-drawer v-model:visible="detailVisible" :width="860" title="网络设备采集详情" :footer="false" unmount-on-close>
      <Detail v-if="currentRecord" :record="currentRecord" @edit="handleDetailEdit" @delete="handleDetailDelete" />
    </a-drawer>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { Message, Modal } from '@arco-design/web-vue'
import { IconPlus, IconDelete, IconDown, IconEdit, IconEye, IconRefresh } from '@arco-design/web-vue/es/icon'
import type { FormItem } from '@/components/search-form/types'
import SearchTable from '@/components/search-table/index.vue'
import { searchFormConfig } from './config/search-form'
import FormDialog from './components/FormDialog.vue'
import Detail from './components/Detail.vue'
import { columns as columnsConfig } from './config/columns'
import {
  fetchNetworkDeviceList,
  fetchNetworkDeviceDetail,
  deleteNetworkDevice,
  type NetworkDeviceService,
  type NetworkDeviceQueryParams,
} from '@/api/ops/network-device'

const loading = ref(false)
const tableData = ref<NetworkDeviceService[]>([])
const formDialogVisible = ref(false)
const detailVisible = ref(false)
const currentRecord = ref<NetworkDeviceService | null>(null)
const formModel = ref({
  keyword: '',
  enabled: undefined as boolean | undefined,
  status: undefined as string | undefined,
  protocol: undefined as string | undefined,
})

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

// 表单项配置
const formItems = computed<FormItem[]>(() => searchFormConfig)

// 表格列配置
const columns = computed(() => columnsConfig)

const getStatusColor = (status?: string) => {
  const colorMap: Record<string, string> = {
    online: 'green',
    offline: 'red',
    error: 'orange',
    unknown: 'gray',
  }
  return colorMap[status || ''] || 'gray'
}

const getStatusText = (status?: string) => {
  const textMap: Record<string, string> = {
    online: '在线',
    offline: '离线',
    error: '异常',
    unknown: '未知',
  }
  return textMap[status || ''] || '-'
}

const statusHint = (status?: string) => {
  const hintMap: Record<string, string> = {
    online: '在线：设备采集正常',
    offline: '离线：采集任务未拿到设备响应',
    error: '异常：采集发生错误，请检查配置',
    unknown: '未知：等待首次采集',
  }
  return hintMap[status || 'unknown']
}

const formatResponseTime = (value?: number) => {
  if (typeof value !== 'number' || value <= 0) return '-'
  return `${value.toFixed(2)} ms`
}

const getResponseTimeColor = (value?: number) => {
  if (!value) return ''
  if (value >= 1000) return 'rgb(var(--danger-6))'
  if (value >= 500) return 'rgb(var(--warning-6))'
  return 'rgb(var(--success-6))'
}

const formatTime = (time?: string) => {
  if (!time) return '-'
  if (time.startsWith('0001-01-01')) return '-'
  const date = new Date(time)
  if (Number.isNaN(date.getTime())) return '-'
  if (date.getFullYear() <= 1970) return '-'
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(
    date.getHours()
  ).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`
}

const parseTags = (tags?: string) => {
  if (!tags) return []
  return tags
    .split(',')
    .map((i) => i.trim())
    .filter(Boolean)
}

const formatDeviceCategory = (category?: string) => {
  const map: Record<string, string> = {
    router: '路由器',
    switch: '交换机',
    firewall: '防火墙',
    access_point: '接入点',
    load_balancer: '负载均衡',
    other: '其他',
  }
  if (!category) return '-'
  return map[category] || category
}

const fetchList = async () => {
  loading.value = true
  try {
    const params: NetworkDeviceQueryParams = { page: pagination.current, size: pagination.pageSize }
    if (formModel.value.keyword) params.keyword = formModel.value.keyword
    if (formModel.value.enabled !== undefined) params.enabled = formModel.value.enabled
    const res: any = await fetchNetworkDeviceList(params)
    let data: NetworkDeviceService[] = res?.details?.data || []
    if (formModel.value.status) data = data.filter((item) => item.status === formModel.value.status)
    if (formModel.value.protocol) data = data.filter((item) => item.protocol === formModel.value.protocol)
    tableData.value = data
    pagination.total = formModel.value.status || formModel.value.protocol ? data.length : res?.details?.total || 0
  } catch (error) {
    Message.error('获取网络设备列表失败')
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

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

const handleFormModelUpdate = (value: any) => {
  formModel.value = value
}

const handleReset = () => {
  formModel.value = {
    keyword: '',
    enabled: undefined,
    status: undefined as string | undefined,
    protocol: undefined as string | undefined,
  }
  pagination.current = 1
  fetchList()
}

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

const handleRefresh = () => {
  fetchList()
  Message.success('数据已刷新')
}

const handleAdd = () => {
  currentRecord.value = null
  formDialogVisible.value = true
}

const handleEdit = (record: NetworkDeviceService) => {
  currentRecord.value = record
  formDialogVisible.value = true
}

const handleFormSuccess = () => {
  fetchList()
}

const handleDetail = async (record: NetworkDeviceService) => {
  try {
    const res: any = await fetchNetworkDeviceDetail(record.id)
    currentRecord.value = (res?.details || record) as NetworkDeviceService
    detailVisible.value = true
  } catch {
    currentRecord.value = record
    detailVisible.value = true
  }
}

const handleDetailEdit = () => {
  detailVisible.value = false
  formDialogVisible.value = true
}

const handleDetailDelete = () => {
  detailVisible.value = false
  if (currentRecord.value) handleDelete(currentRecord.value)
}

const handleDelete = (record: NetworkDeviceService) => {
  Modal.confirm({
    title: '确认删除',
    content: `确认删除设备「${record.name}」吗？删除为软删除，建议先停用后再执行。`,
    okButtonProps: { status: 'danger' },
    onOk: async () => {
      try {
        await deleteNetworkDevice(record.id)
        Message.success('删除成功')
        fetchList()
      } catch (error: any) {
        Message.error(error?.response?.data?.message || '删除失败')
      }
    },
  })
}

onMounted(fetchList)
</script>

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

<style scoped lang="less">
.container {
  margin-top: 20px;
}
</style>
