<template>
  <div>
    <el-popover
      width="300"
      @show="resetState"
      trigger="click"
      v-model:visible="visible"
    >
      <template #reference>
        <div
          style="font-size: 22px;position: relative"
          class="mr15"
          @mouseover="debounce(getUnreadMessageCount)"
          @mouseout="clearTimer"
        >
          <i class="el-icon-message"></i>
          <i class="dot" v-if="!!unReadCount"></i>
        </div>
      </template>
      <el-tabs
        v-model="activeTab"
        stretch
        @tab-click="resetState"
        v-loading="loading"
      >
        <el-tab-pane
          :label="$t('ftlOne.message.unread')"
          name="unread"
        ></el-tab-pane>
        <el-tab-pane :label="$t('ftlOne.message.all')" name="all"></el-tab-pane>
        <div
          class="message-container pr10 ml5"
          style="min-height: 100px; max-height: 300px"
          ref="container"
          @scroll="() => debounce(loadMore)"
        >
          <el-card
            v-for="item in messageCard"
            :key="item.msgId"
            style="border-radius: 5px; --el-card-padding: 12px"
            size="mini"
            class="mb10"
            shadow="hover"
            @click.native="$refs.dialog.open(item.msgId)"
          >
            <div class="f-s-c">
              <span class="message-card__text">{{ item.title }}</span>
              <span class="message-card__text">{{
                formatDate(item.sendTime)
              }}</span>
            </div>
          </el-card>
        </div>
      </el-tabs>
    </el-popover>
    <detail-dialog
      :auth-base-url="authBaseUrl"
      @preventHiddenDropdown="displayWhenDialogHidden"
      ref="dialog"
    ></detail-dialog>
  </div>
</template>

<script>
import axios from "axios";
import DetailDialog from "./dialog";

const token = localStorage.getItem("token") || "";
const requestHeader = {
  Authorization: `Bearer ${token}`,
}; // 请求头

export default {
  name: "FtlMessage",
  props: {
    authBaseUrl: {
      type: String,
      default: "https://gateway-staging.ftlapp.io",
    },
  },
  components: { DetailDialog },
  data() {
    return {
      visible: false,
      unReadCount: 0, // 未读消息数
      timer: null, // 定时器
      messageCard: [], // 消息卡片数据源,
      loading: false, // 是否加载
      activeTab: "unread", // 卡片类别状态
      currentIndex: 1, // 当前页数
      totalMessages: 0, // 全部消息数
      hasMoreData: true, // 是否还有更多数据
    };
  },
  computed: {
    requestMessage() {
      return {
        unread: (index) =>
          axios.get(`${this.url}/get/unReadMessage`, {
            headers: requestHeader,
            params: { current: index, size: 6 },
          }),
        all: (index) =>
          axios.get(`${this.url}/get/allMessage`, {
            headers: requestHeader,
            params: { current: index, size: 6 },
          }),
      };
    }, // 请求策略
    url() {
      return `${this.authBaseUrl}/api/xpush/imm/userMessage`;
    },
  },
  methods: {
    clearTimer() {
      clearTimeout(this.timer);
    },
    debounce(func) {
      if (this.timer) clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        this.timer = null;
        func();
      }, 1000);
    }, // 悬浮到图标上面更新未读消息
    async getUnreadMessageCount() {
      const res = await axios.get(`${this.url}/getUserNoReadMsgCount`, {
        headers: requestHeader,
      });
      if (res && res.data) this.unReadCount = +res.data;
    }, // 获取未读消息条数
    async loadMore() {
      if (this.$refs.container) {
        const scrollHeight = this.$refs.container.scrollHeight;
        if (
          Math.ceil(this.$refs.container.scrollTop) >= scrollHeight - 300 &&
          this.messageCard.length % 6 === 0 &&
          this.hasMoreData
        ) {
          this.currentIndex += 1;
          try {
            this.loading = true;
            const res = await this.requestMessage[this.activeTab](
              this.currentIndex
            );
            if (res && res.data && res.data.records) {
              if (res.data.records.length === 0) {
                this.hasMoreData = false;
              }
              this.messageCard = this.messageCard.concat(res.data.records);
            }
          } catch (e) {
            console.log(e);
          } finally {
            this.loading = false;
          }
        }
      }
    }, // 加载下一页
    formatDate(date) {
      const formatNumber = (num) => {
        if (num < 10) return `0${num}`;
        return `${num}`;
      };
      const localDate = new Date(date);
      return `${localDate.getFullYear()}-${formatNumber(
        localDate.getMonth() + 1
      )}-${formatNumber(localDate.getDate())} ${formatNumber(
        localDate.getHours()
      )}:${formatNumber(localDate.getMinutes())}:${formatNumber(
        localDate.getSeconds()
      )}`;
    }, // 本地时间格式化
    async getMessages() {
      try {
        this.loading = true;
        const res = await this.requestMessage[this.activeTab](1);
        if (res && res.data && res.data.records)
          this.messageCard = res.data.records || [];
        if (res && res.data && res.data.total)
          this.totalMessages = +res.data.total;
      } catch (e) {
        console.log(e);
      } finally {
        this.loading = false;
      }
    }, // 获取消息
    displayWhenDialogHidden() {
      this.$nextTick(() => (this.visible = true));
    },
    resetState() {
      this.currentIndex = 1;
      this.hasMoreData = true;
      this.getMessages();
    }, // 重置一些状态
  },
  mounted() {
    this.getUnreadMessageCount();
  },
};
</script>

<style scoped>
::v-deep .el-card__body{
  padding: 12px;
}

.dot {
  position: absolute;
  width: 5px;
  height: 5px;
  border-radius: 50%;
  background: red;
  top: 4px;
  left: 18px;
}

.message-card__text {
  color: #999;
  font-size: 12px;
}

.message-container {
  overflow-x: hidden;
  overflow-y: auto;
}
</style>
