<template>
  <div class="board_time">{{ time }}</div>
</template>

<script>
import ApiConstant from "@/api/ApiConstant";

export default {
  name: "ServerTime",
  data() {
    return {
      time: "",
      timer: null,
      curDate: Object,
      serverDate: "", // 服务器时间
      serverDateGetLocalTime: null, // 获取服务器时间时的本地时间
    };
  },
  mounted() {
    this.getServerTime(); // 获取服务器时间
  },
  destroyed() {
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
    }
  },
  methods: {
    /* eslint-disable */
    // 获取服务器时间
    getServerTime() {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/epm/ebs/time/current-time`, {
          headers: { isLoading: false },
        })
        .then(({ data }) => {
          if (data.data) {
            this.curDate = data.data;
            this.serverDate = new Date(data.data);
            this.serverDateGetLocalTime = new Date();
          }
        });
      if (this.timer == null) {
        this.timer = setInterval(this.systemTime, 1000);
      }
    },
    // 系统时间
    systemTime() {
      // 当前和取得服务器时间之间的差
      const diffTime =
        new Date().getTime() - this.serverDateGetLocalTime.getTime();

      let date = null;
      if (this.serverDate) {
        date = new Date(this.serverDate.getTime() + diffTime);
      } else {
        date = new Date();
      }

      const minutes = date.getMinutes();
      const seconds = date.getSeconds();

      // 5分钟后台重新取一次
      if (minutes % 5 === 0 && seconds === 0) {
        this.getServerTime();
      }
      function formatTime(time) {
        if (time >= 10) {
          return time;
        } else {
          return "0" + time;
        }
      }
      if (this.$i18n.locale === "en") {
        this.time =
          this.formatToEngTime(date) +
          "  " +
          date.getHours() +
          ":" +
          formatTime(minutes) +
          ":" +
          formatTime(seconds);
      } else {
        this.time =
          date.getFullYear() +
          this.$t("YEAR") +
          (date.getMonth() + 1) +
          this.$t("MONTH") +
          date.getDate() +
          this.$t("DAYS") +
          "  " +
          formatTime(date.getHours()) +
          ":" +
          formatTime(minutes) +
          ":" +
          formatTime(seconds);
      }
    },
  },
};
</script>

<style lang="less" scoped>
.board_time {
  font-size: 16px;
  font-weight: 400;
  color: #fff;
  position: absolute;
  top: 32px;
  right: 52px;
}
</style>
