<script setup>
import { useI18n } from 'vue-i18n';
import { computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import VnRow from 'components/ui/VnRow.vue';
import FormModel from 'components/FormModel.vue';
import VnInput from 'src/components/common/VnInput.vue';
import VnSubToolbar from 'src/components/ui/VnSubToolbar.vue';
import VnSelect from 'src/components/common/VnSelect.vue';

const { t } = useI18n();
const route = useRoute();
const router = useRouter();
const entityId = computed(() => route.params.id ?? null);
const isNew = Boolean(!entityId.value);
const defaultInitialData = {
    parkingFk: null,
    priority: null,
    code: null,
    isRecyclable: false,
};

const shelvingFilter = {
    include: [
        {
            relation: 'worker',
            scope: {
                fields: ['id'],
                include: {
                    relation: 'user',
                    scope: { fields: ['nickname'] },
                },
            },
        },
        { relation: 'parking' },
    ],
};

const onSave = (shelving, newShelving) => {
    if (isNew) {
        router.push({ name: 'ShelvingBasicData', params: { id: newShelving?.id } });
    }
};
</script>
<template>
    <VnSubToolbar v-if="isNew" />
    <FormModel
        :url="isNew ? null : `Shelvings/${entityId}`"
        :url-create="isNew ? 'Shelvings' : null"
        :observe-form-changes="!isNew"
        :filter="shelvingFilter"
        model="shelving"
        :auto-load="!isNew"
        :form-initial-data="isNew ? defaultInitialData : null"
        @on-data-saved="onSave"
    >
        <template #form="{ data, validate }">
            <VnRow>
                <VnInput
                    v-model="data.code"
                    :label="t('shelving.basicData.code')"
                    :rules="validate('Shelving.code')"
                />
                <VnSelect
                    v-model="data.parkingFk"
                    url="Parkings"
                    option-value="id"
                    option-label="code"
                    :filter-options="['id', 'code']"
                    :fields="['id', 'code']"
                    :label="t('shelving.basicData.parking')"
                    :rules="validate('Shelving.parkingFk')"
                />
            </VnRow>
            <VnRow>
                <VnInput
                    v-model="data.priority"
                    type="number"
                    :label="t('shelving.basicData.priority')"
                    :rules="validate('Shelving.priority')"
                />
                <QCheckbox
                    v-model="data.isRecyclable"
                    :label="t('shelving.basicData.recyclable')"
                    :rules="validate('Shelving.isRecyclable')"
                />
            </VnRow>
        </template>
    </FormModel>
</template>
