<script setup>
import {
    NModal,
    NSteps,
    NStep,
    NTabs,
    NTabPane,
    NFlex,
    NGrid,
    NGi,
    NButton,
    NSpin,
    NSelect,
    NInput,
    NFormItemGi,
    NDatePicker,
    NCheckbox
} from 'naive-ui'
import {computed, ref, watch} from "vue";
import AppRadio from "../../../Components/AppRadio.vue";
import axios from "axios";
import {router} from "@inertiajs/vue3";
import AppSearchAddress from '../../../Components/AppSearchAddress.vue';
const show = defineModel('show', { default: false })
const props = defineProps({
    historyId: {
        type: Number
    },
    reportNurseId: {
        type: Number,
        default: null
    },
    patientSource: {
        type: String,
        default: 'manual'
    }
})

const form = ref({
    patient_source: 'mis',
    original_id: null,
    patient_id: null,
    full_name: '',
    urgency_id: 1,
    visit_result_id: null,
    birth_date: null,
    recipient_date: null,
    death_date: null,
    extract_date: null,
    delivery_from_address: null,
    delivery_from_object_id: null,
    received_disease_at: null
})
const isReceivedDisease = ref(false)
const disableReceivedDisease = computed(() => !!isReceivedDisease.value)
const loading = ref(true)
const buttonLoading = ref(false)

const urgencyOptions = [
    {
        label: '0 - Не определено',
        value: 0
    },
    {
        label: '1 - Планово',
        value: 1
    },
    {
        label: '2 - Экстренно',
        value: 2
    }
]
const visitResultOptions = [
    {
        label: '0 - Не определено',
        value: 0
    },
    {
        label: '1 - Выписан',
        value: 1
    },
    {
        label: '2 - Переведён в др. ЛПУ',
        value: 2
    },
    {
        label: '3 - Переведён в дневной стационар',
        value: 3
    },
    {
        label: '4 - Переведён на другой профиль коек',
        value: 4
    },
    {
        label: '5 - Умер',
        value: 5
    },
    {
        label: '6 - Умер в приёмном покое',
        value: 6
    },
    {
        label: '7 - Лечение прервано по инициативе пациента',
        value: 7
    },
    {
        label: '8 - Лечение прервано по инициативе ЛПУ',
        value: 8
    },
    {
        label: '9 - Лечение продолжено',
        value: 9
    },
    {
        label: '10 - Самовольно прерванное лечение',
        value: 10
    },
]

const submit = async () => {
    buttonLoading.value = true
    await axios.post(`/api/nurse/patients/${form.value.patient_id}/correction`, {
        ...form.value,
        report_nurse_id: props.reportNurseId,
    }).then(res => {
        router.reload({
           only: ['patients'],
            onSuccess: () => {
               show.value = false
            },
            onFinish: () => {
               buttonLoading.value = false
            }
        })
    })
}

const fetchPatient = async (historyId) => {
    loading.value = true
    await axios.get(`/api/nurse/patients/${historyId}?patient_source=${props.patientSource}`)
        .then(res => {
            form.value.patient_source = res.data.source_type
            form.value.patient_id = historyId
            form.value.original_id = res.data.original_id
            form.value.full_name = res.data.full_name
            form.value.urgency_id = res.data.urgency_id
            form.value.visit_result_id = res.data.visit_result_id

            form.value.birth_date = res.data.birth_date
            form.value.death_date = res.data.death_date
            form.value.extract_date = res.data.extract_date
            form.value.recipient_date = res.data.recipient_date
            form.value.delivery_from_address = res.data.delivery_from_address
            form.value.delivery_from_object_id = res.data.delivery_from_object_id
            form.value.received_disease_at = res.data.received_disease_at
        })
        .finally((e) => {
            loading.value = false
        })
}

watch(() => props.historyId, async (newHistoryId, historyId) => {
    await fetchPatient(newHistoryId)
})

