<script setup>
import { ref, computed, reactive, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import FetchData from 'components/FetchData.vue';
import TicketDescriptorProxy from 'src/pages/Ticket/Card/TicketDescriptorProxy.vue';
import VnSubToolbar from 'src/components/ui/VnSubToolbar.vue';
import VnProgress from 'src/components/common/VnProgressModal.vue';
import RightMenu from 'src/components/common/RightMenu.vue';
import TicketAdvanceFilter from './TicketAdvanceFilter.vue';
import { dashIfEmpty, toCurrency } from 'src/filters';
import { useVnConfirm } from 'composables/useVnConfirm';
import useNotify from 'src/composables/useNotify.js';
import { useState } from 'src/composables/useState';
import { toDateFormat } from 'src/filters/date.js';
import axios from 'axios';
import VnTable from 'src/components/VnTable/VnTable.vue';

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

const itemPackingTypesOptions = ref([]);
const zonesOptions = ref([]);
const selectedTickets = ref([]);
const vnTableRef = ref({});
const originElRef = ref(null);
const destinationElRef = ref(null);
let today = Date.vnNew().toISOString();
const tomorrow = new Date(today);
tomorrow.setDate(tomorrow.getDate() + 1);
const userParams = reactive({
    dateFuture: tomorrow,
    dateToAdvance: today,
    warehouseFk: user.value.warehouseFk,
    ipt: 'H',
    futureIpt: 'H',
    isFullMovable: true,
});

const ticketColumns = computed(() => [
    {
        label: '',
        name: 'icons',
        hidden: true,
        headerClass: 'horizontal-separator',
    },
    {
        align: 'center',
        label: t('advanceTickets.ticketId'),
        name: 'id',
        headerClass: 'horizontal-separator',
    },
    {
        align: 'left',
        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',
    },
    {
        align: 'left',
        label: t('ticketList.state'),
        name: 'state',
        headerClass: 'horizontal-separator',
        hidden: true,
    },
    {
        label: t('advanceTickets.preparation'),
        name: 'preparation',
        field: 'preparation',
        align: 'left',
        sortable: true,
        headerClass: 'horizontal-separator',
        columnFilter: false,
    },
    {
        align: 'left',
        label: t('advanceTickets.liters'),
        headerClass: 'horizontal-separator',
        name: 'liters',
    },
    {
        align: 'left',
        label: t('advanceTickets.lines'),
        name: 'lines',
        headerClass: 'horizontal-separator',
        format: (row, dashIfEmpty) => dashIfEmpty(row.lines),
    },
    {
        align: 'left',
        label: t('advanceTickets.import'),
        name: 'totalWithVat',
        hidden: true,
        headerClass: 'horizontal-separator',
        format: (row) => toCurrency(row.totalWithVat),
    },
    {
        align: 'left',
        label: t('advanceTickets.futureId'),
        name: 'futureId',
        headerClass: 'vertical-separator horizontal-separator',
        columnClass: 'vertical-separator',
    },
    {
        align: 'left',
        label: t('advanceTickets.futureIpt'),
        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),
    },
    {
        align: 'left',
        label: t('advanceTickets.futureState'),
        name: 'futureState',
        headerClass: 'horizontal-separator',
        hidden: true,
    },
    {
        align: 'left',
        label: t('advanceTickets.futureLiters'),
        headerClass: 'horizontal-separator',
        name: 'futureLiters',
    },
    {
        align: 'left',
        label: t('advanceTickets.futureZone'),
        name: 'futureZoneFk',
        columnClass: 'expand',
        columnFilter: {
            component: 'select',
            inWhere: true,
            attrs: {
                url: 'Zones',
                fields: ['id', 'name'],
            },
        },
        columnField: {
            component: null,
        },
        headerClass: 'horizontal-separator',
        format: (row, dashIfEmpty) => dashIfEmpty(row.futureZoneName),
    },
    {
        align: 'left',
        label: t('advanceTickets.notMovableLines'),
        headerClass: 'horizontal-separator',
        name: 'notMovableLines',
    },
    {
        align: 'left',
        label: t('advanceTickets.futureLines'),
        headerClass: 'horizontal-separator',
        name: 'futureLines',
    },
    {
        align: 'left',
        label: t('advanceTickets.futureImport'),
        name: 'futureTotalWithVat',
        hidden: true,
        headerClass: 'horizontal-separator',
        format: (row) => toCurrency(row.futureTotalWithVat),
    },
]);

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

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

