import { ref } from 'vue'
import { fetchTopologies, fetchLinks, fetchTopologyGraph } from '@/api/ops/netarchTopo'

export type LabeledNumberOption = { label: string; value: number }
export type LabeledStringOption = { label: string; value: string }

function unwrapDetails(res: unknown): Record<string, any> | null {
  const r = res as Record<string, any> | null | undefined
  if (!r || r.code !== 0) return null
  return (r.details ?? r.data ?? null) as Record<string, any> | null
}

/** 报表表单：拓扑 / 链路 / 节点下拉（与流量、网络设备报表共用） */
export function useReportTopologyOptions() {
  const topologyOptions = ref<LabeledNumberOption[]>([])
  const topologyLoading = ref(false)
  const linkOptions = ref<LabeledNumberOption[]>([])
  const linksLoading = ref(false)
  const nodeOptions = ref<LabeledStringOption[]>([])
  const nodesLoading = ref(false)

  async function loadTopologyOptions() {
    topologyOptions.value = []
    topologyLoading.value = true
    try {
      const pageSize = 200
      let page = 1
      const acc: LabeledNumberOption[] = []
      while (true) {
        const res = await fetchTopologies({ page, size: pageSize })
        const d = unwrapDetails(res)
        const rows = Array.isArray(d?.data) ? d.data : []
        const total = typeof d?.total === 'number' ? d.total : 0
        for (const t of rows) {
          const id = t?.id
          if (typeof id === 'number') {
            acc.push({
              label: `${t.name || `拓扑 #${id}`} (ID: ${id})`,
              value: id,
            })
          }
        }
        if (rows.length === 0 || rows.length < pageSize) break
        if (total > 0 && acc.length >= total) break
        page += 1
      }
      topologyOptions.value = acc
    } catch (e) {
      console.error('加载拓扑列表失败:', e)
      topologyOptions.value = []
    } finally {
      topologyLoading.value = false
    }
  }

  async function loadLinksAndNodes(topologyId: number | undefined) {
    linkOptions.value = []
    nodeOptions.value = []
    if (!topologyId) return

    linksLoading.value = true
    nodesLoading.value = true
    try {
      const [linkRes, graphRes] = await Promise.all([
        fetchLinks(topologyId),
        fetchTopologyGraph(topologyId),
      ])

      const linkD = unwrapDetails(linkRes)
      const list = Array.isArray(linkD?.list) ? linkD.list : []
      const linkAcc: LabeledNumberOption[] = [
        { label: '整拓扑（不指定链路）', value: 0 },
      ]
      for (const e of list) {
        const id = e?.id
        if (typeof id !== 'number') continue
        const label = (e.label as string) || `${e.source} → ${e.target}`
        linkAcc.push({
          label: `链路 #${id}：${label}`,
          value: id,
        })
      }
      linkOptions.value = linkAcc

      const g = unwrapDetails(graphRes)
      const nodesFromGraph =
        g?.nodes || g?.data || (Array.isArray(g) ? g : []) || []
      const nodeAcc: LabeledStringOption[] = [{ label: '不指定节点', value: '' }]
      if (Array.isArray(nodesFromGraph)) {
        for (const node of nodesFromGraph) {
          const nid = node?.id != null ? String(node.id) : ''
          if (!nid) continue
          const nl = (node.label as string) || nid
          nodeAcc.push({
            label: `${nl} (${nid})`,
            value: nid,
          })
        }
      }
      nodeOptions.value = nodeAcc
    } catch (e) {
      console.error('加载链路/节点失败:', e)
      linkOptions.value = [{ label: '整拓扑（不指定链路）', value: 0 }]
      nodeOptions.value = [{ label: '不指定节点', value: '' }]
    } finally {
      linksLoading.value = false
      nodesLoading.value = false
    }
  }

  return {
    topologyOptions,
    topologyLoading,
    linkOptions,
    linksLoading,
    nodeOptions,
    nodesLoading,
    loadTopologyOptions,
    loadLinksAndNodes,
  }
}
