import store from '@/stores/index'
import type { RegionItem } from '@/api/common'

/**
 * 根据城市编码从 store 地区树中查找对应的城市名称
 * 遍历省→市→区三级，匹配到即返回名称，未匹配返回编码本身
 * @param code 地区编码（如 '130300'）
 * @returns 匹配到的城市名称，未匹配则返回原编码
 */
export function resolveRegionName(code: string): string {
  if (!code) return ''
  const regions: RegionItem[] = store.state.regions
  for (const province of regions) {
    if (province.code === code) return province.name
    for (const city of province.children) {
      if (city.code === code) return city.name
      if (city.children) {
        for (const district of city.children) {
          if (district.code === code) return district.name
        }
      }
    }
  }
  return code
}
