<template>
  <el-cascader
      v-model="selectedArea"
      :options="areaOptions"
      :props="cascaderProps"
      placeholder="请选择省市区"
      clearable
  />
</template>

<script lang="ts" setup>
import {ref} from 'vue'
import areaData from '@/assets/config/area.json'

interface Area {
  name: string
  code: string
  city?: Area[]   // 省级包含city字段
  area?: Area[]   // 市级包含area字段
}

// 递归处理多级区域数据
const formatAreas = (areas: Area[]):any[] => {
  return areas.map(area => ({
    value: area.code,
    label: area.name,
    children: getChildren(area) // 动态获取子级字段
  }))
}
// 获取子级数据（优先取city字段，其次area字段）
const getChildren = (area: Area) => {
  if (area.city && area.city.length > 0) {
    return formatAreas(area.city)
  }
  if (area.area && area.area.length > 0) {
    return formatAreas(area.area)
  }
  return null
}

const areaOptions = formatAreas(areaData)

const selectedArea = ref<string[]>([])

const cascaderProps = {
  value: 'value',
  label: 'label',
  children: 'children',
  checkStrictly: true,
  emitPath: true // 确保返回完整路径
}

interface CascaderOption {
  value: string
  label: string
  children?: CascaderOption[]
}

</script>