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

import FetchData from 'components/FetchData.vue';
import CrudModel from 'components/CrudModel.vue';
import VnRow from 'components/ui/VnRow.vue';
import VnInput from 'src/components/common/VnInput.vue';
import CreateBankEntityForm from 'src/components/CreateBankEntityForm.vue';
import VnSelectDialog from 'src/components/common/VnSelectDialog.vue';

import axios from 'axios';
import useNotify from 'src/composables/useNotify.js';
import { useQuasar } from 'quasar';

const quasar = useQuasar();
const { notify } = useNotify();
const route = useRoute();
const { t } = useI18n();

const bankEntitiesRef = ref(null);
const supplier = ref(null);
const supplierAccountRef = ref(null);
const wireTransferFk = ref(null);
const bankEntitiesOptions = ref([]);

const onBankEntityCreated = async (dataSaved, rowData) => {
    await bankEntitiesRef.value.fetch();
    rowData.bankEntityFk = dataSaved.id;
};

const onChangesSaved = () => {
    if (supplier.value.payMethodFk !== wireTransferFk.value)
        quasar
            .dialog({
                message: t('Do you want to change the pay method to wire transfer?'),
                ok: {
                    push: true,
                    color: 'primary',
                },
                cancel: true,
            })
            .onOk(async () => {
                await setWireTransfer();
            });
};

const setWireTransfer = async () => {
    try {
        const params = {
            id: route.params.id,
            payMethodFk: wireTransferFk.value,
        };

        await axios.patch(`Suppliers/${route.params.id}`, params);
        notify('globals.dataSaved', 'positive');
    } catch (err) {
        console.error('Error setting wire transfer', err);
    }
};
</script>
<template>
    <FetchData
        ref="bankEntitiesRef"
        url="BankEntities"
        @on-fetch="(data) => (bankEntitiesOptions = data)"
        auto-load
    />
    <FetchData
        url="payMethods/findOne"
        @on-fetch="(data) => (wireTransferFk = data.id)"
        :filter="{ where: { code: 'wireTransfer' } }"
        auto-load
    />
    <FetchData
        :url="`Suppliers/${route.params.id}`"
        @on-fetch="(data) => (supplier = data)"
        auto-load
    />
    <CrudModel
        data-key="SupplierAccount"
        url="SupplierAccounts"
        model="SupplierAccounts"
        :filter="{
            fields: ['id', 'supplierFk', 'iban', 'bankEntityFk', 'beneficiary'],
            where: { supplierFk: route.params.id },
        }"
        ref="supplierAccountRef"
        :default-remove="false"
        :data-required="{ supplierFk: route.params.id }"
        @save-changes="onChangesSaved()"
        auto-load
    >
        <template #body="{ rows }">
            <QCard class="q-pa-md">
                <VnRow
                    v-for="(row, index) in rows"
                    :key="index"
                    class="row q-gutter-md q-mb-md"
                >
                    <VnInput
                        :label="t('supplier.accounts.iban')"
                        v-model="row.iban"
                        :required="true"
                    >
                        <template #append>
                            <QIcon name="info" class="cursor-info">
                                <QTooltip>{{ t('components.iban_tooltip') }}</QTooltip>
                            </QIcon>
                        </template>
                    </VnInput>
                    <VnSelectDialog
                        :label="t('worker.create.bankEntity')"
                        v-model="row.bankEntityFk"
                        :options="bankEntitiesOptions"
                        option-label="bic"
                        option-value="id"
                        hide-selected
                        :required="true"
                        :roles-allowed-to-create="['financial']"
                    >
                        <template #form>
                            <CreateBankEntityForm
                                @on-data-saved="
                                    (_, requestResponse) =>
                                        onBankEntityCreated(requestResponse, row)
                                "
                                :show-entity-field="false"
                            />
                        </template>
                        <template #option="scope">
                            <QItem v-bind="scope.itemProps">
                                <QItemSection v-if="scope.opt">
                                    <QItemLabel
                                        >{{ scope.opt.bic }}
                                        {{ scope.opt.name }}</QItemLabel
                                    >
                                </QItemSection>
                            </QItem>
                        </template>
                    </VnSelectDialog>
                    <VnInput
                        :label="t('supplier.accounts.beneficiary')"
                        v-model="row.beneficiary"
                    >
                        <template #append>
                            <QIcon name="info" class="cursor-pointer">
                                <QTooltip>{{
                                    t(
                                        'Name of the bank account holder if different from the provider'
                                    )
                                }}</QTooltip>
                            </QIcon>
                        </template>
                    </VnInput>
                    <div class="col-1 row justify-center items-center">
                        <QIcon
                            name="delete"
                            size="sm"
                            class="cursor-pointer"
                            color="primary"
                            @click="supplierAccountRef.remove([row])"
                        >
                            <QTooltip>
                                {{ t('Remove account') }}
                            </QTooltip>
                        </QIcon>
                    </div>
                </VnRow>
                <VnRow>
                    <QBtn
                        flat
                        icon="add"
                        shortcut="+"
                        class="cursor-pointer"
                        color="primary"
                        @click="supplierAccountRef.insert()"
                    >
                        <QTooltip>
                            {{ t('Add account') }}
                        </QTooltip>
                    </QBtn>
                </VnRow>
            </QCard>
        </template>
    </CrudModel>
</template>

<i18n>
    es:
        Do you want to change the pay method to wire transfer?: ¿Quieres modificar la forma de pago a transferencia?
        Add account: Añadir cuenta
        Remove account: Remover cuenta
        Name of the bank account holder if different from the provider: Nombre del titular de la cuenta bancaria en caso de ser diferente del proveedor
</i18n>
