<template>
    <div class="el-form-item--col">
        <el-select ref="selectRef" v-model="selectedValue" :empty-values="[null, undefined, 0]" :disabled="disabled"
            :loading="loading" :placeholder="placeholder" :remote-method="remoteMethod" @change="onChange" remote
            filterable clearable>
            <el-option v-for="item in dataList" :key="item.userid" :label="item.accountname" :value="item.userid">
                <div style="display: flex;justify-content: space-between;">
                    <span>{{ item.userid }}</span>
                    <span>{{ item.accountname }}</span>
                </div>
            </el-option>
        </el-select>
        <!-- <el-button icon="Plus" link @click="onPlus" /> -->
    </div>
</template>

<script lang="ts" setup>
import { shallowRef, computed, toRaw } from 'vue'
import { ElMessage } from 'element-plus'
import { useRequest } from '@/hooks/request'
import { queryOrganSelect } from '@/services/api/common'

const props = defineProps({
    modelValue: [Number, String],
    usertype: String,
    disabled: Boolean,
    placeholder: {
        type: String,
        default: '请输入'
    }
})

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

const selectRef = shallowRef()

const selectedValue = computed({
    get: () => props.modelValue,
    set: (val) => emit('update:modelValue', val)
})

const { dataList, loading, runAsync } = useRequest(queryOrganSelect, {
    manual: true
})

const onPlus = () => {
    if (!loading.value) {
        loading.value = true
        runAsync({
            usertype: props.usertype
        }).then((res) => {
            if (res.data.length) {
                selectRef.value.toggleMenu()
            } else {
                ElMessage.warning('暂无数据')
            }
        }).catch((err) => {
            ElMessage.error(err)
        }).finally(() => {
            loading.value = false
        })
    }
}

const remoteMethod = (query: string) => {
    if (query) {
        loading.value = true
        runAsync({
            usertype: props.usertype,
            searchcode: query
        }).finally(() => {
            loading.value = false
        })
    }
}

const onChange = (id?: number) => {
    const item = dataList.value.find((e) => e.userid === id)
    dataList.value = []
    emit('change', toRaw(item))
}
</script>

<style lang="less">
@import './index.less';
</style>