<script setup>
import { NSelect, NModal, NForm, NFormItem, NButton } from 'naive-ui'
import {useReportStore} from "../../../Stores/report.js";
import {computed, onMounted, ref} from "vue";
import {router} from "@inertiajs/vue3";
const show = defineModel('show')
const reportStore = useReportStore()
const formRef = ref()

const users = computed(() => reportStore.departmentUsers.map(itm => ({
    label: `${itm.FAM_V} ${itm.IM_V} ${itm.OT_V}`,
    value: itm.LPUDoctorID
})))

const fetchUsers = () => {
    axios.get('/api/mis/department-users')
        .then((res) => {
            reportStore.departmentUsers = res.data
        })
}

const rules = {
    userId: {
        required: true,
        validator: (rule, value) => {
            if (Number.isInteger(value)) return true

            return false
        },
        trigger: ['change', 'blur'],
        message: 'Выберите ответственного'
    }
}

onMounted(() => {
    reportStore.reportInfo.userId = null
    fetchUsers()
})

const onSubmit = (e) => {
    e.preventDefault()
    formRef.value?.validate((errors) => {
        if (!errors) {
            router.visit(`/report?userId=${reportStore.reportInfo.userId}`)
        }
        else {

        }
    })
}

const onAfterLeave = () => {
    reportStore.reportInfo.userId = null
}
</script>

<template>
    <NModal v-model:show="show"
            preset="card"
            class="max-w-[420px]"
            :mask-closable="false"
            @before-leave="onAfterLeave"
    >
        <NForm id="select-user-form" ref="formRef" :model="reportStore.reportInfo" :rules="rules">
            <NFormItem label="Выберите ответственного" path="userId">
                <NSelect :options="users" v-model:value="reportStore.reportInfo.userId" />
            </NFormItem>
        </NForm>
        <template #action>
            <NButton form-id="select-user-form"
                     type="primary"
                     block
                     @click="onSubmit">
                Перейти к заполнению сводной
            </NButton>
        </template>
    </NModal>
</template>

<style scoped>

</style>
