<template>
	<el-cascader  :filterable="false" :props="cascaderProps" clearable :disabled="disabled" v-model="selectedOptions" @change="handleChange"/>
</template>
<script setup lang="ts" name="china-area">
  import { ref,onMounted,computed } from 'vue'
import type { CascaderProps } from 'element-plus'
import {getCityByList} from "@/api/system/user";
const emit = defineEmits(['update:modelValue', 'change']);
const optionsData = ref();
const mapData=ref({})
const props = defineProps({
	// 当前的值
	modelValue: [String,Array],
	// 类型 (二级联动，三级联动)
	type: {
		type: Number,
		default: 3,
	},
	// 是否禁用
	disabled: {
		type: Boolean,
		default: () => false,
	},
});

const cascaderProps: CascaderProps = {
  value: 'areaCode',
  label: 'name',
  leaf: 'hasChild',
  lazy: true,
  lazyLoad: function (node, resolve) {
    let level = node.level
    let value = node.value
    getCityList(value ? value : 0, level, resolve)
  }
}

const getCityList= (pid:any, level:any, resolve:any)=> {
  getCityByList(pid).then(data => {
    for (let i = 0; i < data.length; i++) {
      data[i].areaCode = parseInt(data[i].areaCode)
      data[i].hasChild = level >= props.type-1 ? true : false
    }
    mapData.value[pid] = data
    resolve(data ? data : [])
  }).catch(e => {
    resolve([])
  });
}

const selectedOptions = computed({
	get: () => {
		return props.modelValue;
	},
	set: (val) => {
		emit('update:modelValue', val);
	},
});

const findListChild= (list:any, value:any)=>{
  let child = null
  for (let i = 0; i < list.length; i++) {
    if (list[i].areaCode == value) {
      child = list[i]
      break;
    }
  }
  return child
}

const handleChange = (value: String[]) => {
  let receiveText = ''
  if (value&&value.length>0) {
    if (mapData.value[0]) {
      for (let i = 0; i < value.length; i++) {
        if (i === 0) {
          let child = findListChild(mapData.value[0], value[i])
          receiveText += child ? child.name : ''
        } else {
          let child = findListChild(mapData.value[value[i - 1]], value[i])
          receiveText += child ? child.name : ''
        }
      }
    }
  }
	emit('change', receiveText);
};

onMounted(() => {
});
</script>
<style lang="scss">
.el-cascader-menu{
  background-color: #ffffff;
}
</style>