const getLanded = async (params) => {
    try {
        const query = `Agencies/getLanded`;
        const { data } = await axios.get(query, { params });
        if (!data) return;
        return data;
    } catch (error) {
        notify(t('advanceTickets.noDeliveryZone'), 'negative');
        console.error('Error getting landed', error);
    }
};

const requestComponentUpdate = async (ticket, isWithoutNegatives) => {
    const query = `tickets/${ticket.futureId}/componentUpdate`;
    if (!ticket.landed) {
        const newLanded = await getLanded({
            shipped: vnTableRef.value.params.dateToAdvance,
            addressFk: ticket.futureAddressFk,
            agencyModeFk: ticket.agencyModeFk ?? ticket.futureAgencyModeFk,
            warehouseFk: ticket.futureWarehouseFk,
        });

        if (!newLanded) {
            notify(t('advanceTickets.noDeliveryZone'), 'negative');
            throw new Error(t('advanceTickets.noDeliveryZone'));
        }

        ticket.landed = newLanded.landed;
        ticket.zoneFk = newLanded.zoneFk;
    }

    const params = {
        clientFk: ticket.futureClientFk,
        nickname: ticket.nickname,
        agencyModeFk: ticket.agencyModeFk ?? ticket.futureAgencyModeFk,
        addressFk: ticket.futureAddressFk,
        zoneFk: ticket.zoneFk ?? ticket.futureZoneFk,
        warehouseFk: ticket.futureWarehouseFk,
        companyFk: ticket.futureCompanyFk,
        shipped: vnTableRef.value.params.dateToAdvance,
        landed: ticket.landed,
        isDeleted: false,
        isWithoutNegatives,
        newTicket: ticket.id ?? undefined,
        keepPrice: true,
    };

    return { query, params };
};

