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

import FetchData from 'components/FetchData.vue';
import VnInput from 'src/components/common/VnInput.vue';
import VnSelect from 'src/components/common/VnSelect.vue';
import TicketDescriptorProxy from 'src/pages/Ticket/Card/TicketDescriptorProxy.vue';
import VnSubToolbar from 'src/components/ui/VnSubToolbar.vue';
import VnSearchbar from 'src/components/ui/VnSearchbar.vue';
import RightMenu from 'src/components/common/RightMenu.vue';
import TicketFutureFilter from './TicketFutureFilter.vue';

import { dashIfEmpty, toCurrency } from 'src/filters';
import { useVnConfirm } from 'composables/useVnConfirm';
import { useArrayData } from 'composables/useArrayData';
import { getDateQBadgeColor } from 'src/composables/getDateQBadgeColor.js';
import useNotify from 'src/composables/useNotify.js';
import { useState } from 'src/composables/useState';
import { toDateTimeFormat } from 'src/filters/date.js';
import axios from 'axios';

const state = useState();
const { t } = useI18n();
const { openConfirmationModal } = useVnConfirm();
const { notify } = useNotify();
const user = state.getUser();

const itemPackingTypesOptions = ref([]);
const selectedTickets = ref([]);

const exprBuilder = (param, value) => {
    switch (param) {
        case 'id':
            return { id: value };
        case 'futureId':
            return { futureId: value };
        case 'liters':
            return { liters: value };
        case 'lines':
            return { lines: value };
        case 'iptColFilter':
            return { ipt: { like: `%${value}%` } };
        case 'futureIptColFilter':
            return { futureIpt: { like: `%${value}%` } };
        case 'totalWithVat':
            return { totalWithVat: value };
    }
};

const userParams = reactive({
    futureScopeDays: Date.vnNew().toISOString(),
    originScopeDays: Date.vnNew().toISOString(),
    warehouseFk: user.value.warehouseFk,
});

const arrayData = useArrayData('FutureTickets', {
    url: 'Tickets/getTicketsFuture',
    userParams: userParams,
    exprBuilder: exprBuilder,
});
const { store } = arrayData;

const params = reactive({
    futureScopeDays: Date.vnNew(),
    originScopeDays: Date.vnNew(),
    warehouseFk: user.value.warehouseFk,
});

const applyColumnFilter = async (col) => {
    try {
        const paramKey = col.columnFilter?.filterParamKey || col.field;
        params[paramKey] = col.columnFilter.filterValue;
        await arrayData.addFilter({ params });
    } catch (err) {
        console.error('Error applying column filter', err);
    }
};

const getInputEvents = (col) => {
    return col.columnFilter.type === 'select'
        ? { 'update:modelValue': () => applyColumnFilter(col) }
        : {
              'keyup.enter': () => applyColumnFilter(col),
          };
};

const tickets = computed(() => store.data);

const ticketColumns = computed(() => [
    {
        label: t('futureTickets.problems'),
        name: 'problems',
        align: 'left',
        columnFilter: null,
    },
    {
        label: t('futureTickets.ticketId'),
        name: 'ticketId',
        align: 'center',
        sortable: true,
        columnFilter: {
            component: VnInput,
            type: 'text',
            filterValue: null,
            filterParamKey: 'id',
            event: getInputEvents,
            attrs: {
                dense: true,
            },
        },
    },
    {
        label: t('futureTickets.shipped'),
        name: 'shipped',
        align: 'left',
        sortable: true,
        columnFilter: null,
    },
    {
        label: t('futureTickets.ipt'),
        name: 'ipt',
        field: 'ipt',
        align: 'left',
        sortable: true,
        columnFilter: {
            component: VnSelect,
            filterParamKey: 'iptColFilter',
            type: 'select',
            filterValue: null,
            event: getInputEvents,
            attrs: {
                options: itemPackingTypesOptions.value,
                'option-value': 'code',
                'option-label': 'description',
                dense: true,
            },
        },
        format: (val) => dashIfEmpty(val),
    },
    {
        label: t('futureTickets.state'),
        name: 'state',
        align: 'left',
        sortable: true,
        columnFilter: null,
    },
    {
        label: t('futureTickets.liters'),
        name: 'liters',
        field: 'liters',
        align: 'left',
        sortable: true,
        columnFilter: {
            component: VnInput,
            type: 'text',
            filterValue: null,
            event: getInputEvents,
            attrs: {
                dense: true,
            },
        },
    },
    {
        label: t('futureTickets.import'),
        field: 'import',
        name: 'import',
        align: 'left',
        sortable: true,
    },
    {
        label: t('futureTickets.availableLines'),
        name: 'lines',
        field: 'lines',
        align: 'center',
        sortable: true,
        columnFilter: {
            component: VnInput,
            type: 'text',
            filterValue: null,
            event: getInputEvents,
            attrs: {
                dense: true,
            },
        },
        format: (val) => dashIfEmpty(val),
    },
    {
        label: t('futureTickets.futureId'),
        name: 'futureId',
        align: 'left',
        sortable: true,
        columnFilter: {
            component: VnInput,
            type: 'text',
            filterValue: null,
            filterParamKey: 'futureId',
            event: getInputEvents,
            attrs: {
                dense: true,
            },
        },
    },
    {
        label: t('futureTickets.futureShipped'),
        name: 'futureShipped',
        align: 'left',
        sortable: true,
        columnFilter: null,
        format: (val) => dashIfEmpty(val),
    },

    {
        label: t('futureTickets.futureIpt'),
        name: 'futureIpt',
        field: 'futureIpt',
        align: 'left',
        sortable: true,
        columnFilter: {
            component: VnSelect,
            filterParamKey: 'futureIptColFilter',
            type: 'select',
            filterValue: null,
            event: getInputEvents,
            attrs: {
                options: itemPackingTypesOptions.value,
                'option-value': 'code',
                'option-label': 'description',
                dense: true,
            },
        },
        format: (val) => dashIfEmpty(val),
    },
    {
        label: t('futureTickets.futureState'),
        name: 'futureState',
        align: 'right',
        sortable: true,
        columnFilter: null,
        format: (val) => dashIfEmpty(val),
    },
]);

