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

import FetchData from 'components/FetchData.vue';
import FetchedTags from 'components/ui/FetchedTags.vue';
import VnInput from 'src/components/common/VnInput.vue';
import VnSelect from 'src/components/common/VnSelect.vue';
import ItemDescriptorProxy from 'src/pages/Item/Card/ItemDescriptorProxy.vue';
import WorkerDescriptorProxy from 'src/pages/Worker/Card/WorkerDescriptorProxy.vue';

import { dashIfEmpty } from 'src/filters';
import useNotify from 'src/composables/useNotify.js';
import { toDateTimeFormat } from 'src/filters/date';

import axios from 'axios';

const route = useRoute();
const { t } = useI18n();
const { notify } = useNotify();
const saleTrackingTableDialogRef = ref(null);
const itemShelvingSaleDialogRef = ref(null);
const saleTrackingFetchDataRef = ref(null);

const sales = ref([]);
const saleTrackings = ref([]);
const itemShelvingsSales = ref([]);
const saleTrackingUrl = computed(() => `SaleTrackings/${route.params.id}/filter`);
const oldQuantity = ref(null);

watch(
    () => route.params.id,
    async () => nextTick(async () => await saleTrackingFetchDataRef.value.fetch())
);

const columns = computed(() => [
    {
        label: t('ticketSaleTracking.isChecked'),
        name: 'isChecked',
        align: 'left',
        sortable: true,
    },
    {
        label: t('ticketSaleTracking.item'),
        name: 'item',
        align: 'left',
        sortable: true,
    },
    {
        label: t('ticketSaleTracking.description'),
        name: 'description',
        align: 'left',
        sortable: true,
    },
    {
        label: t('ticketSaleTracking.quantity'),
        name: 'quantity',
        field: 'quantity',
        align: 'left',
        sortable: true,
    },
    {
        label: t('ticketSaleTracking.parking'),
        name: 'parking',
        field: 'parkingCode',
        align: 'left',
        sortable: true,
        format: (value) => dashIfEmpty(value),
    },
    {
        label: '',
        name: 'actions',
        align: 'left',
        sortable: true,
    },
]);

const logTableColumns = computed(() => [
    {
        label: t('ticketSaleTracking.quantity'),
        name: 'quantity',
        field: 'quantity',
        align: 'left',
        sortable: true,
    },
    {
        label: t('ticketSaleTracking.original'),
        name: 'original',
        field: 'originalQuantity',
        align: 'left',
        sortable: true,
    },
    {
        label: t('ticketSaleTracking.worker'),
        name: 'worker',
        align: 'left',
        sortable: true,
    },
    {
        label: t('ticketSaleTracking.state'),
        name: 'state',
        field: 'state',
        align: 'left',
        sortable: true,
    },
    {
        label: t('ticketSaleTracking.created'),
        name: 'created',
        field: 'created',
        align: 'left',
        sortable: true,
        format: (value) => toDateTimeFormat(value),
    },
]);

const shelvingsTableColumns = computed(() => [
    {
        label: t('ticketSaleTracking.quantity'),
        name: 'quantity',
        align: 'left',
        sortable: true,
    },
    {
        label: t('ticketSaleTracking.worker'),
        name: 'worker',
        align: 'left',
        sortable: true,
    },
    {
        label: t('ticketSaleTracking.shelving'),
        name: 'shelving',
        align: 'original',
        sortable: true,
    },
    {
        label: t('ticketSaleTracking.parking'),
        name: 'parking',
        align: 'left',
        sortable: true,
    },
    {
        label: t('ticketSaleTracking.created'),
        name: 'created',
        field: 'created',
        align: 'left',
        sortable: true,
        format: (value) => toDateTimeFormat(value),
    },
]);

const getSaleTrackings = async (sale) => {
    try {
        const filter = {
            where: { saleFk: sale.saleFk },
            order: ['itemFk DESC'],
        };
        const { data } = await axios.get(`SaleTrackings/listSaleTracking`, {
            params: { filter: JSON.stringify(filter) },
        });
        saleTrackings.value = data;
    } catch (error) {
        console.error(error);
    }
};

const showLog = async (sale) => {
    await getSaleTrackings(sale);
    saleTrackingTableDialogRef.value.show();
};

const getItemShelvingSales = async (sale) => {
    try {
        const filter = {
            where: { saleFk: sale.saleFk },
        };
        const { data } = await axios.get(`ItemShelvingSales/filter`, {
            params: { filter: JSON.stringify(filter) },
        });
        itemShelvingsSales.value = data;
    } catch (error) {
        console.error(error);
    }
};

const showShelving = async (sale) => {
    await getItemShelvingSales(sale);
    itemShelvingSaleDialogRef.value.show();
};

const updateQuantity = async (sale) => {
    try {
        if (oldQuantity.value === sale.quantity) return;
        const params = {
            quantity: sale.quantity,
        };
        await axios.patch(`ItemShelvingSales/${sale.id}`, params);
        oldQuantity.value = null;
    } catch (error) {
        console.error(error);
    }
};

