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

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

import CreateBankEntityForm from '../CreateBankEntityForm.vue';

const $props = defineProps({
    iban: {
        type: String,
        default: null,
    },
    bankEntityFk: {
        type: Number,
        default: null,
    },
    disableElement: {
        type: Boolean,
        default: false,
    },
});
const filter = {
    fields: ['id', 'bic', 'name'],
    order: 'bic ASC',
};
const { t } = useI18n();
const emit = defineEmits(['updateBic']);
const iban = ref($props.iban);
const bankEntityFk = ref($props.bankEntityFk);
const bankEntities = ref([]);

const autofillBic = async (bic) => {
    if (!bic) return;
    const bankEntityId = parseInt(bic.substr(4, 4));
    const ibanCountry = bic.substr(0, 2);
    if (ibanCountry != 'ES') return;

    const existBank = bankEntities.value.find((b) => b.id === bankEntityId);
    bankEntityFk.value = existBank ? bankEntityId : null;
    emit('updateBic', { iban: iban.value, bankEntityFk: bankEntityFk.value });
};

const getBankEntities = (data) => {
    bankEntityFk.value = data.id;
};
</script>
<template>
    <FetchData
        url="BankEntities"
        :filter="filter"
        auto-load
        @on-fetch="(data) => (bankEntities = data)"
    />
    <VnInput
        :label="t('IBAN')"
        clearable
        v-model="iban"
        @update:model-value="autofillBic($event)"
        :disable="disableElement"
    >
        <template #append>
            <QIcon name="info" class="cursor-info">
                <QTooltip>{{ t('components.iban_tooltip') }}</QTooltip>
            </QIcon>
        </template>
    </VnInput>
    <VnSelectDialog
        :label="t('Swift / BIC')"
        :acls="[{ model: 'BankEntity', props: '*', accessType: 'WRITE' }]"
        :options="bankEntities"
        hide-selected
        option-label="bic"
        option-value="id"
        v-model="bankEntityFk"
        @update:model-value="$emit('updateBic', { iban, bankEntityFk })"
        :disable="disableElement"
    >
        <template #form>
            <CreateBankEntityForm @on-data-saved="getBankEntities($event)" />
        </template>
        <template #option="scope">
            <QItem v-bind="scope.itemProps">
                <QItemSection v-if="scope.opt">
                    <QItemLabel>{{ scope.opt.bic }} </QItemLabel>
                    <QItemLabel caption> {{ scope.opt.name }}</QItemLabel>
                </QItemSection>
            </QItem>
        </template>
    </VnSelectDialog>
</template>
