import { defineStore } from 'pinia'

interface NotificationMessageState {
  notificationMsgList: string[] // 页面中监听的未读消息id
  readCardMap: string[] // 已读的消息id
  hasNewMsg: boolean
}

export const useNotificationMessage = defineStore('notificationMessage', {
  state: (): NotificationMessageState => ({
    notificationMsgList: JSON.parse(localStorage.getItem('notificationMsgList')) || [],
    readCardMap: JSON.parse(localStorage.getItem('readCardMap')) || [],
    hasNewMsg: JSON.parse(localStorage.getItem('hasNewMsg')) || false
  }),
  getters: {},
  actions: {
    concatNotificationMsgList(array: any[]) {
      this.notificationMsgList = [...new Set([...this.notificationMsgList, ...array])]
      localStorage.setItem('notificationMsgList', JSON.stringify(this.notificationMsgList))
    },
    removeNotificationMsgList(array: any[]) {
      this.notificationMsgList = this.notificationMsgList.filter((item) => !array.includes(item))

      localStorage.setItem('notificationMsgList', JSON.stringify(this.notificationMsgList))
    },
    setReadCardMap(id: string) {
      // 将页面中从未读到已读的消息id存入readCardMap
      if (this.readCardMap.includes(id)) return
      this.readCardMap.push(id)
      localStorage.setItem('readCardMap', JSON.stringify(this.readCardMap))
      // 将已读的消息从notificationMsgList中删除
      this.notificationMsgList = this.notificationMsgList.filter((item) => {
        return !this.readCardMap.includes(item)
      })
      localStorage.setItem('notificationMsgList', JSON.stringify(this.notificationMsgList))
    },
    hasUnreadMessages() {
      $api.hasUnreadMessages().then((res) => {
        if (res.code === 200) {
          this.hasNewMsg = res.data.has_message
          localStorage.setItem('hasNewMsg', JSON.stringify(this.hasNewMsg))
        }
      })
    },
    setHasNewMsg() {
      this.hasNewMsg = true
      localStorage.setItem('hasNewMsg', JSON.stringify(this.hasNewMsg))
    },
    async markMessageAsRead() {
      if (this.readCardMap.length === 0) return

      await $api.setMessageRead({ id: this.readCardMap }).then((res) => {
        if (res.code === 200) {
          this.readCardMap = []
          localStorage.setItem('readCardMap', JSON.stringify(this.readCardMap))

          // 在将消息标记为已读后，再次检查是否有新消息
          this.hasUnreadMessages()
        }
      })
    },
    clearData() {
      this.notificationMsgList = []
      this.readCardMap = []
      this.hasNewMsg = false
      localStorage.removeItem('hasNewMsg')
      localStorage.removeItem('notificationMsgList')
      localStorage.removeItem('readCardMap')
    }
  }
})