const updateParking = async (sale) => {
    try {
        const filter = {
            fields: ['id'],
            where: {
                code: sale.shelvingFk,
            },
        };
        const { data } = await axios.get(`Shelvings/findOne`, {
            params: { filter: JSON.stringify(filter) },
        });
        const params = {
            parkingFk: sale.parkingFk,
        };
        await axios.patch(`Shelvings/${data.id}`, params);
    } catch (error) {
        console.error(error);
    }
};

const updateShelving = async (sale) => {
    const params = {
        shelvingFk: sale.shelvingFk,
    };

    const { data: patchResponseData } = await axios.patch(
        `ItemShelvings/${sale.itemShelvingFk}`,
        params
    );
    const filter = {
        fields: ['parkingFk'],
        where: {
            code: patchResponseData.shelvingFk,
        },
    };
    const { data: getResponseData } = await axios.get(`Shelvings/findOne`, { filter });
    sale.parkingFk = getResponseData.parkingFk;
};

const saleTrackingNew = async (sale, stateCode, isChecked) => {
    try {
        const params = {
            saleFk: sale.saleFk,
            isChecked,
            quantity: sale.quantity,
            stateCode,
        };
        await axios.post(`SaleTrackings/new`, params);
        notify(t('globals.dataSaved'), 'positive');
    } catch (error) {
        console.error(error);
    }
};

const saleTrackingDel = async ({ saleFk }, stateCode) => {
    try {
        const params = {
            saleFk,
            stateCodes: [stateCode],
        };
        await axios.post(`SaleTrackings/delete`, params);
        notify(t('globals.dataSaved'), 'positive');
    } catch (error) {
        console.error(error);
    }
};

const clickSaleGroupDetail = async (sale) => {
    try {
        if (!sale.saleGroupDetailFk) return;

        await axios.delete(`SaleGroupDetails/${sale.saleGroupDetailFk}`);
        sale.hasSaleGroupDetail = false;
        notify(t('globals.dataSaved'), 'positive');
    } catch (error) {
        console.error(error);
    }
};

const clickPreviousSelected = (sale) => {
    try {
        qCheckBoxController(sale, 'isPreviousSelected');
        if (!sale.isPreviousSelected) sale.isPrevious = false;
    } catch (error) {
        console.error(error);
    }
};

const clickPrevious = (sale) => {
    try {
        qCheckBoxController(sale, 'isPrevious');
        if (sale.isPrevious) sale.isPreviousSelected = true;
    } catch (error) {
        console.error(error);
    }
};

const qCheckBoxController = (sale, action) => {
    const STATE_CODES = {
        isControled: 'CHECKED',
        isPrepared: 'PREPARED',
        isPrevious: 'PREVIOUS_PREPARATION',
        isPreviousSelected: 'PREVIOUS_PREPARATION',
    };
    const stateCode = STATE_CODES[action];
    try {
        if (!sale[action]) {
            saleTrackingNew(sale, stateCode, true);
            sale[action] = true;
        } else {
            saleTrackingDel(sale, stateCode);
            sale[action] = false;
        }
    } catch (error) {
        console.error(error);
    }
};
</script>

