<template>
    <el-cascader
        v-model="selectedValue"
        :options="areaOptions"
        :props="propsCascader"
        @change="handleChange"
        style="width: 100%"
        placeholder="请选择省/市/区"
        clearable
        :key="componentKey"
    />
</template>

<script setup>
    import { ref, watch, onMounted, computed } from 'vue';
    import request from '@/utils/request';

    const props = defineProps({
        modelValue: {
            type: Array,
            default: () => []
        },
        level: {
            type: Number,
            default: 2
        }
    });

    const emit = defineEmits(['update:modelValue']);

    const selectedValue = ref([]);
    const areaOptions = ref([]);

    // 创建一个响应式的key，用于强制重新渲染
    const componentKey = computed(() => {
        // 当modelValue发生变化时，生成新的key
        return props.modelValue ? props.modelValue.join('-') : 'empty';
    });

    // 配置级联选择器属性
    const propsCascader = {
        lazy: true,
        lazyLoad: loadAreaData,
        value: 'id',
        label: 'district',
        checkStrictly: false
    };

    // 监听外部传入的值变化，用于数据回填
    watch(
        () => props.modelValue,
        (newVal) => {
            console.log(newVal, 'AreaSelect received newVal');
            selectedValue.value = newVal || [];
        },
        { immediate: true, deep: true }
    );

    // 值变化时触发
    const handleChange = (value) => {
        console.log('AreaSelect handleChange:', value);
        emit('update:modelValue', value);
    };

    // 加载区域数据
    async function loadAreaData(node, resolve) {
        const { level, value } = node;
        console.log('loadAreaData called:', level, value);
        try {
            let data = [];
            if (level === 0) {
                // 加载省份数据
                data = await getProvinceList();
                console.log('省份数据:', data);
            } else if (level === 1) {
                // 加载城市数据
                data = await getProvinceList(value);
                console.log('城市数据:', data);
            } else if (level === 2) {
                // 加载区县数据
                data = await getProvinceList(value);
                data.forEach((item) => {
                    item.leaf = true;
                });
                console.log('区县数据:', data);
            }
            resolve(data);
        } catch (error) {
            console.error('加载地区数据失败:', error);
            resolve([]);
        }
    }

    function getProvinceList(id = 1) {
        return new Promise((resolve, reject) => {
            request
                .get(`/baseinfo/districtInfo/findInfo/${id}`)
                .then((res) => {
                    resolve(res.data.data);
                })
                .catch((err) => {
                    resolve([]);
                    reject(err);
                });
        });
    }

    onMounted(() => {
        console.log('AreaSelect mounted');
        // 不需要在mounted时预加载，懒加载会自动处理
    });
</script>

<style scoped>
    .el-cascader {
        width: 100%;
    }
</style>
