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

const { t } = useI18n();
const route = useRoute();
const router = useRouter();
const shelvingId = ref(route.params?.id || null);
const isNew = Boolean(!shelvingId.value);
const defaultInitialData = {
    agencyModeFk: null,
    created: null,
    description: '',
    vehicleFk: null,
    workerFk: null,
    isOk: false,
};
const maxDistance = ref();

const routeFilter = {
    fields: [
        'id',
        'workerFk',
        'agencyModeFk',
        'created',
        'm3',
        'warehouseFk',
        'description',
        'vehicleFk',
        'kmStart',
        'kmEnd',
        'started',
        'finished',
        'cost',
        'zoneFk',
        'isOk',
    ],
    include: [
        { relation: 'agencyMode', scope: { fields: ['id', 'name'] } },
        {
            relation: 'vehicle',
            scope: { fields: ['id', 'm3'] },
        },
        { relation: 'zone', scope: { fields: ['id', 'name'] } },
        {
            relation: 'worker',
            scope: {
                fields: ['id'],
                include: {
                    relation: 'user',
                    scope: {
                        fields: ['id'],
                        include: { relation: 'emailUser', scope: { fields: ['email'] } },
                    },
                },
            },
        },
    ],
};
const onSave = (data, response) => {
    if (isNew) {
        axios.post(`Routes/${response?.id}/updateWorkCenter`);
        router.push({ name: 'RouteSummary', params: { id: response?.id } });
    }
};
</script>
<template>
    <VnSubToolbar v-if="isNew" />
    <FetchData
        url="RouteConfigs/findOne"
        @on-fetch="({ kmMax }) => (maxDistance = kmMax)"
        auto-load
        sort-by="id ASC"
    />
    <FormModel
        :url="isNew ? null : `Routes/${route.params?.id}`"
        :url-create="isNew ? 'Routes' : null"
        :observe-form-changes="!isNew"
        :filter="routeFilter"
        model="route"
        :auto-load="!isNew"
        :form-initial-data="isNew ? defaultInitialData : null"
        @on-data-saved="onSave"
    >
        <template #form="{ data }">
            <VnRow>
                <VnSelect
                    :label="t('Worker')"
                    v-model="data.workerFk"
                    url="Workers/search"
                    sort-by="nickname ASC"
                    option-value="id"
                    option-label="nickname"
                    :input-debounce="0"
                >
                    <template #option="{ itemProps, opt }">
                        <QItem v-bind="itemProps">
                            <QItemSection>
                                <QItemLabel>{{ opt.name }}</QItemLabel>
                                <QItemLabel caption>
                                    {{ opt.nickname }}, {{ opt.code }}
                                </QItemLabel>
                            </QItemSection>
                        </QItem>
                    </template>
                </VnSelect>
                <VnSelect
                    :label="t('Vehicle')"
                    v-model="data.vehicleFk"
                    url="Vehicles"
                    sort-by="numberPlate ASC"
                    option-value="id"
                    option-label="numberPlate"
                    :input-debounce="0"
                />
            </VnRow>
            <VnRow>
                <VnSelect
                    :label="t('Agency')"
                    v-model="data.agencyModeFk"
                    url="AgencyModes/isActive"
                    sort-by="name"
                    option-value="id"
                    option-label="name"
                    :input-debounce="0"
                />
                <VnInputDate v-model="data.created" :label="t('Created')" />
            </VnRow>
            <template v-if="!isNew">
                <VnRow>
                    <VnInput v-model="data.kmStart" :label="t('Km Start')" clearable />
                    <QInput
                        v-model.number="data.kmEnd"
                        :label="t('Km End')"
                        clearable
                        type="number"
                    />
                </VnRow>
                <VnRow>
                    <VnInputTime
                        v-model="data.started"
                        :label="t('Hour started')"
                        clearable
                    />
                    <VnInputTime
                        v-model="data.finished"
                        :label="t('Hour finished')"
                        clearable
                    />
                    <div class="col flex items-center">
                        <QCheckbox
                            size="sm"
                            v-model="data.isOk"
                            :label="t('Is served')"
                            clearable
                        />
                    </div>
                </VnRow>
            </template>
            <VnInput
                v-model="data.description"
                :label="t('Description')"
                type="textarea"
                :rows="3"
                clearable
            />
        </template>
    </FormModel>
</template>
<i18n>
es:
    Worker: Trabajador
    Vehicle: Vehículo
    Agency: Agencia
    Km Start: Km de inicio
    Km End: Km de fin
    Hour started: Hora inicio
    Hour finished: Hora fin
    Description: Descripción
    Is served: Se ha servido
    Created: Creado
    The km can not exceed: La distancia debe ser inferior a {maxDistance}
en:
    The km can not exceed: Distance must be lesser than {maxDistance}
</i18n>
