<script setup>
import { ref, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import WorkerDescriptorProxy from 'src/pages/Worker/Card/WorkerDescriptorProxy.vue';
import CustomerDescriptorProxy from 'src/pages/Customer/Card/CustomerDescriptorProxy.vue';
import VnTable from 'components/VnTable/VnTable.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 table = ref();
const selectedRows = ref([]);

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

const columns = computed(() => [
    {
        label: t('salesOrdersTable.dateSend'),
        name: 'dateSend',
        field: 'dateSend',
        align: 'left',
        orderBy: 'date_send',
        columnFilter: false,
    },
    {
        label: t('salesOrdersTable.dateMake'),
        name: 'dateMake',
        field: 'dateMake',
        align: 'left',
        orderBy: 'date_make',
        columnFilter: false,
        format: (row) => toDateTimeFormat(row.date_make),
    },
    {
        label: t('salesOrdersTable.client'),
        name: 'clientFk',
        align: 'left',
        columnFilter: {
            component: 'select',
            attrs: {
                url: 'Clients',
                fields: ['id', 'name'],
                sortBy: 'name ASC',
            },
        },
    },
    {
        label: t('salesOrdersTable.agency'),
        name: 'agencyName',
        align: 'left',
        columnFilter: false,
    },
    {
        label: t('salesOrdersTable.salesPerson'),
        name: 'salesPersonFk',
        align: 'left',
        optionFilter: 'firstName',
        columnFilter: {
            component: 'select',
            attrs: {
                url: 'Workers/activeWithInheritedRole',
                fields: ['id', 'name'],
                sortBy: 'nickname ASC',
                where: { role: 'salesPerson' },
                useLike: false,
            },
        },
    },
    {
        label: t('salesOrdersTable.import'),
        name: 'import',
        field: 'import',
        align: 'left',
        columnFilter: false,
        format: (row) => toCurrency(row.import),
    },
]);

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 table.value.reload();
    } catch (err) {
        console.error('Error deleting orders', err);
    }
};

const openTab = (id) =>
    window.open(`#/order/${id}/summary`, '_blank', 'noopener, noreferrer');
</script>
<template>
    <VnTable
        ref="table"
        class="q-px-none"
        data-key="SalesMonitorOrders"
        url="SalesMonitors/ordersFilter"
        search-url="SalesMonitorOrders"
        order="date_send DESC"
        :right-search="false"
        :expr-builder="exprBuilder"
        auto-load
        :columns="columns"
        :table="{
            'row-key': 'id',
            selection: 'multiple',
        }"
        default-mode="table"
        :row-click="({ id }) => openTab(id)"
        v-model:selected="selectedRows"
        :disable-option="{ card: true }"
    >
        <template #top-left>
            <div class="q-mt-sm">
                <QBtn
                    icon="refresh"
                    size="md"
                    color="primary"
                    dense
                    flat
                    @click="$refs.table.reload()"
                >
                    <QTooltip>{{ $t('globals.refresh') }}</QTooltip>
                </QBtn>
                <QBtn
                    v-if="selectedRows.length"
                    icon="delete"
                    size="md"
                    dense
                    flat
                    color="primary"
                    @click="
                        openConfirmationModal(
                            $t('globals.deleteConfirmTitle'),
                            $t('salesOrdersTable.deleteConfirmMessage'),
                            removeOrders
                        )
                    "
                >
                    <QTooltip>{{ t('salesOrdersTable.delete') }}</QTooltip>
                </QBtn>
            </div>
        </template>
        <template #column-dateSend="{ row }">
            <QTd>
                <QBadge
                    :color="getBadgeColor(row.date_send)"
                    text-color="black"
                    class="q-pa-sm"
                    style="font-size: 14px"
                >
                    {{ toDateFormat(row.date_send) }}
                </QBadge>
            </QTd>
        </template>

        <template #column-clientFk="{ row }">
            <QTd @click.stop>
                <span class="link" v-text="row.clientName" :title="row.clientName" />
                <CustomerDescriptorProxy :id="row.clientFk" />
            </QTd>
        </template>

        <template #column-salesPersonFk="{ row }">
            <QTd @click.stop>
                <span class="link" v-text="row.salesPerson" />
                <WorkerDescriptorProxy :id="row.salesPersonFk" dense />
            </QTd>
        </template>
    </VnTable>
</template>
<style lang="scss" scoped>
.q-td {
    max-width: 140px;
}
</style>
