<script lang="ts" setup>
import { SiteMessage } from "@/types/student-client";
import { store } from "@/store/store";
import { useRoute, useRouter } from "vue-router";
import { onMounted, watch } from "vue";
import { ArrowBack } from "@vicons/ionicons5";
import { updateNotieReadStatusApi } from "@/api/siteMessage";
import { fetchSiteMessage } from "./siteMessageUpdate";

let notice: SiteMessage | undefined = $ref();
const route = useRoute();
const router = useRouter();

function toBack() {
  void router.push({ name: "SiteMessage" });
}

async function markMessageRead(noticeId: string) {
  if (!noticeId) return;
  await updateNotieReadStatusApi(noticeId);
  store.updateSiteMessagesTimeStamp();
  void fetchSiteMessage();
}

function initData() {
  const paramNoticeId = route.params.noticeId as string;
  const curNoticeId = Number(paramNoticeId);
  const curNotice = store.siteMessage.messages.find(
    (item) => item.id === curNoticeId
  );
  notice = curNotice;

  if (notice?.hasRead) return;

  void markMessageRead(paramNoticeId);
}

onMounted(() => {
  initData();
});

watch(
  () => route.params,
  () => {
    initData();
  }
);
</script>

<template>
  <div class="tw-flex tw-justify-end qm-mb-20">
    <n-button @click="toBack">
      <n-icon class="qm-mr-5" :component="ArrowBack" :size="16" />
      返回列表
    </n-button>
  </div>
  <div v-if="notice" class="part-box">
    <div class="message-title">
      <h3>{{ notice.title }}</h3>
      <p class="tips-info">发布时间: {{ notice.publishTime }}</p>
    </div>
    <div class="message-desc" v-html="notice.content"></div>
  </div>
</template>

<style scoped>
.message-title {
  text-align: center;
}
.message-title > h3 {
  font-size: 22px;
  line-height: 1;
  padding: 10px;
}
.message-desc {
  padding-top: 30px;
}
</style>
