<script setup>
import { ref, computed, watch, reactive } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute } from 'vue-router';

import VnInput from 'src/components/common/VnInput.vue';
import WorkerDescriptorProxy from 'src/pages/Worker/Card/WorkerDescriptorProxy.vue';
import ItemDescriptorProxy from 'src/pages/Item/Card/ItemDescriptorProxy.vue';
import CrudModel from 'src/components/CrudModel.vue';
import TicketCreateRequest from './TicketCreateRequest.vue';

import { dashIfEmpty } from 'src/filters';
import { toDateFormat } from 'src/filters/date.js';

const route = useRoute();
const { t } = useI18n();
const createTicketRequestDialogRef = ref(null);
const crudModelRef = ref(null);

watch(
    () => route.params.id,
    async (val) => {
        crudModelFilter.where.ticketFk = val;
        crudModelRef.value.reload();
    }
);

const crudModelFilter = reactive({
    include: [
        {
            relation: 'atender',
            scope: {
                include: {
                    relation: 'user',
                    scope: {
                        fields: ['nickname'],
                    },
                },
            },
        },
        {
            relation: 'requester',
            scope: {
                include: {
                    relation: 'user',
                    scope: {
                        fields: ['nickname'],
                    },
                },
            },
        },
        {
            relation: 'sale',
        },
    ],
    fields: [
        'id',
        'description',
        'created',
        'requesterFk',
        'attenderFk',
        'quantity',
        'price',
        'saleFk',
        'isOk',
    ],
    order: ['created ASC'],
    where: {
        ticketFk: route.params.id,
    },
});

const columns = computed(() => [
    {
        label: t('purchaseRequest.id'),
        name: 'id',
        field: 'id',
        align: 'left',
        columnFilter: null,
    },
    {
        label: t('purchaseRequest.description'),
        name: 'description',
        field: 'description',
        align: 'left',
        format: (val) => dashIfEmpty(val),
    },
    {
        label: t('purchaseRequest.created'),
        name: 'created',
        field: 'created',
        align: 'left',
        format: (val) => toDateFormat(val),
    },
    {
        label: t('purchaseRequest.requester'),
        name: 'requester',
        align: 'left',
        sortable: true,
    },
    {
        label: t('purchaseRequest.atender'),
        name: 'atender',
        align: 'left',
    },
    {
        label: t('purchaseRequest.quantity'),
        name: 'quantity',
        align: 'left',
    },
    {
        label: t('purchaseRequest.price'),
        name: 'price',
        align: 'left',
    },
    {
        label: t('purchaseRequest.saleFk'),
        name: 'saleFk',
        align: 'left',
    },
    {
        label: t('purchaseRequest.state'),
        name: 'state',
        field: 'isOk',
        align: 'left',
        format: (val) => t(getRequestState(val)),
    },
    {
        label: '',
        name: 'actions',
        align: 'left',
        columnFilter: null,
    },
]);

const getRequestState = (state) => {
    switch (state) {
        case null:
            return 'New';
        case false:
            return 'Denied';
        case true:
            return 'Acepted';
    }
};

const isEditable = (isOk) => isOk !== null;

const removeLine = async (row) => crudModelRef.value.remove([row]);

const openCreateModal = () => createTicketRequestDialogRef.value.show();
</script>

<template>
    <QPage class="column items-center q-pa-md">
        <CrudModel
            data-key="PurchaseRequests"
            url="TicketRequests"
            ref="crudModelRef"
            :filter="crudModelFilter"
            :order="['created ASC']"
            :default-remove="false"
            :default-save="false"
            :default-reset="false"
            :limit="0"
            auto-load
        >
            <template #body="{ rows }">
                <QTable
                    :rows="rows"
                    :columns="columns"
                    row-key="id"
                    :pagination="{ rowsPerPage: 0 }"
                    class="full-width q-mt-md"
                    :no-data-label="t('globals.noResults')"
                    @row-click="(_, row) => redirectToTicketSummary(row.ticketFk)"
                >
                    <template #body-cell-description="{ row }">
                        <QTd @click.stop>
                            <VnInput
                                v-model="row.description"
                                @blur="crudModelRef.saveChanges()"
                                :disable="isEditable(row.isOk)"
                            />
                        </QTd>
                    </template>
                    <template #body-cell-requester="{ row }">
                        <QTd @click.stop>
                            <QBtn flat color="primary">
                                {{ row.requester?.user?.nickname }}
                                <WorkerDescriptorProxy :id="row.requesterFk" />
                            </QBtn>
                        </QTd>
                    </template>
                    <template #body-cell-atender="{ row }">
                        <QTd @click.stop>
                            <QBtn flat color="primary">
                                {{ row.atender?.user?.nickname }}
                                <WorkerDescriptorProxy :id="row.attenderFk" />
                            </QBtn>
                        </QTd>
                    </template>
                    <template #body-cell-quantity="{ row }">
                        <QTd @click.stop>
                            <VnInput
                                v-model="row.quantity"
                                @blur="crudModelRef.saveChanges()"
                                :disable="isEditable(row.isOk)"
                            />
                        </QTd>
                    </template>
                    <template #body-cell-price="{ row }">
                        <QTd @click.stop>
                            <VnInput
                                v-model="row.price"
                                @blur="crudModelRef.saveChanges()"
                                :disable="isEditable(row.isOk)"
                            />
                        </QTd>
                    </template>
                    <template #body-cell-saleFk="{ row }">
                        <QTd @click.stop>
                            <QBtn v-if="row.saleFk" flat color="primary">
                                {{ row.sale.itemFk }}
                                <ItemDescriptorProxy :id="row.sale.itemFk" />
                            </QBtn>
                        </QTd>
                    </template>
                    <template #body-cell-actions="{ row }">
                        <QTd>
                            <QIcon
                                @click.stop="removeLine(row)"
                                class="q-ml-sm cursor-pointer"
                                color="primary"
                                name="delete"
                                size="sm"
                            >
                                <QTooltip>
                                    {{ t('globals.delete') }}
                                </QTooltip>
                            </QIcon>
                        </QTd>
                    </template>
                </QTable>
            </template>
        </CrudModel>
        <QDialog
            ref="createTicketRequestDialogRef"
            transition-show="scale"
            transition-hide="scale"
        >
            <TicketCreateRequest @on-request-created="crudModelRef.reload()" />
        </QDialog>
        <QPageSticky :offset="[20, 20]">
            <QBtn @click="openCreateModal()" color="primary" fab icon="add" />
            <QTooltip class="text-no-wrap">
                {{ t('purchaseRequest.newRequest') }}
            </QTooltip>
        </QPageSticky>
    </QPage>
</template>
<i18n>
    es:
        New: Nueva
        Denied: Denegada
        Accepted: Aceptada
</i18n>
