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

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

const route = useRoute();
const { t } = useI18n();
const emit = defineEmits(['onDataSaved']);

const $props = defineProps({
    model: {
        type: String,
        required: true,
    },
    defaultDmsCode: {
        type: String,
        default: null,
    },
    formInitialData: {
        type: Object,
        default: null,
    },
    url: {
        type: String,
        default: null,
    },
});

const warehouses = ref();
const companies = ref();
const dmsTypes = ref();
const allowedContentTypes = ref();
const inputFileRef = ref();
const dms = ref({});

onMounted(() => {
    defaultData();
    if (!$props.formInitialData)
        dms.value.description = t($props.model + 'Description', dms.value);
});
function onFileChange(files) {
    dms.value.hasFileAttached = !!files;
    dms.value.file = files?.name;
}

function mapperDms(data) {
    const formData = new FormData();
    const { files } = data;
    if (files) formData.append(files?.name, files);
    delete data.files;

    const dms = {
        hasFile: !!data.hasFile,
        hasFileAttached: data.hasFileAttached,
        reference: data.reference,
        warehouseId: data.warehouseFk,
        companyId: data.companyFk,
        dmsTypeId: data.dmsTypeFk,
        description: data.description,
    };
    return [formData, { params: dms }];
}

function getUrl() {
    if ($props.url) return $props.url;
    if ($props.formInitialData) return 'dms/' + $props.formInitialData.id + '/updateFile';
    return `${$props.model}/${route.params.id}/uploadFile`;
}

async function save() {
    const body = mapperDms(dms.value);
    const response = await axios.post(getUrl(), body[0], body[1]);
    emit('onDataSaved', body[1].params, response);
}

function defaultData() {
    if ($props.formInitialData) return (dms.value = $props.formInitialData);
    return addDefaultData({
        reference: route.params.id,
    });
}

function setDmsTypes(data) {
    dmsTypes.value = data;
    if (!$props.formInitialData && $props.defaultDmsCode) {
        const { id } = data.find((dmsType) => dmsType.code == $props.defaultDmsCode);
        addDefaultData({ dmsTypeFk: id });
    }
}

function addDefaultData(data) {
    Object.assign(dms.value, data);
}
</script>
<template>
    <FetchData url="Warehouses" @on-fetch="(data) => (warehouses = data)" auto-load />
    <FetchData url="Companies" @on-fetch="(data) => (companies = data)" auto-load />
    <FetchData url="DmsTypes" @on-fetch="setDmsTypes" auto-load />
    <FetchData
        url="DmsContainers/allowedContentTypes"
        @on-fetch="(data) => (allowedContentTypes = data.join(','))"
        auto-load
    />
    <FetchData
        url="UserConfigs/getUserConfig"
        @on-fetch="addDefaultData"
        :auto-load="!$props.formInitialData"
    />
    <FormModelPopup
        :title="formInitialData ? t('globals.edit') : t('globals.create')"
        model="dms"
        :form-initial-data="formInitialData ?? {}"
        :save-fn="save"
    >
        <template #form-inputs>
            <div class="q-gutter-y-ms">
                <VnRow>
                    <VnInput :label="t('globals.reference')" v-model="dms.reference" />
                    <VnSelectFilter
                        :label="t('globals.company')"
                        v-model="dms.companyFk"
                        :options="companies"
                        option-value="id"
                        option-label="code"
                        input-debounce="0"
                    />
                </VnRow>
                <VnRow>
                    <VnSelectFilter
                        :label="t('globals.warehouse')"
                        v-model="dms.warehouseFk"
                        :options="warehouses"
                        option-value="id"
                        option-label="name"
                        input-debounce="0"
                    />
                    <VnSelectFilter
                        :label="t('globals.type')"
                        v-model="dms.dmsTypeFk"
                        :options="dmsTypes"
                        option-value="id"
                        option-label="name"
                        input-debounce="0"
                    />
                </VnRow>
                <QInput
                    :label="t('globals.description')"
                    v-model="dms.description"
                    type="textarea"
                />
                <QFile
                    ref="inputFileRef"
                    :label="t('entry.buys.file')"
                    v-model="dms.files"
                    :multiple="false"
                    :accept="allowedContentTypes"
                    @update:model-value="onFileChange(dms.files)"
                    class="required"
                    :display-value="dms.file"
                >
                    <template #append>
                        <QIcon
                            name="vn:attach"
                            class="cursor-pointer"
                            @click="inputFileRef.pickFiles()"
                        >
                            <QTooltip>{{ t('globals.selectFile') }}</QTooltip>
                        </QIcon>
                        <QIcon name="info" class="cursor-pointer">
                            <QTooltip>{{
                                t('contentTypesInfo', { allowedContentTypes })
                            }}</QTooltip>
                        </QIcon>
                    </template>
                </QFile>
                <QCheckbox
                    v-model="dms.hasFile"
                    :label="t('Generate identifier for original file')"
                />
            </div>
        </template>
    </FormModelPopup>
</template>
<style scoped>
.q-gutter-y-ms {
    display: grid;
    row-gap: 20px;
}
</style>
<i18n>
en:
    contentTypesInfo: Allowed file types {allowedContentTypes}
    EntryDmsDescription: Reference {reference}
es:
    Generate identifier for original file: Generar identificador para archivo original
    contentTypesInfo: Tipos de archivo permitidos {allowedContentTypes}
    EntryDmsDescription: Referencia {reference}

</i18n>
