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

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 VnTable from 'src/components/VnTable/VnTable.vue';
import TicketFutureFilter from './TicketFutureFilter.vue';

import { dashIfEmpty, toCurrency } from 'src/filters';
import { useVnConfirm } from 'composables/useVnConfirm';
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';
import TicketProblems from 'src/components/TicketProblems.vue';

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

const selectedTickets = ref([]);
const vnTableRef = ref({});
const originElRef = ref(null);
const destinationElRef = ref(null);
const userParams = reactive({
    futureScopeDays: Date.vnNew().toISOString(),
    originScopeDays: Date.vnNew().toISOString(),
    warehouseFk: user.value.warehouseFk,
});

const ticketColumns = computed(() => [
    {
        label: '',
        name: 'problems',
        headerClass: 'horizontal-separator',
        align: 'left',
        columnFilter: false,
    },
    {
        label: t('advanceTickets.ticketId'),
        name: 'id',
        align: 'center',
        headerClass: 'horizontal-separator',
    },
    {
        label: t('futureTickets.shipped'),
        name: 'shipped',
        align: 'left',
        columnFilter: false,
        headerClass: 'horizontal-separator',
    },
    {
        align: 'center',
        class: 'shrink',
        label: t('advanceTickets.ipt'),
        name: 'ipt',
        columnFilter: {
            component: 'select',
            attrs: {
                url: 'itemPackingTypes',
                fields: ['code', 'description'],
                where: { isActive: true },
                optionValue: 'code',
                optionLabel: 'description',
                inWhere: false,
            },
        },
        format: (row, dashIfEmpty) => dashIfEmpty(row.ipt),
        headerClass: 'horizontal-separator',
    },
    {
        label: t('ticketList.state'),
        name: 'state',
        align: 'left',
        columnFilter: false,
        headerClass: 'horizontal-separator',
    },
    {
        label: t('advanceTickets.liters'),
        name: 'liters',
        align: 'left',
        headerClass: 'horizontal-separator',
    },
    {
        label: t('advanceTickets.import'),
        name: 'import',
        align: 'left',
        headerClass: 'horizontal-separator',
        columnFilter: false,
        format: (row) => toCurrency(row.totalWithVat),
    },
    {
        label: t('futureTickets.availableLines'),
        name: 'lines',
        field: 'lines',
        align: 'center',
        headerClass: 'horizontal-separator',
        format: (row, dashIfEmpty) => dashIfEmpty(row.lines),
    },
    {
        label: t('advanceTickets.futureId'),
        name: 'futureId',
        align: 'center',
        headerClass: 'horizontal-separator vertical-separator ',
        columnClass: 'vertical-separator',
    },
    {
        label: t('futureTickets.futureShipped'),
        name: 'futureShipped',
        align: 'left',
        headerClass: 'horizontal-separator',
        columnFilter: false,
        format: (row) => toDateTimeFormat(row.futureShipped),
    },
    {
        align: 'center',
        label: t('advanceTickets.futureIpt'),
        class: 'shrink',
        name: 'futureIpt',
        columnFilter: {
            component: 'select',
            attrs: {
                url: 'itemPackingTypes',
                fields: ['code', 'description'],
                where: { isActive: true },
                optionValue: 'code',
                optionLabel: 'description',
            },
        },
        headerClass: 'horizontal-separator',
        format: (row, dashIfEmpty) => dashIfEmpty(row.futureIpt),
    },
    {
        label: t('advanceTickets.futureState'),
        name: 'futureState',
        align: 'right',
        headerClass: 'horizontal-separator',
        class: 'expand',
        columnFilter: false,
        format: (row, dashIfEmpty) => dashIfEmpty(row.futureState),
    },
]);

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

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

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

    let params = { tickets: ticketsToMove };
    await axios.post('Tickets/merge', params);
    notify(t('advanceTickets.moveTicketSuccess'), 'positive');
    selectedTickets.value = [];
    vnTableRef.value.reload();
};

