<template>
  <div class="container">
    <Breadcrumb :items="['运维管理', '网络架构', '拓扑分组']" />
    <SearchTable
      title="拓扑分组管理"
      :form-model="searchForm"
      :form-items="filters"
      @update:form-model="handleFormModelUpdate"
      :data="tableData"
      :columns="columns"
      :loading="loading"
      :pagination="{
        current: page,
        pageSize,
        total,
      }"
      @page-change="handlePageChange"
      @search="handleSearch"
      @reset="handleReset"
      @refresh="fetchData"
    >
      <!-- 工具栏左侧 - 新增按钮 -->
      <template #toolbar-left>
        <a-button type="primary" @click="handleAddGroup">
          <template #icon><icon-plus /></template>
          新增分组
        </a-button>
      </template>

      <!-- 操作列 -->
      <template #operation="{ record }">
        <a-space>
          <!-- 添加子分组：只在顶层分组时显示 (order: 50) -->
          <a-button v-if="!record.parent_id || record.parent_id === 0" type="text" size="small" @click="handleAddSubGroup(record)">
            添加子分组
          </a-button>
          <!-- 详情：只在有父分组时显示 (order: 100) -->
          <!-- <a-button 
            v-if="!!record.parent_id && record.parent_id !== 0" 
            type="text" 
            size="small" 
            @click="handleViewDetail(record)"
          >
            详情
          </a-button> -->
          <!-- 拓扑：只在有父分组时显示 (order: 150) -->
          <a-button v-if="!!record.parent_id && record.parent_id !== 0" type="text" size="small" @click="handleViewTopologies(record)">
            拓扑
          </a-button>
          <!-- 编辑：始终显示 (order: 200) -->
          <a-button type="text" size="small" @click="handleEdit(record)">编辑</a-button>
          <!-- 删除：始终显示 (order: 300) -->
          <a-button type="text" size="small" status="danger" @click="handleDelete(record)">删除</a-button>
        </a-space>
      </template>

      <!-- 表格自定义列：序号 -->
      <template #index="{ rowIndex }">
        {{ rowIndex + 1 + (page - 1) * pageSize }}
      </template>

      <!-- 层级列 -->
      <template #level="{ record }">
        <a-tag :color="record.parent_id === 0 ? 'blue' : 'arcoblue'" bordered>
          {{ record.parent_id === 0 ? '顶层' : `${record.level || 1}级` }}
        </a-tag>
      </template>

      <!-- 拓扑数量列 -->
      <template #topology_count="{ record }">
        <a-tag :color="(record.parent_id ? record.total_topology_count : record.topology_count) > 0 ? 'green' : 'gray'">
          {{ record.parent_id ? record.total_topology_count : record.topology_count || 0 }}
        </a-tag>
      </template>

      <!-- 总链路数列 -->
      <template #total_link_count="{ record }">
        <a-tag :color="record.total_link_count > 0 ? 'green' : 'gray'">
          {{ record.total_link_count || 0 }}
        </a-tag>
      </template>

      <!-- 启用列 -->
      <template #enable="{ record }">
        <a-tag :color="record.enable ? 'blue' : 'gray'" bordered>
          {{ record.enable ? '是' : '否' }}
        </a-tag>
      </template>
    </SearchTable>

    <!-- 分组表单弹窗 -->
    <a-modal
      v-model:visible="formModalVisible"
      :title="formModalTitle"
      :mask-closable="false"
      :width="520"
      @ok="handleFormModalOk"
      @cancel="handleFormModalCancel"
    >
      <a-form ref="formRef" :model="formData" :rules="formRules" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 16 }">
        <a-form-item field="name" label="分组名称" validate-trigger="blur">
          <a-input v-model="formData.name" placeholder="请输入分组名称" :max-length="100" allow-clear />
        </a-form-item>
        <a-form-item field="description" label="分组描述">
          <a-textarea
            v-model="formData.description"
            placeholder="请输入分组描述（可选）"
            :max-length="500"
            :auto-size="{ minRows: 3, maxRows: 5 }"
            allow-clear
          />
        </a-form-item>
        <a-form-item field="sort" label="排序权重">
          <a-input-number v-model="formData.sort" placeholder="请输入排序权重" :min="0" :max="9999" style="width: 100%" />
          <template #extra>
            <span style="color: var(--color-text-3); font-size: 12px">数字越小越靠前</span>
          </template>
        </a-form-item>
        <a-form-item field="enable" label="是否启用">
          <a-switch v-model="formData.enable" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 删除确认对话框 -->
    <a-modal v-model:visible="deleteConfirmVisible" title="删除确认" @ok="handleConfirmDelete" @cancel="deleteConfirmVisible = false">
      <p>确定要删除分组 "{{ groupToDelete?.name }}" 吗？</p>
      <p v-if="groupToDelete?.topology_count && groupToDelete.topology_count > 0" style="color: rgb(var(--warning-6))">
        该分组下还有 {{ groupToDelete.topology_count }} 个拓扑，删除分组不会删除拓扑。
      </p>
    </a-modal>

    <!-- 拓扑列表弹窗 -->
    <TopologyListDialog v-model:open="topologyListDialogVisible" :group-id="currentGroupId" :group-name="currentGroupName" />

    <!-- 添加子分组弹窗 -->
    <SubGroupFormDialog v-model:visible="subGroupDialogVisible" :parent-group="currentParentGroup" @success="fetchData" />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { Message, Modal } from '@arco-design/web-vue'
