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

<script setup>
import { ref, watch, onMounted } 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([])

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

// 监听外部传入的值变化，用于数据回填
watch(() => props.modelValue, (newVal) => {
    console.log(newVal, 'newVal')
    if (newVal && newVal.length > 0) {
        selectedValue.value = newVal
        // 如果有初始值，需要预加载数据
        initAreaData(newVal)
    }
}, { immediate: true, deep: true })

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

// 加载区域数据
async function loadAreaData(node, resolve) {
    const { level, value } = node
    try {
        let data = []
        if (level === 0) {
            // 加载省份数据
            data = await getProvinceList()
            console.log(data, 'data')
        } else if (level === 1) {
            // 加载城市数据
            data = await getProvinceList(value)
        } else if (level === 2) {
            // 加载区县数据
            data = await getProvinceList(value)
            data.forEach(item => {
                item.leaf = true
            })
        }
        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)
        })
    })
}

// 初始化数据（用于回填）
async function initAreaData(codes) {
    try {
        // 加载省份列表
        areaOptions.value = await getProvinceList()

        if (codes.length > 0) {
            // 预加载市
            const cityList = await getProvinceList(codes[0])
            const province = areaOptions.value.find(p => p.id === codes[0])
            if (province) {
                province.children = cityList
            }

            if (codes.length > 1) {
                // 预加载区
                const districtList = await getProvinceList(codes[1])
                const city = cityList.find(c => c.id === codes[1])
                if (city) {
                    city.children = districtList
                }
            }
        }
    } catch (error) {
        console.error('初始化地区数据失败:', error)
    }
}

onMounted(() => {
    // 初始加载省份数据
    loadAreaData({ level: 0 }, (data) => {
        areaOptions.value = data
    })
})
</script>

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