<template>
  <a-modal
    :visible="visible"
    title="拓扑列表"
    :footer="false"
    width="80%"
    @cancel="handleClose"
    @update:visible="handleUpdateVisible"
  >
    <template #title>
      <div style="display: flex; align-items: center; justify-content: space-between;">
        <span>拓扑列表 {{ groupName ? `- ${groupName}` : '' }}</span>
      </div>
    </template>

    <a-button type="primary" style="margin-bottom: 16px;" @click="handleOpenCreate">
      <template #icon><icon-plus /></template>
      新增拓扑
    </a-button>

    <a-spin :loading="loading" style="width: 100%;">
      <a-alert v-if="error" type="error" :content="error" style="margin-bottom: 16px;" />
      <a-empty v-else-if="!loading && data.length === 0" description="暂无拓扑数据" />
      <div v-else>
        <a-table
          :data="data"
          :pagination="{
            current: page,
            pageSize,
            total,
            showTotal: true,
          }"
          size="small"
          @page-change="handlePageChange"
        >
          <template #columns>
            <a-table-column title="序号" data-index="id" :width="80">
              <template #cell="{ rowIndex }">
                {{ (page - 1) * pageSize + rowIndex + 1 }}
              </template>
            </a-table-column>
            <a-table-column title="拓扑名称" data-index="name" />
            <a-table-column title="类型" data-index="type" :width="100" align="center">
              <template #cell="{ record }">
                <a-tag :color="getTypeColor(record.type)">
                  {{ getTypeLabel(record.type) }}
                </a-tag>
              </template>
            </a-table-column>
            <a-table-column title="状态" data-index="status" :width="100" align="center">
              <template #cell="{ record }">
                <a-tag :color="getStatusColor(record.status)">
                  {{ getStatusLabel(record.status) }}
                </a-tag>
              </template>
            </a-table-column>
            <a-table-column title="节点数" data-index="node_count" :width="100" align="center">
              <template #cell="{ record }">
                {{ record.node_count || 0 }}
              </template>
            </a-table-column>
            <a-table-column title="链路数" data-index="link_count" :width="100" align="center">
              <template #cell="{ record }">
                {{ record.link_count || 0 }}
              </template>
            </a-table-column>
            <a-table-column title="启用" data-index="enable" :width="80" align="center">
              <template #cell="{ record }">
                <a-tag :color="record.enable ? 'blue' : 'gray'" bordered>
                  {{ record.enable ? '是' : '否' }}
                </a-tag>
              </template>
            </a-table-column>
            <a-table-column title="创建时间" data-index="created_at" :width="160" align="center">
              <template #cell="{ record }">
                {{ formatTime(record.created_at) }}
              </template>
            </a-table-column>
            <a-table-column title="操作" :width="200" align="center" fixed="right">
              <template #cell="{ record }">
                <a-space>
                  <a-button type="text" size="small" @click="handleViewTopology(record)">
                    拓扑
                  </a-button>
                  <a-button type="text" size="small" @click="handleOpenEdit(record)">
                    编辑
                  </a-button>
                  <a-button type="text" size="small" status="danger" @click="handleDelete(record)">
                    删除
                  </a-button>
                </a-space>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </div>
    </a-spin>

    <!-- 表单弹窗 -->
    <TopologyFormDialog
      v-model:visible="formDialogVisible"
      :mode="formMode"
      :initial-values="currentEditItem"
      :group-id="groupId"
      @submit="handleFormSubmit"
    />
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import { Message, Modal } from '@arco-design/web-vue'
import { IconPlus } from '@arco-design/web-vue/es/icon'
import dayjs from 'dayjs'
import type { Topology } from '@/api/ops/netarchTopo'
import {
  fetchTopologies,
  createTopology,
  updateTopology,
  deleteTopology,
  fetchTopologyDetail,
} from '@/api/ops/netarchTopo'
import TopologyFormDialog from './TopologyFormDialog.vue'

interface Props {
  open: boolean
  groupId: number
  groupName?: string
}

interface Emits {
  (e: 'update:open', value: boolean): void
}

const props = withDefaults(defineProps<Props>(), {
  groupName: '',
})

const emit = defineEmits<Emits>()