import { IconPlus } from '@arco-design/web-vue/es/icon'
import SearchTable from '@/components/search-table/index.vue'
import type { TableColumnData } from '@arco-design/web-vue/es/table/interface'
import type { TopologyGroup } from '@/api/ops/netarchTopo'
import { fetchTopologyGroups, createTopologyGroup, updateTopologyGroup, deleteTopologyGroup } from '@/api/ops/netarchTopo'
import { getColumns } from './config/columns'
import { getFilters } from './config/filters'
import TopologyListDialog from './components/TopologyListDialog.vue'
import SubGroupFormDialog from './components/SubGroupFormDialog.vue'

// 表格列配置
const columns = getColumns()

// 搜索表单配置
const filters = getFilters()

// 搜索表单数据
const searchForm = reactive({
  keyword: '',
  enable: '',
})

// 处理表单模型更新
const handleFormModelUpdate = (newFormModel: Record<string, any>) => {
  // 合并新的值到 searchForm 中，而不是替换整个对象
  Object.assign(searchForm, newFormModel)
}

// 表格数据
const tableData = ref<TopologyGroup[]>([])
const loading = ref(false)

// 分页
const page = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 表单弹窗相关
const formModalVisible = ref(false)
const isEdit = ref(false)
const formRef = ref()
const formData = reactive<Partial<TopologyGroup> & { parent_id: number }>({
  id: undefined,
  name: '',
  description: '',
  sort: 0,
  enable: true,
  parent_id: 0,
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入分组名称' },
    { minLength: 1, message: '分组名称不能为空' },
  ],
}

// 弹窗标题
const formModalTitle = computed(() => (isEdit.value ? '编辑分组' : '新增分组'))

// 删除确认
const deleteConfirmVisible = ref(false)
const groupToDelete = ref<TopologyGroup | null>(null)

// 拓扑列表弹窗
const topologyListDialogVisible = ref(false)
const currentGroupId = ref(0)
const currentGroupName = ref('')

// 添加子分组弹窗
const subGroupDialogVisible = ref(false)
const currentParentGroup = ref<{ id: number; name: string } | null>(null)

// 获取数据
const fetchData = async () => {
  console.log('searchForm', searchForm)
  try {
    loading.value = true
    const res = await fetchTopologyGroups({
      keyword: searchForm.keyword || undefined,
      enable: searchForm.enable ? searchForm.enable === 'true' : undefined,
      page: page.value,
      size: pageSize.value,
    })
    if (res?.code === 0) {
      // API返回结构: { details: { count: number, list: array } }
      const { count = 0, list = [] } = res.details || {}
      total.value = count

      // 构建树形结构
      tableData.value = list
    }
  } catch (error) {
    console.error('Failed to fetch topology groups:', error)
  } finally {
    loading.value = false
  }
}

