<script setup>
import { ref, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import CustomerDescriptorProxy from 'src/pages/Customer/Card/CustomerDescriptorProxy.vue';
import VnTable from 'components/VnTable/VnTable.vue';
import DepartmentDescriptorProxy from 'src/pages/Worker/Department/Card/DepartmentDescriptorProxy.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 'departmentFk':
            return { [`c.departmentFk`]: value };
    }
}

const columns = computed(() => [
    {
        label: t('globals.landed'),
        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('salesClientsTable.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,
    },
    {
        align: 'left',
        name: 'departmentFk',
        label: t('customer.summary.team'),
        component: 'select',
        attrs: {
            url: 'Departments',
        },
        create: true,
        columnField: {
            component: null,
        },
        format: (row, dashIfEmpty) => dashIfEmpty(row.departmentName),
    },
    {
        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 () => {
    const selectedIds = selectedRows.value.map((row) => row.id);
    const params = { deletes: selectedIds };
    await axios.post('SalesMonitors/deleteOrders', params);
    selectedRows.value = [];
    await table.value.reload();
};

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)"
        :row-ctrl-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-departmentFk="{ row }">
            <QTd @click.stop>
                <span class="link" v-text="row.departmentName" />
                <DepartmentDescriptorProxy :id="row.departmentFk" dense />
            </QTd>
        </template>
    </VnTable>
</template>
<style lang="scss" scoped>
.q-td {
    max-width: 140px;
}
</style>
