<script setup>
import axios from 'axios';
import { QIcon, QInput, QItem, QItemSection, QSelect } from 'quasar';
import { computed, onMounted, onUpdated, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute, useRouter } from 'vue-router';

onMounted(() => fetch());
onUpdated(() => fetch());

const { t } = useI18n();
const route = useRoute();
const router = useRouter();
const $props = defineProps({
    id: {
        type: Number,
        required: false,
        default: null,
    },
});
const entityId = computed(() => $props.id || route.params.id);

let wagonTypes = [];
let originalData = {};
const wagon = ref({});
const filteredWagonTypes = ref(wagonTypes);

async function onSubmit() {
    try {
        const params = {
            id: entityId.value,
            label: wagon.value.label,
            plate: wagon.value.plate,
            volume: wagon.value.volume,
            typeFk: wagon.value.typeFk,
        };
        await axios.patch('Wagons', params).then((res) => {
            if (res.status == 200) router.push({ path: `/wagon/list` });
        });
    } catch (error) {
        //
    }
}

async function onReset() {
    if (entityId.value) {
        wagon.value = { ...originalData };
    } else {
        wagon.value = {};
    }
}

async function fetch() {
    try {
        await axios.get('WagonTypes').then(async (res) => {
            if (res.data) {
                filteredWagonTypes.value = wagonTypes = res.data;
            }
        });
        if (entityId.value) {
            await axios.get(`Wagons/${entityId.value}`).then(async (res) => {
                const data = res.data;
                if (data) {
                    wagon.value.label = data.label;
                    wagon.value.plate = data.plate;
                    wagon.value.volume = data.volume;
                    wagon.value.typeFk = data.typeFk;
                    originalData = { ...wagon.value };
                }
            });
        }
    } catch (e) {
        //
    }
}

function filterType(val, update) {
    update(() => {
        const needle = val.toLowerCase();
        filteredWagonTypes.value = wagonTypes.filter(
            (v) => v.name.toLowerCase().indexOf(needle) > -1
        );
    });
}
</script>

<template>
    <QPage class="q-pa-sm q-mx-xl">
        <QCard class="q-pa-sm">
            <QForm @submit="onSubmit()" @reset="onReset()" class="q-pa-md">
                <div class="row q-col-gutter-md q-mb-md">
                    <div class="col">
                        <QInput
                            filled
                            v-model="wagon.label"
                            :label="t('wagon.create.label')"
                            type="number"
                            min="0"
                            :rules="[(val) => !!val || t('wagon.warnings.labelNotEmpty')]"
                        />
                    </div>
                    <div class="col">
                        <QInput
                            filled
                            v-model="wagon.plate"
                            :label="t('wagon.create.plate')"
                            :rules="[(val) => !!val || t('wagon.warnings.plateNotEmpty')]"
                        />
                    </div>
                </div>
                <div class="row q-col-gutter-md q-mb-md">
                    <div class="col">
                        <QInput
                            filled
                            v-model="wagon.volume"
                            :label="t('wagon.create.volume')"
                            type="number"
                            min="0"
                            :rules="[
                                (val) => !!val || t('wagon.warnings.volumeNotEmpty'),
                            ]"
                        />
                    </div>
                    <div class="col">
                        <QSelect
                            filled
                            v-model="wagon.typeFk"
                            use-input
                            fill-input
                            hide-selected
                            input-debounce="0"
                            option-label="name"
                            option-value="id"
                            emit-value
                            map-options
                            :label="t('wagon.create.type')"
                            :options="filteredWagonTypes"
                            :rules="[(val) => !!val || t('wagon.warnings.typeNotEmpty')]"
                            @filter="filterType"
                        >
                            <template v-if="wagon.typeFk" #append>
                                <QIcon
                                    name="cancel"
                                    @click.stop.prevent="wagon.typeFk = null"
                                    class="cursor-pointer"
                                />
                            </template>
                            <template #no-option>
                                <QItem>
                                    <QItemSection class="text-grey">
                                        {{ t('wagon.warnings.noData') }}
                                    </QItemSection>
                                </QItem>
                            </template>
                        </QSelect>
                    </div>
                </div>
                <div>
                    <QBtn :label="t('wagon.type.submit')" type="submit" color="primary" />
                    <QBtn
                        :label="t('wagon.type.reset')"
                        type="reset"
                        color="primary"
                        flat
                        class="q-ml-sm"
                    />
                </div>
            </QForm>
        </QCard>
    </QPage>
</template>

<style lang="scss" scoped>
.q-page {
    display: flex;
    justify-content: center;
    align-items: flex-start;
}
.q-card {
    width: 70%;
}
</style>
