<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 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(() => [
    {
        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,
    },
    {
        label: t('basicData.movable'),
        name: 'movable',
        align: 'left',
    },
    {
        required: true,
        label: t('basicData.quantity'),
        name: 'quantity',
        field: 'quantity',
        align: 'left',
    },
    {
        required: true,
        label: t('basicData.pricePPU'),
        name: 'price',
        field: 'price',
        align: 'left',
        format: (val) => toCurrency(val),
    },
    {
        required: true,
        label: t('basicData.newPricePPU'),
        name: 'newPrice',
        field: (row) => row.component.newPrice,
        align: 'left',
        format: (val) => toCurrency(val),
    },
    {
        required: true,
        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 || 0, 0);
});
const showMovableColumn = computed(() => (haveDifferences.value > 0 ? ['movable'] : []));
const haveDifferences = computed(() => _ticketData.value.sale?.haveDifferences);
const ticketHaveNegatives = () => {
    let _haveNegatives = false;
    let haveNotNegatives = false;
    _ticketData.value.withoutNegatives = false;
    _ticketData.value?.sale?.items.forEach((item) => {
        if (item.quantity > item.movable) _haveNegatives = true;
        else haveNotNegatives = true;
    });

    haveNegatives.value = _haveNegatives && haveNotNegatives && haveDifferences.value;
    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
    />
    <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="_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>
    </QDrawer>
    <QTable
        :visible-columns="showMovableColumn"
        :rows="rows"
        :columns="columns"
        row-key="id"
        :pagination="{ rowsPerPage: 0 }"
        class="full-width q-mt-md"
        :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="display: contents">
                <div class="column">
                    <span>{{ row.item.name }}</span>
                    <span class="color-vn-label">{{ row.item.subName }}</span>
                    <FetchedTags :item="row.item" />
                </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>
