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

import ItemDescriptorProxy from 'src/pages/Item/Card/ItemDescriptorProxy.vue';
import VnSubToolbar from 'src/components/ui/VnSubToolbar.vue';
import ExpeditionNewTicket from './ExpeditionNewTicket.vue';
import WorkerDescriptorProxy from 'src/pages/Worker/Card/WorkerDescriptorProxy.vue';

import { useStateStore } from 'stores/useStateStore';
import { useArrayData } from 'composables/useArrayData';
import { useVnConfirm } from 'composables/useVnConfirm';
import useNotify from 'src/composables/useNotify.js';
import { toDateTimeFormat } from 'src/filters/date';
import axios from 'axios';
import VnTable from 'src/components/VnTable/VnTable.vue';
import VnBtnSelect from 'src/components/common/VnBtnSelect.vue';
import FetchData from 'src/components/FetchData.vue';

const route = useRoute();
const stateStore = useStateStore();
const { t } = useI18n();
const { notify } = useNotify();
const { openConfirmationModal } = useVnConfirm();
const newTicketDialogRef = ref(null);
const logsTableDialogRef = ref(null);
const vnTableRef = ref();
const expeditionsLogsData = ref([]);
const selectedExpeditions = ref([]);
const allColumnNames = ref([]);
const newTicketWithRoute = ref(false);
const selectedRows = ref([]);
const hasSelectedRows = computed(() => selectedRows.value.length > 0);
const expeditionStateTypes = ref([]);

const expeditionsFilter = computed(() => ({
    where: { ticketFk: route.params.id },
    order: ['created DESC'],
}));

const ticketArrayData = useArrayData('ticketData');
const ticketStore = ticketArrayData.store;
const ticketData = computed(() => ticketStore.data);

const columns = computed(() => [
    {
        align: 'left',
        label: t('expedition.id'),
        name: 'id',
        chip: {
            condition: () => true,
        },
        isId: true,
        columnFilter: {
            inWhere: true,
        },
    },
    {
        label: t('expedition.item'),
        name: 'packagingItemFk',
        align: 'left',
        cardVisible: true,
        columnFilter: {
            inWhere: true,
        },
    },
    {
        label: t('expedition.name'),
        name: 'packageItemName',
        align: 'left',
        isTitle: true,
        columnFilter: {
            inWhere: true,
        },
    },
    {
        label: t('expedition.packageType'),
        name: 'freightItemName',
        align: 'left',
        columnFilter: {
            inWhere: true,
        },
    },
    {
        label: t('expedition.counter'),
        name: 'counter',
        align: 'left',
        columnFilter: {
            inWhere: true,
        },
    },
    {
        label: t('expedition.externalId'),
        name: 'externalId',
        align: 'left',
        cardVisible: true,
        columnFilter: {
            inWhere: true,
        },
    },
    {
        label: t('expedition.created'),
        name: 'created',
        align: 'left',
        cardVisible: true,
        format: (row) => toDateTimeFormat(row.created),
    },
    {
        label: t('expedition.state'),
        name: 'state',
        align: 'left',
        cardVisible: true,
        columnFilter: { inWhere: true },
    },
    {
        align: 'right',
        name: 'tableActions',
        actions: [
            {
                title: t('expedition.historyAction'),
                icon: 'history',
                isPrimary: true,
                action: (row) => showLog(row),
            },
        ],
    },
]);

const logTableColumns = computed(() => [
    {
        label: t('expedition.state'),
        name: 'state',
        field: 'state',
        align: 'center',
        sortable: true,
    },
    {
        label: t('expedition.name'),
        name: 'name',
        field: 'name',
        align: 'center',
        columnFilter: null,
    },
    {
        label: t('expedition.created'),
        name: 'created',
        field: 'created',
        align: 'center',
        format: (value) => toDateTimeFormat(value),
    },
    {
        label: t('expedition.isScanned'),
        name: 'isScanned',
        field: 'isScanned',
        align: 'center',
    },
]);

const showNewTicketDialog = (withRoute = false) => {
    newTicketWithRoute.value = withRoute;
    newTicketDialogRef.value.show();
};

const deleteExpedition = async () => {
    try {
        const expeditionIds = selectedRows.value.map((expedition) => expedition.id);
        const params = { expeditionIds };
        await axios.post('Expeditions/deleteExpeditions', params);
        vnTableRef.value.reload();
        selectedExpeditions.value = [];
        notify(t('expedition.expeditionRemoved'), 'positive');
    } catch (error) {
        console.error(error);
    }
};

const showLog = async (expedition) => {
    await getExpeditionState(expedition);
    logsTableDialogRef.value.show();
};

const getExpeditionState = async (expedition) => {
    try {
        const filter = {
            where: { expeditionFk: expedition.id },
            order: ['created DESC'],
        };

        const { data: expeditionStates } = await axios.get(`ExpeditionStates/filter`, {
            params: { filter: JSON.stringify(filter) },
        });
        const { data: scannedStates } = await axios.get(`ExpeditionStates`, {
            params: { filter: JSON.stringify(filter), fields: ['id', 'isScanned'] },
        });

        expeditionsLogsData.value = expeditionStates.map((state) => {
            const scannedState = scannedStates.find((s) => s.id === state.id);
            return {
                ...state,
                isScanned: scannedState ? scannedState.isScanned : false,
            };
        });
    } catch (error) {
        console.error(error);
    }
};

