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

import VnInput from 'src/components/common/VnInput.vue';

import { useRoute, useRouter } from 'vue-router';
import axios from 'axios';

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 zoneTypes = [];
let originalData = {};
const zone = ref({});
const filteredZoneTypes = ref(zoneTypes);

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

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

async function fetch() {
    try {
        await axios.get('ZoneTypes').then(async (res) => {
            if (res.data) {
                filteredZoneTypes.value = zoneTypes = res.data;
            }
        });
        if (entityId.value) {
            await axios.get(`Zones/${entityId.value}`).then(async (res) => {
                const data = res.data;
                if (data) {
                    zone.value.label = data.label;
                    zone.value.plate = data.plate;
                    zone.value.volume = data.volume;
                    zone.value.typeFk = data.typeFk;
                    originalData = { ...zone.value };
                }
            });
        }
    } catch (e) {
        //
    }
}

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

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

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

.q-form {
    width: 70%;
}
</style>
