<script setup>
import { ref, computed } from 'vue';
import { useRoute } from 'vue-router';
import { useI18n } from 'vue-i18n';
import axios from 'axios';
import { useRole } from 'src/composables/useRole';
import FormModel from 'components/FormModel.vue';
import VnSelect from 'src/components/common/VnSelect.vue';
import { useArrayData } from 'src/composables/useArrayData';
import FetchData from 'components/FetchData.vue';

const { hasAny } = useRole();
const { t } = useI18n();
const fetchData = ref();
const originaLockerId = ref();
const lockers = ref([]);
const { store } = useArrayData('Worker');
const entityId = computed(() => useRoute().params.id);
const filter = computed(() => ({
    where: {
        gender: store.data?.sex,
        or: [{ workerFk: null }, { workerFk: entityId.value }],
    },
}));

const save = async (data) => {
    const lockerId = data.id ?? originaLockerId.value;
    const workerFk = lockerId == originaLockerId.value ? null : entityId.value;

    return axios.patch(`Lockers/${lockerId}`, { workerFk });
};

const init = async (data) => {
    await fetchData.value.fetch();
    originaLockerId.value = data.id;
};
</script>
<template>
    <FetchData
        ref="fetchData"
        url="Lockers/codes"
        :filter="filter"
        @on-fetch="(data) => (lockers = data)"
    />
    <FormModel
        :url="`Workers/${entityId}/locker`"
        model="worker"
        auto-load
        :save-fn="save"
        @on-fetch="init"
    >
        <template #form="{ data }">
            <VnSelect
                :label="t('Locker')"
                v-model="data.id"
                :options="lockers"
                option-label="code"
                option-value="id"
                hide-selected
                :readonly="!hasAny(['productionBoss', 'hr'])"
            />
        </template>
    </FormModel>
</template>
