<script setup>
import { ref, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { useQuasar, date } 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 VnTable from 'components/VnTable/VnTable.vue';
import WorkerDescriptorProxy from 'src/pages/Worker/Card/WorkerDescriptorProxy.vue';
import EntryStockBoughtDetail from 'src/pages/Entry/EntryStockBoughtDetail.vue';
import TravelDescriptorProxy from '../Travel/Card/TravelDescriptorProxy.vue';
import { useFilterParams } from 'src/composables/useFilterParams';
import axios from 'axios';

const { t } = useI18n();
const quasar = useQuasar();
const filterDate = ref(useFilterParams('StockBoughts').params);
const footer = ref({ bought: 0, reserve: 0 });
const columns = computed(() => [
    {
        align: 'left',
        label: 'Id',
        name: 'id',
        isId: true,
        columnFilter: false,
        visible: false,
    },
    {
        align: 'left',
        name: 'workerFk',
        label: t('entryStockBought.buyer'),
        isTitle: true,
        component: 'select',
        isEditable: false,
        cardVisible: true,
        create: true,
        attrs: {
            url: 'TicketRequests/getItemTypeWorker',
            fields: ['id', 'nickname'],
            optionLabel: 'nickname',
            sortBy: 'nickname ASC',
            optionValue: 'id',
        },
        columnFilter: false,
        width: '60%',
    },
    {
        align: 'center',
        label: t('entryStockBought.reserve'),
        name: 'reserve',
        columnFilter: false,
        create: true,
        component: 'number',
        summation: true,
        format: ({ reserve }, dashIfEmpty) => dashIfEmpty(round(reserve)),
        width: '20%',
    },
    {
        align: 'right',
        label: t('entryStockBought.bought'),
        name: 'bought',
        summation: true,
        cardVisible: true,
        style: ({ reserve, bought }) => boughtStyle(bought, reserve),
        columnFilter: false,
        width: '20%',
    },
    {
        label: t('entryStockBought.date'),
        name: 'dated',
        component: 'date',
        visible: false,
        create: true,
    },
    {
        align: 'center',
        name: 'tableActions',
        actions: [
            {
                title: t('entryStockBought.viewMoreDetails'),
                name: 'searchBtn',
                icon: 'search',
                isPrimary: true,
                action: (row) => {
                    quasar.dialog({
                        component: EntryStockBoughtDetail,
                        componentProps: {
                            workerFk: row.workerFk,
                            dated: filterDate.value.dated,
                        },
                    });
                },
            },
        ],
    },
]);
const fetchDataRef = ref();
const travelDialogRef = ref(false);
const tableRef = ref();
const travel = ref(null);
const filter = computed(() => ({
    fields: ['id', 'm3', 'ref', 'warehouseInFk'],
    include: [
        {
            relation: 'warehouseIn',
            scope: {
                fields: ['code', 'name'],
            },
        },
    ],
    where: {
        shipped: date.adjustDate(filterDate.value.dated, {
            hour: 0,
            minute: 0,
            second: 0,
        }),
        m3: { neq: null },
    },
}));

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

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

function round(value) {
    return Math.round(value * 100) / 100;
}

function boughtStyle(bought, reserve) {
    return reserve < bought ? { color: 'var(--q-negative)' } : '';
}

async function beforeSave(data, getChanges) {
    const changes = data.creates;
    if (!changes) return data;
    const patchPromises = [];

    for (const change of changes) {
        if (change?.isReal === false && change?.reserve > 0) {
            const postData = {
                workerFk: change.workerFk,
                reserve: change.reserve,
                dated: filterDate.value.dated,
            };
            const promise = axios.post('StockBoughts', postData).catch((error) => {
                console.error('Error processing change: ', change, error);
            });

            patchPromises.push(promise);
        }
    }

    await Promise.all(patchPromises);
    const filteredChanges = changes.filter((change) => change?.isReal !== false);
    data.creates = filteredChanges;
}
</script>
<template>
    <VnSubToolbar>
        <template #st-data>
            <FetchData
                ref="fetchDataRef"
                url="Travels"
                :filter="filter"
                @on-fetch="
                    (data) => {
                        travel = data.find(
                            (data) => data.warehouseIn?.code?.toLowerCase() === 'vnh',
                        );
                    }
                "
            />
            <VnRow class="travel">
                <div v-show="travel">
                    <span style="color: var(--vn-label-color)">
                        {{ t('entryStockBought.purchaseSpaces') }}:
                    </span>
                    <span>
                        {{ travel?.m3 }}
                    </span>
                    <QBtn
                        v-if="travel?.m3"
                        style="max-width: 20%"
                        flat
                        icon="search"
                        @click="openDialog()"
                        :title="t('entryStockBought.editTravel')"
                        color="primary"
                        data-cy="edit-travel"
                    />
                </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="travel"
            @on-data-saved="fetchDataRef.fetch()"
        >
            <template #form-inputs="{ data }">
                <span class="link">
                    {{ data.ref }}
                    <TravelDescriptorProxy :id="data.id" />
                </span>
                <VnInput v-model="data.m3" :label="t('m3')" type="number" />
            </template>
        </FormModelPopup>
    </QDialog>
    <div class="table-container">
        <div class="column items-center">
            <VnTable
                ref="tableRef"
                data-key="StockBoughts"
                url="StockBoughts/getStockBought"
                :beforeSaveFn="beforeSave"
                save-url="StockBoughts/crud"
                search-url="StockBoughts"
                order="bought DESC"
                :is-editable="true"
                @on-fetch="
                    async (data) => {
                        setFooter(data);
                        await fetchDataRef.fetch();
                    }
                "
                :columns="columns"
                :footer="true"
                table-height="80vh"
                :column-search="false"
                :without-header="true"
                :user-params="{ dated: Date.vnNew() }"
                auto-load
            >
                <template #column-workerFk="{ row }">
                    <span class="link" @click.stop>
                        {{ row?.worker?.user?.nickname }}
                        <WorkerDescriptorProxy :id="row?.workerFk" />
                    </span>
                </template>
                <template #column-footer-reserve>
                    <span>
                        {{ round(footer.reserve) }}
                    </span>
                </template>
                <template #column-footer-bought>
                    <span :style="boughtStyle(footer?.bought, footer?.reserve)">
                        {{ round(footer.bought) }}
                    </span>
                </template>
            </VnTable>
        </div>
    </div>
</template>
<style lang="scss" scoped>
.travel {
    margin-bottom: 0px;
}
.table-container {
    display: flex;
    justify-content: center;
}
.column {
    min-width: 35%;
    margin-top: 5%;
}
.text-negative {
    color: $negative !important;
}
</style>
