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

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

import { useState } from 'src/composables/useState';
import { useStateStore } from 'stores/useStateStore';
import axios from 'axios';
import useNotify from 'src/composables/useNotify.js';
import VnInputNumber from 'src/components/common/VnInputNumber.vue';

const props = defineProps({
    viewAction: {
        type: String,
        default: 'create',
    },
});

const stateStore = useStateStore();
const { t } = useI18n();
const route = useRoute();
const router = useRouter();
const state = useState();
const { notify } = useNotify();

const fetchTravelThermographsRef = ref(null);
const allowedContentTypes = ref('');
const user = state.getUser();
const dmsTypesOptions = ref([]);
const companiesOptions = ref([]);
const warehousesOptions = ref([]);
const temperaturesOptions = ref([]);
const thermographForm = ref({});
const inputFileRef = ref(null);

onBeforeMount(async () => {
    if (props.viewAction === 'create') {
        setCreateDefaultParams();
    } else {
        await setEditDefaultParams();
    }

    if (route.query.thermographData) {
        const thermographData = JSON.parse(route.query.thermographData);
        for (let key in thermographForm) {
            thermographForm[key] = thermographData[key];
        }
    }
});

const fetchDmsTypes = async () => {
    try {
        const params = {
            filter: {
                where: { code: 'thermograph' },
            },
        };
        const { data } = await axios.get('DmsTypes/findOne', { params });
        return data;
    } catch (err) {
        console.error('Error fetching Dms Types');
    }
};

const setCreateDefaultParams = async () => {
    const dataResponse = await fetchDmsTypes();
    thermographForm.value.companyId = user.value.companyFk;
    thermographForm.value.warehouseId = user.value.warehouseFk;
    thermographForm.value.reference = route.params.id;
    thermographForm.value.dmsTypeId = dataResponse.id;
    thermographForm.value.state = 'Ok';
    thermographForm.value.description = t('travel.thermographs.travelFileDescription', {
        travelId: route.params.id,
    }).toUpperCase();
};

const setEditDefaultParams = async () => {
    const filterObj = { include: { relation: 'dms' } };
    const filter = encodeURIComponent(JSON.stringify(filterObj));
    const { data } = await axios.get(
        `TravelThermographs/${route.query.travelThermographFk}?filter=${filter}`
    );

    if (data) {
        thermographForm.value.thermographFk = data.thermographFk;
        thermographForm.value.state = data.result;
        thermographForm.value.reference = data.dms?.reference;
        thermographForm.value.warehouseId = data.warehouseFk;
        thermographForm.value.companyId = data.dms?.companyFk;
        thermographForm.value.dmsTypeId = data.dms?.dmsTypeFk;
        thermographForm.value.description = data.dms?.description || '';
        thermographForm.value.hasFile = data.dms?.hasFile;
        thermographForm.value.hasFileAttached = false;
        thermographForm.value.maxTemperature = data.maxTemperature;
        thermographForm.value.minTemperature = data.minTemperature;
        thermographForm.value.temperatureFk = data.temperatureFk;
        thermographForm.value.travelThermographFk = data.id;
    }
};

const onSubmit = async () => {
    const formData = new FormData();
    if (Array.isArray(thermographForm.value.files)) {
        thermographForm.value.hasFileAttached = true;
        thermographForm.value.files.forEach((file) => {
            formData.append(file.name, file);
        });
    }
    delete thermographForm.value.files;
    await axios.post(`/travels/${route.params.id}/saveThermograph`, formData, {
        params: thermographForm.value,
        headers: {
            'Content-Type': 'multipart/form-data',
        },
    });
    router.push({ name: 'TravelThermographsIndex' });
    notify(t('Thermograph created'), 'positive');
};