// 构建树形结构
const buildTree = (flatData: TopologyGroup[]): TopologyGroup[] => {
  const map = new Map<number, TopologyGroup>()
  const roots: TopologyGroup[] = []

  // 先创建所有节点的映射
  flatData.forEach((item) => {
    map.set(item.id!, { ...item, children: [] })
  })

  // 构建树形结构
  flatData.forEach((item) => {
    const node = map.get(item.id!)!
    if (item.parent_id === 0 || item.parent_id === undefined) {
      roots.push(node)
    } else {
      const parent = map.get(item.parent_id)
      if (parent) {
        if (!parent.children) {
          parent.children = []
        }
        parent.children.push(node)
      }
    }
  })

  // 计算每个分组的总拓扑数和链路数
  const calculateTotals = (node: TopologyGroup): void => {
    if (!node.children || node.children.length === 0) {
      node.total_topology_count = node.topology_count || 0
      node.total_link_count = node.total_link_count || 0
      return
    }

    let totalTopo = node.topology_count || 0
    let totalLinks = node.total_link_count || 0

    node.children.forEach((child) => {
      calculateTotals(child)
      totalTopo += child.total_topology_count || 0
      totalLinks += child.total_link_count || 0
    })

    node.total_topology_count = totalTopo
    node.total_link_count = totalLinks
  }

  roots.forEach((root) => calculateTotals(root))

  return roots
}

// 搜索
const handleSearch = () => {
  page.value = 1
  fetchData()
}

// 重置
const handleReset = () => {
  searchForm.keyword = ''
  searchForm.enable = ''
  page.value = 1
  fetchData()
}

// 页码变化
const handlePageChange = (current: number) => {
  page.value = current
  fetchData()
}

// 新增分组
const handleAddGroup = () => {
  isEdit.value = false
  resetFormData()
  formModalVisible.value = true
}

// 编辑分组
const handleEdit = (record: TopologyGroup) => {
  isEdit.value = true
  Object.assign(formData, {
    id: record.id,
    name: record.name,
    description: record.description,
    sort: record.sort || 0,
    enable: record.enable ?? true,
  })
  formModalVisible.value = true
}

// 删除分组
const handleDelete = (record: TopologyGroup) => {
  groupToDelete.value = record
  deleteConfirmVisible.value = true
}

// 查看拓扑列表
const handleViewTopologies = (record: TopologyGroup) => {
  currentGroupId.value = record.id!
  currentGroupName.value = record.name
  topologyListDialogVisible.value = true
}

// 查看详情
const handleViewDetail = (record: TopologyGroup) => {
  isEdit.value = true
  Object.assign(formData, {
    id: record.id,
    name: record.name,
    description: record.description,
    sort: record.sort || 0,
    enable: record.enable ?? true,
  })
  formModalVisible.value = true
}

// 添加子分组
const handleAddSubGroup = (record: TopologyGroup) => {
  currentParentGroup.value = {
    id: record.id!,
    name: record.name,
  }
  subGroupDialogVisible.value = true
}

// 确认删除
const handleConfirmDelete = async () => {
  if (!groupToDelete.value?.id) return

  try {
    loading.value = true
    await deleteTopologyGroup(groupToDelete.value.id)
    Message.success('删除成功')
    deleteConfirmVisible.value = false
    groupToDelete.value = null
    await fetchData()
  } catch (error) {
    console.error('Failed to delete group:', error)
  } finally {
    loading.value = false
  }
}

// 弹窗确认
const handleFormModalOk = async () => {
  try {
    const valid = await formRef.value?.validate()
    if (valid) return

    loading.value = true
    if (isEdit.value && formData.id) {
      await updateTopologyGroup({ ...formData, id: formData.id })
      Message.success('修改成功')
    } else {
      await createTopologyGroup({ ...formData, parent_id: 0 })
      Message.success('创建成功')
    }
    formModalVisible.value = false
    await fetchData()
  } catch (error) {
    console.error('Failed to save group:', error)
  } finally {
    loading.value = false
  }
}

// 弹窗取消
const handleFormModalCancel = () => {
  formModalVisible.value = false
  formRef.value?.resetFields()
}

// 重置表单数据
const resetFormData = () => {
  Object.assign(formData, {
    id: undefined,
    name: '',
    description: '',
    sort: 0,
    enable: true,
    parent_id: 0,
  })
}

// 初始化
onMounted(() => {
  fetchData()
})
</script>

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

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