import { ref } from 'vue'
import { listRegionTree } from '@/api/system/region'

/**
 * 地区数据组合式函数 - 全局缓存，替代 element-china-area-data
 * @Author: Antigravity
 */

// 全局缓存，避免重复请求
const regionOptions = ref<any[]>([])
const regionMap = ref<Record<string, string>>({})
let loaded = false
let loading: Promise<void> | null = null

/** 递归转换后端树数据为 el-cascader 所需格式 { value, label, children } */
function transformTree(nodes: any[]): any[] {
  if (!nodes || nodes.length === 0) return []
  return nodes.map(node => {
    const item: any = { value: node.code, label: node.name }
    if (node.children && node.children.length > 0) {
      item.children = transformTree(node.children)
    }
    return item
  })
}

/** 递归构建 code -> name 映射 */
function buildMap(nodes: any[], map: Record<string, string>) {
  for (const node of nodes) {
    if (node.code && node.name) {
      map[node.code] = node.name
    }
    if (node.children && node.children.length > 0) {
      buildMap(node.children, map)
    }
  }
}

export function useRegionData() {
  /** 加载地区数据（自动缓存，多次调用不重复请求） */
  const loadRegionData = () => {
    if (loaded) return Promise.resolve()
    if (loading) return loading
    loading = listRegionTree().then((res: any) => {
      const data = res.data || res || []
      regionOptions.value = transformTree(data)
      const map: Record<string, string> = {}
      buildMap(data, map)
      regionMap.value = map
      loaded = true
    }).catch((err: any) => {
      console.error('获取地区树异常:', err)
    }).finally(() => {
      loading = null
    })
    return loading
  }

  /** 根据 code 获取地区名称（替代 codeToText） */
  const codeToName = (code: string): string => {
    return regionMap.value[code] || ''
  }

  /** 将 code 数组转换为名称字符串（如 "北京 北京市 东城区"） */
  const codesToText = (codes: string[], separator = ''): string => {
    return codes.map(c => regionMap.value[c] || '').filter(Boolean).join(separator)
  }

  return { regionOptions, regionMap, codeToName, codesToText, loadRegionData }
}
