import { shallowRef, computed } from 'vue'
import { timerTask } from '@/utils/timer'
import { queryNotice, postNoticeReaded } from '@/services/api/common'
import { useLoginStore } from '@/stores'

export function useNotice() {
    const { getLoginId } = useLoginStore()
    const dataList = shallowRef<Ermcp.NoticeRsp[]>([])
    const loading = shallowRef(false)

    // 未读列表
    const unreadList = computed(() => {
        const data = dataList.value ?? []
        return data.filter((e) => !e.readed)
    })

    const getNoticeList = () => {
        timerTask.clearTimeout('systemNotice')
        loading.value = true
        return queryNotice({
            data: {
                loginID: getLoginId()
            },
            success: (res) => {
                dataList.value = res.data
            },
            complete: () => {
                loading.value = false
                // 轮询查询系统通知
                timerTask.setTimeout(() => {
                    getNoticeList()
                }, 60 * 1000, 'systemNotice')
            }
        })
    }

    // 更新已读
    const updateNoticeReaded = (id: number) => {
        return postNoticeReaded({
            data: {
                loginID: Number(getLoginId()),
                noticeID: id,
            },
        })
    }

    return {
        loading,
        dataList,
        unreadList,
        getNoticeList,
        updateNoticeReaded,
    }
}