<script setup>
import axios from 'axios';
import { ref } from 'vue';
import { useQuasar } from 'quasar';
import { useI18n } from 'vue-i18n';
import { useRouter, useRoute } 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';

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

const router = useRouter();
const route = useRoute();
const quasar = useQuasar();
const { t } = useI18n();
const { openReport, sendEmail } = usePrintService();

const ticket = ref(props.ticket);

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;
    quasar.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 =
        route.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);
    }

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

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

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

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

function confirmDelete() {
    quasar
        .dialog({
            component: VnConfirm,
            componentProps: {
                promise: remove,
            },
        })
        .onOk(async () => await router.push({ name: 'TicketList' }));
}

async function remove() {
    const id = route.params.id;
    await axios.post(`Tickets/${id}/setDeleted`);

    quasar.notify({
        message: t('Ticket deleted'),
        type: 'positive',
    });
    quasar.notify({
        message: t('You can undo this action within the first hour'),
        icon: 'info',
    });
}
</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>
    <template v-if="!ticket.isDeleted">
        <QSeparator />
        <QItem @click="confirmDelete()" v-ripple clickable>
            <QItemSection avatar>
                <QIcon name="delete" />
            </QItemSection>
            <QItemSection>{{ t('Delete ticket') }}</QItemSection>
        </QItem>
    </template>
</template>

<i18n>
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
</i18n>
