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

import useNotify from 'src/composables/useNotify.js';
import FormModel from 'components/FormModel.vue';
import VnRow from 'components/ui/VnRow.vue';
import VnInput from 'src/components/common/VnInput.vue';
import VnSelect from 'src/components/common/VnSelect.vue';
import VnLocation from 'src/components/common/VnLocation.vue';
import VnCheckbox from 'src/components/common/VnCheckbox.vue';
import { getDifferences, getUpdatedValues } from 'src/filters';
import VnConfirm from 'src/components/ui/VnConfirm.vue';

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

function handleLocation(data, location) {
    const { town, code, provinceFk, countryFk } = location ?? {};
    data.postcode = code;
    data.city = town;
    data.provinceFk = provinceFk;
    data.countryFk = countryFk;
}
function onBeforeSave(formData, originalData) {
    return getUpdatedValues(
        Object.keys(getDifferences(formData, originalData)),
        formData,
    );
}

async function checkEtChanges(data, _, originalData) {
    isTaxDataChecked.value = data.isTaxDataChecked;
    const equalizatedHasChanged = originalData.isEqualizated != data.isEqualizated;
    const hasToInvoiceByAddress =
        originalData.hasToInvoiceByAddress || data.hasToInvoiceByAddress;
    if (equalizatedHasChanged && hasToInvoiceByAddress) {
        quasar.dialog({
            component: VnConfirm,
            componentProps: {
                title: t('You changed the equalization tax'),
                message: t('Do you want to spread the change?'),
                promise: () => acceptPropagate(data),
            },
        });
    } else if (equalizatedHasChanged) {
        await acceptPropagate(data);
    }
}

async function acceptPropagate({ isEqualizated }) {
    await axios.patch(`Clients/${route.params.id}/addressesPropagateRe`, {
        isEqualizated,
    });
    notify(t('Equivalent tax spreaded'), 'warning');
}
const isTaxDataChecked = ref(false);

function isRequired({ isTaxDataChecked: taxDataChecked }) {
    if (!isTaxDataChecked.value) {
        return false;
    } else {
        return taxDataChecked;
    }
}
</script>

