<template>
  <transition
    name="fade"
    mode="out-in"
    appear
    :duration="{ enter: 500, leave: 300 }"
  >
    <div v-if="unreadMessage" :key="unreadMessage.id" class="popup">
      <h5
        style=" padding: 5px; background:rgba(19,187,138,1);
              border-radius:6px 6px 0px 0px; font-size:14px;
              font-weight:500;
              color:rgba(255,255,255,1);
              line-height:20px;"
      >
        {{ unreadMessage.title }}
      </h5>

      <p
        style="text-overflow: ellipsis; text-indent: 2em; text-align: left; height: 100px; overflow: hidden; margin: 20px;"
      >
        {{ unreadMessageContent }}
      </p>
      <div style="text-align: left; margin-left: 20px; margin-bottom: 10px;">
        <router-link
          :to="'/site-message/' + unreadMessage.id"
          ondragstart="return false;"
        >
          详情 >>>
        </router-link>
        <span
          style="display: inline-block; margin-left: 20px; cursor: pointer;"
          @click="ignoreMessage"
          >忽略</span
        >
      </div>
    </div>
  </transition>
</template>

<script>
import { mapState } from "vuex";

export default {
  name: "SiteMessagePopup",
  data() {
    let ignoreMessageIds = window.sessionStorage.getItem("ignoreMessageIds");
    if (ignoreMessageIds) {
      ignoreMessageIds = JSON.parse(ignoreMessageIds);
    } else {
      ignoreMessageIds = [];
    }
    return {
      ignoreMessageIds,
    };
  },
  computed: {
    ...mapState(["siteMessages"]),
    unreadMessage() {
      const unreadMessages = this.siteMessages
        .filter(v => v.hasRead === false)
        .filter(v => this.ignoreMessageIds.includes(v.id) === false)
        .reverse();
      if (unreadMessages.length > 0) {
        return unreadMessages[0];
      } else {
        return null;
      }
    },
    unreadMessageContent() {
      const div = document.createElement("div");
      div.innerHTML = this.unreadMessage.content;
      const text = div.textContent || div.innerText || "";
      return text.slice(0, 90) + (text.length > 90 ? "..." : "");
    },
  },
  methods: {
    ignoreMessage() {
      this.ignoreMessageIds.push(this.unreadMessage.id);
      window.sessionStorage.setItem(
        "ignoreMessageIds",
        JSON.stringify(this.ignoreMessageIds)
      );
    },
  },
};
</script>

<style scoped>
.popup {
  position: sticky;
  bottom: 20px;
  left: calc(100%);
  margin-right: 20px;
  margin-top: -200px;
  width: 320px;
  height: 200px;
  background: rgba(255, 255, 255, 1);
  box-shadow: 0px 2px 10px 0px rgba(0, 0, 0, 0.1);
  border-radius: 6px;
  border: 1px solid rgba(221, 221, 221, 1);
  z-index: 100;
}
</style>
