<script setup>
import {computed, onMounted, ref, watch} from "vue";
import {NSkeleton, NText} from 'naive-ui'
import {useReportStore} from "../../../Stores/report.js";

const props = defineProps({
    title: {
        type: String,
        default: null
    },
    status: {
        type: String,
        default: null
    }
})

const reportStore = useReportStore()

const isLoading = ref(true)
const countPatient = ref(null)
const fetchPatientCount = async () => {
    isLoading.value = true
    const data = {
        status: props.status,
        startAt: reportStore.timestampCurrentRange[0],
        endAt: reportStore.timestampCurrentRange[1],
        departmentId: reportStore.reportInfo.department.department_id
    }
    await axios.post('/api/mis/patients/count', data).then((res) => {
        countPatient.value = res.data
    }).finally(() => {
        isLoading.value = false
    })
}

const computedHeader = computed(() => {
    if (countPatient.value !== null) {
        return `${props.title} (${countPatient.value})`
    } else {
        return props.title
    }
})

onMounted(async () => {
    await fetchPatientCount()
})

watch(() => reportStore.timestampCurrentRange, (newRange, oldRange) => {
    // Проверяем, что диапазон изменился и валиден
    if (newRange &&
        newRange.length === 2 &&
        (!oldRange || newRange[0] !== oldRange[0] || newRange[1] !== oldRange[1])) {
        fetchPatientCount()
    }
}, { deep: true })
</script>

<template>
    <NSkeleton text style="width: 128px; height: 22px" round v-if="isLoading" />
    <NText v-else>
        {{ computedHeader }}
    </NText>
</template>

<style scoped>

</style>
