notice.js 2.64 KB
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { 
  getMessageListApi, 
  readMessageApi, 
} from '../../api/message'
import { getStageObj } from "../../utils/storageVal";

export const useNoticeStore = defineStore('notice', () => {
  // 状态定义
  const messageList = ref([]); // 消息列表
  const unreadCount = ref(0); // 未读消息数量
  const unReolveCount = ref(0); // 未处理消息数量

  // 计算属性
  const hasUnreadMessages = computed(() => unreadCount.value > 0);
  const displayUnreadCount = computed(() => {
    if (unreadCount.value > 999) return "999+";
    return unreadCount.value;
  });

  // 获取消息数量-列表
  const getMessageList = async (params = {}) => {
    try {
      const requestParams = {
        accountId: getStageObj("account").id,
      };

      const response = await getMessageListApi(requestParams);
      unreadCount.value = response.data.unread;
      // updateUnreadCount('set', response.data.unread);
      
      const unReolveCount = response.data.list?.filter(item => item.status === 'NEW').length;
      updateUnresolveCount('set', unReolveCount);
    } catch (error) {
      console.error("获取消息列表失败:", error);
    } finally {
    }
  };

  // 标记消息为已读
  const markMessageAsRead = async (messageId) => {
    try {
      const response = await readMessageApi({ id: messageId, isRead: true });
      updateUnreadCount('reduce');
    } catch (error) {
      console.error("标记消息已读失败:", error);
    }
  };

  // 更新未读数量 -计算更新  --需要走接口 异步更新 及更新角标
  const updateUnreadCount =  async (type = 'reduce', count = 0) => {
    await getMessageList();
    // console.log("开始降低未读数量2-22",type,count);
    // if (type === 'reduce') {
    //   unreadCount.value = unreadCount.value > 0 ? unreadCount.value - 1 : 0;
    // } else {
    //   unreadCount.value = count;
    // }
    
    updateTabbarBadge();
  };

  // 更新未处理数量 -计算更新
  const updateUnresolveCount = (type, count = 0) => {
    unReolveCount.value = count;
  };

 // 更新tabbar-角标
const updateTabbarBadge = (type = 'reduce') => {
  console.log('====[updateTabbarBadge]====>更新tabbar角标数量',unreadCount.value);
  if (unreadCount.value > 0) {
    uni.setTabBarBadge({
      index: 3,
      text: unreadCount.value,
    });
  } else {
    // 隐藏
    uni.hideTabBarRedDot({
      index: 3,
    });
  }
}

  return {
    messageList,
    unreadCount,
    unReolveCount,
    hasUnreadMessages,
    displayUnreadCount,
    getMessageList,
    markMessageAsRead,
    updateUnreadCount,
    updateTabbarBadge,
  };
})