<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 workerList = ref([]);
const agencyList = ref([]);
const vehicleList = 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="Workers/search"
        :filter="{ fields: ['id', 'nickname'] }"
        sort-by="nickname ASC"
        limit="30"
        @on-fetch="(data) => (workerList = data)"
        auto-load
    />
    <FetchData
        url="AgencyModes/isActive"
        :filter="{ fields: ['id', 'name'] }"
        sort-by="name"
        limit="30"
        @on-fetch="(data) => (agencyList = data)"
        auto-load
    />
    <FetchData
        url="Vehicles"
        :filter="{ fields: ['id', 'numberPlate'] }"
        sort-by="numberPlate ASC"
        limit="30"
        @on-fetch="(data) => (vehicleList = data)"
        auto-load
    />
    <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 class="row q-gutter-md q-mb-md">
                <VnSelect
                    :label="t('Worker')"
                    v-model="data.workerFk"
                    :options="workerList"
                    option-value="id"
                    option-label="nickname"
                    emit-value
                    map-options
                    use-input
                    :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"
                    :options="vehicleList"
                    option-value="id"
                    option-label="numberPlate"
                    emit-value
                    map-options
                    use-input
                    :input-debounce="0"
                />
            </VnRow>
            <VnRow class="row q-gutter-md q-mb-md">
                <VnSelect
                    :label="t('Agency')"
                    v-model="data.agencyModeFk"
                    :options="agencyList"
                    option-value="id"
                    option-label="name"
                    emit-value
                    map-options
                    use-input
                    :input-debounce="0"
                />
                <VnInputDate v-model="data.created" :label="t('Created')" />
            </VnRow>
            <template v-if="!isNew">
                <VnRow class="row q-gutter-md q-mb-md">
                    <VnInput v-model="data.kmStart" :label="t('Km Start')" clearable />
                    <QInput
                        v-model.number="data.kmEnd"
                        :label="t('Km End')"
                        :rules="[
                            (val) =>
                                val < maxDistance ||
                                t('Distance must be lesser than 4000'),
                        ]"
                        clearable
                        type="number"
                    />
                </VnRow>
                <VnRow class="row q-gutter-md q-mb-md">
                    <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>
            <VnRow class="row q-gutter-md q-mb-md">
                <VnInput
                    v-model="data.description"
                    :label="t('Description')"
                    type="textarea"
                    :rows="3"
                    clearable
                />
            </VnRow>
        </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
    Distance must be lesser than {maxDistance}: La distancia debe ser inferior a {maxDistance}
</i18n>