watch(
    () => vnTableRef.value.tableRef?.$el,
    ($el) => {
        if (!$el) return;
        const head = $el.querySelector('thead');
        const firstRow = $el.querySelector('thead > tr');

        const newRow = document.createElement('tr');
        destinationElRef.value = document.createElement('th');
        originElRef.value = document.createElement('th');

        newRow.classList.add('bg-header');
        destinationElRef.value.classList.add('text-uppercase', 'color-vn-label');
        originElRef.value.classList.add('text-uppercase', 'color-vn-label');

        destinationElRef.value.setAttribute('colspan', '7');
        originElRef.value.setAttribute('colspan', '9');

        originElRef.value.textContent = `${t('advanceTickets.origin')}`;
        destinationElRef.value.textContent = `${t('advanceTickets.destination')}`;

        newRow.append(destinationElRef.value, originElRef.value);
        head.insertBefore(newRow, firstRow);
    },
    { once: true, inmmediate: true },
);

watch(
    () => vnTableRef.value.params,
    () => {
        if (originElRef.value && destinationElRef.value) {
            destinationElRef.value.textContent = `${t('advanceTickets.origin')}`;
            originElRef.value.textContent = `${t('advanceTickets.destination')}`;
        }
    },
    { deep: true },
);
</script>

<template>
    <VnSearchbar
        data-key="futureTicket"
        :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">
        <VnTable
            data-key="futureTickets"
            ref="vnTableRef"
            url="Tickets/getTicketsFuture"
            search-url="futureTickets"
            :user-params="userParams"
            :limit="0"
            :columns="ticketColumns"
            :table="{
                'row-key': '$index',
                selection: 'multiple',
            }"
            v-model:selected="selectedTickets"
            :right-search="false"
            auto-load
            :disable-option="{ card: true }"
        >
            <template #column-problems="{ row }">
                <span class="q-gutter-x-xs">
                    <QIcon
                        v-if="row.futureAgencyFk !== row.agencyFk && row.agencyFk"
                        color="primary"
                        name="vn:agency-term"
                        size="xs"
                        class="q-mr-xs"
                    >
                        <QTooltip class="column">
                            <span>
                                {{
                                    t('advanceTickets.originAgency', {
                                        agency: row.futureAgency,
                                    })
                                }}
                            </span>
                            <span>
                                {{
                                    t('advanceTickets.destinationAgency', {
                                        agency: row.agency,
                                    })
                                }}
                            </span>
                        </QTooltip>
                    </QIcon>
                    <TicketProblems :row />
                </span>
            </template>
            <template #column-id="{ row }">
                <QBtn flat class="link" @click.stop dense>
                    {{ row.id }}
                    <TicketDescriptorProxy :id="row.id" />
                </QBtn>
            </template>
            <template #column-shipped="{ row }">
                <QBadge
                    text-color="black"
                    :color="getDateQBadgeColor(row.shipped)"
                    class="q-ma-none"
                >
                    {{ toDateTimeFormat(row.shipped) }}
                </QBadge>
            </template>
            <template #column-state="{ row }">
                <QBadge
                    v-if="row.state"
                    text-color="black"
                    :color="row.classColor"
                    class="q-ma-none"
                    dense
                >
                    {{ row.state }}
                </QBadge>
                <span v-else> {{ dashIfEmpty(row.state) }}</span>
            </template>
            <template #column-import="{ row }">
                <QBadge
                    :text-color="
                        totalPriceColor(row.totalWithVat) === 'warning'
                            ? 'black'
                            : 'white'
                    "
                    :color="totalPriceColor(row.totalWithVat)"
                    class="q-ma-none"
                    dense
                >
                    {{ toCurrency(row.totalWithVat || 0) }}
                </QBadge>
            </template>
            <template #column-futureId="{ row }">
                <QBtn flat class="link" @click.stop dense>
                    {{ row.futureId }}
                    <TicketDescriptorProxy :id="row.futureId" />
                </QBtn>
            </template>
            <template #column-futureShipped="{ row }">
                <QBadge
                    text-color="black"
                    :color="getDateQBadgeColor(row.futureShipped)"
                    class="q-ma-none"
                >
                    {{ toDateTimeFormat(row.futureShipped) }}
                </QBadge>
            </template>
            <template #column-futureState="{ row }">
                <QBadge
                    text-color="black"
                    :color="row.futureClassColor"
                    class="q-mr-xs"
                    dense
                >
                    {{ row.futureState }}
                </QBadge>
            </template>
        </VnTable>
    </QPage>
</template>

<style scoped lang="scss">
:deep(.vertical-separator) {
    border-left: 4px solid white !important;
}

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