import { reactive, toRefs, computed } from 'vue'
import { timerTask } from '@/utils/timer'
import { queryNotice, postNoticeReaded } from '@/services/api/common'
import { useLoginStore } from './login'
import { defineStore } from '../store'

/**
 * 系统通知存储对象
 */
export const useNotice = defineStore(() => {
    const state = reactive({
        loading: false,
        noticeList: <Ermcp.NoticeRsp[]>[], // 通知列表
    })

    // 未读列表
    const unreadList = computed(() => {
        return state.noticeList.filter((e) => !e.readed)
    })

    // 获取通知列表
    const getNoticeList = async () => {
        try {
            const loginStore = useLoginStore()
            state.loading = true
            timerTask.clearTimeout('systemNotice')
            const res = await queryNotice({
                loginID: loginStore.loginId
            })
            state.noticeList = res.data
        } finally {
            state.loading = false
            // 轮询查询系统通知
            timerTask.setTimeout(() => {
                getNoticeList()
            }, 60 * 1000, 'systemNotice')
        }
    }

    // 更新已读
    const updateNoticeReaded = (id: number) => {
        const loginStore = useLoginStore()
        const item = state.noticeList.find((e) => e.autoid === id)

        if (item && !item.readed) {
            postNoticeReaded({
                loginID: Number(loginStore.loginId),
                noticeID: id,
            }).then(() => {
                item.readed = true
            })
        }
    }

    return {
        ...toRefs(state),
        unreadList,
        getNoticeList,
        updateNoticeReaded,
    }
})