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

import TicketBasicData from './TicketBasicData.vue';
import TicketBasicDataForm from './TicketBasicDataForm.vue';
import { useVnConfirm } from 'composables/useVnConfirm';

import axios from 'axios';
import useNotify from 'src/composables/useNotify.js';

const { notify } = useNotify();
const route = useRoute();
const router = useRouter();
const { t } = useI18n();
const stepperRef = ref(null);
const { openConfirmationModal } = useVnConfirm();

const step = ref(1);
const formData = ref({});
const initialDataLoaded = ref(false);
const haveNegatives = ref(false);

const ticketFilter = {
    include: [
        { relation: 'address' },
        {
            relation: 'client',
            scope: {
                fields: [
                    'salesPersonFk',
                    'name',
                    'isActive',
                    'isFreezed',
                    'isTaxDataChecked',
                    'credit',
                    'email',
                    'phone',
                    'mobile',
                    'hasElectronicInvoice',
                ],
                include: {
                    relation: 'salesPersonUser',
                    scope: { fields: ['id', 'name'] },
                },
            },
        },
        { relation: 'invoiceOut' },
    ],
};

const getTicketData = async () => {
    const params = { filter: JSON.stringify(ticketFilter) };
    const { data } = await axios.get(`tickets/${route.params.id}`, { params });
    formData.value = data;
    initialDataLoaded.value = true;
};

const isFormInvalid = () => {
    return (
        !formData.value.clientFk ||
        !formData.value.addressFk ||
        !formData.value.agencyModeFk ||
        !formData.value.companyFk ||
        !formData.value.shipped ||
        !formData.value.landed ||
        !formData.value.zoneFk
    );
};

const getPriceDifference = async () => {
    try {
        const params = {
            landed: formData.value.landed,
            addressId: formData.value.addressFk,
            agencyModeId: formData.value.agencyModeFk,
            zoneId: formData.value.zoneFk,
            warehouseId: formData.value.warehouseFk,
            shipped: formData.value.shipped,
        };
        const { data } = await axios.post(
            `tickets/${formData.value.id}/priceDifference`,
            params
        );
        formData.value.sale = data;
    } catch (error) {
        console.error(error);
    }
};

const submit = async () => {
    try {
        if (!formData.value.option)
            return notify(t('basicData.chooseAnOption'), 'negative');

        const params = {
            clientFk: formData.value.clientFk,
            nickname: formData.value.nickname,
            agencyModeFk: formData.value.agencyModeFk,
            addressFk: formData.value.addressFk,
            zoneFk: formData.value.zoneFk,
            warehouseFk: formData.value.warehouseFk,
            companyFk: formData.value.companyFk,
            shipped: formData.value.shipped,
            landed: formData.value.landed,
            isDeleted: formData.value.isDeleted,
            option: formData.value.option,
            isWithoutNegatives: formData.value.withoutNegatives,
            withWarningAccept: formData.value.withWarningAccept,
            keepPrice: false,
        };

        const { data } = await axios.post(
            `tickets/${formData.value.id}/componentUpdate`,
            params
        );

        if (!data) return;

        const ticketToMove = data.id;
        notify(t('basicData.unroutedTicket'), 'positive');
        router.push({ name: 'TicketSummary', params: { id: ticketToMove } });
    } catch (error) {
        console.error(error);
    }
};

const submitWithNegatives = async () => {
    formData.value.withWarningAccept = true;
    submit();
};

const onNextStep = async () => {
    if (step.value === 1) {
        if (isFormInvalid())
            return notify(t('basicData.someFieldsAreInvalid'), 'negative');

        await getPriceDifference();
        stepperRef.value.next();
    } else if (step.value === 2) {
        if (haveNegatives.value && !formData.value.withoutNegatives)
            openConfirmationModal(
                t('basicData.negativesConfirmTitle'),
                t('basicData.negativesConfirmMessage'),
                submitWithNegatives
            );
        else submit();
    }
};

onBeforeMount(async () => await getTicketData());
</script>
<template>
    <QStepper
        v-model="step"
        ref="stepperRef"
        color="primary"
        animated
        keep-alive
        style="margin: auto"
        :style="{
            'max-width': step > 1 ? 'none' : '800px',
        }"
    >
        <QStep :name="1" :title="t('globals.pageTitles.basicData')" :done="step > 1">
            <TicketBasicDataForm
                v-if="initialDataLoaded"
                @update-form="($event) => (formData = $event)"
                :form-data="formData"
            />
        </QStep>
        <QStep :name="2" :title="t('basicData.priceDifference')">
            <TicketBasicData
                :form-data="formData"
                v-model:haveNegatives="haveNegatives"
                @update-form="($event) => (formData = $event)"
            />
        </QStep>
        <template #navigation>
            <QStepperNavigation class="flex justify-between">
                <QBtn
                    flat
                    color="primary"
                    @click="stepperRef.previous()"
                    :label="t('basicData.back')"
                    class="q-ml-sm"
                    :class="{ invisible: step === 1 }"
                />
                <QBtn
                    @click="onNextStep()"
                    color="primary"
                    :label="step === 2 ? t('basicData.finalize') : t('basicData.next')"
                />
            </QStepperNavigation>
        </template>
    </QStepper>
</template>
