<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 VnSelectFilter from 'components/common/VnSelectFilter.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';
import RouteSearchbar from "pages/Route/Card/RouteSearchbar.vue";
import {useStateStore} from "stores/useStateStore";

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

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 />
    <template v-if="stateStore.isHeaderMounted()">
        <Teleport to="#searchbar">
            <RouteSearchbar />
        </Teleport>
    </template>
    <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
    />
    <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">
                <div class="col">
                    <VnSelectFilter
                        :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>
                    </VnSelectFilter>
                </div>
                <div class="col">
                    <VnSelectFilter
                        :label="t('Vehicle')"
                        v-model="data.vehicleFk"
                        :options="vehicleList"
                        option-value="id"
                        option-label="numberPlate"
                        emit-value
                        map-options
                        use-input
                        :input-debounce="0"
                    />
                </div>
            </VnRow>
            <VnRow class="row q-gutter-md q-mb-md">
                <div class="col">
                    <VnSelectFilter
                        :label="t('Agency')"
                        v-model="data.agencyModeFk"
                        :options="agencyList"
                        option-value="id"
                        option-label="name"
                        emit-value
                        map-options
                        use-input
                        :input-debounce="0"
                    />
                </div>
                <div class="col">
                    <VnInputDate v-model="data.created" :label="t('Created')" />
                </div>
            </VnRow>
            <template v-if="!isNew">
                <VnRow class="row q-gutter-md q-mb-md">
                    <div class="col">
                        <VnInput
                            v-model="data.kmStart"
                            :label="t('Km Start')"
                            clearable
                        />
                    </div>
                    <div class="col">
                        <VnInput v-model="data.kmEnd" :label="t('Km End')" clearable />
                    </div>
                </VnRow>
                <VnRow class="row q-gutter-md q-mb-md">
                    <div class="col">
                        <VnInputTime
                            v-model="data.started"
                            :label="t('Hour started')"
                            clearable
                        />
                    </div>
                    <div class="col">
                        <VnInputTime
                            v-model="data.finished"
                            :label="t('Hour finished')"
                            clearable
                        />
                    </div>
                    <div class="col flex items-center">
                        <QCheckbox
                            size="sm"
                            v-model="data.isOk"
                            :label="t('Is served')"
                        />
                    </div>
                </VnRow>
            </template>
            <VnRow class="row q-gutter-md q-mb-md">
                <div class="col">
                    <VnInput
                        v-model="data.description"
                        :label="t('Description')"
                        type="textarea"
                        :rows="3"
                        clearable
                    />
                </div>
            </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
</i18n>
