<script setup>
import { ref, computed } from 'vue';
import { useI18n } from 'vue-i18n';

import FetchData from 'components/FetchData.vue';
import WorkerDescriptorProxy from 'src/pages/Worker/Card/WorkerDescriptorProxy.vue';
import CustomerDescriptorProxy from 'src/pages/Customer/Card/CustomerDescriptorProxy.vue';
import VnPaginate from 'components/ui/VnPaginate.vue';

import { toDateFormat, toDateTimeFormat } from 'src/filters/date.js';
import { toCurrency } from 'src/filters';
import { useVnConfirm } from 'composables/useVnConfirm';
import axios from 'axios';

const { t } = useI18n();
const { openConfirmationModal } = useVnConfirm();

const paginateRef = ref(null);
const workersActiveOptions = ref([]);
const clientsOptions = ref([]);
const selectedRows = ref([]);

const dateRange = (value) => {
    const minHour = new Date(value);
    minHour.setHours(0, 0, 0, 0);
    const maxHour = new Date(value);
    maxHour.setHours(23, 59, 59, 59);

    return [minHour, maxHour];
};

function exprBuilder(param, value) {
    switch (param) {
        case 'date_send':
            return {
                [`o.date_send`]: {
                    between: dateRange(value),
                },
            };
        case 'clientFk':
            return { [`c.id`]: value };
        case 'salesPersonFk':
            return { [`c.${param}`]: value };
    }
}

const columns = computed(() => [
    {
        label: t('salesOrdersTable.date'),
        name: 'date',
        field: 'dated',
        align: 'left',
        columnFilter: null,
    },
    {
        label: t('salesOrdersTable.client'),
        name: 'client',
        align: 'left',
        sortable: true,
    },
    {
        label: t('salesOrdersTable.salesPerson'),
        name: 'salesPerson',
        align: 'left',
        sortable: true,
    },
]);

const getBadgeColor = (date) => {
    const today = Date.vnNew();
    today.setHours(0, 0, 0, 0);

    const orderLanded = new Date(date);
    orderLanded.setHours(0, 0, 0, 0);

    const difference = today - orderLanded;

    if (difference == 0) return 'warning';
    if (difference < 0) return 'success';
    if (difference > 0) return 'alert';
};

const removeOrders = async () => {
    try {
        const selectedIds = selectedRows.value.map((row) => row.id);
        const params = { deletes: selectedIds };
        await axios.post('SalesMonitors/deleteOrders', params);
        selectedRows.value = [];
        await paginateRef.value.fetch();
    } catch (err) {
        console.error('Error deleting orders', err);
    }
};

const redirectToOrderSummary = (orderId) => {
    const url = `#/order/${orderId}/summary`;
    window.open(url, '_blank');
};
</script>

<template>
    <FetchData
        url="Workers/activeWithInheritedRole"
        :filter="{
            fields: ['id', 'nickname'],
            order: 'nickname ASC',
            where: { role: 'salesPerson' },
        }"
        auto-load
        @on-fetch="(data) => (workersActiveOptions = data)"
    />
    <FetchData
        url="Clients"
        :filter="{
            fields: ['id', 'name'],
            order: 'name ASC',
        }"
        auto-load
        @on-fetch="(data) => (clientsOptions = data)"
    />

    <QCard style="max-height: 380px; overflow-y: scroll">
        <VnPaginate
            ref="paginateRef"
            data-key="SalesMonitorOrders"
            url="SalesMonitors/ordersFilter"
            order="date_make DESC"
            :limit="6"
            :expr-builder="exprBuilder"
            auto-load
        >
            <template #body="{ rows }">
                <QTable
                    :rows="rows"
                    :columns="columns"
                    row-key="id"
                    selection="multiple"
                    v-model:selected="selectedRows"
                    :pagination="{ rowsPerPage: 0 }"
                    :no-data-label="t('globals.noResults')"
                    @row-click="(_, row) => redirectToOrderSummary(row.id)"
                >
                    <template #top>
                        <QBtn
                            v-if="selectedRows.length > 0"
                            icon="delete"
                            size="md"
                            color="primary"
                            @click="
                                openConfirmationModal(
                                    t('salesOrdersTable.deleteConfirmTitle'),
                                    t('salesOrdersTable.deleteConfirmMessage'),
                                    removeOrders
                                )
                            "
                        >
                            <QTooltip>{{ t('salesOrdersTable.delete') }}</QTooltip>
                        </QBtn>
                    </template>
                    <template #body-cell-date="{ row }">
                        <QTd>
                            <QBadge
                                :color="getBadgeColor(row.date_send)"
                                text-color="black"
                                class="q-ma-none q-mb-md"
                                dense
                                style="font-size: 14px"
                            >
                                {{ toDateFormat(row.date_send) }}
                            </QBadge>
                            <div>{{ toDateTimeFormat(row.date_make) }}</div>
                        </QTd>
                    </template>
                    <template #body-cell-client="{ row }">
                        <QTd>
                            <div class="q-mb-md">
                                <span class="link">{{ row.clientName }}</span>
                                <CustomerDescriptorProxy :id="row.clientFk" />
                            </div>
                            <span> {{ row.agencyName }}</span>
                        </QTd>
                    </template>
                    <template #body-cell-salesPerson="{ row }">
                        <QTd>
                            <div class="q-mb-md">
                                <span class="link">{{ row.salesPerson }}</span>
                                <WorkerDescriptorProxy :id="row.salesPersonFk" dense />
                            </div>
                            <span>{{ toCurrency(row.import) }}</span>
                        </QTd>
                    </template>
                </QTable>
            </template>
        </VnPaginate>
    </QCard>
</template>
<style lang="scss" scoped>
.q-td {
    color: gray;
}
</style>
