<!-- @/components/TreeSelect.vue -->
<template>
    <a-tree-select v-model:value="modelValue" show-search :style="{ width: width }"
        :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" :placeholder="placeholder" :allow-clear="allowClear"
        :tree-default-expand-all="defaultExpandAll" :tree-data="localTreeData" :tree-node-filter-prop="filterProp"
        :disabled="disabled" :loading="loading"  @change="handleChange" @search="handleSearch" @focus="handleFocus"
        @blur="handleBlur">
      
    </a-tree-select>
</template>

<script setup>
import { ref, watch, onMounted,defineModel } from 'vue'
import { useDicsStore } from '@/store'
const dicsStore = useDicsStore()
const modelValue = defineModel();
const props = defineProps({
    allowClear:{
        type:Boolean,
        default:false
    },
    width: {
        type: String,
        default: '100%'
    },
    placeholder: {
        type: String,
        default: '请选择节点'
    },
    filterProp: {
        type: String,
        default: 'label'
    },
    defaultExpandAll: {
        type: Boolean,
        default: true
    },
    disabled: {
        type: Boolean,
        default: false
    },
    // 是否启用从 store 自动加载（可选）
    useStore: {
        type: Boolean,
        default: true
    }
})

const emit = defineEmits(['update:modelValue', 'change', 'search', 'focus', 'blur'])


const localTreeData = ref([])
const loading = ref(false)

// 监听 store 数据变化（响应式）
watch(
    () => dicsStore.orgTree,
    (newVal) => {
        if (newVal?.length > 0) {
            localTreeData.value = newVal
            console.log('localTreeData',localTreeData.value)
            // modelValue.value=localTreeData.value[0].value
            loading.value = false
        }
    },
    { immediate: true }
)

// 组件挂载时：如果启用了 store，且数据未加载，则主动加载
onMounted(async () => {
    if (props.useStore) {
        if (dicsStore.orgTree.length === 0 && !loading.value) {
            loading.value = true
            try {
                await dicsStore.loadOrgTree()
                // 数据会通过 watch 自动同步
            } catch (error) {
                loading.value = false
            }
        }
    }
})

const handleChange = (value, label, extra) => {
    emit('change', value, label, extra)
}

const handleSearch = (value) => {
    console.log(value)
    emit('search', value)
}

const handleFocus = () => {
    emit('focus')
}

const handleBlur = () => {
    emit('blur')
}
</script>