const visible = ref(false)
const loading = ref(false)
const error = ref<string | null>(null)
const data = ref<Topology[]>([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(20)

// 表单弹窗状态
const formDialogVisible = ref(false)
const formMode = ref<'create' | 'edit'>('create')
const currentEditItem = ref<Topology | null>(null)

// 监听 open 变化
watch(() => props.open, (val) => {
  visible.value = val
  if (val) {
    page.value = 1
    loadData()
  }
})

// 更新可见性
const handleUpdateVisible = (val: boolean) => {
  visible.value = val
  if (!val) {
    emit('update:open', false)
  }
}

// 加载数据
const loadData = async () => {
  loading.value = true
  error.value = null
  try {
    if (!props.groupId) {
      return
    }
    const response = await fetchTopologies({
      group_id: props.groupId,
      page: page.value,
      size: pageSize.value,
    })
    
    if (response.code === 0) {
      data.value = response.details?.data || []
      total.value = response.details?.total || 0
    } else {
      error.value = response.message || '加载失败'
    }
  } catch (err: any) {
    error.value = err.message || '加载失败'
  } finally {
    loading.value = false
  }
}

// 处理页码变更
const handlePageChange = (current: number) => {
  page.value = current
  loadData()
}

// 关闭弹窗
const handleClose = () => {
  visible.value = false
}

// 跳转到拓扑详情页
const handleViewTopology = (topology: Topology) => {
  window.open(`/#/netarch/topo?id=${topology.id}`, '_blank')
}

// 打开新增弹窗
const handleOpenCreate = () => {
  formMode.value = 'create'
  currentEditItem.value = null
  formDialogVisible.value = true
}

// 打开编辑弹窗
const handleOpenEdit = async (topology: Topology) => {
  try {
    const response = await fetchTopologyDetail(topology.id)
    if (response.code === 0) {
      formMode.value = 'edit'
      currentEditItem.value = response.details
      formDialogVisible.value = true
    } else {
      Message.error(response.message || '获取详情失败')
    }
  } catch (err: any) {
    Message.error(err.message || '获取详情失败')
  }
}

// 删除
const handleDelete = (topology: Topology) => {
  Modal.confirm({
    title: '删除确认',
    content: `确定要删除拓扑「${topology.name}」吗？`,
    onOk: async () => {
      try {
        const response = await deleteTopology(topology.id)
        if (response.code === 0) {
          Message.success('删除成功')
          loadData()
        } else {
          Message.error(response.message || '删除失败')
        }
      } catch (err: any) {
        Message.error(err.message || '删除失败')
      }
    },
  })
}

// 表单提交
const handleFormSubmit = async (values: any) => {
  try {
    const payload = {
      ...values,
      group_id: props.groupId,
    }
    
    if (formMode.value === 'create') {
      const response = await createTopology(payload)
      if (response.code === 0) {
        Message.success('新增成功')
        formDialogVisible.value = false
        loadData()
      } else {
        throw new Error(response.message || '新增失败')
      }
    } else {
      const response = await updateTopology({ ...payload, id: currentEditItem.value!.id })
      if (response.code === 0) {
        Message.success('编辑成功')
        formDialogVisible.value = false
        loadData()
      } else {
        throw new Error(response.message || '编辑失败')
      }
    }
  } catch (err: any) {
    Message.error(err.message)
    throw err
  }
}

// 获取状态颜色
const getStatusColor = (status?: string) => {
  const colorMap: Record<string, string> = {
    pending: 'gray',
    discovering: 'blue',
    active: 'green',
    error: 'red',
  }
  return colorMap[status || ''] || 'gray'
}

// 获取状态标签
const getStatusLabel = (status?: string) => {
  const labelMap: Record<string, string> = {
    pending: '待处理',
    discovering: '发现中',
    active: '活跃',
    error: '错误',
  }
  return labelMap[status || ''] || status || '-'
}

// 获取类型标签
const getTypeLabel = (type?: string) => {
  const typeMap: Record<string, string> = {
    layer2: '二层',
    layer3: '三层',
    physical: '物理',
  }
  return typeMap[type || ''] || type || '-'
}

// 获取类型颜色
const getTypeColor = (type?: string) => {
  return 'arcoblue'
}

// 格式化时间
const formatTime = (time?: string) => {
  return time ? dayjs(time).format('YYYY-MM-DD HH:mm') : '-'
}
</script>

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