const isLessThan50 = (totalWithVat) =>
    parseInt(totalWithVat) > 0 && parseInt(totalWithVat) < 50;

const totalPriceColor = (totalWithVat) =>
    isLessThan50(totalWithVat) ? 'warning' : 'transparent';

const moveTicketsFuture = async () => {
    try {
        const ticketsToMove = selectedTickets.value.map((ticket) => ({
            originId: ticket.id,
            destinationId: ticket.futureId,
            originShipped: ticket.shipped,
            destinationShipped: ticket.futureShipped,
            workerFk: ticket.workerFk,
        }));

        let params = { tickets: ticketsToMove };
        await axios.post('Tickets/merge', params);
        notify(t('futureTickets.moveTicketSuccess'), 'positive');
        selectedTickets.value = [];
        arrayData.fetch({ append: false });
    } catch (error) {
        console.error('Error moving tickets to future', error);
    }
};
onMounted(async () => {
    await arrayData.fetch({ append: false });
});
</script>

<template>
    <FetchData
        url="itemPackingTypes"
        :filter="{
            fields: ['code', 'description'],
            order: 'description ASC',
            where: { isActive: true },
        }"
        auto-load
        @on-fetch="(data) => (itemPackingTypesOptions = data)"
    />
    <VnSearchbar
        data-key="FutureTickets"
        :label="t('Search ticket')"
        :info="t('futureTickets.searchInfo')"
    />
    <VnSubToolbar>
        <template #st-data>
            <QBtn
                icon="keyboard_double_arrow_right"
                color="primary"
                :disable="!selectedTickets.length"
                @click.stop="
                    openConfirmationModal(
                        t('futureTickets.moveTicketTitle'),
                        t(`futureTickets.moveTicketDialogSubtitle`, {
                            selectedTickets: selectedTickets.length,
                        }),
                        moveTicketsFuture
                    )
                "
            >
                <QTooltip>
                    {{ t('futureTickets.futureTicket') }}
                </QTooltip>
            </QBtn>
        </template>
    </VnSubToolbar>
    <RightMenu>
        <template #right-panel>
            <TicketFutureFilter data-key="FutureTickets" />
        </template>
    </RightMenu>
    <QPage class="column items-center q-pa-md">
        <QTable
            :rows="tickets"
            :columns="ticketColumns"
            row-key="id"
            selection="multiple"
            v-model:selected="selectedTickets"
            :pagination="{ rowsPerPage: 0 }"
            :no-data-label="t('globals.noResults')"
            style="max-width: 99%"
        >
            <template #header="props">
                <QTr>
                    <QTh class="horizontal-separator" />
                    <QTh
                        class="horizontal-separator text-uppercase color-vn-label"
                        colspan="8"
                        translate
                    >
                        {{ t('futureTickets.origin') }}
                    </QTh>
                    <QTh
                        class="horizontal-separator text-uppercase color-vn-label"
                        colspan="4"
                        translate
                    >
                        {{ t('futureTickets.destination') }}
                    </QTh>
                </QTr>
                <QTr>
                    <QTh>
                        <QCheckbox v-model="props.selected" />
                    </QTh>
                    <QTh
                        v-for="(col, index) in ticketColumns"
                        :key="index"
                        :class="{ 'vertical-separator': col.name === 'futureId' }"
                    >
                        {{ col.label }}
                    </QTh>
                </QTr>
            </template>
            <template #top-row="{ cols }">
                <QTr>
                    <QTd />
                    <QTd
                        v-for="(col, index) in cols"
                        :key="index"
                        style="max-width: 100px"
                    >
                        <component
                            :is="col.columnFilter.component"
                            v-if="col.columnFilter"
                            v-model="col.columnFilter.filterValue"
                            v-bind="col.columnFilter.attrs"
                            v-on="col.columnFilter.event(col)"
                            dense
                        />
                    </QTd>
                </QTr>
            </template>
            <template #header-cell-availableLines="{ col }">
                <QTh class="vertical-separator">
                    {{ col.label }}
                </QTh>
            </template>
            <template #body-cell-problems="{ row }">
                <QTd class="q-gutter-x-xs">
                    <QIcon
                        v-if="row.isTaxDataChecked === 0"
                        color="primary"
                        name="vn:no036"
                        size="xs"
                    >
                        <QTooltip>
                            {{ t('futureTickets.noVerified') }}
                        </QTooltip>
                    </QIcon>
                    <QIcon
                        v-if="row.hasTicketRequest"
                        color="primary"
                        name="vn:buyrequest"
                        size="xs"
                    >
                        <QTooltip>
                            {{ t('futureTickets.purchaseRequest') }}
                        </QTooltip>
                    </QIcon>
                    <QIcon
                        v-if="row.itemShortage"
                        color="primary"
                        name="vn:unavailable"
                        size="xs"
                    >
                        <QTooltip>
                            {{ t('futureTickets.noVisible') }}
                        </QTooltip>
                    </QIcon>
                    <QIcon
                        v-if="row.isFreezed"
                        color="primary"
                        name="vn:frozen"
                        size="xs"
                    >
                        <QTooltip>
                            {{ t('futureTickets.clientFrozen') }}
                        </QTooltip>
                    </QIcon>
                    <QIcon v-if="row.risk" color="primary" name="vn:risk" size="xs">
                        <QTooltip>
                            {{ t('futureTickets.risk') }}: {{ row.risk }}
                        </QTooltip>
                    </QIcon>
                    <QIcon
                        v-if="row.hasComponentLack"
                        color="primary"
                        name="vn:components"
                        size="xs"
                    >
                        <QTooltip>
                            {{ t('futureTickets.componentLack') }}
                        </QTooltip>
                    </QIcon>
                    <QIcon
                        v-if="row.hasRounding"
                        color="primary"
                        name="sync_problem"
                        size="xs"
                    >
                        <QTooltip>
                            {{ t('futureTickets.rounding') }}
                        </QTooltip>
                    </QIcon>
                </QTd>
            </template>
            <template #body-cell-ticketId="{ row }">
                <QTd>
                    <QBtn flat class="link">
                        {{ row.id }}
                        <TicketDescriptorProxy :id="row.id" />
                    </QBtn>
                </QTd>
            </template>
            <template #body-cell-shipped="{ row }">
                <QTd class="shipped">
                    <QBadge
                        text-color="black"
                        :color="getDateQBadgeColor(row.shipped)"
                        class="q-ma-none"
                    >
                        {{ toDateTimeFormat(row.shipped) }}
                    </QBadge>
                </QTd>
            </template>
            <template #body-cell-state="{ row }">
                <QTd>
                    <QBadge
                        text-color="black"
                        :color="row.classColor"
                        class="q-ma-none"
                        dense
                    >
                        {{ row.state }}
                    </QBadge>
                </QTd>
            </template>
            <template #body-cell-import="{ row }">
                <QTd>
                    <QBadge
                        :text-color="
                            totalPriceColor(row.totalWithVat) === 'warning'
                                ? 'black'
                                : 'white'
                        "
                        :color="totalPriceColor(row.totalWithVat)"
                        class="q-ma-none"
                        dense
                    >
                        {{ toCurrency(row.totalWithVat || 0) }}
                    </QBadge>
                </QTd>
            </template>
            <template #body-cell-futureId="{ row }">
                <QTd class="vertical-separator">
                    <QBtn flat class="link" dense>
                        {{ row.futureId }}
                        <TicketDescriptorProxy :id="row.futureId" />
                    </QBtn>
                </QTd>
            </template>
            <template #body-cell-futureShipped="{ row }">
                <QTd class="shipped">
                    <QBadge
                        text-color="black"
                        :color="getDateQBadgeColor(row.futureShipped)"
                        class="q-ma-none"
                    >
                        {{ toDateTimeFormat(row.futureShipped) }}
                    </QBadge>
                </QTd>
            </template>
            <template #body-cell-futureState="{ row }">
                <QTd>
                    <QBadge
                        text-color="black"
                        :color="row.futureClassColor"
                        class="q-ma-none"
                        dense
                    >
                        {{ row.futureState }}
                    </QBadge>
                </QTd>
            </template>
        </QTable>
    </QPage>
</template>

<style scoped lang="scss">
.shipped {
    min-width: 132px;
}
.vertical-separator {
    border-left: 4px solid white !important;
}

.horizontal-separator {
    border-bottom: 4px solid white !important;
}
</style>
