<script setup>
import { ref, computed, onMounted, onBeforeMount, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import TicketDescriptorProxy from 'src/pages/Ticket/Card/TicketDescriptorProxy.vue';
import WorkerDescriptorProxy from 'src/pages/Worker/Card/WorkerDescriptorProxy.vue';
import ItemDescriptorProxy from 'src/pages/Item/Card/ItemDescriptorProxy.vue';
import VnInput from 'src/components/common/VnInput.vue';
import ItemRequestDenyForm from './ItemRequestDenyForm.vue';
import ItemRequestFilter from './ItemRequestFilter.vue';
import VnSearchbar from 'src/components/ui/VnSearchbar.vue';
import VnSelect from 'components/common/VnSelect.vue';
import { useStateStore } from 'stores/useStateStore';
import { useArrayData } from 'composables/useArrayData';
import { toDateFormat } from 'src/filters/date';
import { toCurrency } from 'filters/index';
import useNotify from 'src/composables/useNotify.js';
import { getDateQBadgeColor } from 'src/composables/getDateQBadgeColor.js';
import axios from 'axios';
import RightMenu from 'src/components/common/RightMenu.vue';

const { t } = useI18n();
const { notify } = useNotify();
const stateStore = useStateStore();
let filterParams = ref({});
const denyFormRef = ref(null);
const denyRequestId = ref(null);
const denyRequestIndex = ref(null);
const itemRequestsOptions = ref([]);
const arrayData = useArrayData('ItemRequests', {
    url: 'TicketRequests/filter',
    userParams: filterParams,
    order: ['shippedDate ASC', 'isOk ASC'],
});
const store = arrayData.store;

watch(
    () => store.data,
    (value) => (itemRequestsOptions.value = value)
);

const columns = computed(() => [
    {
        label: t('item.buyRequest.ticketId'),
        name: 'id',
        field: 'id',
        align: 'left',
        sortable: true,
    },
    {
        label: t('item.buyRequest.shipped'),
        field: 'shipped',
        name: 'shipped',
        align: 'left',
        sortable: true,
    },
    {
        label: t('globals.description'),
        field: 'description',
        name: 'description',
        align: 'left',
        sortable: true,
    },
    {
        label: t('item.buyRequest.requester'),
        name: 'requester',
        align: 'left',
        sortable: true,
    },
    {
        label: t('item.buyRequest.requested'),
        field: 'quantity',
        name: 'requested',
        align: 'left',
        sortable: true,
    },
    {
        label: t('item.buyRequest.price'),
        field: 'price',
        name: 'price',
        align: 'left',
        sortable: true,
        format: (val) => toCurrency(val),
    },
    {
        label: t('item.buyRequest.attender'),
        field: 'attender',
        name: 'attender',
        align: 'left',
        sortable: true,
    },
    {
        label: t('item.buyRequest.item'),
        field: 'item',
        name: 'item',
        align: 'left',
        sortable: true,
    },
    {
        label: t('item.buyRequest.achieved'),
        field: 'achieved',
        name: 'achieved',
        align: 'left',
        sortable: true,
    },
    {
        label: t('item.buyRequest.concept'),
        field: 'concept',
        name: 'concept',
        align: 'left',
        sortable: true,
    },
    {
        label: t('item.buyRequest.state'),
        field: 'state',
        name: 'state',
        align: 'left',
        sortable: true,
    },
    {
        label: '',
        name: 'action',
        align: 'left',
        columnFilter: null,
    },
]);

const changeQuantity = async (request) => {
    try {
        if (request.saleFk) {
            const params = {
                quantity: request.saleQuantity,
            };

            await axios.patch(`Sales/${request.saleFk}`, params);
            notify(t('globals.dataSaved'), 'positive');
            confirmRequest(request);
        } else confirmRequest(request);
    } catch (error) {
        console.error('Error changing quantity:: ', error);
    }
};

const confirmRequest = async (request) => {
    try {
        if (request.itemFk && request.saleQuantity) {
            const params = {
                itemFk: request.itemFk,
                quantity: request.saleQuantity,
                attenderFk: request.attenderFk,
            };

            const { data } = await axios.post(
                `TicketRequests/${request.id}/confirm`,
                params
            );

            request.itemDescription = data.concept;
            request.isOk = true;
            notify(t('globals.dataSaved'), 'positive');
        }
    } catch (error) {
        console.error('Error confirming request:: ', error);
    }
};

const getState = (isOk) => {
    if (isOk === null) return t('Pending');
    else if (isOk) return t('Accepted');
    else return t('Denied');
};

const showDenyRequestForm = (requestId, rowIndex) => {
    denyRequestId.value = requestId;
    denyRequestIndex.value = rowIndex;
    denyFormRef.value.show();
};

const onDenyAccept = (_, responseData) => {
    itemRequestsOptions.value[denyRequestIndex.value].isOk = responseData.isOk;
    itemRequestsOptions.value[denyRequestIndex.value].attenderFk =
        responseData.attenderFk;
    itemRequestsOptions.value[denyRequestIndex.value].response = responseData.response;
    denyRequestId.value = null;
    denyRequestIndex.value = null;
};

onMounted(async () => {
    await arrayData.fetch({ append: false });
    stateStore.rightDrawer = true;
});

onBeforeMount(() => {
    const today = Date.vnNew();
    today.setHours(0, 0, 0, 0);

    const nextWeek = Date.vnNew();
    nextWeek.setHours(23, 59, 59, 59);
    nextWeek.setDate(nextWeek.getDate() + 7);

    filterParams.value = {
        from: today,
        to: nextWeek,
        state: 'pending',
    };
});
</script>

<template>
    <VnSearchbar
        data-key="ItemRequests"
        url="TicketRequests/filter"
        :label="t('globals.search')"
        :info="t('You can search by Id or alias')"
        :redirect="false"
    />
    <RightMenu>
        <template #right-panel>
            <ItemRequestFilter data-key="ItemRequests" />
        </template>
    </RightMenu>
    <QPage class="column items-center q-pa-md">
        <QTable
            :rows="itemRequestsOptions"
            :columns="columns"
            row-key="id"
            :pagination="{ rowsPerPage: 0 }"
            class="full-width q-mt-md"
            :no-data-label="t('globals.noResults')"
        >
            <template #body-cell-id="{ row }">
                <QTd>
                    <QBtn flat color="primary"> {{ row.ticketFk }}</QBtn>
                    <TicketDescriptorProxy :id="row.ticketFk" />
                </QTd>
            </template>

            <template #body-cell-shipped="{ row }">
                <QTd>
                    <QBadge
                        v-if="getDateQBadgeColor(row.shipped)"
                        :color="getDateQBadgeColor(row.shipped)"
                        text-color="black"
                        class="q-ma-none"
                        dense
                        style="font-size: 14px"
                    >
                        {{ toDateFormat(row.shipped) }}
                    </QBadge>
                    <span v-else>{{ toDateFormat(row.shipped) }}</span>
                </QTd>
            </template>
            <template #body-cell-requester="{ row }">
                <QTd>
                    <QBtn flat dense color="primary"> {{ row.requesterName }}</QBtn>
                    <WorkerDescriptorProxy :id="row.requesterFk" />
                </QTd>
            </template>
            <template #body-cell-attender="{ row }">
                <QTd>
                    <VnSelect
                        v-model="row.attenderFk"
                        :where="{ role: 'buyer' }"
                        sort-by="id"
                        url="Workers"
                        hide-selected
                        option-label="firstName"
                        option-value="id"
                        dense
                    />
                </QTd>
            </template>
            <template #body-cell-item="{ row }">
                <QTd>
                    <VnInput
                        v-model.number="row.itemFk"
                        type="number"
                        :disable="row.isOk != null"
                        dense
                    />
                </QTd>
            </template>
            <template #body-cell-achieved="{ row }">
                <QTd>
                    <VnInput
                        v-model.number="row.saleQuantity"
                        @blur="changeQuantity(row)"
                        type="number"
                        :disable="!row.itemFk || row.isOk != null"
                        dense
                    />
                </QTd>
            </template>
            <template #body-cell-concept="{ row }">
                <QTd>
                    <QBtn flat dense color="primary"> {{ row.itemDescription }}</QBtn>
                    <ItemDescriptorProxy :id="row.itemFk" />
                </QTd>
            </template>
            <template #body-cell-state="{ row }">
                <QTd>
                    <span>{{ getState(row.isOk) }}</span>
                </QTd>
            </template>
            <template #body-cell-action="{ row, rowIndex }">
                <QTd>
                    <QIcon
                        v-if="row.response?.length"
                        name="insert_drive_file"
                        color="primary"
                        size="sm"
                    >
                        <QTooltip>
                            {{ row.response }}
                        </QTooltip>
                    </QIcon>
                    <QIcon
                        v-if="row.isOk == null"
                        name="thumb_down"
                        color="primary"
                        size="sm"
                        class="fill-icon"
                        @click="showDenyRequestForm(row.id, rowIndex)"
                    >
                        <QTooltip>
                            {{ t('Discard') }}
                        </QTooltip>
                    </QIcon>
                </QTd>
            </template>
        </QTable>
        <QDialog ref="denyFormRef" transition-show="scale" transition-hide="scale">
            <ItemRequestDenyForm
                :request-id="denyRequestId"
                @on-data-saved="onDenyAccept"
            />
        </QDialog>
    </QPage>
</template>

<i18n>
es:
    Discard: Descartar
    You can search by Id or alias: Buscar peticiones por identificador o alias
    Denied: Denegada
    Accepted: Aceptada
    Pending: Pendiente
</i18n>
