<script setup lang="ts">
import { store } from "@/store/store";
import { watch, onMounted, computed } from "vue";
import { useRouter } from "vue-router";
import { ChevronForward } from "@vicons/ionicons5";
import { fetchSiteMessage } from "./siteMessageUpdate";

const router = useRouter();

const firstUnreadMessage = computed(() => store.siteMessage.firstUnreadMessage);
const showPopover = computed(() => !!firstUnreadMessage.value);

function updateSiteMessage() {
  const { messages, ignoreMessageIds } = store.siteMessage;
  if (!messages) return;
  const unreadMessages = messages
    .filter((item) => !item.hasRead && !ignoreMessageIds.includes(item.id))
    .reverse();
  store.siteMessage.unreadCount = unreadMessages.length;
  store.siteMessage.firstUnreadMessage = unreadMessages[0] || null;
}

function toView() {
  if (!firstUnreadMessage.value) return;
  void router.push({
    name: "SiteMessageDetail",
    params: {
      noticeId: firstUnreadMessage.value.id,
    },
  });
}

function toIgnore() {
  if (!firstUnreadMessage.value) return;

  if (store.siteMessage.ignoreMessageIds.includes(firstUnreadMessage.value.id))
    return;

  store.siteMessage.ignoreMessageIds.push(firstUnreadMessage.value.id);
  updateSiteMessage();
}

watch(
  () => store.siteMessage.messages,
  () => {
    updateSiteMessage();
  },
  {
    deep: true,
    immediate: true,
  }
);

onMounted(() => {
  void fetchSiteMessage();
});
</script>

<template>
  <n-popover
    trigger="manual"
    :show="showPopover"
    :showArrow="false"
    placement="top-end"
  >
    <template #trigger>
      <div class="site-message-notification"></div>
    </template>
    <div v-if="firstUnreadMessage" class="site-message-main">
      <h2 class="site-message-title">
        {{ firstUnreadMessage.title }}
      </h2>
      <div class="site-message-body" v-html="firstUnreadMessage.content"></div>
      <div class="site-message-action box-justify">
        <n-button text color="#328358" @click="toView">
          详情
          <n-icon :component="ChevronForward" :size="16"></n-icon>
        </n-button>
        <n-button text color="#999" @click="toIgnore">忽略</n-button>
      </div>
    </div>
  </n-popover>
</template>

<style scoped>
.site-message-notification {
  position: fixed;
  bottom: 20px;
  right: 15px;
  width: 280px;
  height: 0;
  z-index: 999;
}
.site-message-main {
  width: 280px;
  margin: -8px -14px;
  border-radius: 3px;
  overflow: hidden;
}
.site-message-title {
  padding: 10px;
  line-height: 1;
  font-size: var(--app-font-size);
  color: var(--app-color-white);
  background-color: var(--app-color-success);
  text-align: center;
}
.site-message-body {
  padding: 20px;
  height: 140px;
  overflow: hidden;
}
.site-message-action {
  padding: 10px 15px;
}
</style>
