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

import axios from 'axios';

import { useValidator } from 'src/composables/useValidator';
import useNotify from 'src/composables/useNotify';

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

const { notify } = useNotify();
const { t } = useI18n();
const { validate } = useValidator();
const route = useRoute();
const router = useRouter();

const filterCompanies = { order: ['code'] };
const filterWarehouses = { order: ['name'] };

const inputFileRef = ref();
const allowedContentTypes = ref([]);
const optionsCompanies = ref([]);
const optionsWarehouses = ref([]);
const optionsDmsTypes = ref([]);
const isLoading = ref(false);
const dms = ref({
    hasFile: true,
});

const setCurrentDms = (data) => {
    dms.value.reference = data.reference;
    dms.value.companyId = data.companyFk;
    dms.value.warehouseId = data.warehouseFk;
    dms.value.dmsTypeId = data.dmsTypeFk;
    dms.value.description = data.description;
};

const saveData = async () => {
    try {
        const formData = new FormData();
        const files = dms.value.files;

        if (files && files.length > 0) {
            for (let file of files) {
                formData.append(file.name, file);
            }
            dms.value.hasFileAttached = true;

            const url = `dms/${route.params.dmsId}/updateFile`;
            await axios.post(url, formData, {
                params: dms.value,
            });
            notify('globals.dataSaved', 'positive');
            toCustomerFileManagement();
        }
    } catch (error) {
        notify(error.message, 'negative');
    }
};

const toCustomerFileManagement = () => {
    router.push({ name: 'CustomerFileManagement' });
};
</script>

<template>
    <FetchData :url="`Dms/${route.params.dmsId}`" @on-fetch="setCurrentDms" auto-load />
    <FetchData
        @on-fetch="(data) => (allowedContentTypes = data)"
        auto-load
        url="DmsContainers/allowedContentTypes"
    />
    <FetchData
        :filter="filterCompanies"
        @on-fetch="(data) => (optionsCompanies = data)"
        auto-load
        url="Companies"
    />
    <FetchData
        :filter="filterWarehouses"
        @on-fetch="(data) => (optionsWarehouses = data)"
        auto-load
        url="Warehouses"
    />
    <FetchData
        :filter="filterWarehouses"
        @on-fetch="(data) => (optionsDmsTypes = data)"
        auto-load
        url="DmsTypes"
    />

    <Teleport to="#st-actions">
        <QBtnGroup push class="q-gutter-x-sm">
            <QBtn
                :disabled="isLoading"
                :label="t('globals.cancel')"
                :loading="isLoading"
                @click="toCustomerFileManagement"
                color="primary"
                flat
                icon="close"
            />
            <QBtn
                :disabled="isLoading"
                :label="t('globals.save')"
                :loading="isLoading"
                @click.stop="saveData"
                color="primary"
                icon="save"
            />
        </QBtnGroup>
    </Teleport>

    <QCard class="q-pa-lg">
        <QCardSection>
            <QForm>
                <VnRow>
                    <div class="col">
                        <VnInput
                            :label="t('Reference')"
                            clearable
                            v-model="dms.reference"
                        />
                    </div>
                    <div class="col">
                        <VnSelect
                            :label="t('Company')"
                            :options="optionsCompanies"
                            :rules="validate('entry.companyFk')"
                            option-label="code"
                            option-value="id"
                            v-model="dms.companyId"
                        />
                    </div>
                </VnRow>

                <VnRow>
                    <div class="col">
                        <VnSelect
                            :label="t('Warehouse')"
                            :options="optionsWarehouses"
                            option-label="name"
                            option-value="id"
                            v-model="dms.warehouseId"
                        />
                    </div>
                    <div class="col">
                        <VnSelect
                            :label="t('Type')"
                            :options="optionsDmsTypes"
                            option-label="name"
                            option-value="id"
                            v-model="dms.dmsTypeId"
                        />
                    </div>
                </VnRow>

                <VnRow>
                    <div class="col">
                        <VnInput
                            :label="t('Description')"
                            :rules="validate('route.description')"
                            clearable
                            type="textarea"
                            v-model="dms.description"
                        />
                    </div>
                </VnRow>

                <VnRow>
                    <div class="col">
                        <QFile
                            ref="inputFileRef"
                            class="required"
                            :label="t('File')"
                            v-model="dms.files"
                            multiple
                            :accept="allowedContentTypes.join(',')"
                            clearable
                            clear-icon="close"
                        >
                            <template #append>
                                <QBtn
                                    icon="vn:attach"
                                    flat
                                    round
                                    padding="xs"
                                    @click="inputFileRef.pickFiles()"
                                >
                                    <QTooltip>
                                        {{ t('Select a file') }}
                                    </QTooltip>
                                </QBtn>
                                <QBtn icon="info" flat round padding="xs">
                                    <QTooltip max-width="30rem">
                                        {{
                                            `${t(
                                                'Allowed content types'
                                            )}: ${allowedContentTypes.join(', ')}`
                                        }}
                                    </QTooltip>
                                </QBtn>
                            </template>
                        </QFile>
                    </div>
                </VnRow>

                <QCheckbox
                    :label="t('Generate identifier for original file')"
                    v-model="dms.hasFile"
                    disable
                />
            </QForm>
        </QCardSection>
    </QCard>
</template>

<i18n>
en:
    clientFileDescription: '{dmsTypeName} FROM CLIENT {clientName} ID {clientId}'
es:
    Reference: Referencia
    Company: Empresa
    Warehouse: Almacén
    Type: Tipo
    Description: Descripción
    clientFileDescription: '{dmsTypeName} DEL CLIENTE {clientName} ID {clientId}'
    File: Fichero
    Select a file: Selecciona un fichero
    Allowed content types: Tipos de archivo permitidos
    Generate identifier for original file: Generar identificador para archivo original
</i18n>