watch(() => isReceivedDisease.value, (value) => {
    if (value) form.value.received_disease_at = null
})

const canShowExtractDateField = ref(false)
const canShowDeathDateField = ref(false)
watch(() => form.value.visit_result_id, (newVisitResultId, oldVisitResultId) => {
    if ([1, 2, 3, 4, 7, 8, 9, 10].includes(newVisitResultId)) {
        canShowDeathDateField.value = false
        canShowExtractDateField.value = true
    } else if ([5, 6].includes(newVisitResultId)) {
        canShowDeathDateField.value = true
        canShowExtractDateField.value = false
    } else {
        canShowDeathDateField.value = false
        canShowExtractDateField.value = false
    }
})
</script>

<template>
    <NModal v-model:show="show"
            segmented
            preset="card"
            title="Редактирование пациента"
            class="max-w-xl min-h-[500px] relative"
            draggable
            :closable="!buttonLoading"
    >
        <div v-if="loading">
            <NSpin class="absolute top-1/2 left-1/2 -translate-x-1/2" />
        </div>
        <NGrid v-else cols="2" x-gap="8">
            <NFormItemGi span="2" label="ФИО">
                <NInput v-model:value="form.full_name" placeholder="Иванов Иван Иванович" />
            </NFormItemGi>
            <NFormItemGi span="1" label="Срочность">
                <NSelect filterable v-model:value="form.urgency_id" :options="urgencyOptions" />
            </NFormItemGi>
            <NFormItemGi span="1" label="Исход госпитализации">
                <NSelect filterable v-model:value="form.visit_result_id" :options="visitResultOptions" />
            </NFormItemGi>
            <NFormItemGi span="1" label="Дата рождения">
                <NDatePicker v-model:formatted-value="form.birth_date" class="w-full" format="dd.MM.yyyy" value-format="yyyy-MM-dd" clearable />
            </NFormItemGi>
            <NFormItemGi span="1" label="Дата и время госпитализации">
                <NDatePicker v-model:formatted-value="form.recipient_date" type="datetime" class="w-full" format="dd.MM.yyyy HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" clearable />
            </NFormItemGi>
            <NFormItemGi v-if="canShowExtractDateField" span="1" label="Дата и время выписки">
                <NDatePicker v-model:formatted-value="form.extract_date" type="datetime" class="w-full" format="dd.MM.yyyy HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" clearable />
            </NFormItemGi>
            <NFormItemGi v-if="canShowDeathDateField" span="1" label="Дата и время смерти">
                <NDatePicker v-model:formatted-value="form.death_date" type="datetime" class="w-full" format="dd.MM.yyyy HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" clearable />
            </NFormItemGi>
            <NFormItemGi span="2" label="Поступил от начала заболевания">
                <NGrid cols="2" x-gap="8">
                    <NGi>
                        <NDatePicker v-model:formatted-value="form.received_disease_at"
                                     type="datetime"
                                     class="w-full"
                                     format="dd.MM.yyyy HH:mm:ss"
                                     value-format="yyyy-MM-dd HH:mm:ss"
                                     clearable
                                     :disabled="disableReceivedDisease"
                        />
                    </NGi>
                    <NGi class="flex items-center">
                        <NCheckbox class="text-nowrap" v-model:checked="isReceivedDisease">
                            Неизвестно
                        </NCheckbox>
                    </NGi>
                </NGrid>
            </NFormItemGi>
            <NFormItemGi span="2" label="Откуда доставлен">
                <AppSearchAddress v-model:value="form.delivery_from_address"
                                  v-model:objectid="form.delivery_from_object_id"
                                  placeholder="Начните вводить адрес"
                />
            </NFormItemGi>
        </NGrid>
        <template v-if="!loading" #action>
            <NFlex justify="end">
                <NButton secondary type="primary" @click="submit" :loading="buttonLoading">
                    Сохранить
                </NButton>
            </NFlex>
        </template>
    </NModal>
</template>

<style scoped>

</style>
