<script setup>
import { ref, computed, watch } from 'vue';
import VnInputDate from 'components/common/VnInputDate.vue';
import useNotify from 'src/composables/useNotify.js';
import axios from 'axios';

const isLoading = ref(false);
const dateFrom = ref();
const dateTo = ref();

const optionsTo = computed(() => (date) => {
    if (!dateFrom.value) return true;
    return new Date(date) >= new Date(dateFrom.value);
});

watch(dateFrom, (newDateFrom) => {
    if (dateTo.value && new Date(dateTo.value) < new Date(newDateFrom))
        dateTo.value = newDateFrom;
});

const recalc = async () => {
    const { notify } = useNotify();

    const params = {
        schema: 'bs',
        params: [new Date(dateFrom.value), new Date(dateTo.value)],
    };

    try {
        isLoading.value = true;
        await axios.post('Applications/waste_addSales/execute-proc', params);
        notify('wasteRecalc.recalcOk', 'positive');
    } catch (err) {
        console.error(err);
    } finally {
        isLoading.value = false;
    }
};
</script>

<template>
    <div class="q-pa-lg row justify-center">
        <QCard class="bg-light" style="width: 300px">
            <QCardSection>
                <VnInputDate
                    class="q-mb-lg"
                    v-model="dateFrom"
                    :label="$t('globals.from')"
                    rounded
                    dense
                />
                <VnInputDate
                    class="q-mb-lg"
                    v-model="dateTo"
                    :options="optionsTo"
                    :label="$t('globals.to')"
                    :disable="!dateFrom"
                    rounded
                    dense
                />
                <QBtn
                    color="primary"
                    text-color="white"
                    :label="$t('globals.recalc')"
                    :loading="isLoading"
                    :disable="isLoading || !(dateFrom && dateTo)"
                    @click="recalc()"
                />
            </QCardSection>
        </QCard>
    </div>
</template>
