<script setup>
	import { getDictData } from '@/api/basic.info/dict'
	import { getAllChildrenData } from '@/api/emergencySupport'

	const props = defineProps({
		value: {
			type: Array,
			required: true
		},
		readonly: {
			type: Boolean,
			required: false,
			default: false
		}
	})

	const regionOptions = ref([])

	const selected = ref(props.value)

	const load = (id) => {
		return getAllChildrenData(id)
			.then((res) => {
				const datas = res.map((v) => {
					let row = { label: v.dictLabel, value: v.dictValue, id: v.id, pid: v.parentId, sortCode: v.sortCode }
					row['isLeaf'] = v.sortCode.toString().length >= 6
					return row
				})
				return datas
				// if (cb) {
				// 	cb(datas)
				// } else {
				// 	regionOptions.value = datas || []
				// }
			})
			.catch()
	}

	watch(
		() => props.value,
		(n, o) => {
			selected.value = n
			loadOptions()
		}
	)
	const getDataId = (datas, rid) => {
		console.log('333', datas, rid)
		return datas.find((d) => d.value === rid)
	}
	const loadOptions = async () => {
		if (regionOptions.value.length <= 0) {
			await getFirstLevel()
		}
		const [pid, cid1, cid2] = selected.value
		const p = getDataId(regionOptions.value, pid)
		const query1 = {
			id: p.id,
			isQueryFristNode: false
		}
		// console.log('111', regionOptions.value)
		load(query1).then((datas) => {
			console.log('222', datas)
			p.children = datas
			const c1 = getDataId(p.children, cid1)
			const query2 = {
				id: c1.id,
				isQueryFristNode: false
			}
			load(query2).then((datas) => {
				c1.children = datas
			})
		})
		// initProvince(query, (data) => {
		// 	console.log(regionOptions.value)
		// 	console.log(data)
		// })
	}

	const loadRegionData = (selectedOptions) => {
		const targetOption = selectedOptions[selectedOptions.length - 1]
		targetOption.loading = true
		const query = {
			id: targetOption.id,
			isQueryFristNode: selectedOptions.length >= 2
		}
		// initProvince(query, (data) => {
		// 	targetOption.loading = false
		// 	targetOption.children = data
		// })
		load(query).then((datas) => {
			targetOption.loading = false
			targetOption.children = datas
		})
	}

	const emit = defineEmits(['on-change', 'update:value'])

	const selectChanged = (val, selectedOptions) => {
		console.log('region select', val, selectedOptions)
		emit('update:value', val)
		emit('on-change', val, selectedOptions)
	}

	const getFirstLevel = () => {
		return load({
			id: '1781533421287342082',
			isQueryFristNode: true
		}).then((datas) => {
			regionOptions.value = datas || []
		})
	}

	onMounted(() => {
		getFirstLevel()
	})
</script>

<template>
	<a-cascader
		:disabled="readonly"
		class="address-box"
		:options="regionOptions"
		:load-data="loadRegionData"
		placeholder="请选择"
		v-model:value="selected"
		change-on-select
		@change="selectChanged"
	/>
</template>

<style scoped></style>
