<script setup>
import axios from 'axios';
import { ref } from 'vue';
import { useQuasar } from 'quasar';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import { usePrintService } from 'composables/usePrintService';
import SendEmailDialog from 'components/common/SendEmailDialog.vue';
import VnConfirm from 'components/ui/VnConfirm.vue';
import VnSmsDialog from 'components/common/VnSmsDialog.vue';
import toDate from 'filters/toDate';
import VnInputNumber from 'src/components/common/VnInputNumber.vue';
import { useArrayData } from 'src/composables/useArrayData';

const props = defineProps({
    ticket: {
        type: Object,
        required: true,
    },
});

const { push, currentRoute } = useRouter();
const { dialog, notify } = useQuasar();
const { t } = useI18n();
const { openReport, sendEmail } = usePrintService();
const ticketSummary = useArrayData('TicketSummary');
const ticket = ref(props.ticket);
const ticketId = currentRoute.value.params.id;
const weight = ref();
const actions = {
    clone: async () => {
        const opts = { message: t('Ticket cloned'), type: 'positive' };
        let clonedTicketId;

        try {
            const { data } = await axios.post(`Tickets/cloneAll`, {
                ticketsIds: [ticket.value.id],
                withWarehouse: true,
                negative: false,
            });
            clonedTicketId = data[0].id;
        } catch (e) {
            opts.message = t('It was not able to clone the ticket');
            opts.type = 'negative';
        } finally {
            notify(opts);

            if (clonedTicketId)
                push({ name: 'TicketSummary', params: { id: clonedTicketId } });
        }
    },
    setWeight: async () => {
        try {
            const invoiceIds = (
                await axios.post(`Tickets/${ticketId}/setWeight`, {
                    weight: weight.value,
                })
            ).data;

            notify({ message: t('Weight set'), type: 'positive' });
            if (invoiceIds.length)
                notify({
                    message: t('invoiceIds', { invoiceIds: invoiceIds.join() }),
                    type: 'positive',
                });
            await ticketSummary.fetch({ updateRouter: false });
        } catch (e) {
            notify({ message: e.message, type: 'negative' });
        }
    },
    remove: async () => {
        try {
            await axios.post(`Tickets/${ticketId}/setDeleted`);

            notify({ message: t('Ticket deleted'), type: 'positive' });
            notify({
                message: t('You can undo this action within the first hour'),
                icon: 'info',
            });

            push({ name: 'TicketList' });
        } catch (e) {
            notify({ message: e.message, type: 'negative' });
        }
    },
};

function openDeliveryNote(type = 'deliveryNote', documentType = 'pdf') {
    const path = `Tickets/${ticket.value.id}/delivery-note-${documentType}`;
    openReport(path, {
        recipientId: ticket.value.clientFk,
        type: type,
    });
}

function sendDeliveryNoteConfirmation(type = 'deliveryNote', documentType = 'pdf') {
    const customer = ticket.value.client;
    dialog({
        component: SendEmailDialog,
        componentProps: {
            data: {
                address: customer.email,
                type: type,
                documentType: documentType,
            },
            promise: sendDeliveryNote,
        },
    });
}

async function sendDeliveryNote({ address, type, documentType }) {
    const id = ticket.value.id;
    const customer = ticket.value.client;
    let pathName = 'delivery-note-email';
    if (documentType == 'csv') pathName = 'delivery-note-csv-email';

    const path = `Tickets/${id}/${pathName}`;
    return sendEmail(path, {
        recipientId: customer.id,
        recipient: address,
        type: type,
    });
}

const shipped = toDate(ticket.value.shipped);
function showSmsDialog(template, customData) {
    const address = ticket.value.address;
    const client = ticket.value.client;
    const phone =
        currentRoute.value.params.phone ||
        address.mobile ||
        address.phone ||
        client.mobile ||
        client.phone;

    const data = {
        orderId: ticket.value.id,
        shipped: shipped,
    };

    if (typeof customData === 'object') {
        Object.assign(data, customData);
    }

    dialog({
        component: VnSmsDialog,
        componentProps: {
            phone: phone,
            template: template,
            locale: client?.user?.lang ?? 'default_locale',
            data: data,
            promise: sendSms,
        },
    });
}

async function showSmsDialogWithChanges() {
    const query = `TicketLogs/${ticketId}/getChanges`;
    const response = await axios.get(query);

    showSmsDialog('orderChanges', { changes: response.data });
}

async function sendSms(body) {
    await axios.post(`Tickets/${ticketId}/sendSms`, body);
    notify({
        message: 'Notification sent',
        type: 'positive',
    });
}

