<!-- 子机构开户下拉查询推荐人 -->
<template>
    <app-remote-select v-model="selectedValue" :options="dataList"
        :option-props="{ label: 'accountName', value: 'userId' }" :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, PropType } from 'vue'
import { useRequest } from '@/hooks/request'
import { queryInvestorSelect } from '@/services/api/common'
import AppRemoteSelect from '@pc/components/base/remote-select/index.vue'

const props = defineProps({
    modelValue: String,
    params: {
        type: Object as PropType<Model.InvestorSelectReq>
    },
})

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

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

const { dataList, loading, run } = useRequest(queryInvestorSelect, {
    manual: true,
    params: props.params,
    onSuccess: (res) => {
        if (!res.data.some((e) => e.userId.toString() === selectedValue.value?.toString())) {
            selectedValue.value = undefined
            onChange()
        }
    }
})

const onReset = () => {
    if (!loading.value) {
        run(props.params)
    }
}

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

const onChange = (value?: number) => {
    const item = dataList.value.find((e) => e.userId === value)
    emit('change', item && toRaw(item))
}

defineExpose({
    onReset
})
</script>