<template>
    <a-cascader
        style="width: 500px"
        v-model:value="modelValue"
        :options="options"
        :load-data="loadData"
        placeholder="请选择行政区划"
        :change-on-select="changeOnSelect"
    />
</template>
<script lang="ts" setup>
import api from "@/axios";
import {onMounted, ref, watch} from 'vue';
import type {CascaderProps} from 'ant-design-vue';

// withDefaultsde作用是设置组件默认值属性，有两个值，第二个值是设置第一个值所有属性的默认值的
withDefaults(defineProps<{
  changeOnSelect?:boolean,
}>(),{
  changeOnSelect:false
})

const modelValue = defineModel('value', {
  default: [  ]
})
const options = ref<CascaderProps['options']>([]);
const DivisionTree = async () =>{
  const resp =  await api.get<TreeNodeVo<string>[]>('/common/administrativeDivisionByParentCode',{parentCode:'0'})
  options.value =  resp.data as TreeNodeVo<string>[]
}
const loadData: CascaderProps['loadData'] = async selectedOptions => {
  const targetOption = selectedOptions[selectedOptions.length - 1];
  targetOption.loading = true;
  const resp =  await api.get<TreeNodeVo<string>[]>('/common/administrativeDivisionByParentCode',{parentCode:targetOption.value})
  targetOption.loading = false;
  targetOption.children = [options.value,...resp.data]
};
const transformData =  (val:any,tree:any)=>{
  for(let i = 0; i< val.length - 1;i++){
    tree.forEach(async(item:any)=>{
      if(item.value === val[i]){
        item.children = []
        let data =  await api.get<TreeNodeVo<string>[]>('/common/administrativeDivisionByParentCode',{parentCode:val[i]})
        item.children = data.data.map((items:any)=>{
          return {
            label:items.label,
            value:items.value,
            isLeaf:items.isLeaf
          }
        })
        transformData(val,item.children)
      }
    })
  }
}

watch(modelValue,async ()=> await  transformData(modelValue.value,options.value))
onMounted(async () => {
  await  DivisionTree()
  await  transformData(modelValue.value,options.value)
});
</script>

