<script setup>
import { useRoute } from 'vue-router';
import { computed, onMounted, onUnmounted, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useQuasar } from 'quasar';
import FetchedTags from 'components/ui/FetchedTags.vue';
import SendEmailDialog from 'components/common/SendEmailDialog.vue';
import SupplierConsumptionFilter from './SupplierConsumptionFilter.vue';
import ItemDescriptorProxy from 'src/pages/Item/Card/ItemDescriptorProxy.vue';

import { toDate } from 'src/filters';
import { dashIfEmpty } from 'src/filters';
import { usePrintService } from 'composables/usePrintService';
import useNotify from 'src/composables/useNotify.js';
import axios from 'axios';
import { useStateStore } from 'stores/useStateStore';
import { useState } from 'src/composables/useState';
import { useArrayData } from 'composables/useArrayData';

const state = useState();
const stateStore = useStateStore();
const { t } = useI18n();
const route = useRoute();
const { openReport, sendEmail } = usePrintService();
const quasar = useQuasar();
const { notify } = useNotify();
const totalRows = ref({});
const arrayData = useArrayData('SupplierConsumption', {
    url: 'Suppliers/consumption',
    order: ['itemTypeFk', 'itemName', 'itemSize'],
    userFilter: { where: { supplierFk: route.params.id } },
});

const store = arrayData.store;

onUnmounted(() => state.unset('SupplierConsumption'));
const dateRanges = computed(() => {
    const { from, to } = arrayData.store?.userParams || {};
    return { from, to };
});

const reportParams = computed(() => ({
    recipientId: Number(route.params.id),
    ...dateRanges.value,
}));

async function getSupplierConsumptionData() {
    await arrayData.fetch({ append: false });
}

const rows = computed(() => {
    return totalEntryPrice(store.data) || [];
});

const openReportPdf = () => {
    openReport(`Suppliers/${route.params.id}/campaign-metrics-pdf`, reportParams.value);
};

const getSupplierContacts = async () => {
    try {
        const params = {
            filter: {
                where: {
                    supplierFk: route.params.id,
                    email: { neq: null },
                },
                limit: 1,
            },
        };

        const { data } = await axios.get('SupplierContacts', params);

        if (data && data.length) return data[0].email;
    } catch (err) {
        notify('This supplier does not have a contact with an email address', 'negative');
        console.error('Error fetching supplierContacts: ', err);
    }
};

const openSendEmailDialog = async () => {
    const email = await getSupplierContacts();
    quasar.dialog({
        component: SendEmailDialog,
        componentProps: {
            data: {
                address: email,
            },
            promise: sendCampaignMetricsEmail,
        },
    });
};

const sendCampaignMetricsEmail = ({ address }) => {
    sendEmail(`Suppliers/${route.params.id}/campaign-metrics-email`, {
        recipient: address,
        ...reportParams.value,
    });
};

const totalEntryPrice = (rows) => {
    let totalPrice = 0;
    let totalQuantity = 0;
    if (!rows) return totalPrice;
    for (const row of rows) {
        let total = 0;
        let quantity = 0;

        if (row.buys) {
            for (const buy of row.buys) {
                total = total + buy.total;
                quantity = quantity + buy.quantity;
            }
        }

        row.total = total;
        row.quantity = quantity;
        totalPrice = totalPrice + total;
        totalQuantity = totalQuantity + quantity;
    }
    totalRows.value = { totalPrice, totalQuantity };
    return rows;
};

onMounted(async () => {
    stateStore.rightDrawer = true;
    await getSupplierConsumptionData();
});
</script>

<template>
    <Teleport to="#st-actions" v-if="stateStore.isSubToolbarShown()">
        <QBtn
            :disabled="!dateRanges.from || !dateRanges.to || !rows.length"
            color="primary"
            icon-right="picture_as_pdf"
            no-caps
            class="q-mr-md"
            @click="openReportPdf()"
        >
            <QTooltip>
                {{ t('Open as PDF') }}
            </QTooltip>
        </QBtn>
        <QBtn
            :disabled="!dateRanges.from || !dateRanges.to || !rows.length"
            color="primary"
            icon-right="email"
            no-caps
            @click="openSendEmailDialog()"
        >
            <QTooltip>
                {{ t('Send to email') }}
            </QTooltip>
        </QBtn>
    </Teleport>
    <Teleport to="#st-data" v-if="stateStore.isSubToolbarShown()">
        <div class="row q-gutter-md">
            <div>
                {{ t('Total entries') }}:
                <QChip :dense="$q.screen.lt.sm" text-color="white">
                    {{ totalRows.totalPrice }} €
                </QChip>
            </div>
            <QSeparator dark vertical />
            <div>
                {{ t('Total stems entries') }}:
                <QChip :dense="$q.screen.lt.sm" text-color="white">
                    {{ totalRows.totalQuantity }}
                </QChip>
            </div>
        </div>
    </Teleport>
    <QPage class="column items-center q-pa-md">
        <QDrawer v-model="stateStore.rightDrawer" side="right" :width="256" show-if-above>
            <QScrollArea class="fit text-grey-8">
                <SupplierConsumptionFilter data-key="SupplierConsumption" />
            </QScrollArea>
        </QDrawer>
        <QTable
            :rows="rows"
            row-key="id"
            hide-header
            class="full-width q-mt-md"
            :no-data-label="t('No results')"
        >
            <template #body="{ row }">
                <QTr>
                    <QTd no-hover>
                        <span class="label">{{ t('supplier.consumption.entry') }}: </span>
                        <span>{{ row.id }}</span>
                    </QTd>
                    <QTd no-hover>
                        <span class="label">{{ t('supplier.consumption.date') }}: </span>
                        <span>{{ toDate(row.shipped) }}</span></QTd
                    >
                    <QTd colspan="6" no-hover>
                        <span class="label"
                            >{{ t('supplier.consumption.reference') }}:
                        </span>
                        <span>{{ row.invoiceNumber }}</span>
                    </QTd>
                </QTr>
                <QTr v-for="(buy, index) in row.buys" :key="index">
                    <QTd no-hover>
                        <QBtn flat color="blue" dense no-caps>{{ buy.itemName }}</QBtn>
                        <ItemDescriptorProxy :id="buy.itemFk" />
                    </QTd>

                    <QTd no-hover>
                        <span>{{ buy.subName }}</span>
                        <FetchedTags :item="buy" />
                    </QTd>
                    <QTd no-hover> {{ dashIfEmpty(buy.quantity) }}</QTd>
                    <QTd no-hover> {{ dashIfEmpty(buy.price) }}</QTd>
                    <QTd colspan="2" no-hover> {{ dashIfEmpty(buy.total) }}</QTd>
                </QTr>
                <QTr>
                    <QTd colspan="5" no-hover>
                        <span class="label">{{ t('Total entry') }}: </span>
                        <span>{{ row.total }} €</span>
                    </QTd>
                    <QTd no-hover>
                        <span class="label">{{ t('Total stems') }}: </span>
                        <span>{{ row.quantity }}</span>
                    </QTd>
                </QTr>
            </template>
        </QTable>
    </QPage>
</template>

<style scoped lang="scss">
.label {
    color: var(--vn-label-color);
}
</style>

<i18n>
es:
    Total entry: Total entrada
    Total entries: Total de las entradas
    Total stems entries: Total de tallos de las entradas
    Total stems: Total tallos
    Open as PDF: Abrir como PDF
    Send to email: Enviar por email
    This supplier does not have a contact with an email address: Este proveedor no tiene un email de contacto
</i18n>
