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

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

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

const $props = defineProps({
    formData: {
        type: Object,
        required: true,
    },
    haveNegatives: {
        type: Boolean,
        required: true,
        default: false,
    },
});

const emit = defineEmits(['updateForm', 'update:haveNegatives']);

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

const _ticketData = ref($props.formData);
const ticketUpdateActions = ref(null);
const haveNegatives = computed({
    get: () => $props.haveNegatives,
    set: (val) => emit('update:haveNegatives', val),
});
const rows = computed(() => _ticketData.value?.sale?.items || []);

watch(
    () => _ticketData.value,
    (val) => emit('updateForm', val),
    { deep: true }
);

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

const loadDefaultTicketAction = () => {
    const isSalesAssistant = hasAny(['salesAssistant']);
    _ticketData.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 * item.quantity,
        0
    );
});

const ticketHaveNegatives = () => {
    let _haveNegatives = false;
    let haveNotNegatives = false;
    _ticketData.value.withoutNegatives = false;
    const haveDifferences = _ticketData.value.sale.haveDifferences;
    _ticketData.value.sale.items.forEach((item) => {
        if (item.quantity > item.movable) _haveNegatives = true;
        else haveNotNegatives = true;
    });

    haveNegatives.value = _haveNegatives && haveNotNegatives && haveDifferences;
    if (haveNegatives.value) _ticketData.value.withoutNegatives = true;
};

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

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

<template>
    <FetchData
        url="TicketUpdateActions"
        @on-fetch="(data) => (ticketUpdateActions = data)"
        auto-load
    />
    <RightMenu>
        <template #right-panel>
            <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-center" horizontal>
                    <span>
                        {{ t('basicData.price') }}:
                        {{ toCurrency(totalPrice) }}
                    </span>
                </QCardSection>
                <QCardSection class="column items-center" horizontal>
                    <span>
                        {{ t('basicData.newPrice') }}: {{ toCurrency(totalNewPrice) }}
                    </span>
                </QCardSection>
                <QCardSection class="column items-center" 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="_ticketData.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="_ticketData.withoutNegatives"
                        :toggle-indeterminate="false"
                    />
                    <QIcon name="info" size="xs" class="q-ml-sm">
                        <QTooltip max-width="350px">
                            {{ t('basicData.withoutNegativesInfo') }}
                        </QTooltip>
                    </QIcon>
                </QCardSection>
            </QCard>
        </template>
    </RightMenu>
    <QTable
        :rows="rows"
        :columns="columns"
        row-key="id"
        :pagination="{ rowsPerPage: 0 }"
        class="full-width q-mt-md"
        :no-data-label="t('globals.noResults')"
    >
        <template #body-cell-item="{ row }">
            <QTd>
                <QBtn flat color="primary">
                    {{ row.itemFk }}
                    <ItemDescriptorProxy :id="row.itemFk" />
                </QBtn>
            </QTd>
        </template>
        <template #body-cell-description="{ row }">
            <QTd>
                <div class="column">
                    <span>{{ row.item.name }}</span>
                    <span class="color-vn-label">{{ row.item.subName }}</span>
                    <FetchedTags :item="row.item" :max-length="6" />
                </div>
            </QTd>
        </template>
        <template #body-cell-movable="{ row }">
            <QTd>
                <QBadge
                    v-if="_ticketData?.sale?.haveDifferences"
                    :text-color="row.quantity > row.movable ? 'black' : 'white'"
                    :color="row.quantity > row.movable ? 'negative' : 'transparent'"
                    :label="row.movable"
                />
            </QTd>
        </template>
    </QTable>
</template>
