import { computed, ref, unref } from 'vue'
import { getTownOptions, getVillageTree } from '@/api/home'

/** 模块级缓存，各弹框共用，避免重复请求 */
let cachedTowns = null
let cachedVillageTree = null
let loadingPromise = null

async function ensureLoaded() {
  if (cachedTowns && cachedVillageTree) {
    return
  }
  if (loadingPromise) {
    await loadingPromise
    return
  }
  loadingPromise = Promise.all([getTownOptions(), getVillageTree()])
    .then(([townRes, treeRes]) => {
      cachedTowns = Array.isArray(townRes?.data) ? townRes.data : []
      cachedVillageTree = Array.isArray(treeRes?.data) ? treeRes.data : []
    })
    .catch(() => {
      cachedTowns = cachedTowns || []
      cachedVillageTree = cachedVillageTree || []
    })
    .finally(() => {
      loadingPromise = null
    })
  await loadingPromise
}

/** 县 → 乡镇 → 村：取出乡镇节点 */
function extractTownNodes(tree) {
  const roots = Array.isArray(tree) ? tree : []
  if (!roots.length) {
    return []
  }
  // 标准结构：单个县根，children 为乡镇
  if (roots.length === 1 && Array.isArray(roots[0].children)) {
    return roots[0].children
  }
  return roots
}

/**
 * 从村树解析村选项；可选按乡镇过滤。
 * @param {Array} tree
 * @param {number|string|null|undefined} townDeptId
 * @returns {{ deptId: *, deptName: string }[]}
 */
export function resolveVillageOptions(tree, townDeptId) {
  const townNodes = extractTownNodes(tree)
  const towns =
    townDeptId != null && townDeptId !== ''
      ? townNodes.filter((t) => String(t.id) === String(townDeptId))
      : townNodes
  const villages = []
  for (const town of towns) {
    for (const v of town.children || []) {
      if (v?.id == null) {
        continue
      }
      villages.push({ deptId: v.id, deptName: v.label || '' })
    }
  }
  return villages
}

/**
 * 大屏弹框：乡镇下拉 + 按乡镇联动村下拉。
 * @param {import('vue').Ref|import('vue').ComputedRef|*} townDeptIdRef query.townDeptId
 */
export function useScreenTownVillageOptions(townDeptIdRef) {
  const townOptions = ref([])
  const villageTree = ref([])
  const optionsLoading = ref(false)

  const villageOptions = computed(() =>
    resolveVillageOptions(villageTree.value, unref(townDeptIdRef))
  )

  async function loadTownVillageOptions() {
    optionsLoading.value = true
    try {
      await ensureLoaded()
      townOptions.value = cachedTowns || []
      villageTree.value = cachedVillageTree || []
    } finally {
      optionsLoading.value = false
    }
  }

  return {
    townOptions,
    villageOptions,
    optionsLoading,
    loadTownVillageOptions
  }
}
