import { ref } from 'vue'
import { fetchNetworkDeviceList } from '@/api/ops/network-device'

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

function unwrapListRes(res: unknown): { data: any[]; total: number } {
  const r = res as Record<string, any> | null | undefined
  const d = r?.details ?? r
  return {
    data: Array.isArray(d?.data) ? d.data : [],
    total: typeof d?.total === 'number' ? d.total : 0,
  }
}

/** 网络设备报表：按服务表 ID / 按 service_identity 下拉选项 */
export function useReportNetworkDevicePickOptions() {
  const networkDeviceIdOptions = ref<LabeledNumberOption[]>([])
  const networkDeviceIdentityOptions = ref<LabeledStringOption[]>([])
  const networkDeviceOptionsLoading = ref(false)

  async function loadNetworkDevicePickOptions() {
    networkDeviceIdOptions.value = []
    networkDeviceIdentityOptions.value = []
    networkDeviceOptionsLoading.value = true
    try {
      const pageSize = 500
      let page = 1
      const idAcc: LabeledNumberOption[] = []
      const identAcc: LabeledStringOption[] = []

      while (true) {
        const res = await fetchNetworkDeviceList({ page, size: pageSize })
        const u = unwrapListRes(res)
        const chunk = u.data
        const total = u.total
        for (const s of chunk) {
          const id = s?.id
          const name = (s?.name as string) || ''
          const ident = (s?.service_identity as string) || ''
          if (typeof id === 'number') {
            idAcc.push({
              label: ident ? `${name || ident} (ID: ${id})` : `网络设备 #${id}`,
              value: id,
            })
          }
          if (ident) {
            identAcc.push({
              label: name ? `${name} (${ident})` : ident,
              value: ident,
            })
          }
        }
        if (chunk.length === 0 || chunk.length < pageSize) break
        if (total > 0 && idAcc.length >= total) break
        page += 1
      }
      networkDeviceIdOptions.value = idAcc
      networkDeviceIdentityOptions.value = identAcc
    } catch (e) {
      console.error('加载网络设备选项失败:', e)
      networkDeviceIdOptions.value = []
      networkDeviceIdentityOptions.value = []
    } finally {
      networkDeviceOptionsLoading.value = false
    }
  }

  return {
    networkDeviceIdOptions,
    networkDeviceIdentityOptions,
    networkDeviceOptionsLoading,
    loadNetworkDevicePickOptions,
  }
}
