<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 } from 'src/filters';
import { useArrayData } from 'composables/useArrayData';
import { useVnConfirm } from 'composables/useVnConfirm';
import useNotify from 'src/composables/useNotify.js';
import axios from 'axios';
import VnTable from 'src/components/VnTable/VnTable.vue';
import VnUsesMana from 'src/components/ui/VnUsesMana.vue';

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 selectedRows = ref([]);
const hasSelectedRows = computed(() => selectedRows.value.length > 0);
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: [],
});
const tableRef = ref([]);

watch(
    () => route.params.id,
    () => tableRef.value.reload()
);

const columns = computed(() => [
    {
        align: 'left',
        name: 'statusIcons',
    },
    {
        align: 'center',
        label: t('lines.image'),
        name: 'image',
        columnField: {
            component: VnImg,
            attrs: (id) => {
                return {
                    id,
                    width: '50px',
                };
            },
        },
        columnFilter: false,
    },
    {
        align: 'left',
        label: t('ticketSale.visible'),
        name: 'visible',
        format: (row, dashIfEmpty) => dashIfEmpty(row.visible),
    },
    {
        align: 'left',
        label: t('ticketSale.available'),
        name: 'available',
        format: (row, dashIfEmpty) => dashIfEmpty(row.available),
    },
    {
        align: 'left',
        label: t('ticketSale.id'),
        name: 'itemFk',
    },
    {
        align: 'left',
        label: t('ticketSale.quantity'),
        name: 'quantity',
        format: (row) => toCurrency(row.quantity),
    },
    {
        align: 'left',
        label: t('ticketSale.item'),
        name: 'item',
        format: (row) => row?.item?.name,
        columnClass: 'expand',
    },
    {
        align: 'left',
        label: t('ticketSale.price'),
        name: 'price',
        format: (row) => toCurrency(row.price),
    },
    {
        align: 'left',
        label: t('ticketSale.discount'),
        name: 'discount',
        format: (row) => toPercentage(row.discount),
    },
    {
        align: 'left',
        label: t('ticketSale.amount'),
        name: 'amount',
        format: (row) => parseInt(row.amount * row.quantity),
    },
    {
        align: 'left',
        label: t('ticketSale.packaging'),
        name: 'itemPackingTypeFk',
        format: (row, dashIfEmpty) => dashIfEmpty(row?.item?.itemPackingTypeFk),
    },
    {
        align: 'right',
        name: 'tableActions',
        actions: [
            {
                title: t('ticketSale.history'),
                icon: 'history',
                isPrimary: true,
                action: (row) => goToLog(row.id),
            },
        ],
    },
]);

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 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 });
    tableRef.value.reload();
};

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');
        window.location.reload();
    } 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 [...selectedRows.value];
});

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 = () => {
    selectedRows.value.forEach((sale) => {
        const index = sales.value.indexOf(sale);
        sales.value.splice(index, 1);
    });
};

const removeSales = async () => {
    try {
        const params = {
            sales: selectedRows.value.filter((sale) => sale.id),
            ticketId: store.data.id,
        };
        selectedRows.value
            .filter((sale) => !sale.id)
            .forEach((sale) =>
                tableRef.value.CrudModelRef.formData.splice(sale.$index, 1)
            );

        if (params.sales.length == 0) return;
        await axios.post('Sales/deleteSales', params);
        removeSelectedSales();
        notify('globals.dataSaved', 'positive');
        window.location.reload();
    } catch (err) {
        console.error('Error deleting sales', err);
    }
};

const setTransferParams = async () => {
    try {
        selectedSales.value = selectedValidSales.value;
        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();
});

onUnmounted(() => (stateStore.rightDrawer = false));

const items = ref([]);
const newRow = ref({});

const updateItem = (row) => {
    const selectedItem = items.value.find((item) => item.id === row.itemFk);
    if (selectedItem) {
        row.item = selectedItem;
        row.itemFk = selectedItem.id;
        row.price = selectedItem.price;
        row.discount = 0;
        row.quantity = 0;
        row.amount = row.price * row.quantity;
    }
    endNewRow(selectedItem);
};

function handleOnDataSave({ CrudModelRef }) {
    const { copy } = addRow(CrudModelRef.formData);
    CrudModelRef.insert(copy);
}

const addRow = (original = null) => {
    let copy = null;
    if (!original) {
        copy = { isNew: true };
    } else {
        copy = {
            itemFk: original.itemFk,
            item: original.item,
            quantity: original.quantity,
            price: original.price,
            discount: original.discount,
            amount: original.amount,
            isNew: true,
        };
    }
    newRow.value = copy;
    return { original, copy };
};

const endNewRow = (row) => {
    if (row.itemFk && row.quantity) {
        row.isNew = false;
    }
};

