<script setup>
import { onMounted, ref, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { storeToRefs } from 'pinia';

import FetchData from 'components/FetchData.vue';
import VnSelect from 'src/components/common/VnSelect.vue';
import VnInputDate from 'components/common/VnInputDate.vue';

import { useInvoiceOutGlobalStore } from 'src/stores/invoiceOutGlobal.js';

const { t } = useI18n();
const invoiceOutGlobalStore = useInvoiceOutGlobalStore();

// invoiceOutGlobalStore state and getters
const { initialDataLoading, formInitialData, invoicing, status } =
    storeToRefs(invoiceOutGlobalStore);

// invoiceOutGlobalStore actions
const { makeInvoice, setStatusValue } = invoiceOutGlobalStore;

const clientsToInvoice = ref('all');
const companiesOptions = ref([]);
const printersOptions = ref([]);
const serialTypesOptions = ref([]);

const handleInvoiceOutSerialsFetch = (data) => {
    serialTypesOptions.value = Array.from(
        new Set(data.map((item) => item.type).filter((type) => type))
    );
};

const formData = ref({});

const optionsInitialData = computed(() => {
    const optionsArrays = [
        companiesOptions.value,
        printersOptions.value,
        serialTypesOptions.value,
    ];
    return optionsArrays.every((arr) => arr.length > 0);
});

const getStatus = computed({
    get() {
        return status.value;
    },
    set(value) {
        setStatusValue(value.value);
    },
});

onMounted(async () => {
    await invoiceOutGlobalStore.init();
    formData.value = { invoiceDate: formInitialData.value.invoiceDate };
});
</script>

<template>
    <FetchData
        url="Companies"
        @on-fetch="(data) => (companiesOptions = data)"
        auto-load
    />
    <FetchData url="Printers" @on-fetch="(data) => (printersOptions = data)" auto-load />
    <FetchData
        url="invoiceOutSerials"
        @on-fetch="handleInvoiceOutSerialsFetch"
        auto-load
    />
    <QForm
        v-if="!initialDataLoading && optionsInitialData"
        @submit="makeInvoice(formData, clientsToInvoice)"
        class="form-container q-pa-md"
        style="max-width: 256px"
    >
        <div class="column q-gutter-y-sm">
            <QRadio
                v-model="clientsToInvoice"
                dense
                val="all"
                :label="t('allClients')"
                :dark="true"
            />
            <QRadio
                v-model="clientsToInvoice"
                dense
                val="one"
                :label="t('oneClient')"
                :dark="true"
                class="q-mb-sm"
            />
            <VnSelect
                v-if="clientsToInvoice === 'one'"
                :label="t('client')"
                v-model="formData.clientId"
                url="Clients"
                option-value="id"
                option-label="name"
                hide-selected
                dense
                outlined
                rounded
            >
                <template #option="scope">
                    <QItem v-bind="scope.itemProps">
                        <QItemSection>
                            <QItemLabel>
                                #{{ scope.opt?.id }} {{ scope.opt?.name }}
                            </QItemLabel>
                        </QItemSection>
                    </QItem>
                </template>
            </VnSelect>
            <VnSelect
                :label="t('invoiceOutSerialType')"
                v-model="formData.serialType"
                :options="serialTypesOptions"
                option-value="type"
                option-label="type"
                hide-selected
                dense
                outlined
                rounded
            />
            <VnInputDate
                v-model="formData.invoiceDate"
                :label="t('invoiceDate')"
                is-outlined
            />
            <VnInputDate
                v-model="formData.maxShipped"
                :label="t('maxShipped')"
                is-outlined
            />
            <VnSelect
                :label="t('company')"
                v-model="formData.companyFk"
                :options="companiesOptions"
                option-label="code"
                dense
                outlined
                rounded
            />
            <VnSelect
                :label="t('printer')"
                v-model="formData.printer"
                :options="printersOptions"
                dense
                outlined
                rounded
            />
        </div>

        <QBtn
            v-if="!invoicing"
            :label="t('invoiceOut')"
            type="submit"
            color="primary"
            class="q-mt-md full-width"
            unelevated
            rounded
            dense
        />
        <QBtn
            v-if="invoicing"
            :label="t('stop')"
            color="primary"
            class="q-mt-md full-width"
            unelevated
            rounded
            dense
            @click="getStatus = 'stopping'"
        />
    </QForm>
</template>

<style scoped>
.form-container * {
    max-width: 100%;
}
</style>

<i18n>
en:
    invoiceDate: Invoice date
    maxShipped: Max date
    allClients: All clients
    oneClient: One client
    company: Company
    printer: Printer
    invoiceOut: Invoice out
    client: Client
    invoiceOutSerialType: Serial Type
    stop: Stop

es:
    invoiceDate: Fecha de factura
    maxShipped: Fecha límite
    allClients: Todos los clientes
    oneClient: Un solo cliente
    company: Empresa
    printer: Impresora
    invoiceOut: Facturar
    client: Cliente
    invoiceOutSerialType: Tipo de Serie
    stop: Parar
</i18n>
