<template>
    <el-select
        v-model="customerId"
        :placeholder="placeholder"
        filterable
        :disabled="props.disabled"
        :clearable="props.clearable"
        remote
        :remote-method="remoteMethod"
        @clear="clearCustomer"
        @visible-change="handleVisibleChange"
        @change="changeSelect"
        @blur="blurSelect"
        :loading="loading"
        :popper-class="'customer-select-' + props.source"
        :persistent="persistent"
        fit-input-width
    >
        <el-option v-for="item in customerOption" :key="item.id" :label="item[props.queryName]" :value="item.id"></el-option>
        <template #empty>
            <div>{{ loadingFlag ? '加载中' : '无数据' }}</div>
        </template>
    </el-select>
</template>

<script setup lang="ts">
    const customerId = defineModel<string | number>({ required: true })
    const props = defineProps({
        disabled:{
            type: Boolean,
            default: false
        },
        selectedName: {
            type: String
        },
        source: {
            type: String
        },
        clearable: {
            type: Boolean,
            default: true
        },
        listFn: {
            type: Function
        },
        params: {
            type: Object
        },
        queryName: {
            type: String,
            default: 'customerName'
        },
        searchName: {
            type: String,
            default: 'customerName'
        },
        placeholder: {
            type: String,
            default: '请选择客户'
        },
        isRemote: {
            type: Boolean,
            default: true
        }
    })
    const emits = defineEmits(['changeSelect', 'blurSelect'])
    const persistent = ref(true)

    watch(() => props.selectedName, (newVal) => {
        if(!customerOption.value.find(item => item.customerName === newVal)) {
            let obj = { id: customerId.value }
            obj[props.queryName] = newVal
            customerOption.value.push(obj)
        }
    })

    const customerOption = ref([])
    let pageParams = {
        pageIndex: 1,
        pageSize: import.meta.env.VITE_APP_PAGESIZE,
    }

    const totalItems = ref(0)
    const loading = ref(false)
    const loadingFlag = ref(false)
    const getData = () => {
        if(props.listFn) {
            if(pageParams.pageIndex === 1) {
                loading.value = true
                loadingFlag.value = true
            }
            let params = {
                ...props.params,
                ...pageParams
            }
            props.listFn(params).then(res => {
                if(res.success) {
                    let datas = res.result.records
                    if(pageParams.pageIndex === 1) {
                        customerOption.value = []
                    }
                    customerOption.value = [...customerOption.value, ...datas]
                    totalItems.value = res.result.total
                }
                if(customerOption.value.length != 0) {
                    loading.value = false
                }
                loadingFlag.value = false
            })
        }
    }
    setTimeout(() => {
        if(props.isRemote) {
            getData()
        }
    }, 0)


    const remoteMethod = (query: string) => {
        if(props.isRemote) {
            props.params[props.searchName] = query
            pageParams.pageIndex = 1
            if(query && props.queryName == 'customerName') {
                props.params.id = undefined
            }
            getData()
        }
    }

    const changeSelect = (val: string | number) => {
        let name = customerOption.value.find(item => item.id === val)?.customerName
        emits('changeSelect', { id: val, name: name })
    }

    const blurSelect = (val: string | number) => {
        emits('blurSelect', val)
    }

    const clearCustomer = () => {
        if(props.queryName == 'customerName') {
            props.params.id = undefined
        }
    }

    const dropdownMenu = ref(null);
    const handleVisibleChange = (visible) => {
        if(visible) {
            dropdownMenu.value = document.querySelector(`.customer-select-${ props.source } .el-select-dropdown__wrap`);
            if(dropdownMenu.value) {
                dropdownMenu.value.addEventListener('scroll', handleScroll);
            }
        } else {
            pageParams.pageIndex = 1
            if(dropdownMenu.value) {
                dropdownMenu.value.removeEventListener('scroll', handleScroll);
                dropdownMenu.value = null
            }
        }
    }

    const handleScroll = (event) => {
        const target = event.target;
        if (target.scrollTop + target.clientHeight >= target.scrollHeight) {
            // 滚动到底部
            if (customerOption.value.length < totalItems.value) {
                pageParams.pageIndex++;
                getData();
            }
        }
    }

    onActivated(() => {
        persistent.value = true
    })

    onDeactivated(() => {
        persistent.value = false
    })
</script>
