<script setup>
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';

import axios from 'axios';
import { useQuasar } from 'quasar';

import VnRow from 'components/ui/VnRow.vue';

const $props = defineProps({
    clients: {
        type: Array,
        required: true,
    },
    promise: {
        type: Function,
        required: true,
    },
});

const { t } = useI18n();
const quasar = useQuasar();

const newObservation = ref(null);

const onSubmit = async () => {
    try {
        const data = $props.clients.map((item) => {
            return { clientFk: item.clientFk, text: newObservation.value };
        });
        await axios.post('ClientObservations', data);

        const payload = {
            defaulters: $props.clients,
            observation: newObservation.value,
        };
        await axios.post('Defaulters/observationEmail', payload);

        await $props.promise();

        quasar.notify({
            message: t('globals.dataSaved'),
            type: 'positive',
        });
    } catch (error) {
        quasar.notify({
            message: t(`${error.message}`),
            type: 'negative',
        });
    }
};
</script>

<template>
    <QDialog ref="dialogRef">
        <QCard class="q-pa-md q-mb-md">
            <QCardSection>
                <QForm @submit="onSubmit()" class="q-pa-sm">
                    <div>
                        {{
                            t('Add observation to all selected clients', {
                                numberClients: t($props.clients.length),
                            })
                        }}
                    </div>
                    <VnRow class="row q-gutter-md q-mb-md">
                        <div class="col">
                            <QInput
                                :label="t('Message')"
                                type="textarea"
                                v-model="newObservation"
                            />
                        </div>
                    </VnRow>
                    <div class="q-mt-lg row justify-end">
                        <QBtn
                            :label="t('globals.cancel')"
                            color="primary"
                            flat
                            class="q-mr-md"
                            v-close-popup
                        />
                        <QBtn
                            :label="t('globals.save')"
                            type="submit"
                            color="primary"
                            v-close-popup
                        />
                    </div>
                </QForm>
            </QCardSection>
        </QCard>
    </QDialog>
</template>

<i18n>
    es:
        Add observation to all selected clients: Añadir observación a { numberClients } cliente(s) seleccionado(s)
        Message: Mensaje
</i18n>