const onThermographCreated = async (data) => {
    await fetchTravelThermographsRef.value.fetch();
    thermographForm.value = {
        ...thermographForm.value,
        ...data,
        travelThermographFk: data.id,
        warehouseId: data.warehouseFk,
    };
};
</script>
<template>
    <FetchData
        url="DmsContainers/allowedContentTypes"
        @on-fetch="(data) => (allowedContentTypes = data.join(', '))"
        auto-load
    />
    <FetchData
        url="DmsTypes"
        :filter="{ order: 'name' }"
        @on-fetch="(data) => (dmsTypesOptions = data)"
        auto-load
    />
    <FetchData
        url="Companies"
        @on-fetch="(data) => (companiesOptions = data)"
        :filter="{ order: 'code' }"
        auto-load
    />
    <FetchData
        url="Warehouses"
        @on-fetch="(data) => (warehousesOptions = data)"
        :filter="{ order: 'name' }"
        auto-load
    />
    <FetchData
        @on-fetch="(data) => (temperaturesOptions = data)"
        auto-load
        url="Temperatures"
    />
    <QPage class="column items-center full-width">
        <QForm
            model="travel"
            :form-initial-data="thermographForm"
            :observe-form-changes="viewAction === 'create'"
            :default-actions="true"
            @submit="onSubmit()"
            class="full-width"
            style="max-width: 800px"
        >
            <Teleport to="#st-actions" v-if="stateStore?.isSubToolbarShown()">
                <div>
                    <QBtnGroup push class="q-gutter-x-sm">
                        <slot name="moreActions" />
                        <QBtn
                            color="primary"
                            icon="restart_alt"
                            flat
                            @click="reset()"
                            :label="t('globals.reset')"
                        />
                        <QBtn
                            color="primary"
                            icon="save"
                            @click="onSubmit()"
                            :label="t('globals.save')"
                        />
                    </QBtnGroup>
                </div>
            </Teleport>
            <QCard class="q-pa-lg">
                <VnRow>
                    <VnSelectDialog
                        :label="t('travel.thermographs.thermograph')"
                        v-model="thermographForm.travelThermographFk"
                        url="TravelThermographs"
                        :fields="['id', 'thermographFk']"
                        :where="{
                            or: [{ travelFk: null }, { travelFk: $route.params.id }],
                        }"
                        sort-by="thermographFk ASC"
                        option-label="thermographFk"
                        :disable="viewAction === 'edit'"
                        :tooltip="t('New thermograph')"
                    >
                        <template #form>
                            <CreateThermographForm
                                @on-data-saved="onThermographCreated"
                            />
                        </template>
                    </VnSelectDialog>
                    <VnInput
                        v-model="thermographForm.state"
                        :label="t('travel.thermographs.state')"
                    />
                </VnRow>
                <VnRow>
                    <VnInput
                        v-model="thermographForm.reference"
                        :label="t('travel.thermographs.reference')"
                    />
                    <VnSelect
                        :label="t('travel.thermographs.type')"
                        v-model="thermographForm.dmsTypeId"
                        :options="dmsTypesOptions"
                        option-value="id"
                        option-label="name"
                    />
                </VnRow>
                <VnRow>
                    <VnSelect
                        :label="t('travel.thermographs.company')"
                        v-model="thermographForm.companyId"
                        :options="companiesOptions"
                        option-value="id"
                        option-label="code"
                    />
                    <VnSelect
                        :label="t('travel.thermographs.warehouse')"
                        v-model="thermographForm.warehouseId"
                        :options="warehousesOptions"
                        option-value="id"
                        option-label="name"
                    />
                </VnRow>
                <VnRow>
                    <VnSelect
                        :label="t('travel.thermographs.temperature')"
                        :options="temperaturesOptions"
                        hide-selected
                        option-label="name"
                        option-value="code"
                        v-model="thermographForm.temperatureFk"
                        :required="true"
                    />
                    <VnInputNumber
                        v-model="thermographForm.maxTemperature"
                        :label="t('globals.maxTemperature')"
                    />
                    <VnInputNumber
                        v-model="thermographForm.minTemperature"
                        :label="t('globals.minTemperature')"
                    />
                </VnRow>

                <VnRow v-if="viewAction === 'edit'" class="row q-gutter-md q-mb-md">
                    <QInput
                        :label="t('globals.description')"
                        type="textarea"
                        v-model="thermographForm.description"
                        fill-input
                    />
                </VnRow>
                <VnRow>
                    <QFile
                        ref="inputFileRef"
                        :label="t('travel.thermographs.file')"
                        multiple
                        :accept="allowedContentTypes"
                        v-model="thermographForm.files"
                    >
                        <template #append>
                            <QIcon
                                name="vn:attach"
                                class="cursor-pointer q-mr-sm"
                                @click="inputFileRef.pickFiles()"
                            >
                                <QTooltip>{{ t('Select files') }}</QTooltip>
                            </QIcon>
                            <QIcon name="info" class="cursor-pointer">
                                <QTooltip>{{
                                    t('globals.allowedFilesText', {
                                        allowedContentTypes: allowedContentTypes,
                                    })
                                }}</QTooltip>
                            </QIcon>
                        </template>
                    </QFile>
                </VnRow>
            </QCard>
        </QForm>
    </QPage>
</template>
<i18n>
    es:
        Select files: Selecciona ficheros
        Thermograph created: Termógrafo creado
        New thermograph: Nuevo termógrafo
</i18n>
