<script setup>
import { onMounted, ref, computed, onUnmounted, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter, 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 TicketEditManaProxy from './TicketEditMana.vue';
import VnImg from 'src/components/ui/VnImg.vue';

import VnSubToolbar from 'src/components/ui/VnSubToolbar.vue';
import TicketSaleMoreActions from './TicketSaleMoreActions.vue';
import TicketTransfer from './TicketTransfer.vue';

import { useStateStore } from 'stores/useStateStore';
import { toCurrency, toPercentage, dashIfEmpty } from 'src/filters';
import { useArrayData } from 'composables/useArrayData';
import { useVnConfirm } from 'composables/useVnConfirm';
import useNotify from 'src/composables/useNotify.js';
import axios from 'axios';

const route = useRoute();
const router = useRouter();
const stateStore = useStateStore();
const { t } = useI18n();
const { notify } = useNotify();
const { openConfirmationModal } = useVnConfirm();
const editPriceProxyRef = ref(null);
const stateBtnDropdownRef = ref(null);

const arrayData = useArrayData('ticketData');
const { store } = arrayData;

const ticketConfig = ref(null);
const isLocked = ref(false);
const isTicketEditable = ref(false);
const sales = ref([]);
const editableStatesOptions = ref([]);
const selectedSales = ref([]);
const mana = ref(null);
const manaCode = ref('mana');
const ticketState = computed(() => store.data?.ticketState?.state?.code);
const transfer = ref({
    lastActiveTickets: [],
    sales: [],
});

watch(
    () => route.params.id,
    async () => await getSales()
);

const columns = computed(() => [
    {
        label: '',
        name: 'statusIcons',
        align: 'left',
    },
    {
        label: '',
        name: 'picture',
        align: 'left',
    },
    {
        label: t('ticketSale.visible'),
        name: 'visible',
        field: 'visible',
        align: 'left',
        sortable: true,
    },
    {
        label: t('ticketSale.available'),
        name: 'available',
        field: 'available',
        align: 'left',
        sortable: true,
    },
    {
        label: t('ticketSale.id'),
        name: 'itemFk',
        field: 'itemFk',
        align: 'left',
        sortable: true,
    },
    {
        label: t('ticketSale.quantity'),
        name: 'quantity',
        field: 'quantity',
        align: 'left',
        sortable: true,
    },
    {
        label: t('ticketSale.item'),
        name: 'item',
        field: 'item',
        align: 'left',
        sortable: true,
    },
    {
        label: t('ticketSale.price'),
        name: 'price',
        field: 'price',
        align: 'left',
        sortable: true,
        format: (val) => toCurrency(val),
    },
    {
        label: t('ticketSale.discount'),
        name: 'discount',
        field: 'discount',
        align: 'left',
        sortable: true,
    },
    {
        label: t('ticketSale.amount'),
        name: 'amount',
        field: 'amount',
        align: 'left',
        sortable: true,
        format: (val) => toCurrency(val),
    },
    {
        label: t('ticketSale.packaging'),
        name: 'itemPackingTypeFk',
        field: 'item',
        align: 'left',
        sortable: true,
        format: (val) => dashIfEmpty(val?.itemPackingTypeFk),
    },
    {
        label: '',
        name: 'history',
        align: 'left',
        columnFilter: null,
    },
]);

const getConfig = async () => {
    try {
        let filter = {
            fields: ['daysForWarningClaim'],
        };
        const { data } = await axios.get(`TicketConfigs`, { filter });
        ticketConfig.value = data;
    } catch (err) {
        console.error('Error getting ticket config', err);
    }
};

const onSalesFetched = (salesData) => {
    sales.value = salesData;
    for (let sale of salesData) sale.amount = getSaleTotal(sale);
};

const getSales = async () => {
    try {
        const { data } = await axios.get(`Tickets/${route.params.id}/getSales`);
        onSalesFetched(data);
    } catch (err) {
        console.error('Error fetching sales', err);
    }
};

const getSaleTotal = (sale) => {
    if (sale.quantity == null || sale.price == null) return null;

    const price = sale.quantity * sale.price;
    const discount = (sale.discount * price) / 100;

    return price - discount;
};

const resetChanges = async () => {
    arrayData.fetch({ append: false });
    getSales();
};

const updateQuantity = async (sale) => {
    try {
        const payload = { quantity: sale.quantity };
        await axios.post(`Sales/${sale.id}/updateQuantity`, payload);
        notify('globals.dataSaved', 'positive');
    } catch (err) {
        console.error('Error updating quantity', err);
    }
};

const addSale = async (sale) => {
    try {
        const payload = {
            barcode: sale.itemFk,
            quantity: sale.quantity,
        };

        const { data } = await axios.post(`tickets/${route.params.id}/addSale`, payload);

        if (!data) return;

        const newSale = data;
        sale.id = newSale.id;
        sale.image = newSale.item.image;
        sale.subName = newSale.item.subName;
        sale.concept = newSale.concept;
        sale.quantity = newSale.quantity;
        sale.discount = newSale.discount;
        sale.price = newSale.price;
        sale.item = newSale.item;

        notify('globals.dataSaved', 'positive');
    } catch (err) {
        console.error('Error adding sale', err);
    }
};

const changeQuantity = (sale) => {
    if (
        !sale.itemFk ||
        sale.quantity == null ||
        edit.value?.oldQuantity === sale.quantity
    )
        return;
    if (!sale.id) return addSale(sale);
    updateQuantity(sale);
};

const updateConcept = async (sale) => {
    try {
        const data = { newConcept: sale.concept };
        await axios.post(`Sales/${sale.id}/updateConcept`, data);
        notify('globals.dataSaved', 'positive');
    } catch (err) {
        console.error('Error updating concept', err);
    }
};

const DEFAULT_EDIT = {
    price: null,
    discount: null,
    sale: null,
    sales: null,
    oldQuantity: null,
};
const edit = ref({ ...DEFAULT_EDIT });
const usesMana = ref(null);

const getUsesMana = async () => {
    const { data } = await axios.get('Sales/usesMana');
    usesMana.value = data;
};

const getMana = async () => {
    const { data } = await axios.get(`Tickets/${route.params.id}/getSalesPersonMana`);
    mana.value = data;
    await getUsesMana();
};

const selectedValidSales = computed(() => {
    if (!sales.value) return;
    return selectedSales.value.filter((sale) => sale.id != undefined);
});

const onOpenEditPricePopover = async (sale) => {
    await getMana();
    edit.value = {
        sale: JSON.parse(JSON.stringify(sale)),
        price: sale.price,
    };
};

const onOpenEditDiscountPopover = async (sale) => {
    await getMana();
    if (isLocked.value) return;
    if (sale) {
        edit.value = {
            sale: JSON.parse(JSON.stringify(sale)),
            discount: sale.discount,
        };
    } else {
        edit.value = {
            discount: null,
            sales: selectedValidSales.value,
        };
    }
};

const updatePrice = async (sale) => {
    try {
        const newPrice = edit.value.price;
        if (newPrice != null && newPrice != sale.price) {
            await axios.post(`Sales/${sale.id}/updatePrice`, { newPrice });
            sale.price = newPrice;
            edit.value = { ...DEFAULT_EDIT };
            notify('globals.dataSaved', 'positive');
        }
        await getMana();
    } catch (err) {
        console.error('Error updating price', err);
    }
};

const changeDiscount = (sale) => {
    const newDiscount = edit.value.discount;
    if (newDiscount != null && newDiscount != sale.discount) updateDiscount([sale]);
};

const updateDiscount = async (sales, newDiscount = null) => {
    const saleIds = sales.map((sale) => sale.id);
    const _newDiscount = newDiscount || edit.value.discount;
    const params = {
        salesIds: saleIds,
        newDiscount: _newDiscount,
        manaCode: manaCode.value,
    };
    await axios.post(`Tickets/${route.params.id}/updateDiscount`, params);
    notify('globals.dataSaved', 'positive');
    for (let sale of sales) sale.discount = _newDiscount;
    edit.value = { ...DEFAULT_EDIT };
};

const getNewPrice = computed(() => {
    if (edit.value?.sale) {
        const sale = edit.value.sale;
        let newDiscount = sale.discount;
        let newPrice = edit.value.price || sale.price;

        if (edit.value.discount != null) newDiscount = edit.value.discount;

        if (edit.value.price != null) newPrice = edit.value.price;

        const price = sale.quantity * newPrice;
        const discount = (newDiscount * price) / 100;
        return price - discount;
    }

    return 0;
});

const newOrderFromTicket = async () => {
    try {
        const { data } = await axios.post(`Orders/newFromTicket`, {
            ticketFk: Number(route.params.id),
        });
        const routeData = router.resolve({ name: 'OrderCatalog', params: { id: data } });
        window.open(routeData.href, '_blank');
    } catch (err) {
        console.error('Error creating new order', err);
    }
};

const goToLog = (saleId) => {
    router.push({
        name: 'TicketLog',
        params: {
            originId: route.params.id,
            changedModel: 'Sale',
            changedModelId: saleId,
        },
    });
};

const changeTicketState = async (val) => {
    try {
        stateBtnDropdownRef.value.hide();
        const params = { ticketFk: route.params.id, code: val };
        await axios.post('Tickets/state', params);
        notify('globals.dataSaved', 'positive');
        await resetChanges();
    } catch (err) {
        console.error('Error changing ticket state', err);
    }
};

const removeSelectedSales = () => {
    selectedSales.value.forEach((sale) => {
        const index = sales.value.indexOf(sale);
        sales.value.splice(index, 1);
    });
};

const removeSales = async () => {
    try {
        const params = { sales: selectedValidSales.value, ticketId: store.data.id };
        await axios.post('Sales/deleteSales', params);
        removeSelectedSales();
        notify('globals.dataSaved', 'positive');
    } catch (err) {
        console.error('Error deleting sales', err);
    }
};

const insertRow = () => sales.value.push({ ...DEFAULT_EDIT });

const setTransferParams = async () => {
    try {
        const checkedSales = JSON.parse(JSON.stringify(selectedSales.value));
        transfer.value = {
            lastActiveTickets: [],
            sales: checkedSales,
        };

        const params = { ticketId: store.data.id };
        const { data } = await axios.get(
            `clients/${store.data.clientFk}/lastActiveTickets`,
            {
                params,
            }
        );
        transfer.value.lastActiveTickets = data;
    } catch (err) {
        console.error('Error setting transfer params', err);
    }
};

onMounted(async () => {
    stateStore.rightDrawer = true;
    getConfig();
    getSales();
});

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

<template>
    <FetchData
        :url="`Tickets/${route.params.id}/isEditable`"
        auto-load
        @on-fetch="(data) => (isTicketEditable = data)"
    />
    <FetchData
        :url="`Tickets/${route.params.id}/isLocked`"
        auto-load
        @on-fetch="(data) => (isLocked = data)"
    />
    <FetchData
        url="States/editableStates"
        :filter="{ fields: ['code', 'name', 'id', 'alertLevel'], order: 'name ASC' }"
        auto-load
        @on-fetch="(data) => (editableStatesOptions = data)"
    />
    <VnSubToolbar>
        <template #st-actions>
            <QBtnGroup push class="q-gutter-x-sm" flat>
                <QBtn
                    :label="t('ticketSale.ok')"
                    color="primary"
                    :disable="!isTicketEditable || ticketState === 'OK'"
                    @click="changeTicketState('OK')"
                >
                    <QTooltip>{{ t(`Change ticket state to 'Ok'`) }}</QTooltip>
                </QBtn>
                <QBtnDropdown
                    ref="stateBtnDropdownRef"
                    color="primary"
                    :label="t('ticketSale.state')"
                    :disable="!isTicketEditable"
                >
                    <VnSelect
                        :options="editableStatesOptions"
                        hide-selected
                        option-label="name"
                        option-value="code"
                        hide-dropdown-icon
                        focus-on-mount
                        @update:model-value="changeTicketState"
                    />
                </QBtnDropdown>
                <TicketSaleMoreActions
                    :ticket="store.data"
                    :is-ticket-editable="isTicketEditable"
                    :sales="selectedValidSales"
                    :disable="!selectedSales.length"
                    :mana="mana"
                    :ticket-config="ticketConfig"
                    @get-mana="getMana()"
                    @update-discounts="updateDiscount"
                />
                <QBtn
                    color="primary"
                    icon="delete"
                    :disable="!isTicketEditable || !selectedSales.length"
                    @click="
                        openConfirmationModal(
                            t('Continue anyway?'),
                            t('You are going to delete lines of the ticket'),
                            removeSales
                        )
                    "
                >
                    <QTooltip>{{ t('Remove lines') }}</QTooltip>
                </QBtn>
                <QBtn
                    color="primary"
                    icon="vn:splitline"
                    :disable="!isTicketEditable || !selectedSales.length"
                    @click="setTransferParams()"
                >
                    <QTooltip>{{ t('Transfer lines') }}</QTooltip>
                    <TicketTransfer
                        :transfer="transfer"
                        :ticket="store.data"
                        @refresh-data="resetChanges()"
                    />
                </QBtn>
            </QBtnGroup>
        </template>
    </VnSubToolbar>
    <QDrawer side="right" :width="270" v-model="stateStore.rightDrawer">
        <div
            class="q-pa-md q-mb-md q-ma-md color-vn-text"
            style="border: 2px solid black"
        >
            <QCardSection class="justify-center text-subtitle1" horizontal>
                <span class="q-mr-xs color-vn-label"
                    >{{ t('ticketSale.subtotal') }}:
                </span>
                <span>{{ toCurrency(store.data?.totalWithoutVat) }}</span>
            </QCardSection>
            <QCardSection class="justify-center text-subtitle1" horizontal>
                <span class="q-mr-xs color-vn-label"> {{ t('ticketSale.tax') }}: </span>
                <span>{{
                    toCurrency(store.data?.totalWithVat - store.data?.totalWithoutVat)
                }}</span>
            </QCardSection>
            <QCardSection
                class="justify-center text-weight-bold text-subtitle1"
                horizontal
            >
                <span class="q-mr-xs color-vn-label"> {{ t('ticketSale.total') }}: </span>
                <span>{{ toCurrency(store.data?.totalWithVat) }}</span>
            </QCardSection>
        </div></QDrawer
    >
    <QTable
        :rows="sales"
        :columns="columns"
        row-key="id"
        :pagination="{ rowsPerPage: 0 }"
        class="full-width q-mt-md"
        selection="multiple"
        v-model:selected="selectedSales"
        :no-data-label="t('globals.noResults')"
    >
        <template #body-cell-statusIcons="{ row }">
            <QTd class="q-gutter-x-xs">
                <router-link
                    v-if="row.claim?.claimFk"
                    :to="{ name: 'ClaimBasicData', params: { id: row.claim?.claimFk } }"
                >
                    <QIcon color="primary" name="vn:claims" size="xs">
                        <QTooltip>
                            {{ t('ticketSale.claim') }}:
                            {{ row.claim?.claimFk }}
                        </QTooltip>
                    </QIcon>
                </router-link>
                <QIcon v-if="row.visible < 0" color="primary" name="warning" size="xs">
                    <QTooltip>
                        {{ t('ticketSale.visible') }}: {{ row.visible || 0 }}
                    </QTooltip>
                </QIcon>
                <QIcon v-if="row.reserved" color="primary" name="vn:reserva" size="xs">
                    <QTooltip>
                        {{ t('ticketSale.reserved') }}
                    </QTooltip>
                </QIcon>
                <QIcon
                    v-if="row.itemShortage"
                    color="primary"
                    name="vn:unavailable"
                    size="xs"
                >
                    <QTooltip>
                        {{ t('ticketSale.noVisible') }}
                    </QTooltip>
                </QIcon>
                <QIcon
                    v-if="row.hasComponentLack"
                    color="primary"
                    name="vn:components"
                    size="xs"
                >
                    <QTooltip>
                        {{ t('ticketSale.hasComponentLack') }}
                    </QTooltip>
                </QIcon>
            </QTd>
        </template>
        <template #body-cell-picture="{ row }">
            <QTd>
                <div class="image-wrapper">
                    <VnImg :id="row.itemFk" class="rounded" />
                </div>
            </QTd>
        </template>
        <template #body-cell-visible="{ row }">
            <QTd @click.stop>
                <QBadge :color="row.visible < 0 ? 'alert' : 'transparent'" dense>
                    {{ row.visible }}
                </QBadge>
            </QTd>
        </template>
        <template #body-cell-available="{ row }">
            <QTd @click.stop>
                <QBadge :color="row.available < 0 ? 'alert' : 'transparent'" dense>
                    {{ row.available }}
                </QBadge>
            </QTd>
        </template>
        <template #body-cell-itemFk="{ row }">
            <QTd @click.stop>
                <div v-if="row.id">
                    <QBtn flat color="primary" dense>
                        {{ row.itemFk }}
                    </QBtn>
                    <ItemDescriptorProxy :id="row.itemFk" />
                </div>
                <VnSelect
                    v-else
                    hide-selected
                    option-label="name"
                    option-value="id"
                    url="Items/withName"
                    :fields="['id', 'name']"
                    sort-by="id DESC"
                    @update:model-value="changeQuantity(row)"
                    v-model="row.itemFk"
                >
                    <template #option="scope">
                        <QItem v-bind="scope.itemProps">
                            <QItemSection>
                                <QItemLabel> #{{ scope.opt?.id }} </QItemLabel>
                                <QItemLabel caption>{{ scope.opt?.name }}</QItemLabel>
                            </QItemSection>
                        </QItem>
                    </template>
                </VnSelect>
            </QTd>
        </template>
        <template #body-cell-quantity="{ row }">
            <QTd @click.stop>
                <VnInput
                    v-if="isTicketEditable"
                    v-model.number="row.quantity"
                    @keyup.enter="changeQuantity(row)"
                    @blur="changeQuantity(row)"
                    @focus="edit.oldQuantity = row.quantity"
                />
                <span v-else>{{ row.quantity }}</span>
            </QTd>
        </template>
        <template #body-cell-item="{ row }">
            <QTd class="col">
                <div class="column">
                    <span>{{ row.concept }}</span>
                    <span class="color-vn-label">{{ row.item?.subName }}</span>
                    <FetchedTags v-if="row.item" :item="row.item" />
                    <QPopupProxy v-if="row.id && isTicketEditable">
                        <VnInput v-model="row.concept" @change="updateConcept(row)" />
                    </QPopupProxy>
                </div>
            </QTd>
        </template>
        <template #body-cell-price="{ row }">
            <QTd>
                <template v-if="isTicketEditable && row.id">
                    <QBtn flat color="primary" dense @click="onOpenEditPricePopover(row)">
                        {{ toCurrency(row.price) }}
                    </QBtn>
                    <TicketEditManaProxy
                        ref="editPriceProxyRef"
                        :mana="mana"
                        :new-price="getNewPrice"
                        @save="updatePrice(row)"
                    >
                        <VnInput
                            v-model.number="edit.price"
                            :label="t('ticketSale.price')"
                            type="number"
                        />
                    </TicketEditManaProxy>
                </template>
                <span v-else>{{ toCurrency(row.price) }}</span>
            </QTd>
        </template>
        <template #body-cell-discount="{ row }">
            <QTd>
                <template v-if="!isLocked && row.id">
                    <QBtn
                        flat
                        color="primary"
                        dense
                        @click="onOpenEditDiscountPopover(row)"
                    >
                        {{ toPercentage(row.discount / 100) }}
                    </QBtn>
                    <TicketEditManaProxy
                        :mana="mana"
                        :new-price="getNewPrice"
                        @save="changeDiscount(row)"
                    >
                        <VnInput
                            v-model.number="edit.discount"
                            :label="t('ticketSale.discount')"
                            type="number"
                        />
                    </TicketEditManaProxy>
                </template>
                <span v-else>{{ toPercentage(row.discount / 100) }}</span>
            </QTd>
        </template>
        <template #body-cell-history="{ row }">
            <QTd>
                <QBtn
                    v-if="row.$hasLogs"
                    @click.stop="goToLog(row.id)"
                    color="primary"
                    icon="history"
                    size="md"
                    flat
                >
                    <QTooltip class="text-no-wrap">
                        {{ t('ticketSale.history') }}
                    </QTooltip>
                </QBtn>
            </QTd>
        </template>
        <template #bottom-row>
            <QBtn
                class="cursor-pointer fill-icon q-ml-md q-my-lg"
                color="primary"
                icon="add_circle"
                size="md"
                round
                flat
                shortcut="+"
                :disable="!isTicketEditable"
                @click="insertRow()"
            >
                <QTooltip>
                    {{ t('Add item') }}
                </QTooltip>
            </QBtn>
        </template>
    </QTable>

    <QPageSticky :offset="[20, 20]">
        <QBtn @click="newOrderFromTicket()" color="primary" fab icon="add" shortcut="+" />
        <QTooltip class="text-no-wrap">
            {{ t('Add item to basket') }}
        </QTooltip>
    </QPageSticky>
</template>

<i18n>
es:
    New item: Nuevo artículo
    Add item to basket: Añadir artículo a la cesta
    Change ticket state to 'Ok': Cambiar estado del ticket a 'Ok'
    Remove lines: Eliminar líneas
    Continue anyway?: ¿Continuar de todas formas?
    You are going to delete lines of the ticket: Vas a eliminar lineas del ticket
    Add item: Añadir artículo
    Transfer lines: Transferir líneas
</i18n>
