<script setup>
	import * as all from './data'
	import { getEnumListByEnumId, getTreeDataByEnumId } from '@/utils/systemEnum'
	import { Cascader } from 'ant-design-vue'
	import { clone } from '@/utils/systemUtils'
	const props = defineProps({
		type: {
			type: String,
			required: true
		},
		value: {
			type: [String, Number],
			required: true
		},
		readonly: {
			type: Boolean,
			required: false,
			default: false
		},
		loadType: {
			type: String,
			required: false,
			default: 'static'
		},
		multiple: {
			type: Boolean,
			required: false,
			default: false
		}
	})

	const selected = ref(null)

	watch(
		() => props.value,
		(n, o) => {
			selected.value = parseValue(options.value, n)
		}
	)

	const parseValue = (arr, v) => {
		if (Array.isArray(v)) return v
		v = v + ''
		const helper = (node, path) => {
			path.push(node.value)

			if (node.value === v) {
				return path
			}
			if (node.children) {
				for (const child of node.children) {
					const result = helper(child, [...path]) // 使用新的路径数组
					if (result) {
						return result
					}
				}
			}

			return null
		}

		// 遍历顶层节点
		for (const node of arr) {
			const result = helper(node, [])
			if (result) {
				return result
			}
		}

		return null
	}

	const findValue = (arr, val) => {
		if (arr.length <= 0) return
		if (null == val) return []
		for (const a of arr) {
			if (a.value === val) return a
			if (a.children && a.children.length > 0) {
				return findValue(a.children, val)
			}
		}
		return null
	}

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

	const handleChange = (n) => {
		emit('update:value', n)
		const o = n ? n.map((d) => findValue(options.value, d)) : []
		emit('on-change', n, clone(o))
	}

	const options = ref([])

	onMounted(() => {
		if (props.loadType === 'static') {
			options.value = all[props.type]
		} else if (props.loadType === 'enum') {
			getTreeDataByEnumId(props.type).then((list) => {
				options.value = list || []
			})
		}
	})
</script>

<template>
	<a-cascader
		v-if="props.multiple"
		:disabled="readonly"
		multiple
		:show-checked-strategy="Cascader.SHOW_CHILD"
		class="address-box"
		:options="options"
		placeholder="请选择"
		v-model:value="selected"
		change-on-select
		@change="handleChange"
	/>
	<a-cascader
		v-else
		:disabled="readonly"
		class="address-box"
		:options="options"
		placeholder="请选择"
		v-model:value="selected"
		change-on-select
		@change="handleChange"
	/>
</template>

<style scoped></style>
