<script lang="ts" setup>
import { SiteMessage } from "@/types/student-client";
import { updateNotieReadStatusApi } from "@/api/siteMessage";
import { store } from "@/store/store";
import { DataTableColumns, NIcon } from "naive-ui";
import { h, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import { RowKey } from "naive-ui/lib/data-table/src/interface";
import { MailOpen, MailUnread } from "@vicons/ionicons5";
import { fetchSiteMessage } from "./siteMessageUpdate";

const router = useRouter();

const columns: DataTableColumns<SiteMessage> = [
  {
    type: "selection",
  },
  {
    title: "标题",
    key: "title",
    render(row) {
      return h("p", { class: "qm-link-text", onClick: () => toDetail(row) }, [
        h(NIcon, {
          component: row.hasRead ? MailOpen : MailUnread,
          size: 18,
          class: "qm-mr-10 qm-vertical-mid",
          color: row.hasRead ? "#999" : "#2d8cf0",
        }),
        h("span", {}, row.title),
      ]);
    },
  },
  {
    title: "发送时间",
    key: "publishTime",
    width: 180,
  },
];
const messageList = computed(() => store.siteMessage.messages);
let selectedMessageIds = $ref<RowKey[]>([]);
const pagination = $ref({
  page: 1,
  pageSize: 10,
  onChange: (page: number) => {
    pagination.page = page;
  },
});

function selectedChange(ids: RowKey[]) {
  selectedMessageIds = ids;
}
function toDetail(row: SiteMessage) {
  void router.push({ name: "SiteMessageDetail", params: { noticeId: row.id } });
}

async function toMarkRead() {
  if (!selectedMessageIds.length) {
    $message.error("请先选择要标记的信息！");
    return;
  }
  await updateNotieReadStatusApi(selectedMessageIds.join());
  $message.success("修改成功！");
  store.updateSiteMessagesTimeStamp();
  void fetchSiteMessage();
}

onMounted(() => {
  void fetchSiteMessage();
});

// make ts happy
function rowKey(row: { id: number }) {
  return row.id;
}
</script>

<template>
  <div class="box-justify qm-mb-20">
    <h3 class="qm-big-text">公告通知</h3>
    <n-button @click="toMarkRead"
      ><n-icon class="qm-mr-5" :component="MailOpen" :size="16"></n-icon
      >标记为已读</n-button
    >
  </div>
  <div class="part-box">
    <div class="tips-info qm-mb-5">*仅保留近1年的公告通知。</div>
    <n-data-table
      :columns="columns"
      :data="messageList"
      :pagination="pagination"
      :rowKey="rowKey"
      @update:checkedRowKeys="selectedChange"
    ></n-data-table>
  </div>
</template>