onMounted(async () => {
    stateStore.rightDrawer = true;
    const filteredColumns = columns.value.filter((col) => col.name !== 'history');
    allColumnNames.value = filteredColumns.map((col) => col.name);
});

onUnmounted(() => (stateStore.rightDrawer = false));
</script>

<template>
    <FetchData
        url="expeditionStateTypes"
        @on-fetch="(data) => (expeditionStateTypes = data)"
        auto-load
    />
    <VnSubToolbar>
        <template #st-actions>
            <QBtnGroup push class="q-gutter-x-sm" flat>
                <VnBtnSelect
                    :disable="!hasSelectedRows"
                    color="primary"
                    :label="t('globals.changeState')"
                    :select-props="{
                        options: expeditionStateTypes,
                        optionLabel: 'description',
                    }"
                    :promise="
                        async (stateTypeFk) => {
                            await vnTableRef.CrudModelRef.saveChanges({
                                updates: selectedRows.map(({ id }) => ({
                                    data: { stateTypeFk },
                                    where: { id },
                                })),
                            });
                            vnTableRef.tableRef.clearSelection();
                        }
                    "
                />
                <QBtnDropdown
                    ref="btnDropdownRef"
                    color="primary"
                    :label="t('expedition.move')"
                    :disable="!hasSelectedRows"
                >
                    <template #label>
                        <QTooltip>{{ t('Select lines to see the options') }}</QTooltip>
                    </template>
                    <QList>
                        <QItem
                            clickable
                            v-close-popup
                            v-ripple
                            @click="showNewTicketDialog(false)"
                        >
                            <QItemSection>
                                <QItemLabel>{{
                                    t('expedition.newTicketWithoutRoute')
                                }}</QItemLabel>
                            </QItemSection>
                        </QItem>
                        <QItem
                            clickable
                            v-close-popup
                            v-ripple
                            @click="showNewTicketDialog(true)"
                        >
                            <QItemSection>
                                <QItemLabel>{{
                                    t('expedition.newTicketWithRoute')
                                }}</QItemLabel>
                            </QItemSection>
                        </QItem>
                    </QList>
                </QBtnDropdown>
                <QBtn
                    :disable="!hasSelectedRows"
                    icon="delete"
                    color="primary"
                    @click="
                        openConfirmationModal(
                            '',
                            t('expedition.removeExpeditionSubtitle'),
                            deleteExpedition
                        )
                    "
                >
                    <QTooltip>{{ t('expedition.removeExpedition') }}</QTooltip>
                </QBtn>
            </QBtnGroup>
        </template>
    </VnSubToolbar>
    <VnTable
        ref="vnTableRef"
        data-key="TicketExpedition"
        url="Expeditions/filter"
        search-url="expeditions"
        :columns="columns"
        :filter="expeditionsFilter"
        v-model:selected="selectedRows"
        :table="{
            'row-key': 'id',
            selection: 'multiple',
        }"
        save-url="Expeditions/crud"
        auto-load
        :expr-builder="
            (param, value) => {
                switch (param) {
                    case 'expeditionFk':
                        return { id: value };
                    case 'packageItemName':
                        return { packagingItemFk: value };
                }
            }
        "
        order="created DESC"
    >
        <template #column-packagingItemFk="{ row }">
            <span class="link" @click.stop>
                {{ row.packagingItemFk }}
                <ItemDescriptorProxy :id="row.packagingItemFk" />
            </span>
        </template>
    </VnTable>
    <QDialog ref="newTicketDialogRef" transition-show="scale" transition-hide="scale">
        <ExpeditionNewTicket
            :ticket="ticketData"
            :with-route="newTicketWithRoute"
            :selected-expeditions="selectedRows"
        />
    </QDialog>
    <QDialog ref="logsTableDialogRef" transition-show="scale" transition-hide="scale">
        <QTable
            ref="tableRef"
            data-key="TicketExpeditionLog"
            :rows="expeditionsLogsData"
            :columns="logTableColumns"
            class="q-pa-md full-width"
        >
            <template #body-cell-name="{ row }">
                <QTd style="text-align: center">
                    <span class="link" @click.stop>
                        <QBtn flat dense>{{ row.name }}</QBtn>
                        <WorkerDescriptorProxy :id="row.workerFk" />
                    </span>
                </QTd>
            </template>
            <template #body-cell-isScanned="{ row }">
                <QTd style="text-align: center">
                    <QCheckbox disable v-model="row.isScanned">
                        {{
                            row.isScanned === 1 ? t('expedition.yes') : t('expedition.no')
                        }}
                    </QCheckbox>
                </QTd>
            </template>
        </QTable>
    </QDialog>
</template>
