<!-- 查询托管银行支持银行 -->
<template>
    <div class="el-form-item--col">
        <el-select ref="selectRef" v-model="selectedItem" :loading="loading" :placeholder="placeholder"
            value-key="bankId" :remote-method="remoteMethod" @change="onChange" remote filterable clearable>
            <el-option v-for="item in dataList" :key="item.bankId" :label="item.bankName" :value="item" />
        </el-select>
        <!-- <el-button icon="Plus" link @click="onPlus" /> -->
    </div>
</template>

<script lang="ts" setup>
import { computed, shallowRef, toRaw, PropType, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useRequest } from '@/hooks/request'
import { getBankInfoByCusBank } from '@/services/api/bank'
import { i18n } from '@/stores'

const props = defineProps({
    cusbankid: String,
    selected: {
        type: Object as PropType<Model.BankInfoByCusBankRsp>
    },
    placeholder: {
        type: String,
        default: i18n.global.t('common.pleaseenter')
    }
})

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

const selectRef = shallowRef()

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

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

const onPlus = () => {
    if (!loading.value) {
        loading.value = true
        runAsync({
            cusBankId: props.cusbankid
        }).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({
            cusBankId: props.cusbankid,
            bankName: query
        }).finally(() => {
            loading.value = false
        })
    }
}

const onChange = (item?: Model.BankInfoByCusBankRsp) => {
    emit('change', item && toRaw(item))
}

watch(() => props.selected, (e) => {
    if (e) {
        dataList.value = [e]
    } else {
        dataList.value = []
    }
})
</script>

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