const moveTicketsAdvance = async () => {
    let ticketsToMove = [];
    for (const ticket of selectedTickets.value) {
        if (!ticket.id) {
            try {
                const { query, params } = await requestComponentUpdate(ticket, false);
                axios.post(query, params);
            } catch (e) {
                console.error('Error moving ticket', e);
            }
            continue;
        }
        ticketsToMove.push({
            originId: ticket.futureId,
            destinationId: ticket.id,
            originShipped: ticket.futureShipped,
            destinationShipped: ticket.shipped,
            workerFk: ticket.workerFk,
        });
    }

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

const progressLength = ref(0);
const progressPercentage = computed(() => {
    if (progressLength.value === 0 || selectedTickets.value.length === 0) return 0;
    return progressLength.value / selectedTickets.value.length;
});
const splitErrors = ref([]);
const showProgressDialog = ref(false);
const cancelProgress = ref(false);

const progressAdd = () => {
    progressLength.value++;
    if (progressLength.value === selectedTickets.value.length) {
        notify(
            t('advanceTickets.moveTicketSuccess', {
                ticketsNumber: progressLength.value - splitErrors.value.length,
            }),
            'positive'
        );
    }
};

const splitTickets = async () => {
    try {
        showProgressDialog.value = true;
        for (const ticket of selectedTickets.value) {
            if (cancelProgress.value) break;
            try {
                const { query, params } = await requestComponentUpdate(ticket, true);
                await axios.post(query, params);
                progressAdd(ticket.futureId);
            } catch (e) {
                splitErrors.value.push({
                    id: ticket.futureId,
                    reason: e.message || e.response?.data?.error?.message,
                });
                progressAdd(ticket.futureId);
            }
        }
    } finally {
        vnTableRef.value.reload();
    }
};

const resetProgressData = () => {
    if (cancelProgress.value) cancelProgress.value = false;
    progressLength.value = 0;
    splitErrors.value = [];
    selectedTickets.value = [];
};

const handleCloseProgressDialog = () => {
    showProgressDialog.value = false;
    resetProgressData();
};

const handleCancelProgress = () => (cancelProgress.value = true);

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');

        destinationElRef.value.textContent = `${t(
            'advanceTickets.destination'
        )} ${toDateFormat(vnTableRef.value.params.dateToAdvance)}`;
        originElRef.value.textContent = `${t('advanceTickets.origin')} ${toDateFormat(
            vnTableRef.value.params.dateFuture
        )}`;

        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.destination'
            )} ${toDateFormat(vnTableRef.value.params.dateToAdvance)}`;
            originElRef.value.textContent = `${t('advanceTickets.origin')} ${toDateFormat(
                vnTableRef.value.params.dateFuture
            )}`;
        }
    },
    { deep: true }
);
</script>
<template>
    <FetchData
        url="itemPackingTypes"
        :filter="{
            fields: ['code', 'description'],
            order: 'description ASC',
            where: { isActive: true },
        }"
        auto-load
        @on-fetch="(data) => (itemPackingTypesOptions = data)"
    />
    <FetchData
        url="Zones"
        :filter="{
            fields: ['id', 'name'],
            order: 'name ASC',
        }"
        auto-load
        @on-fetch="(data) => (zonesOptions = data)"
    />
    <VnSubToolbar>
        <template #st-data>
            <QBtn
                icon="keyboard_double_arrow_left"
                color="primary"
                class="q-mr-sm"
                :disable="!selectedTickets.length"
                @click.stop="
                    openConfirmationModal(
                        t('advanceTickets.advanceTicketTitle'),
                        t(`advanceTickets.advanceTitleSubtitle`, {
                            selectedTickets: selectedTickets.length,
                        }),
                        moveTicketsAdvance
                    )
                "
            >
                <QTooltip>
                    {{ t('advanceTickets.advanceTickets') }}
                </QTooltip>
            </QBtn>
            <QBtn
                icon="alt_route"
                color="primary"
                :disable="!selectedTickets.length"
                @click.stop="
                    openConfirmationModal(
                        t('advanceTickets.advanceWithoutNegativeTitle'),
                        t(`advanceTickets.advanceWithoutNegativeSubtitle`, {
                            selectedTickets: selectedTickets.length,
                        }),
                        splitTickets
                    )
                "
            >
                <QTooltip>
                    {{ t('advanceTickets.advanceTicketsWithoutNegatives') }}
                </QTooltip>
            </QBtn>
        </template>
    </VnSubToolbar>
    <RightMenu>
        <template #right-panel>
            <TicketAdvanceFilter data-key="advanceTickets" />
        </template>
    </RightMenu>
    <QPage class="column items-center q-pa-md">
        <VnTable
            data-key="advanceTickets"
            ref="vnTableRef"
            url="Tickets/getTicketsAdvance"
            search-url="advanceTickets"
            :user-params="userParams"
            :limit="0"
            :columns="ticketColumns"
            :table="{
                'row-key': '$index',
                selection: 'multiple',
            }"
            v-model:selected="selectedTickets"
            :pagination="{ rowsPerPage: 0 }"
            :no-data-label="t('globals.noResults')"
            :right-search="false"
            auto-load
            :disable-option="{ card: true }"
        >
            <template #column-icons="{ row }">
                <QIcon
                    v-if="row.futureAgency !== row.agency && row.agency"
                    color="primary"
                    name="vn:agency-term"
                    size="xs"
                >
                    <QTooltip class="column">
                        <span>
                            {{
                                t('advanceTickets.originAgency', {
                                    agency: row.futureAgency,
                                })
                            }}
                        </span>
                        <span>
                            {{
                                t('advanceTickets.destinationAgency', {
                                    agency: row.agency,
                                })
                            }}
                        </span>
                    </QTooltip>
                </QIcon>
            </template>
            <template #column-id="{ row }">
                <QBtn flat class="link">
                    {{ row.id }}
                    <TicketDescriptorProxy :id="row.id" />
                </QBtn>
            </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="isLessThan50(row.totalWithVat) ? '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" dense>
                    {{ row.futureId }}
                    <TicketDescriptorProxy :id="row.futureId" />
                </QBtn>
            </template>
            <template #column-futureState="{ row }">
                <QBadge
                    text-color="black"
                    :color="row.futureClassColor"
                    class="q-ma-none"
                    dense
                >
                    {{ row.futureState }}
                </QBadge>
            </template>
            <template #column-futureImport="{ row }">
                <QBadge
                    :text-color="isLessThan50(row.futureTotalWithVat) ? 'black' : 'white'"
                    :color="totalPriceColor(row.futureTotalWithVat)"
                    class="q-ma-none"
                    dense
                >
                    {{ toCurrency(row.futureTotalWithVat || 0) }}
                </QBadge>
            </template>
        </VnTable>
        <VnProgress
            :progress="progressPercentage"
            :cancelled="cancelProgress"
            v-model:show-dialog="showProgressDialog"
            @cancel="handleCancelProgress()"
            @close="handleCloseProgressDialog()"
        >
            <div v-if="splitErrors.length" class="column">
                <span>{{ t('advanceTickets.errorsList') }}:</span>
                <span v-for="(error, index) in splitErrors" :key="index">
                    {{ error.id }}: {{ error.reason }}
                </span>
            </div>
        </VnProgress>
    </QPage>
</template>

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

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