<script setup>
import {
    NModal, NDataTable, NEmpty, NSpin, NDrawer, NDrawerContent, NInput, NIcon, NTooltip, NFlex, NText
} from 'naive-ui'
import { TbEye } from 'vue-icons-plus/tb'
import { format, formatDistanceStrict } from 'date-fns'
import { ru } from 'date-fns/locale'
import { computed, h, ref, watch } from 'vue'
import TooltipColumn from '../../Report/Components/DataTableColumns/TooltipColumn.vue'

const props = defineProps({
    departmentId: { required: true },
})

const open = defineModel('open')
const loading = ref(true)
const observablePatients = ref([])
const currentPatient = ref(null)
const showDrawer = ref(false)

const columns = [
    {
        title: '№',
        key: 'index',
        width: 50,
        render: (_, i) => i + 1,
    },
    {
        title: 'ФИО',
        key: 'full_name',
        width: 280,
        ellipsis: { tooltip: { arrow: false } },
    },
    {
        title: 'Возраст',
        key: 'age',
        width: 80,
        render: (row) => row.birth_date
            ? formatDistanceStrict(new Date(row.birth_date), new Date(), { locale: ru })
            : '—',
    },
    {
        title: 'Д/р',
        key: 'birth_date',
        width: 100,
        render: (row) => row.birth_date ? format(new Date(row.birth_date), 'dd.MM.yyyy') : '—',
    },
    {
        title: 'Д/п',
        key: 'ingoing_date',
        width: 134,
        render: (row) => {
            const d = row.migrations?.[0]?.ingoing_date
            return d ? format(new Date(d), 'dd.MM.yyyy HH:mm') : '—'
        },
    },
    {
        title: 'Диагноз',
        key: 'diagnosis',
        width: 90,
        render: (row) => {
            const m = row.migrations?.[0]
            return m?.diagnosis_code
                ? h(TooltipColumn, { triggerText: m.diagnosis_code, contentText: m.diagnosis_name })
                : '—'
        },
    },
    {
        title: '',
        key: 'actions',
        width: 44,
        align: 'center',
        render: (row) => h(
            NIcon,
            {
                style: 'cursor:pointer',
                size: 18,
                onClick: () => { currentPatient.value = row; showDrawer.value = true },
            },
            () => h(TbEye)
        ),
    },
]

const startAt = computed(() => {
    const urlParams = new URLSearchParams(window.location.search)
    return urlParams.get('startAt')
})

const endAt = computed(() => {
    const urlParams = new URLSearchParams(window.location.search)
    return urlParams.get('endAt')
})

const fetch = (startAt, endAt) => {
    loading.value = true
    axios.get('/api/statistics/reports/observable-patients', {
        params: { startAt, endAt, departmentId: props.departmentId }
    }).then((res) => {
        observablePatients.value = res.data ?? []
    }).finally(() => {
        loading.value = false
    })
}

watch([open, () => props.departmentId], ([open, departmentId]) => {
    if (open && departmentId) fetch(startAt.value, endAt.value)
}, { immediate: true, deep: true })
</script>

<template>
    <NModal
        v-model:show="open"
        title="Пациенты на контроле"
        preset="card"
        :mask-closable="false"
        :close-on-esc="false"
        class="max-w-5xl overflow-clip h-[calc(100vh-220px)]"
        id="modal-observable-patients"
    >
        <template v-if="loading">
            <div class="flex items-center justify-center h-full">
                <NSpin />
            </div>
        </template>
        <template v-else-if="observablePatients.length">
            <NDataTable
                :columns="columns"
                :data="observablePatients"
                table-layout="fixed"
                size="small"
                :loading="loading"
                max-height="calc(100vh - 320px)"
                :row-key="(row) => row.id"
            />
        </template>
        <template v-else>
            <div class="h-full flex items-center justify-center">
                <NEmpty description="Пациентов на контроле не найдено!" />
            </div>
        </template>

        <NDrawer
            v-model:show="showDrawer"
            placement="bottom"
            :min-height="400"
            :max-height="600"
            :default-height="400"
            resizable
            :trap-focus="false"
            :block-scroll="false"
            to="#modal-observable-patients"
        >
            <NDrawerContent title="Причина постановки на контроль" closable>
                <NFlex vertical :size="12">
                    <NInput
                        type="textarea"
                        readonly
                        :rows="5"
                        :value="currentPatient?.observable_reason"
                        placeholder="Причина не указана"
                    />
                    <template v-if="currentPatient?.comment">
                        <NText depth="3" style="font-size:12px;">Комментарий:</NText>
                        <NInput
                            type="textarea"
                            readonly
                            :rows="4"
                            :value="currentPatient?.comment"
                        />
                    </template>
                </NFlex>
            </NDrawerContent>
        </NDrawer>
    </NModal>
</template>

<style scoped>
:deep(.n-data-table-th),
:deep(.n-data-table-td) {
    font-size: var(--n-font-size);
}
</style>
