<script setup>
import { NModal, NDataTable, 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";

const open = defineModel('open')
const props = defineProps({
    patientInfo: {
        type: Number,
    }
})

const {filtersRef} = useMedicalHistoryFilter()
const {errorApi} = useNotification()
const loading = ref(true)
const patient = ref({})
const showArchiveHistoryModal = ref(false)
const selectedArchiveHistoryId = ref(null)
const selectedArchiveHistoryType = ref(props.patientInfo.type)
const isCreateNewArchiveHistoryModal = ref(false)
const archiveInfo = ref({
    id: props.patientInfo.id,
    num: null,
    post_in: null,
    status: null
})
const emits = defineEmits(['historyUpdated', 'closeWithoutSave'])

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

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

const patientData = ref({
    ...patient.value.info
})

const loadPatientData = async () => {
    if (!props.patientInfo.id) return

    loading.value = true
    try {
        await axios.get(`/api/si/patients/${props.patientInfo.id}?view_type=${props.patientInfo.type}`).then(res => {
            patient.value = res.data
            patientData.value = res.data.info
            archiveInfo.value = res.data.archiveInfo ?? {
                // historyable_type: res.data.historyable_type,
                id: props.patientInfo.id,
                num: null,
                post_in: null,
                status: null,
            }
        })
    } catch (error) {
        errorApi(error)
        console.error(error)
    } finally {
        loading.value = false
    }
}

const onShowArchiveHistoryModal = (id) => {
    if (id === null) {
        isCreateNewArchiveHistoryModal.value = true
        selectedArchiveHistoryId.value = props.patientInfo.id
    } else {
        isCreateNewArchiveHistoryModal.value = false
        selectedArchiveHistoryId.value = id
    }
    selectedArchiveHistoryType.value = props.patientInfo.type
    showArchiveHistoryModal.value = true
}

const columns = [
    {
        title: 'Выдача',
        key: 'issue_at',
        width: 100
    },
    {
        title: 'Возврат',
        key: 'return_at',
        width: 100
    },
    {
        title: 'Организация',
        key: 'org',
        width: 220
    },
    {
        title: 'ФИО',
        key: 'employee_name',
        width: 180
    },
    {
        title: 'Должность',
        key: 'employee_post',
        width: 120
    },
]
const rowProps = (row) => ({
    onDblclick: () => {
        onShowArchiveHistoryModal(row.id)
    }
})

const onUpdateHistory = async ({data}) => {
    await loadPatientData()
    const updatedData = {
        status: archiveInfo.value.status,
    }
    emits('historyUpdated', {
        data: updatedData,
        patientId: props.patientInfo.id
    })
}

const hasCreateNew = computed(() => archiveInfo.value === null)

const onSubmit = async () => {
    try {
        await axios.post(`/api/archive/histories/info/${props.patientInfo.id}`, archiveInfo.value).then(res => {
            // onCloseWithoutSave()
            const updatedData = {
                status: archiveInfo.value.status,
            }
            emits('historyUpdated', {
                data: updatedData,
                patientId: props.patientInfo.id
            })
            open.value = false
        })

    } catch (error) {
        errorApi(error)
        console.error(error)
    } finally {
        loading.value = false
    }
}

// Наблюдаем за изменением patientId
watch(() => props.patientInfo, async (newId) => {
    if (newId) {
        await loadPatientData()
    }
}, { immediate: true })
</script>

<template>
    <NModal v-model:show="open" preset="card" class="max-w-4xl relative" closable @close="onCloseWithoutSave">
        <template #header>
            {{ patient.info?.medcardnum }} {{ patient.info?.family }} {{ patient.info?.name }} {{ patient.info?.ot }}
        </template>
        <NSpace vertical>
            <NFlex inline justify="space-between" align="center" :wrap="false">
                <NForm inline :show-feedback="false">
                    <NFormItem label="Статус карты">
                        <NTag :type="archiveInfo.status?.variant ?? 'error'" :bordered="false" round>
                            {{ archiveInfo.status?.text ?? 'Нет в архиве' }}
                        </NTag>
                    </NFormItem>
                    <NFormItem label="№ в архиве">
                        <NInput v-model:value="archiveInfo.num" />
                    </NFormItem>
                    <NFormItem label="Дата поступления карты в архив">
                        <NDatePicker v-model:value="archiveInfo.post_in" format="dd.MM.yyyy" />
                    </NFormItem>
                    <NFormItem label="№ карты в МИС / СофтИнфо">
                        <NTag :bordered="false" round class="w-full justify-center">
                            {{ archiveInfo.mis_num }} / {{ archiveInfo.foxpro_num }}
                        </NTag>
                    </NFormItem>
                </NForm>
            </NFlex>
            <NButton @click="onShowArchiveHistoryModal(null)" :disabled="!patientData.can_be_issued">
                Добавить
            </NButton>
            <NDataTable :row-props="rowProps" min-height="420px" max-height="420px" :columns="columns" :data="patient?.journal" />
        </NSpace>
        <template #action>
            <NFlex justify="end" align="center">
                <NSpace align="center" :size="0">
                    <NButton secondary @click="onCloseWithoutSave">
                        Закрыть без сохранения
                    </NButton>
                    <NDivider vertical />
                    <NButton secondary type="primary" @click="onSubmit">
                        Сохранить
                    </NButton>
                </NSpace>
            </NFlex>
        </template>

        <div v-show="loading" class="absolute inset-0 z-10 bg-white flex items-center justify-center">
            <NSpin :show="true" />
        </div>
    </NModal>
    <ArchiveHistoryMoveModal @history-updated="onUpdateHistory" @close-without-save="selectedArchiveHistoryId = null" :is-create-new="isCreateNewArchiveHistoryModal" v-model:open="showArchiveHistoryModal" :type="selectedArchiveHistoryType" :archive-history-id="selectedArchiveHistoryId" />
</template>

<style scoped>

</style>
