<template>
  <a-cascader
      v-model:value="modelValue"
      :placeholder="placeholder"
      :change-on-select="changeOnSelect"
      :options="administrativeDivisionTree"
      :load-data="loadData"
      :allow-clear="allowClear"
  />
</template>

<script setup lang="ts">
import api from "@/axios";
import {onMounted, ref} from "vue";
import {CascaderProps} from "ant-design-vue";
import {isEmpty} from "lodash-es";

withDefaults(defineProps<{
  placeholder?: string,
  changeOnSelect?: boolean
  allowClear?: boolean
}>(), {
  placeholder: '请选择行政区划',
  changeOnSelect: true,
  allowClear: true
})


const modelValue = defineModel('value', {
  default: []
})

const administrativeDivisionTree = ref<TreeNodeVo<string>[]>([])

const loadData: CascaderProps['loadData'] = selectedOptions => {
  const targetOption = selectedOptions[selectedOptions.length - 1];
  targetOption.loading = true;
  administrativeDivisionByParentCode(targetOption.value as string).then(data => {
    targetOption.loading = false
    targetOption.children = data
    administrativeDivisionTree.value = [...administrativeDivisionTree.value]
  })
}

/**
 * 根据父级编码查询行政区划
 * @param code
 */
const administrativeDivisionByParentCode = async (code: string = '0'): Promise<TreeNodeVo<string>[]> => {
  const resp = await api.get<TreeNodeVo<string>[]>('/common/administrativeDivisionByParentCode', {
    parentCode: code
  })
  //解决点击无加载提示
  return resp.data.map(item => {
    delete item.children
    return item
  });
}

onMounted(async () => {
  administrativeDivisionTree.value = await administrativeDivisionByParentCode()
  if (!isEmpty(modelValue.value)) {
    const ps = modelValue.value.map(code => administrativeDivisionByParentCode(code))
    Promise.all(ps).then(data => {
      let i = 0;
      const deepChildren = (treeData: TreeNodeVo<string>[]) => {
        treeData.forEach(item => {
          if (item.value === modelValue.value[i]) {
            item.children = data[i]
            i++;
            deepChildren(item.children)
          }
        })
      }
      deepChildren(administrativeDivisionTree.value)
    })
  }
})

</script>

<style scoped lang="scss">

</style>
