import { ref } from 'vue'
import { fetchServerList } from '@/api/ops/server'
import { fetchDatabaseList } from '@/api/ops/database'
import { fetchMiddlewareList } from '@/api/ops/middleware'
import { fetchNetworkDeviceList } from '@/api/ops/network-device'

export type ReportTargetIdentityOption = { 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,
  }
}

/** 按报表「数据源」加载目标标识下拉选项（复用各模块已有列表接口，分页拉全量） */
export function useReportTargetIdentityOptions() {
  const targetIdentityOptions = ref<ReportTargetIdentityOption[]>([])
  const targetOptionsLoading = ref(false)

  async function loadTargetIdentityOptions(dataSource: string) {
    targetIdentityOptions.value = []
    if (!dataSource) return

    targetOptionsLoading.value = true
    try {
      const pageSize = 500
      let page = 1
      const acc: ReportTargetIdentityOption[] = []

      while (true) {
        let chunk: any[] = []
        let total = 0

        switch (dataSource) {
          case 'dc-host': {
            const res = await fetchServerList({ page, size: pageSize })
            const u = unwrapListRes(res)
            chunk = u.data
            total = u.total
            for (const s of chunk) {
              if (s?.server_identity) {
                acc.push({
                  label: `${s.name || s.server_identity} (${s.server_identity})`,
                  value: s.server_identity,
                })
              }
            }
            break
          }
          case 'dc-database': {
            const res = await fetchDatabaseList({ page, size: pageSize })
            const u = unwrapListRes(res)
            chunk = u.data
            total = u.total
            for (const s of chunk) {
              if (s?.service_identity) {
                acc.push({
                  label: `${s.name || s.service_identity} (${s.service_identity})`,
                  value: s.service_identity,
                })
              }
            }
            break
          }
          case 'dc-middleware': {
            const res = await fetchMiddlewareList({ page, size: pageSize })
            const u = unwrapListRes(res)
            chunk = u.data
            total = u.total
            for (const s of chunk) {
              if (s?.service_identity) {
                acc.push({
                  label: `${s.name || s.service_identity} (${s.service_identity})`,
                  value: s.service_identity,
                })
              }
            }
            break
          }
          case 'dc-network': {
            const res = await fetchNetworkDeviceList({ page, size: pageSize })
            const u = unwrapListRes(res)
            chunk = u.data
            total = u.total
            for (const s of chunk) {
              if (s?.service_identity) {
                acc.push({
                  label: `${s.name || s.service_identity} (${s.service_identity})`,
                  value: s.service_identity,
                })
              }
            }
            break
          }
          default:
            targetIdentityOptions.value = []
            return
        }

        if (chunk.length === 0) break
        if (chunk.length < pageSize) break
        if (total > 0 && acc.length >= total) break
        page += 1
      }

      targetIdentityOptions.value = acc
    } catch (e) {
      console.error('加载目标标识选项失败:', e)
      targetIdentityOptions.value = []
    } finally {
      targetOptionsLoading.value = false
    }
  }

  return {
    targetIdentityOptions,
    targetOptionsLoading,
    loadTargetIdentityOptions,
  }
}

/** 故障报表服务标识：合并各资源类型的 service_identity / server_identity（去重） */
export function useFaultReportServiceIdentityOptions() {
  const faultServiceIdentityOptions = ref<ReportTargetIdentityOption[]>([])
  const faultServiceOptionsLoading = ref(false)

  async function loadFaultServiceIdentityOptions() {
    faultServiceIdentityOptions.value = []
    faultServiceOptionsLoading.value = true
    try {
      const pageSize = 500
      const seen = new Set<string>()
      const acc: ReportTargetIdentityOption[] = []

      async function pullServers() {
        let page = 1
        while (true) {
          const res = await fetchServerList({ page, size: pageSize })
          const u = unwrapListRes(res)
          const chunk = u.data
          const total = u.total
          for (const s of chunk) {
            const ident = (s?.server_identity as string) || ''
            if (!ident || seen.has(ident)) continue
            seen.add(ident)
            acc.push({
              label: `[主机] ${s.name || ident} (${ident})`,
              value: ident,
            })
          }
          if (chunk.length === 0 || chunk.length < pageSize) break
          if (total > 0 && page * pageSize >= total) break
          page += 1
        }
      }

      async function pullNetwork() {
        let page = 1
        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 ident = (s?.service_identity as string) || ''
            if (!ident || seen.has(ident)) continue
            seen.add(ident)
            acc.push({
              label: `[网络] ${s.name || ident} (${ident})`,
              value: ident,
            })
          }
          if (chunk.length === 0 || chunk.length < pageSize) break
          if (total > 0 && page * pageSize >= total) break
          page += 1
        }
      }

      async function pullDb() {
        let page = 1
        while (true) {
          const res = await fetchDatabaseList({ page, size: pageSize })
          const u = unwrapListRes(res)
          const chunk = u.data
          const total = u.total
          for (const s of chunk) {
            const ident = (s?.service_identity as string) || ''
            if (!ident || seen.has(ident)) continue
            seen.add(ident)
            acc.push({
              label: `[数据库] ${s.name || ident} (${ident})`,
              value: ident,
            })
          }
          if (chunk.length === 0 || chunk.length < pageSize) break
          if (total > 0 && page * pageSize >= total) break
          page += 1
        }
      }

      async function pullMw() {
        let page = 1
        while (true) {
          const res = await fetchMiddlewareList({ page, size: pageSize })
          const u = unwrapListRes(res)
          const chunk = u.data
          const total = u.total
          for (const s of chunk) {
            const ident = (s?.service_identity as string) || ''
            if (!ident || seen.has(ident)) continue
            seen.add(ident)
            acc.push({
              label: `[中间件] ${s.name || ident} (${ident})`,
              value: ident,
            })
          }
          if (chunk.length === 0 || chunk.length < pageSize) break
          if (total > 0 && page * pageSize >= total) break
          page += 1
        }
      }

      await pullServers()
      await pullNetwork()
      await pullDb()
      await pullMw()

      faultServiceIdentityOptions.value = acc
    } catch (e) {
      console.error('加载故障报表服务标识失败:', e)
      faultServiceIdentityOptions.value = []
    } finally {
      faultServiceOptionsLoading.value = false
    }
  }

  return {
    faultServiceIdentityOptions,
    faultServiceOptionsLoading,
    loadFaultServiceIdentityOptions,
  }
}
