<template>
    <app-remote-select v-model="selectedValue" :options="dataList"
        :option-props="{ label: 'accountname', value: 'userid' }" :disabled="disabled" :remote-method="remoteMethod"
        @change="onChange" @reset="onReset">
        <template #default="{ option }">
            <div style="display: flex;justify-content: space-between;">
                <span>{{ option.userid }}</span>
                <span>{{ option.accountname }}</span>
            </div>
        </template>
    </app-remote-select>
</template>

<script lang="ts" setup>
import { computed, toRaw } from 'vue'
import { useRequest } from '@/hooks/request'
import { queryOrganSelect } from '@/services/api/common'
import AppRemoteSelect from '@pc/components/base/remote-select/index.vue'

const props = defineProps({
    modelValue: [Number, String],
    usertype: String,
    disabled: Boolean
})

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

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

const { dataList, loading, run } = useRequest(queryOrganSelect, {
    params: {
        usertype: props.usertype
    }
})

const onReset = () => {
    if (!loading.value) {
        selectedValue.value = undefined
        run()
    }
}

const remoteMethod = (query: string) => {
    if (!loading.value) {
        if (query) {
            run({
                searchcode: query
            })
        } else if (!dataList.value.length) {
            onReset()
        }
    }
}

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