<script setup>
import { useI18n } from 'vue-i18n';
import axios from 'axios';

import VnInput from 'src/components/common/VnInput.vue';

const { t } = useI18n();
const model = defineModel({ type: [Number, String] });
const emit = defineEmits(['updateBic']);

const getIbanCountry = (bank) => {
    return bank.substr(0, 2);
};

const autofillBic = async (iban) => {
    if (!iban) return;

    const bankEntityId = parseInt(iban.substr(4, 4));
    const ibanCountry = getIbanCountry(iban);

    if (ibanCountry != 'ES') return;

    const filter = { where: { id: bankEntityId } };
    const params = { filter: JSON.stringify(filter) };

    const { data } = await axios.get(`BankEntities`, { params });

    emit('updateBic', data[0]?.id);
};
</script>
<template>
    <VnInput
        :label="t('IBAN')"
        clearable
        v-model="model"
        @update:model-value="autofillBic($event)"
    >
        <template #append>
            <QIcon name="info" class="cursor-info">
                <QTooltip>{{ t('components.iban_tooltip') }}</QTooltip>
            </QIcon>
        </template>
    </VnInput>
</template>
