<script setup>
import { NModal, NSelect, NSpace, NFlex, NButton, NForm, NFormItem, NInput, NDatePicker, NDivider, NSpin, NTag } from 'naive-ui'
import ArchiveHistoryMoveModal from '../ArchiveHistoryMoveModal/Index.vue'
import {computed, ref, watch} from "vue";
import {useMedicalHistoryFilter} from "../../../Composables/useMedicalHistoryFilter.js";
import {useNotification} from "../../../Composables/useNotification.js";
import {useDebounceFn} from "@vueuse/core";

const open = defineModel('open')

const {errorApi} = useNotification()
const loading = ref(false)
const archiveInfo = ref({
    id: null,
    num: null,
    post_in: null,
})
const archiveInfoRules = {
    id: [
        {
            required: true,
            validator(rule, value) {
                console.log(value)
                if (!value) {
                    return new Error('Это поле необходимо заполнить')
                }
                else if (!Number(value)) {
                    return new Error('Ошибка при получении ID')
                }
                return true
            },
            trigger: ['input', 'blur']
        }
    ],
    num: [
        {
            required: true,
            message: 'Это поле необходимо заполнить',
            trigger: 'blur'
        }
    ],
    post_in: [
        {
            required: true,
            message: 'Это поле необходимо заполнить',
            trigger: 'blur'
        }
    ]
}
const loadingFilterPatients = ref(false)
const formRef = ref(null)

const emits = defineEmits(['historyUpdated', 'closeWithoutSave'])

const onResetData = () => {
    archiveInfo.value = {
        id: null,
        num: null,
        post_in: null,
    }
}

const onCloseWithoutSave = () => {
    emits('closeWithoutSave')
    open.value = false
    onResetData()
}

const filteredPatients = ref([])

const debounceSearchCard = useDebounceFn(async (query) => {
    loadingFilterPatients.value = true
    await axios.post('/api/mis/patients/search', {
        query
    }).then(res => {
        filteredPatients.value = res.data
    }).finally(() => {
        loadingFilterPatients.value = false
    })
}, 1000)

const handleSearchCard = (query) => {
    debounceSearchCard(query)
}

const onSubmit = async (e) => {
    e.preventDefault()
    formRef.value?.validate(async (errors) => {
        if (!errors) {
            loading.value = true
            try {
                await axios.post(`/api/archive/create`, archiveInfo.value).then(res => {
                    open.value = false
                })

            } catch (error) {
                errorApi(error)
                console.error(error)
            } finally {
                loading.value = false
            }
        }
        else {
            console.log(errors)
            errorApi(null, 'Проверьте заполненность формы')
        }
    })
}
</script>

<template>
    <NModal v-model:show="open"
            preset="card"
            class="max-w-xl relative"
            :mask-closable="false"
            closable
            title="Добавить карту в архив"
            @close="onCloseWithoutSave">
        <NFlex class="w-full" :wrap="false">
            <NForm ref="formRef" id="formAddToArchive" class="w-full" :model="archiveInfo" :rules="archiveInfoRules">
                <NFormItem label="Карта пациента" path="id">
                    <NSelect placeholder="№ карты фамилия имя отчество ИЛИ фамилия имя отчество"
                             size="large"
                             :remote
                             filterable
                             :loading="loadingFilterPatients"
                             :options="filteredPatients"
                             v-model:value="archiveInfo.id"
                             @search="handleSearchCard"
                    />
                </NFormItem>
                <NFormItem size="large" label="Дата поступления карты в архив" path="post_in">
                    <NDatePicker class="w-full"
                                 v-model:value="archiveInfo.post_in"
                                 format="dd.MM.yyyy"
                    />
                </NFormItem>
                <NFormItem size="large" label="№ в архиве" path="num">
                    <NInput v-model:value="archiveInfo.num" />
                </NFormItem>
            </NForm>
        </NFlex>
        <template #action>
            <NFlex justify="end" align="center">
                <NSpace align="center" :size="0">
                    <NButton secondary
                             type="primary"
                             attr-type="submit"
                             form="formAddToArchive"
                             @click="onSubmit">
                        Добавить карту
                    </NButton>
                </NSpace>
            </NFlex>
        </template>

        <div v-show="loading"
             class="absolute inset-0 z-10 backdrop-blur flex items-center justify-center rounded-[8px]">
            <NSpin :show="true" />
        </div>
    </NModal>
</template>

<style scoped>

</style>