<template>
    <FormModel
        :url-update="`Clients/${route.params.id}/updateFiscalData`"
        auto-load
        model="Customer"
        :mapper="onBeforeSave"
        observe-form-changes
        @on-data-saved="checkEtChanges"
    >
        <template #form="{ data, validate, validations }">
            {{ isTaxDataChecked }} {{ data.isTaxDataChecked }}
            <VnRow>
                <VnInput
                    :label="t('Social name')"
                    :required="true"
                    :rules="validate('client.socialName')"
                    clearable
                    uppercase="true"
                    v-model="data.socialName"
                >
                    <template #append>
                        <QIcon name="info" class="cursor-info">
                            <QTooltip>{{ t('onlyLetters') }}</QTooltip>
                        </QIcon>
                    </template>
                </VnInput>
                <VnInput :label="t('Tax number')" clearable v-model="data.fi" required />
            </VnRow>

            <VnRow>
                <VnInput
                    :label="t('Street')"
                    clearable
                    v-model="data.street"
                    :uppercase="true"
                    required
                />
            </VnRow>

            <VnRow>
                <VnSelect
                    :label="t('Sage tax type')"
                    url="SageTaxTypes"
                    hide-selected
                    option-label="vat"
                    option-value="id"
                    v-model="data.sageTaxTypeFk"
                    data-cy="sageTaxTypeFk"
                    :required="isRequired(data)"
                    :rules="[(val) => validations.required(data.sageTaxTypeFk, val)]"
                />
                <VnSelect
                    :label="t('Sage transaction type')"
                    url="SageTransactionTypes"
                    hide-selected
                    option-label="transaction"
                    option-value="id"
                    data-cy="sageTransactionTypeFk"
                    v-model="data.sageTransactionTypeFk"
                    :required="isRequired(data)"
                    :rules="[
                        (val) => validations.required(data.sageTransactionTypeFk, val),
                    ]"
                >
                    <template #option="scope">
                        <QItem v-bind="scope.itemProps">
                            <QItemSection>
                                <QItemLabel>{{ scope.opt.name }}</QItemLabel>
                                <QItemLabel caption>
                                    {{ `${scope.opt.id}: ${scope.opt.transaction}` }}
                                </QItemLabel>
                            </QItemSection>
                        </QItem>
                    </template>
                </VnSelect>
            </VnRow>

            <VnRow>
                <VnLocation
                    :rules="validate('Worker.postcode')"
                    :roles-allowed-to-create="['deliveryAssistant', 'administrative']"
                    :acls="[{ model: 'Town', props: '*', accessType: 'WRITE' }]"
                    :location="data"
                    :required="true"
                    @update:model-value="(location) => handleLocation(data, location)"
                />
            </VnRow>
            <VnRow>
                <VnCheckbox :label="t('Active')" v-model="data.isActive" />
                <VnCheckbox :label="t('Frozen')" v-model="data.isFreezed" />
            </VnRow>
            <VnRow>
                <VnCheckbox :label="t('Has to invoice')" v-model="data.hasToInvoice" />
                <VnCheckbox
                    v-model="data.isVies"
                    :label="t('globals.isVies')"
                    :info="t('whenActivatingIt')"
                />
            </VnRow>

            <VnRow>
                <VnCheckbox :label="t('Notify by email')" v-model="data.isToBeMailed" />
                <VnCheckbox
                    :label="t('Invoice by address')"
                    v-model="data.hasToInvoiceByAddress"
                />
            </VnRow>

            <VnRow>
                <VnCheckbox
                    v-model="data.isEqualizated"
                    :label="t('Is equalizated')"
                    :info="t('inOrderToInvoice')"
                />
                <VnCheckbox :label="t('Daily invoice')" v-model="data.hasDailyInvoice" />
            </VnRow>

            <VnRow>
                <VnCheckbox
                    :label="t('Electronic invoice')"
                    v-model="data.hasElectronicInvoice"
                />
                <VnCheckbox
                    :label="t('Verified data')"
                    v-model="data.isTaxDataChecked"
                    @update:model-value="isTaxDataChecked = !isTaxDataChecked"
                />
            </VnRow>
        </template>
    </FormModel>
</template>

<i18n>
es:
    Social name: Razón social
    Tax number: NIF / CIF
    Street: Dirección fiscal
    Sage tax type: Tipo de impuesto Sage
    Sage transaction type: Tipo de transacción Sage
    Postcode: Código postal
    City: Población
    Province: Provincia
    Country: País
    Active: Activo
    Frozen: Congelado
    Has to invoice: Factura
    Notify by email: Notificar vía e-mail
    Invoice by address: Facturar por consignatario
    Is equalizated: Recargo de equivalencia
    Verified data: Datos comprobados
    Incoterms authorization: Autorización incoterms
    Electronic invoice: Factura electrónica
    onlyLetters: Sólo se pueden usar letras, números y espacios
    whenActivatingIt: Al activarlo, no informar el código del país en el campo nif
    inOrderToInvoice: Para facturar no se consulta este campo, sino el RE de consignatario. Al modificar este campo si no esta marcada la casilla Facturar por consignatario, se propagará automaticamente el cambio a todos lo consignatarios, en caso contrario preguntará al usuario si quiere o no propagar
    Daily invoice: Facturación diaria
    Equivalent tax spreaded: Recargo de equivalencia propagado
    You changed the equalization tax: Has cambiado el recargo de equivalencia
    Do you want to spread the change?: ¿Deseas propagar el cambio a sus consignatarios?
en:
    onlyLetters: Only letters, numbers and spaces can be used
    whenActivatingIt: When activating it, do not enter the country code in the ID field
    inOrderToInvoice: In order to invoice, this field is not contulted, but the consignee's ET. When modifiying this field if the invoice by address option is not checked, the change will be automatically propagated to all addresses, otherwise the user will be asked if he wants to propagate it or not
</i18n>
