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

import VnSelect from 'src/components/common/VnSelect.vue';
import VnRow from 'components/ui/VnRow.vue';
import FormModelPopup from 'components/FormModelPopup.vue';
import FetchData from 'components/FetchData.vue';

import useNotify from 'src/composables/useNotify.js';
import axios from 'axios';

const emit = defineEmits(['onDataSaved']);

const { t } = useI18n();
const { notify } = useNotify();
const route = useRoute();

const dmsOptions = ref([]);
const dmsId = ref(null);

const importDms = async () => {
    try {
        if (!dmsId.value) throw new Error(t(`The document identifier can't be empty`));

        const data = {
            ticketFk: route.params.id,
            dmsFk: dmsId.value,
        };

        await axios.post('ticketDms', data);
        notify(t('globals.dataSaved'), 'positive');
        dmsId.value = null;
        emit('onDataSaved');
    } catch (e) {
        throw new Error(e.message);
    }
};
</script>

<template>
    <FetchData
        url="Dms"
        :filter="{ fields: ['id'], order: 'id ASC' }"
        auto-load
        @on-fetch="(data) => (dmsOptions = data)"
    />
    <FormModelPopup
        url-create="genera"
        model="DmsImport"
        :title="t('Select document id')"
        :form-initial-data="{}"
        :save-fn="importDms"
    >
        <template #form-inputs>
            <VnRow>
                <VnSelect
                    :label="t('Document')"
                    :options="dmsOptions"
                    hide-selected
                    option-label="id"
                    option-value="id"
                    v-model="dmsId"
                />
            </VnRow>
        </template>
    </FormModelPopup>
</template>

<i18n>
es:
    Select document id: Introduzca id de gestion documental
    Document: Documento
    The document indentifier can't be empty: El número de documento no puede estar vacío
</i18n>
