<template>
  <div class="message">
    <el-badge :value="unreadCount > 0 ? unreadCount : undefined" class="item">
      <i :class="'iconfont icon-xiaoxi'" class="toolBar-icon" @click="getMessage" />
    </el-badge>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from "vue";
import { useRouter } from "vue-router";
import { getNoticeList } from "@/api/modules/homeEntry";
import { localGet } from "@/utils/index";
import mittBus from "@/utils/mittBus";

const router = useRouter();
const unreadCount = ref<number>(0);

// 获取未读消息数量
const getUnreadCount = async () => {
  try {
    const phone = localGet("iphone") || localGet("geeker-user")?.userInfo?.phone || "";
    if (!phone) return;

    // 使用与 notice.vue 相同的 receiverId 格式
    const receiverId = "store_" + phone;
    const res: any = await getNoticeList({
      pageNum: 1,
      pageSize: 100,
      receiverId,
      noticeType: 1
    });
    if (res.code == 200 || res.code == "200") {
      const noticeList = res.data?.records || res.data?.list || [];
      // 计算未读消息数量
      unreadCount.value = noticeList.filter((item: any) => !item.isRead).length;
    }
  } catch (error) {
    console.error("获取消息列表失败:", error);
  }
};

const getMessage = () => {
  router.push(`/home/notice`);
};

onMounted(() => {
  // 初始化获取未读数量
  getUnreadCount();

  // 监听消息更新事件，当消息页面有操作时（标记已读等）更新未读数量
  mittBus.on("updateUnreadCount", () => {
    getUnreadCount();
  });
});

onBeforeUnmount(() => {
  // 移除事件监听
  mittBus.off("updateUnreadCount");
});
</script>

<style scoped lang="scss">
.message {
  display: flex;
  align-items: center;
  .item {
    :deep(.el-badge__content) {
      border: none;
    }
  }
}
</style>