<template>
    <FetchData
        ref="saleTrackingFetchDataRef"
        :url="saleTrackingUrl"
        :filter="{ order: ['concept ASC', 'quantity DESC'] }"
        auto-load
        @on-fetch="(data) => (sales = data)"
    />
    <QTable
        :rows="sales"
        :columns="columns"
        row-key="id"
        :pagination="{ rowsPerPage: 0 }"
        class="full-width q-mt-md"
        :no-data-label="t('globals.noResults')"
    >
        <template #body-cell-isChecked="{ row }">
            <QTd @click.stop style="width: 20%">
                <QCheckbox
                    :model-value="!!row.hasSaleGroupDetail"
                    color="pink"
                    class="pink"
                    :toggle-indeterminate="false"
                    @update:model-value="clickSaleGroupDetail(row)"
                >
                    <QTooltip>
                        {{ t('ticketSaleTracking.saleGroupDetail') }}
                    </QTooltip>
                </QCheckbox>
                <QCheckbox
                    :model-value="!!row.isPreviousSelected"
                    color="info"
                    class="info"
                    :toggle-indeterminate="false"
                    @update:model-value="clickPreviousSelected(row)"
                >
                    <QTooltip>
                        {{ t('ticketSaleTracking.previousSelected') }}
                    </QTooltip>
                </QCheckbox>
                <QCheckbox
                    :model-value="!!row.isPrevious"
                    color="cyan"
                    class="cyan"
                    :toggle-indeterminate="false"
                    @update:model-value="clickPrevious(row)"
                >
                    <QTooltip>
                        {{ t('ticketSaleTracking.previous') }}
                    </QTooltip>
                </QCheckbox>
                <QCheckbox
                    :model-value="!!row.isPrepared"
                    color="warning"
                    class="warning"
                    :toggle-indeterminate="false"
                    @update:model-value="qCheckBoxController(row, 'isPrepared')"
                >
                    <QTooltip>
                        {{ t('ticketSaleTracking.prepared') }}
                    </QTooltip>
                </QCheckbox>
                <QCheckbox
                    :model-value="!!row.isControled"
                    color="yellow"
                    class="yellow"
                    :toggle-indeterminate="false"
                    @update:model-value="qCheckBoxController(row, 'isControled')"
                >
                    <QTooltip>
                        {{ t('ticketSaleTracking.checked') }}
                    </QTooltip>
                </QCheckbox>
            </QTd>
        </template>
        <template #body-cell-item="{ row }">
            <QTd @click.stop style="width: 20%">
                <div>
                    <span class="link">
                        <QBtn flat>
                            {{ row.itemFk }}
                        </QBtn>
                        <ItemDescriptorProxy :id="row.itemFk" />
                    </span>
                </div>
            </QTd>
        </template>
        <template #body-cell-description="{ row }">
            <QTd class="col">
                <div class="column">
                    <span>{{ row.concept }}</span>
                    <span v-if="row.subName" class="color-vn-label">
                        {{ row.subName }}
                    </span>
                    <FetchedTags :item="row" tag="value" />
                </div>
            </QTd>
        </template>
        <template #body-cell-quantity="{ row }">
            <QTd style="width: 10%">
                {{ row.quantity }}
            </QTd>
        </template>
        <template #body-cell-parking="{ row }">
            <QTd style="width: 10%">
                {{ dashIfEmpty(row.parkingFk) }}
            </QTd>
        </template>
        <template #body-cell-actions="{ row }">
            <QTd style="width: 20%">
                <QBtn
                    @click.stop="showLog(row)"
                    color="primary"
                    icon="history"
                    size="md"
                    flat
                >
                    <QTooltip class="text-no-wrap">
                        {{ t('ticketSaleTracking.historyAction') }}
                    </QTooltip>
                </QBtn>
                <QBtn
                    @click.stop="showShelving(row)"
                    color="primary"
                    icon="vn:inventory"
                    size="md"
                    flat
                >
                    <QTooltip class="text-no-wrap">
                        {{ t('ticketSaleTracking.shelvingAction') }}
                    </QTooltip>
                </QBtn>
            </QTd>
        </template>
    </QTable>
    <QDialog
        ref="saleTrackingTableDialogRef"
        transition-show="scale"
        transition-hide="scale"
    >
        <QTable
            data-key="saleTrackingLog"
            :rows="saleTrackings"
            :columns="logTableColumns"
            class="q-pa-sm full-width"
        >
            <template #body-cell-worker="{ row }">
                <QTd>
                    <QBtn flat class="link">
                        {{ row.name }}
                        <WorkerDescriptorProxy :id="row.workerFk" />
                    </QBtn>
                </QTd>
            </template>
        </QTable>
    </QDialog>
    <QDialog
        ref="itemShelvingSaleDialogRef"
        transition-show="scale"
        transition-hide="scale"
    >
        <QTable
            data-key="itemShelvingsSales"
            :rows="itemShelvingsSales"
            :columns="shelvingsTableColumns"
            class="q-pa-sm full-width"
        >
            <template #body-cell-quantity="{ row }">
                <QTd>
                    <VnInput
                        v-model.number="row.quantity"
                        @keyup.enter="updateQuantity(row)"
                        @blur="updateQuantity(row)"
                        @focus="oldQuantity = row.quantity"
                    />
                </QTd>
            </template>
            <template #body-cell-worker="{ row }">
                <QTd>
                    <QBtn flat class="link">
                        {{ row.name }}
                        <WorkerDescriptorProxy :id="row.userFk" />
                    </QBtn>
                </QTd>
            </template>
            <template #body-cell-shelving="{ row }">
                <QTd>
                    <VnSelect
                        url="Shelvings"
                        hide-selected
                        option-label="code"
                        option-value="code"
                        v-model="row.shelvingFk"
                        @update:model-value="updateShelving(row)"
                        style="max-width: 120px"
                    />
                </QTd>
            </template>
            <template #body-cell-parking="{ row }">
                <QTd>
                    <VnSelect
                        url="Parkings"
                        hide-selected
                        option-label="code"
                        option-value="id"
                        v-model="row.parkingFk"
                        @update:model-value="updateParking(row)"
                        style="max-width: 120px"
                    />
                </QTd>
            </template>
        </QTable>
    </QDialog>
</template>

<style lang="scss">
$estados: (
    'info': var(--q-info),
    'warning': var(--q-warning),
    'cyan': #00bcd4,
    'pink': pink,
    'yellow': #ffeb3b,
);

@each $estado, $color in $estados {
    .q-checkbox.#{$estado} {
        > .q-checkbox__inner > .q-checkbox__bg.absolute {
            border-radius: 50% !important;
            & .q-checkbox__svg > .q-checkbox__truthy {
                stroke: $color;
            }
        }
    }
}

@media (min-width: 560px) {
    .q-dialog__inner--minimized > div {
        max-width: 900px;
    }
}
</style>