function openConfirmDialog(callback) {
    dialog({
        component: VnConfirm,
        componentProps: {
            promise: actions[callback],
        },
    });
}
</script>
<template>
    <QItem v-ripple clickable>
        <QItemSection avatar>
            <QIcon name="picture_as_pdf" />
        </QItemSection>
        <QItemSection>{{ t('Open Delivery Note...') }}</QItemSection>
        <QItemSection side>
            <QIcon name="keyboard_arrow_right" />
        </QItemSection>
        <QMenu anchor="top end" self="top start" auto-close bordered>
            <QList>
                <QItem @click="openDeliveryNote('deliveryNote')" v-ripple clickable>
                    <QItemSection>{{ t('With prices') }}</QItemSection>
                </QItem>
                <QItem @click="openDeliveryNote('withoutPrices')" v-ripple clickable>
                    <QItemSection>{{ t('Without prices') }}</QItemSection>
                </QItem>
                <QItem
                    @click="openDeliveryNote('deliveryNote', 'csv')"
                    v-ripple
                    clickable
                >
                    <QItemSection>{{ t('As CSV') }}</QItemSection>
                </QItem>
            </QList>
        </QMenu>
    </QItem>
    <QItem v-ripple clickable>
        <QItemSection avatar>
            <QIcon name="send" />
        </QItemSection>
        <QItemSection>{{ t('Send Delivery Note...') }}</QItemSection>
        <QItemSection side>
            <QIcon name="keyboard_arrow_right" />
        </QItemSection>
        <QMenu anchor="top end" self="top start" auto-close>
            <QList>
                <QItem
                    @click="sendDeliveryNoteConfirmation('deliveryNote')"
                    v-ripple
                    clickable
                >
                    <QItemSection>{{ t('With prices') }}</QItemSection>
                </QItem>
                <QItem
                    @click="sendDeliveryNoteConfirmation('withoutPrices')"
                    v-ripple
                    clickable
                >
                    <QItemSection>{{ t('Without prices') }}</QItemSection>
                </QItem>
                <QItem
                    @click="sendDeliveryNoteConfirmation('deliveryNote', 'csv')"
                    v-ripple
                    clickable
                >
                    <QItemSection>{{ t('As CSV') }}</QItemSection>
                </QItem>
            </QList>
        </QMenu>
    </QItem>
    <QItem @click="openDeliveryNote('proforma')" v-ripple clickable>
        <QItemSection avatar>
            <QIcon name="receipt" />
        </QItemSection>
        <QItemSection>{{ t('Open Proforma Invoice') }}</QItemSection>
    </QItem>
    <QItem v-ripple clickable>
        <QItemSection avatar>
            <QIcon name="sms" />
        </QItemSection>
        <QItemSection>{{ t('Send SMS...') }}</QItemSection>
        <QItemSection side>
            <QIcon name="keyboard_arrow_right" />
        </QItemSection>
        <QMenu anchor="top end" self="top start" auto-close>
            <QList>
                <QItem @click="showSmsDialog('pendingPayment')" v-ripple clickable>
                    <QItemSection>{{ t('Pending payment') }}</QItemSection>
                </QItem>
                <QItem @click="showSmsDialog('minAmount')" v-ripple clickable>
                    <QItemSection>{{ t('Minimum amount') }}</QItemSection>
                </QItem>
                <QItem
                    @click="showSmsDialogWithChanges('orderChanges')"
                    v-ripple
                    clickable
                >
                    <QItemSection>{{ t('Order changes') }}</QItemSection>
                </QItem>
            </QList>
        </QMenu>
    </QItem>
    <QItem @click="openConfirmDialog('clone')" v-ripple clickable>
        <QItemSection avatar>
            <QIcon name="content_copy" />
        </QItemSection>
        <QItemSection>{{ t('To clone ticket') }}</QItemSection>
    </QItem>
    <QItem @click="$refs.weightDialog.show()" v-ripple clickable>
        <QItemSection avatar>
            <QIcon name="weight" />
        </QItemSection>
        <QItemSection>{{ t('Set weight') }}</QItemSection>
    </QItem>
    <template v-if="!ticket.isDeleted">
        <QSeparator />
        <QItem @click="openConfirmDialog('remove')" v-ripple clickable>
            <QItemSection avatar>
                <QIcon name="delete" />
            </QItemSection>
            <QItemSection>{{ t('Delete ticket') }}</QItemSection>
        </QItem>
    </template>
    <VnConfirm
        ref="weightDialog"
        :title="t('Set weight')"
        :message="t('This ticket may be invoiced, do you want to continue?')"
        :promise="actions.setWeight"
    >
        <template #customHTML>
            <VnInputNumber
                :label="t('globals.weight')"
                v-model="weight"
                class="full-width"
            />
        </template>
    </VnConfirm>
</template>
<i18n>
en:
    invoiceIds: "Invoices have been generated with the following ids: {invoiceIds}"

es:
    Open Delivery Note...: Abrir albarán...
    Send Delivery Note...: Enviar albarán...
    With prices: Con precios
    Without prices: Sin precios
    As CSV: Como CSV
    Open Proforma Invoice: Abrir factura proforma
    Delete ticket: Eliminar ticket
    Send SMS...: Enviar SMS
    Pending payment: Pago pendiente
    Minimum amount: Importe mínimo
    Order changes: Cambios del pedido
    Ticket deleted: Ticket eliminado
    You can undo this action within the first hour: Puedes deshacer esta acción dentro de la primera hora
    To clone ticket: Clonar ticket
    Ticket cloned: Ticked clonado
    It was not able to clone the ticket: No se pudo clonar el ticket
    Set weight: Establecer peso
    Weight set: Peso establecido
    This ticket may be invoiced, do you want to continue?: Es posible que se facture este ticket, desea continuar?
    invoiceIds: "Se han generado las facturas con los siguientes ids: {invoiceIds}"
</i18n>
