<!-- 资金账户下拉列表 -->
<template>
    <app-remote-select v-model="selectedValue" :options="dataList"
        :option-props="{ label: 'relatedName', value: 'accountId' }" :remote-method="remoteMethod" @change="onChange"
        @reset="onReset">
        <template #default="{ option }">
            <div style="display: flex;justify-content: space-between;">
                <span>{{ option.accountId }}</span>
                <span>{{ option.relatedName }}</span>
            </div>
        </template>
    </app-remote-select>
</template>

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

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

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

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

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

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

const remoteMethod = (query: string) => {
    if (!loading.value) {
        if (query) {
            run({
                searchCode: query
            })
        } else if (!selectedValue.value) {
            onReset()
        }
    }
}

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

defineExpose({
    onReset
})
</script>