<template>
	<a-cascader :fieldNames="{children:'children', label:'name', value: 'areaCode' }" 
  :options="optionsData" :loadData="loadData" placeholder="请选择所属区域"
  allow-clear :disabled="disabled" v-model:value="selectedOptions" @change="handleChange"/>
</template>
<script setup lang="ts" name="china-area">
  import { ref,onMounted,computed,watch } from 'vue'
  import type { CascaderProps } from 'ant-design-vue';
import {getCityByList} from "@/api/system/user";
const emit = defineEmits(['update:modelValue', 'change']);
const optionsData = ref([]);
const props = defineProps({
	// 当前的值
	modelValue: [String,Array],
	// 类型 (二级联动，三级联动)
	type: {
		type: Number,
		default: 3,
	},
	// 是否禁用
	disabled: {
		type: Boolean,
		default: () => false,
	},
});

watch(
      () => props,
      () => {
        props && setData(props.modelValue);
      },
      {
        deep: true,
      },
    );
const getCityData= async (pid:any)=> {
  const data = await getCityByList(pid)
  optionsData.value = data.map(item=>{
    item.isLeaf= false
    return item
  })
}
const changeFlag =ref(false)
const selectedOptions = computed({
	get: () => {
		return props.modelValue;
	},
	set: (val) => {
		emit('update:modelValue', val);
	},
});
const setData=async(data)=>{
  if(changeFlag.value) return
  let index1 = findListChild(optionsData.value,data[0])
  let data1 = await getCityByList(data[0])
  optionsData.value[index1].children =data1


  let index2 = findListChild(data1,data[1])
  let data2 = await getCityByList(data[1])
  optionsData.value[index1].children[index2].children = data2


  let index3 = findListChild(data2,data[2])
  let data3 = await getCityByList(data[2])
  optionsData.value[index1].children[index2].children[index3].children =data3

}

const findListChild= (list:any, value:any)=>{
  let child = null
  let index = 0
  for (let i = 0; i < list.length; i++) {
    if (list[i].areaCode == value) {
      child = list[i]
      index = i
      break;
    }
  }
  return index
}
const loadData: CascaderProps['loadData'] = async (selectedOptions) => {
    const targetOption = selectedOptions[selectedOptions.length - 1];
    targetOption.loading = true;
    const data = await getCityByList(targetOption.areaCode)
    targetOption.loading = false;
    targetOption.children = [...data].map(item=>{
      item.isLeaf= (selectedOptions.length==props.type)
      return item
    })
    optionsData.value = [...optionsData.value];
  };
const handleChange = (value1) => {
  changeFlag.value = true
};

onMounted(async () => {
  await getCityData(0)
  
});
</script>
<style lang="less">
.ant-cascader-menu{
  background-color: #ffffff;
}
</style>
