<script setup>
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useState } from 'src/composables/useState';
import { useQuasar } from 'quasar';

import VnSubToolbar from 'src/components/ui/VnSubToolbar.vue';
import FetchData from 'components/FetchData.vue';
import FormModelPopup from 'components/FormModelPopup.vue';
import VnInput from 'src/components/common/VnInput.vue';
import VnRow from 'components/ui/VnRow.vue';
import RightMenu from 'src/components/common/RightMenu.vue';
import EntryStockBoughtFilter from './EntryStockBoughtFilter.vue';
import VnTable from 'components/VnTable/VnTable.vue';
import WorkerDescriptorProxy from 'src/pages/Worker/Card/WorkerDescriptorProxy.vue';
import EntryStockBoughtDetail from 'src/pages/Entry/EntryStockBoughtDetail.vue';

const { t } = useI18n();
const quasar = useQuasar();
const state = useState();
const user = state.getUser();
const columns = [
    {
        align: 'left',
        label: 'Id',
        name: 'id',
        isId: true,
        columnFilter: false,
        visible: false,
    },
    {
        align: 'left',
        name: 'workerFk',
        label: t('Buyer'),
        isTitle: true,
        component: 'select',
        cardVisible: true,
        create: true,
        attrs: {
            url: 'Workers/activeWithInheritedRole',
            fields: ['id', 'name'],
            where: { role: 'buyer' },
            optionFilter: 'firstName',
            optionLabel: 'name',
            optionValue: 'id',
            useLike: false,
        },
        columnFilter: false,
    },
    {
        align: 'center',
        label: t('Reserve'),
        name: 'reserve',
        columnFilter: false,
        create: true,
        component: 'number',
        summation: true,
    },
    {
        align: 'center',
        label: t('Bought'),
        name: 'bought',
        summation: true,
        cardVisible: true,
        columnFilter: false,
    },
    {
        align: 'left',
        label: t('Date'),
        name: 'dated',
        component: 'date',
        visible: false,
        create: true,
    },
    {
        align: 'left',
        name: 'tableActions',
        actions: [
            {
                title: t('View more details'),
                icon: 'search',
                isPrimary: true,
                action: (row) => {
                    quasar.dialog({
                        component: EntryStockBoughtDetail,
                        componentProps: {
                            workerFk: row.workerFk,
                            dated: userParams.value.dated,
                        },
                    });
                },
            },
        ],
    },
];

const fetchDataRef = ref();
const travelDialogRef = ref(false);
const tableRef = ref();
const travel = ref(null);
const userParams = ref({
    dated: Date.vnNew(),
});

const filter = ref({
    fields: ['id', 'm3', 'warehouseInFk'],
    include: [
        {
            relation: 'warehouseIn',
            scope: {
                fields: ['code'],
            },
        },
    ],
    where: {
        shipped: (userParams.value.dated
            ? new Date(userParams.value.dated)
            : Date.vnNew()
        ).setHours(0, 0, 0, 0),
        m3: { neq: null },
    },
});

const setUserParams = async ({ dated }) => {
    const shipped = (dated ? new Date(dated) : Date.vnNew()).setHours(0, 0, 0, 0);
    filter.value.where.shipped = shipped;
    fetchDataRef.value?.fetch();
};

function openDialog() {
    travelDialogRef.value = true;
}

function setFooter(data) {
    const footer = {
        bought: 0,
        reserve: 0,
    };
    data.forEach((row) => {
        footer.bought += row?.bought;
        footer.reserve += row?.reserve;
    });
    tableRef.value.footer = footer;
}

function round(value) {
    return Math.round(value * 100) / 100;
}
</script>
<template>
    <VnSubToolbar>
        <template #st-data>
            <FetchData
                ref="fetchDataRef"
                url="Travels"
                auto-load
                :filter="filter"
                @on-fetch="
                    (data) => {
                        travel = data.find(
                            (data) => data.warehouseIn?.code.toLowerCase() === 'vnh'
                        );
                    }
                "
            />
            <VnRow class="travel">
                <div v-if="travel">
                    <span style="color: var(--vn-label-color)">
                        {{ t('Purchase Spaces') }}:
                    </span>
                    <span>
                        {{ travel?.m3 }}
                    </span>
                    <QBtn
                        v-if="travel?.m3"
                        style="max-width: 20%"
                        flat
                        icon="edit"
                        @click="openDialog()"
                        :title="t('Edit travel')"
                        color="primary"
                    />
                </div>
            </VnRow>
        </template>
    </VnSubToolbar>
    <QDialog v-model="travelDialogRef" :maximized="true" :class="['vn-row', 'wrap']">
        <FormModelPopup
            :url-update="`Travels/${travel?.id}`"
            model="travel"
            :title="t('Travel m3')"
            :form-initial-data="{ id: travel?.id, m3: travel?.m3 }"
            @on-data-saved="fetchDataRef.fetch()"
        >
            <template #form-inputs="{ data }">
                <VnInput
                    v-model="data.id"
                    :label="t('id')"
                    type="number"
                    disable
                    readonly
                />
                <VnInput v-model="data.m3" :label="t('m3')" type="number" />
            </template>
        </FormModelPopup>
    </QDialog>
    <RightMenu>
        <template #right-panel>
            <EntryStockBoughtFilter
                data-key="StockBoughts"
                @set-user-params="setUserParams"
            />
        </template>
    </RightMenu>
    <div class="table-container">
        <div class="column items-center">
            <VnTable
                ref="tableRef"
                data-key="StockBoughts"
                url="StockBoughts/getStockBought"
                save-url="StockBoughts/crud"
                order="reserve DESC"
                :right-search="false"
                :is-editable="true"
                @on-fetch="(data) => setFooter(data)"
                :create="{
                    urlCreate: 'StockBoughts',
                    title: t('Reserve some space'),
                    onDataSaved: () => tableRef.reload(),
                    formInitialData: {
                        workerFk: user.id,
                        dated: Date.vnNow(),
                    },
                }"
                :columns="columns"
                :user-params="userParams"
                :footer="true"
                table-height="80vh"
                auto-load
                :column-search="false"
            >
                <template #column-workerFk="{ row }">
                    <span class="link" @click.stop>
                        {{ row?.worker?.user?.name }}
                        <WorkerDescriptorProxy :id="row?.workerFk" />
                    </span>
                </template>
                <template #column-bought="{ row }">
                    <span :class="{ 'text-negative': row.reserve < row.bought }">
                        {{ row?.bought }}
                    </span>
                </template>
                <template #column-footer-reserve>
                    <span>
                        {{ round(tableRef.footer.reserve) }}
                    </span>
                </template>
                <template #column-footer-bought>
                    <span
                        :class="{
                            'text-negative':
                                tableRef.footer.reserve < tableRef.footer.bought,
                        }"
                    >
                        {{ round(tableRef.footer.bought) }}
                    </span>
                </template>
            </VnTable>
        </div>
    </div>
</template>
<style lang="scss" scoped>
.travel {
    margin-bottom: 0px;
}
.table-container {
    display: flex;
    justify-content: center;
}
.column {
    display: flex;
    flex-direction: column;
    align-items: center;
}
.text-negative {
    color: $negative !important;
}
</style>
<i18n>
    es:
        Edit travel: Editar envío
        Travel: Envíos
        Purchase Spaces: Espacios de compra
        Buyer: Comprador
        Reserve: Reservado
        Bought: Comprado
        Date: Fecha
        View more details: Ver más detalles
        Reserve some space: Reservar espacio
        This buyer has already made a reservation for this date: Este comprador ya ha hecho una reserva para esta fecha 
</i18n>
