<script setup>
import { useRoute } from 'vue-router';
import { computed, onMounted } 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 { useArrayData } from 'composables/useArrayData';

const stateStore = useStateStore();
const { t } = useI18n();
const route = useRoute();
const { openReport, sendEmail } = usePrintService();
const quasar = useQuasar();
const { notify } = useNotify();

const arrayData = useArrayData('SupplierConsumption', {
    url: 'Suppliers/consumption',
    order: ['itemTypeFk', 'itemName', 'itemSize'],
    userFilter: { where: { supplierFk: route.params.id } },
});

const store = arrayData.store;

const dateRanges = computed(() => {
    const ranges = {
        from: null,
        to: null,
    };

    if (route.query && route.query.params) {
        const params = JSON.parse(route.query.params);
        if (params.from && params.to) {
            ranges.from = params.from;
            ranges.to = params.to;
        }
    }

    return ranges;
});

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

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

const rows = computed(() => 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 calculateTotal = (buysArray = []) =>
    buysArray.reduce((accumulator, { total }) => accumulator + total, 0);

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

<template>
    <Teleport to="#st-actions" v-if="stateStore.isSubToolbarShown()">
        <QBtn
            :disabled="!dateRanges.from && !dateRanges.to"
            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"
            color="primary"
            icon-right="email"
            no-caps
            @click="openSendEmailDialog()"
        >
            <QTooltip>
                {{ t('Send to email') }}
            </QTooltip>
        </QBtn>
    </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
            :pagination="{ rowsPerPage: 0 }"
            class="full-width q-mt-md"
            :no-data-label="t('No results')"
        >
            <template #body="{ row }">
                <QTr>
                    <QTd no-hover class="label">{{
                        t('supplier.consumption.entry')
                    }}</QTd>
                    <QTd no-hover>{{ row.id }}</QTd>
                    <QTd no-hover class="label">{{ t('supplier.consumption.date') }}</QTd>
                    <QTd no-hover>{{ toDate(row.shipped) }}</QTd>
                    <QTd no-hover class="label">{{
                        t('supplier.consumption.reference')
                    }}</QTd>
                    <QTd no-hover>{{ row.invoiceNumber }}</QTd>
                </QTr>
                <QTr v-for="(buy, index) in row.buys" :key="index">
                    <QTd no-hover>
                        <QBtn flat color="blue" dense>{{ buy.itemName }}</QBtn>
                        <ItemDescriptorProxy :id="buy.itemFk" />
                    </QTd>

                    <QTd no-hover>
                        <span>{{ buy.subName }}</span>
                        <fetched-tags :item="buy" :max-length="5" />
                    </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="6" no-hover>
                        <span class="label">{{ t('Total entry') }}: </span>
                        <span>{{ calculateTotal(row.buys) }}</span>
                    </QTd>
                </QTr>
            </template>
        </QTable>
    </QPage>
</template>

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

<i18n>
es:
    Total entry: Total entrada
    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>
