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

import FetchData from 'components/FetchData.vue';
import VnSelectFilter from 'src/components/common/VnSelectFilter.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';

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 thermographFilter = {
    fields: ['thermographFk'],
    where: {
        travelFk: null,
    },
    order: 'thermographFk ASC',
};
const fetchTravelThermographsRef = ref(null);
const allowedContentTypes = ref('');
const user = state.getUser();
const thermographsOptions = ref([]);
const dmsTypesOptions = ref([]);
const companiesOptions = ref([]);
const warehousesOptions = ref([]);
const inputFileRef = ref(null);

const thermographForm = reactive({
    thermographId: null,
    state: null,
    reference: null,
    dmsTypeId: null,
    companyId: null,
    warehouseId: null,
    files: [],
    description: 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: 'miscellaneous' },
            },
        };
        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.companyId = user.value.companyFk;
    thermographForm.warehouseId = user.value.warehouseFk;
    thermographForm.reference = route.params.id;
    thermographForm.dmsTypeId = dataResponse.id;
    thermographForm.state = 'Ok';
    thermographForm.description = t('travel.thermographs.travelFileDescription', {
        travelId: route.params.id,
    }).toUpperCase();
};

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

        if (data) {
            thermographForm.thermographId = data.thermographFk;
            thermographForm.state = data.result;
            thermographForm.reference = data.dms?.reference;
            thermographForm.warehouseId = data.dms?.warehouseFk;
            thermographForm.companyId = data.dms?.companyFk;
            thermographForm.dmsTypeId = data.dms?.dmsTypeFk;
            thermographForm.description = data.dms?.description || '';
            thermographForm.hasFile = data.dms?.hasFile;
            thermographForm.hasFileAttached = false;
        }
    } catch (err) {
        console.error('Error fetching termograph');
    }
};

const onSubmit = () => {
    props.viewAction === 'create' ? createThermograph() : updateThermograph();
};

const createThermograph = async () => {
    const formData = new FormData();

    thermographForm.files.forEach((file) => {
        formData.append(file.name, file);
    });

    try {
        await axios.post(`/travels/${route.params.id}/createThermograph`, formData, {
            params: thermographForm,
            headers: {
                'Content-Type': 'multipart/form-data',
            },
        });
        router.push({ name: 'TravelThermographsIndex' });
        notify(t('Thermograph created'), 'positive');
    } catch (error) {
        console.error('Error creating thermograph');
    }
};

const updateThermograph = async () => {
    const formData = new FormData();

    thermographForm.files.forEach((file) => {
        formData.append(file.name, file);
    });

    try {
        await axios.post(`travels/${route.params.id}/updateThermograph`, formData, {
            params: thermographForm,
            headers: {
                'Content-Type': 'multipart/form-data',
            },
        });
        router.push({ name: 'TravelThermographsIndex' });
        notify(t('Thermograph created'), 'positive');
    } catch (error) {
        console.error('Error creating thermograph');
    }
};

const onThermographCreated = async (data) => {
    await fetchTravelThermographsRef.value.fetch();
    thermographForm.thermographId = data.thermographId;
};
</script>

<template>
    <FetchData
        url="DmsContainers/allowedContentTypes"
        @on-fetch="(data) => (allowedContentTypes = data.join(', '))"
        auto-load
    />
    <FetchData
        ref="fetchTravelThermographsRef"
        url="TravelThermographs"
        @on-fetch="(data) => (thermographsOptions = data)"
        :filter="thermographFilter"
        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
    />
    <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 class="row q-gutter-md q-mb-md">
                    <div class="col">
                        <VnSelectDialog
                            :label="t('travel.thermographs.thermograph')"
                            v-model="thermographForm.thermographId"
                            :options="thermographsOptions"
                            option-value="thermographFk"
                            option-label="thermographFk"
                            :disable="viewAction === 'edit'"
                            :tooltip="t('New thermograph')"
                        >
                            <template #form>
                                <CreateThermographForm
                                    @on-data-saved="onThermographCreated($event, data)"
                                />
                            </template>
                        </VnSelectDialog>
                    </div>
                    <div class="col">
                        <VnInput
                            v-model="thermographForm.state"
                            :label="t('travel.thermographs.state')"
                        />
                    </div>
                </VnRow>
                <VnRow class="row q-gutter-md q-mb-md">
                    <div class="col">
                        <VnInput
                            v-model="thermographForm.reference"
                            :label="t('travel.thermographs.reference')"
                        />
                    </div>
                    <div class="col">
                        <VnSelectFilter
                            :label="t('travel.thermographs.type')"
                            v-model="thermographForm.dmsTypeId"
                            :options="dmsTypesOptions"
                            option-value="id"
                            option-label="name"
                        />
                    </div>
                </VnRow>
                <VnRow class="row q-gutter-md q-mb-md">
                    <div class="col">
                        <VnSelectFilter
                            :label="t('travel.thermographs.company')"
                            v-model="thermographForm.companyId"
                            :options="companiesOptions"
                            option-value="id"
                            option-label="code"
                        />
                    </div>
                    <div class="col">
                        <VnSelectFilter
                            :label="t('travel.thermographs.warehouse')"
                            v-model="thermographForm.warehouseId"
                            :options="warehousesOptions"
                            option-value="id"
                            option-label="name"
                        />
                    </div>
                </VnRow>
                <VnRow v-if="viewAction === 'edit'" class="row q-gutter-md q-mb-md">
                    <div class="col">
                        <QInput
                            :label="t('globals.description')"
                            type="textarea"
                            v-model="thermographForm.description"
                            fill-input
                        />
                    </div>
                </VnRow>
                <VnRow class="row q-gutter-md q-mb-md">
                    <div class="col">
                        <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>
                    </div>
                </VnRow>
            </QCard>
        </QForm>
    </QPage>
</template>

<i18n>
es:
    Select files: Selecciona ficheros
    Thermograph created: Termógrafo creado
    New thermograph: Nuevo termógrafo
</i18n>
