import cityCodeJson from '@/utils/json/cityCode.json'

/** el-cascader 省市区配置（须配合 normalizeRegionTree 使用） */
export const REGION_CASCADER_PROPS = {
  value: 'code',
  label: 'name',
  children: 'children',
  emitPath: true,
  leaf: 'leaf',
  disabled: 'disabled'
}

/**
 * 规范化地区树供 el-cascader 使用。
 * Element UI 默认把 children: [] 当作叶子并可点击选中；
 * 后端 RegionTreeVO 对无下级节点也返回空数组，导致省/市被误选。
 * 仅 type=3（区县）标记为 leaf；无下级的非区县节点 disabled。
 */
export function normalizeRegionTree(nodes) {
  if (!nodes || !nodes.length) {
    return []
  }
  return nodes.map(node => {
    const hasChildren = node.children && node.children.length > 0
    const children = hasChildren ? normalizeRegionTree(node.children) : undefined
    const isDistrict = node.type === 3
    const item = {
      code: node.code,
      name: node.name,
      type: node.type,
      leaf: isDistrict,
      disabled: !isDistrict && !hasChildren
    }
    if (children && children.length) {
      item.children = children
    }
    return item
  })
}

/** 根据区县 code 回显级联选中路径 */
export function findRegionPath(nodes, targetCode, path) {
  if (!nodes || !nodes.length) {
    return null
  }
  for (let i = 0; i < nodes.length; i++) {
    const node = nodes[i]
    const nextPath = (path || []).concat(node.code)
    if (String(node.code) === String(targetCode)) {
      return nextPath
    }
    if (node.children && node.children.length) {
      const found = findRegionPath(node.children, targetCode, nextPath)
      if (found) {
        return found
      }
    }
  }
  return null
}

/** 根据级联 code 路径拼地区名称 */
export function getRegionNamesByCodes(regionTree, codes) {
  const names = []
  let nodes = regionTree
  for (let i = 0; i < codes.length; i++) {
    const code = codes[i]
    const node = (nodes || []).find(item => String(item.code) === String(code))
    if (!node) {
      break
    }
    names.push(node.name)
    nodes = node.children || []
  }
  return names
}

/** 根据级联路径找到末级节点 */
export function findRegionNodeByCodes(regionTree, codes) {
  let nodes = regionTree
  let node = null
  for (let i = 0; i < codes.length; i++) {
    node = (nodes || []).find(item => String(item.code) === String(codes[i]))
    if (!node) {
      return null
    }
    nodes = node.children || []
  }
  return node
}

/**
 * 解析级联选择结果。
 * @returns {{ valid: boolean, code?: string, name?: string }}
 */
export function parseRegionSelection(regionTree, codes) {
  if (!codes || !codes.length) {
    return { valid: true, code: undefined, name: undefined }
  }
  const lastNode = findRegionNodeByCodes(regionTree, codes)
  if (!lastNode || lastNode.type !== 3) {
    return { valid: false }
  }
  const names = getRegionNamesByCodes(regionTree, codes)
  return {
    valid: true,
    code: String(codes[codes.length - 1]),
    name: names.join('/')
  }
}

let cachedRegionTree = null

/**
 * 将 cityCode.json 转为与后端 RegionTreeVO 一致的三级树结构。
 * code 为字符串；省级 id 取行政区划 code 数值，供省份多选等场景使用。
 */
export function convertCityCodeToRegionTree(cityCodeList) {
  return (cityCodeList || []).map(province => {
    const provinceCode = String(province.code)
    const cities = (province.cityList || []).map(city => {
      const cityCode = String(city.code)
      const areas = (city.areaList || []).map(area => ({
        code: String(area.code),
        name: area.name,
        type: 3
      }))
      const cityNode = {
        code: cityCode,
        name: city.name,
        type: 2
      }
      if (areas.length) {
        cityNode.children = areas
      }
      return cityNode
    })
    const provinceNode = {
      id: Number(provinceCode),
      code: provinceCode,
      name: province.name,
      type: 1
    }
    if (cities.length) {
      provinceNode.children = cities
    }
    return provinceNode
  })
}

/** 从本地 cityCode.json 获取省市区树（带模块级缓存） */
export function getRegionTreeFromCityCode() {
  if (!cachedRegionTree) {
    cachedRegionTree = convertCityCodeToRegionTree(cityCodeJson)
  }
  return cachedRegionTree
}

/** 从地区树提取省级选项（运费模版等省份多选） */
export function getProvinceOptionsFromTree(regionTree) {
  return (regionTree || [])
    .filter(item => item.type === 1)
    .map(item => ({ id: item.id, name: item.name }))
}
