<template>
    <el-select ref="selectDropRef" :multiple-limit="limit" @change="changeSelect" multiple v-model="value" filterable popper-class="custom-dropdown" remote reserve-keyword :remote-method="remoteMethod" remote-show-suffix clearable placeholder="请选择适用企业">
        <div class="optionBox" infinite-scroll-delay="500" infinite-scroll-distance="20" v-infinite-scroll="load">
            <template v-if="optionsV.length">
                <el-option v-for="item in optionsV" :key="item.value" :label="item.cpyName" :value="item.cpyid"></el-option>
            </template>
            <template v-for="item in options" :key="item.cpyid">
                <el-option v-if="!isOptionsV(item.cpyid)" :label="item.cpyName" :value="item.cpyid"></el-option>
            </template>
        </div>
    </el-select>
</template>
<script setup lang="ts">
import { getEnterpriseDetail, getEnterpriseList } from '@/api/cdt/menus'
import { propTypes } from '@/utils/propTypes';
// 防抖
import { debounce } from 'lodash';
const props = defineProps({
    modelValue: propTypes.any.def([]),
    params: {
        type: Object,
        default: () => ({})
    },
    limit: {
        type: Number,
        default: 0
    }
})
const emit = defineEmits(['change', 'update:modelValue', 'changeItem'])
const value = ref<string[]>([])
const options = ref([])
const optionsV = ref([])
const total = ref(0)
const selectDropRef = ref(null)
const queryParams = ref({
    pageSize: 10,
    pageNum: 1,
    cpyName: '',
})
const getList = async (hasRx = true) => {
    if (hasRx) {
        queryParams.value.pageNum = 1
        options.value = []
    }
    const res = await getEnterpriseList({ ...queryParams.value, ...props.params })
    total.value = res.total;
    if (hasRx) {
        options.value = res.rows
    } else {
        options.value = options.value.concat(res.rows)
    }
}
const remoteMethod = (text: string) => {
    if (text) {
        queryParams.value.cpyName = text
        selectSearch()
    }
}
const load = () => {
    if (options.value.length < total.value) {
        queryParams.value.pageNum++
        getList(false)
    }
}
const changeSelect = (val: string[]) => {
    const itemInfo = options.value.filter(item => val.includes(item.cpyid))
    emit('update:modelValue', val)
    emit('change', val)
    emit('changeItem', itemInfo)
}
// 判断是否在optionsV
const isOptionsV = (val: string) => {
    return optionsV.value.some((item) => item.cpyid === val)
}
// 获取当前id对应的企业信息
const selectSearch = debounce(() => {
    getList()
}, 500)
// 根据values获取下拉框的options
const getOptions = async (values: string[]) => {
    if (!values.length) {
        return
    }
    values.forEach(async (item) => {
        if ([...optionsV.value, ...options.value].find((v) => v.cpyid === item)) {
            return
        }
        const res = await getEnterpriseDetail(item)
        res?.data && optionsV.value.push(res.data)
    })
}
onMounted(() => {
    getList()
    nextTick(() => {
      // 获取下拉框的dom
      const dropdown = document.querySelector('.custom-dropdown .el-select-dropdown__wrap');
      dropdown.addEventListener('scroll', () => {
        if (dropdown.scrollTop + dropdown.clientHeight >= dropdown.scrollHeight) {
          // 在这里执行你的操作
          load()
        }
      });
    });
})
watch(() => props.modelValue, (val) => {
    value.value = val
    getOptions(val)
}, { immediate: true })
</script>