watch(
    () => newRow.value.itemFk,
    (newItemFk) => {
        if (newItemFk) {
            updateItem(newRow.value);
        }
    }
);
</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="!hasSelectedRows"
                    :mana="mana"
                    :ticket-config="ticketConfig"
                    @get-mana="getMana()"
                    @update-discounts="updateDiscount"
                />
                <QBtn
                    color="primary"
                    icon="delete"
                    :disable="!isTicketEditable || !hasSelectedRows"
                    @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 || !hasSelectedRows"
                    @click="setTransferParams()"
                >
                    <QTooltip>{{ t('Transfer lines') }}</QTooltip>
                    <TicketTransfer
                        :transfer="transfer"
                        :ticket="store.data"
                        @refresh-data="resetChanges()"
                    />
                </QBtn>
            </QBtnGroup>
        </template>
    </VnSubToolbar>
    <QDrawer side="right" :width="265" 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-end 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-end 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-end 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
    >
    <VnTable
        ref="tableRef"
        data-key="TicketSales"
        :url="`Tickets/${route.params.id}/getSales`"
        :columns="columns"
        v-model:selected="selectedRows"
        :bottom="true"
        :table="{
            'row-key': 'id',
            selection: 'multiple',
        }"
        :right-search="false"
        :column-search="false"
        :disable-option="{ card: true }"
        auto-load
        @on-fetch="onSalesFetched"
        :create="{
            onDataSaved: handleOnDataSave,
        }"
        :create-as-dialog="false"
        :crud-model="{
            paginate: false,
        }"
        :default-remove="false"
        :default-reset="false"
        :default-save="false"
        :disabled-attr="isTicketEditable"
    >
        <template #column-statusIcons="{ row }">
            <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>
        </template>
        <template #body-cell-picture="{ row }">
            <QTd>
                <div class="image-wrapper">
                    <VnImg :id="row.itemFk" class="rounded" zoom-resolution="1600x900" />
                </div>
            </QTd>
        </template>
        <template #column-image="{ row }">
            <div class="image-wrapper">
                <VnImg :id="parseInt(row?.item?.id)" class="rounded" />
            </div>
        </template>
        <template #column-visible="{ row }">
            <QBadge :color="row.visible < 0 ? 'alert' : 'transparent'" dense>
                {{ row.visible }}
            </QBadge>
        </template>
        <template #column-available="{ row }">
            <QBadge :color="row.available < 0 ? 'alert' : 'transparent'" dense>
                {{ row.available }}
            </QBadge>
        </template>
        <template #column-itemFk="{ row }">
            <VnSelect
                v-if="row.isNew"
                url="Items/WithName"
                :fields="['id', 'name']"
                :sort-by="['id DESC']"
                :options="items"
                option-label="name"
                option-value="id"
                v-model="row.itemFk"
                @update:model-value="updateItem(row)"
            >
                <template #option="scope">
                    <QItem v-bind="scope.itemProps">
                        <QItemSection>
                            <QItemLabel>
                                {{ scope.opt?.id }} - {{ scope.opt?.name }}</QItemLabel
                            >
                        </QItemSection>
                    </QItem>
                </template>
            </VnSelect>
            <span v-else class="link" @click.stop>
                {{ row?.itemFk }}
                <ItemDescriptorProxy :id="row?.itemFk" />
            </span>
        </template>
        <template #column-item="{ row }">
            <div class="row column full-width justify-between items-start">
                {{ row?.item?.name }}
                <div v-if="row?.item?.subName" class="subName">
                    {{ row?.item?.subName.toUpperCase() }}
                </div>
            </div>
            <FetchedTags :item="row" :max-length="6" />
            <QPopupProxy v-if="row.id && isTicketEditable">
                <VnInput v-model="row.concept" @change="updateConcept(row)" />
            </QPopupProxy>
        </template>
        <template #column-quantity="{ row }">
            <VnInput
                v-if="row.isNew"
                v-model.number="row.quantity"
                type="number"
                @blur="changeQuantity(row)"
                @focus="edit.oldQuantity = row.quantity"
            />
            <VnInput
                v-else-if="isTicketEditable"
                v-model.number="row.quantity"
                @blur="changeQuantity(row)"
                @focus="edit.oldQuantity = row.quantity"
            />
            <span v-else>{{ row.quantity }}</span>
        </template>
        <template #column-price="{ row }">
            <template v-if="isTicketEditable && row.id">
                <QBtn flat class="link" 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>
        </template>
        <template #column-discount="{ row }">
            <template v-if="!isLocked && row.id">
                <QBtn flat class="link" dense @click="onOpenEditDiscountPopover(row)">
                    {{ toPercentage(row.discount / 100) }}
                </QBtn>
                <TicketEditManaProxy
                    :mana="mana"
                    :new-price="getNewPrice"
                    :uses-mana="usesMana"
                    :mana-code="manaCode"
                    @save="changeDiscount(row)"
                >
                    <VnInput
                        v-model.number="edit.discount"
                        :label="t('ticketSale.discount')"
                        type="number"
                    />
                    <div v-if="usesMana" class="column q-gutter-y-sm q-mt-sm">
                        <VnUsesMana :mana-code="manaCode" />
                    </div>
                </TicketEditManaProxy>
            </template>
            <span v-else>{{ toPercentage(row.discount / 100) }}</span>
        </template>
        <template #column-amount="{ row }">
            {{ toCurrency(row.quantity * row.price) }}
        </template>
    </VnTable>

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

<style lang="scss" scoped>
.image-wrapper {
    height: 50px;
    width: 50px;
}

.subName {
    text-transform: uppercase;
    color: var(--vn-label-color);
}
</style>

<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>
