<template>
    <el-select placeholder="选择业务类型" v-model="resourceType" @change="changeResource" :disabled="props.disabled">
        <el-option v-for="item in dictData.businessData" :label="item.label" :value="item.value"></el-option>
    </el-select>
    <el-select
        :disabled="props.disabled"
        placeholder="选择"
        v-model="resourceTypeId"
        fit-input-width
        filterable
        remote
        :remote-method="remoteMethod"
        @visible-change="handleVisibleChange"
        popper-class="customer-select"
        :loading="loading"
        :persistent="persistent"
    >
        <el-option v-for="item in linkWorkData" :label="item.label" :value="item.value"></el-option>
        <template #empty>
            <div>{{ loadingFlag ? '加载中' : '无数据' }}</div>
        </template>
    </el-select>
</template>

<script setup lang="ts">
    import request from '@/utils/request';
    import { listDetialByCodes } from "@/api/system/dict/";

    const props = defineProps(['resourceName', 'disabled', 'customerId'])

    const resourceType = defineModel<string>()
    const resourceTypeId = defineModel('resourceTypeId')

    const dictData: any = reactive({
        businessData: []
    })
    const getDictData = () => {
        listDetialByCodes(['work_data_group']).then((res => {
            if(res.success) {
                dictData.businessData = res.result['work_data_group'].filter(item => item.label != '业绩目标')
                if(props.resourceName) {
                    changeResourceType(resourceType.value)
                    linkWorkData.value.push({
                        label: props.resourceName,
                        value: resourceTypeId.value
                    })
                }
            }
        }))
    }

    const linkWorkData = ref([])
    const totalItems = ref(0)
    let pageParams = { pageIndex: 1, pageSize: import.meta.env.VITE_APP_PAGESIZE }
    let extField = null
    let params: any = {}

    const changeResourceType = (val: string) => {
        let obj: { extField: string } = dictData.businessData.find((a: { value: string }) => a.value == val)
        if(!obj.extField) return
        extField = JSON.parse(obj.extField)
        params = { commonScope: 1, commonScopeType: val, customerId: props.customerId }
        if(val == '10' || val == '11') {
            params.customerForm = val
            params.hasPublicCustomer = 0
            params.hasGarbageCustomer = 0
        }
    }

    const changeResource = (val) => {
        resourceTypeId.value = undefined
        changeResourceType(val)
    }

    const getData = () => {
        if(pageParams.pageIndex === 1) {
            loading.value = true
            loadingFlag.value = true
        }
        let requestParams = { ...pageParams, ...params }
        request({
            url: extField.requesUrl,
            method: extField.method,
            data: requestParams
        }).then(res => {
            if(res.success) {
                let datas = (res.result.records || []).map((item: any) => {
                    let data = { label: item[extField.fieldKey.nameKey], value: item[extField.fieldKey.idKey] }
                    return data
                })
                if(pageParams.pageIndex === 1) {
                    linkWorkData.value = []
                }
                linkWorkData.value = [...linkWorkData.value, ...datas]
                totalItems.value = res.result.total
            }
            if(linkWorkData.value.length != 0) {
                loading.value = false
            }
            loadingFlag.value = false
        })
    }

    const persistent = ref(true)
    const loading = ref(false)
    const loadingFlag = ref(false)

    const remoteMethod = (query: string) => {
        if(resourceType.value) {
            params[params.commonScopeType == '20' ? 'liaisonName' : extField.fieldKey.nameKey] = query
            pageParams.pageIndex = 1
            getData()
        }
    }

    const dropdownMenu = ref(null);
    const handleVisibleChange = (visible) => {
        if(visible) {
            dropdownMenu.value = document.querySelector(`.customer-select .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 (linkWorkData.value.length < totalItems.value) {
                pageParams.pageIndex++;
                getData();
            }
        }
    }

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

    onDeactivated(() => {
        persistent.value = false
    })

    onMounted(() => {
        getDictData()
    })
</script>
