<script setup>
import {NDataTable, NEllipsis, NTag} from "naive-ui"
import {computed, h, reactive, ref, watch} from "vue"
import {useMedicalHistoryFilter} from "../../../Composables/useMedicalHistoryFilter.js";
import ArchiveHistoryModal from '../ArchiveHistoryModal/Index.vue'
import {useArchiveCard} from "../../../Stores/ArchiveCard.js";

const props = defineProps({
    filters: {
        type: Array,
        default: []
    },
    data: {
        type: Array,
        default: []
    },
    maxHeight: {
        type: String,
        default: null
    },
    minHeight: {
        type: String,
        default: null
    },
})

const { isLoading, handlePageChange, handlePageSizeChange, meta, filtersRef } = useMedicalHistoryFilter(props.filters)
const archiveCardStore = useArchiveCard()
const dataTable = ref(props.data ?? [])

const archiveStatusColumn = (status) => {
    const tagType = status?.variant ?? 'error'
    const tagText = status?.text ?? 'Нет в архиве'

    return h(
        NEllipsis,
        null,
        {
            default: () => h(NTag, {type: tagType, bordered: false, round: true, size: 'small'}, tagText)
        })
}

const columns = ref([
    {
        title: '№ карты',
        key: 'medcardnum',
        width: 80,
        render: (row) => h(NEllipsis, null, { default: () => row.medcardnum })
    },
    {
        title: 'ФИО',
        key: 'fullname',
        width: 200,
        render: (row) => h(NEllipsis, null, { default: () => row.fullname })
    },
    {
        title: 'Исход',
        key: 'visitresult',
        width: 60,
        render: (row) => h(NEllipsis, null, { default: () => row.visitresult ?? 'Н/д' })
    },
    {
        title: 'Отделение',
        key: 'department',
        width: 220,
        render: (row) => h(NEllipsis, null, { default: () => row.department })
    },
    {
        title: 'Дата рождения',
        key: 'dr',
        width: 100,
        render: (row) => h(NEllipsis, null, { default: () => row.dr })
    },
    {
        title: 'Дата поступления',
        key: 'daterecipient',
        width: 100,
        render: (row) => h(NEllipsis, null, { default: () => row.daterecipient })
    },
    {
        title: 'Дата выписки',
        key: 'dateextract',
        width: 80,
        render: (row) => h(NEllipsis, null, { default: () => row.dateextract })
    },
    {
        title: '№ архива',
        key: 'card_num',
        width: 80,
        render: (row) => h(NEllipsis, null, { default: () => row.card_num || '-' })
    },
    {
        title: 'Дата архива',
        key: 'datearhiv',
        width: 80,
        render: (row) => h(NEllipsis, null, { default: () => row.datearhiv })
    },
    {
        title: 'Статус',
        key: 'status',
        width: 60,
        render: (row) => archiveStatusColumn(row.status)
    }
])
const showArchiveHistoryModal = ref(false)
const selectedPatientInfo = ref({})
const rowProps = (row) => ({
    onDblclick: () => {
        selectedPatientInfo.value = {id: row.id, type: row.history_type}
        showArchiveHistoryModal.value = true
    }
})

const pagination = computed(() => {
    return {
        page: meta.value.current_page || 1,
        pageCount: meta.value.last_page || 1,
        pageSize: meta.value.per_page || 15,
        itemCount: meta.value.total || 0,
        pageSizes: [15, 50, 100],
        showSizePicker: true,
        prefix({ itemCount }) {
            return `Всего карт ${itemCount}`
        },
        onUpdatePage: (page) => {
            handlePageChange(page)
        },
        onUpdatePageSize: handlePageSizeChange
    }
})

const onCloseWithoutSave = () => {
    selectedPatientInfo.value = null
}

const onUpdateHistory = ({data, patientId}) => {
    if (dataTable.value.length > 0) {
        let needUpdateItem = dataTable.value.findIndex(itm => itm.id === patientId)
        dataTable.value[needUpdateItem] = {
            ...dataTable.value[needUpdateItem],
            status: data.status
        }
    }
}

watch(() => props.data, (newData) => {
    dataTable.value = newData
})

watch(() => archiveCardStore.isOpenArchiveCard, (isOpen) => {
    if (isOpen) {
        selectedPatientInfo.value = Object.assign(archiveCardStore.preOpenCard)
        showArchiveHistoryModal.value = true
        archiveCardStore.setPreOpenCard(null)
    }
})
</script>

<template>
    <NDataTable remote
                :single-line="false"
                striped
                :loading="isLoading"
                :row-props="rowProps"
                :columns="columns"
                :pagination="pagination"
                :max-height="maxHeight"
                size="small"
                :min-height="minHeight"
                :data="dataTable"
    />
    <ArchiveHistoryModal v-model:open="showArchiveHistoryModal"
                         :patient-info="selectedPatientInfo"
                         @history-updated="onUpdateHistory"
                         @close-without-save="onCloseWithoutSave"
    />
</template>

<style scoped>

</style>
