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

import ItemDescriptorProxy from 'src/pages/Item/Card/ItemDescriptorProxy.vue';
import FetchedTags from 'components/ui/FetchedTags.vue';
import FetchData from 'components/FetchData.vue';

import { useStateStore } from 'stores/useStateStore';
import { toCurrency } from 'filters/index';
import { useRole } from 'src/composables/useRole';

const haveNegatives = defineModel('haveNegatives', { type: Boolean, required: true });
const formData = defineModel({ type: Object, required: true });

const stateStore = useStateStore();
const { t } = useI18n();
const { hasAny } = useRole();

const ticketUpdateActions = ref(null);
const rows = computed(() => formData.value?.sale?.items || []);

const columns = computed(() => [
    {
        required: true,
        label: t('basicData.item'),
        name: 'item',
        align: 'left',
        format: (val) => val.name,
    },
    {
        required: true,
        label: t('basicData.description'),
        name: 'description',
        align: 'left',
        hidden: true,
    },
    {
        name: 'subName',
        align: 'left',
        required: true,
    },
    {
        label: t('basicData.movable'),
        name: 'movable',
    },
    {
        required: true,
        label: t('basicData.quantity'),
        name: 'quantity',
        field: 'quantity',
        classes: 'number',
    },
    {
        required: true,
        label: t('basicData.pricePPU'),
        name: 'price',
        field: 'price',
        classes: 'number',
        format: (val) => toCurrency(val),
    },
    {
        required: true,
        label: t('basicData.newPricePPU'),
        name: 'newPrice',
        field: (row) => row.component.newPrice,
        classes: 'number',
        format: (val) => toCurrency(val),
    },
    {
        required: true,
        label: t('basicData.difference'),
        name: 'difference',
        field: (row) => row.component.difference,
        classes: 'number',
        format: (val) => toCurrency(val),
        autoWidth: true,
    },
]);

const loadDefaultTicketAction = () => {
    const isSalesAssistant = hasAny(['salesAssistant']);
    formData.value.option = isSalesAssistant ? 'mana' : 'renewPrices';
};

const totalPrice = computed(() => {
    return rows.value.reduce((acc, item) => acc + item.price * item.quantity, 0);
});

const totalNewPrice = computed(() => {
    return rows.value.reduce(
        (acc, item) => acc + item.component.newPrice * item.quantity,
        0
    );
});

const totalDifference = computed(() => {
    return rows.value.reduce((acc, item) => acc + item.component?.difference || 0, 0);
});
const showMovableColumn = computed(() => (haveDifferences.value > 0 ? ['movable'] : []));
const haveDifferences = computed(() => formData.value.sale?.haveDifferences);
async function ticketHaveNegatives() {
    let _haveNegatives = false;
    let haveNotNegatives = false;
    formData.value.withoutNegatives = false;
    formData.value?.sale?.items.forEach((item) => {
        if (item.quantity > item.movable) _haveNegatives = true;
        else haveNotNegatives = true;
    });

    haveNegatives.value = _haveNegatives && haveNotNegatives && haveDifferences.value;
    await nextTick();
    if (haveNegatives.value) formData.value.withoutNegatives = true;
}

onMounted(async () => {
    stateStore.rightDrawer = true;
    loadDefaultTicketAction();
    await ticketHaveNegatives();
});

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

<template>
    <FetchData
        url="TicketUpdateActions"
        @on-fetch="(data) => (ticketUpdateActions = data)"
        auto-load
    />
    <QDrawer side="right" :width="265" v-model="stateStore.rightDrawer">
        <QCard
            class="q-pa-md q-mb-md q-ma-md color-vn-text"
            bordered
            flat
            style="border-color: black"
        >
            <QCardSection horizontal>
                <span class="text-weight-bold text-subtitle1 text-center full-width">
                    {{ t('basicData.total') }}
                </span>
            </QCardSection>
            <QCardSection class="column items-left" horizontal>
                <span>
                    {{ t('basicData.price') }}:
                    {{ toCurrency(totalPrice) }}
                </span>
            </QCardSection>
            <QCardSection class="column items-left" horizontal>
                <span>
                    {{ t('basicData.newPrice') }}: {{ toCurrency(totalNewPrice) }}
                </span>
            </QCardSection>
            <QCardSection class="column items-left" horizontal>
                <span>
                    {{ t('basicData.difference') }}: {{ toCurrency(totalDifference) }}
                </span>
            </QCardSection>
        </QCard>
        <QCard
            v-if="totalDifference"
            class="q-pa-md q-mb-md q-ma-md color-vn-text"
            bordered
            flat
            style="border-color: black"
        >
            <QCardSection horizontal>
                <span class="text-weight-bold text-subtitle1 text-center full-width">
                    {{ t('basicData.chargeDifference') }}
                </span>
            </QCardSection>
            <QCardSection
                v-for="(action, index) in ticketUpdateActions"
                :key="index"
                horizontal
            >
                <QRadio
                    v-model="formData.option"
                    :val="action.code"
                    :label="action.description"
                    dense
                />
            </QCardSection>
        </QCard>
        <QCard
            v-if="haveNegatives"
            class="q-pa-md q-mb-md q-ma-md color-vn-text"
            bordered
            flat
            style="border-color: black"
        >
            <QCardSection horizontal class="flex row items-center">
                <QCheckbox
                    :label="t('basicData.withoutNegatives')"
                    v-model="formData.withoutNegatives"
                    :toggle-indeterminate="false"
                />
                <QIcon name="info" size="xs" class="q-ml-sm">
                    <QTooltip max-width="350px">
                        {{ t('basicData.withoutNegativesInfo') }}
                    </QTooltip>
                </QIcon>
            </QCardSection>
        </QCard>
    </QDrawer>
    <QTable
        :visible-columns="showMovableColumn"
        :rows="rows"
        :columns="columns"
        row-key="id"
        :pagination="{ rowsPerPage: 0 }"
        class="full-width"
        :no-data-label="t('globals.noResults')"
        flat
    >
        <template #body-cell-item="{ row }">
            <QTd @click.stop class="link">
                <QBtn flat>
                    {{ row.itemFk }}
                    <ItemDescriptorProxy :id="row.itemFk" />
                </QBtn>
            </QTd>
        </template>
        <template #body-cell-description="{ row }">
            <QTd style="min-width: 120px; max-width: 120px">
                <div class="column q-pb-xs" style="min-width: 120px">
                    <span>{{ row.item.name }}</span>
                    <FetchedTags :item="row.item" class="full-width" />
                </div>
            </QTd>
        </template>
        <template #body-cell-subName="{ row }">
            <QTd>
                <span class="color-vn-label">{{ row.item.subName }}</span>
            </QTd>
        </template>
        <template #body-cell-movable="{ row }">
            <QTd class="number">
                <QChip
                    v-if="formData?.sale?.haveDifferences"
                    :text-color="row.quantity > row.movable ? 'black' : 'white'"
                    :color="row.quantity > row.movable ? 'negative' : 'transparent'"
                    :label="row.movable"
                    dense
                    square
                />
            </QTd>
        </template>
    </QTable>
</template>
