<template>
  <p class="text-clock">现在是{{ text }}</p>
</template>

<script>
import { formatDate } from "@/utils/utils";

export default {
  name: "text-clock",
  data() {
    return {
      text: "",
      setT: null,
      week: ["日", "一", "二", "三", "四", "五", "六"],
    };
  },
  mounted() {
    this.parseDate();
    this.start();
  },
  methods: {
    parseDate() {
      const now = new Date();
      const timeStr = formatDate("YYYY年M月D日_mm:ss", now).split("_");
      const weekDay = `星期${this.week[now.getDay()]}`;

      const hourNum = now.getHours();
      const val = hourNum > 12 ? hourNum - 12 : hourNum;
      const hour = ("00" + val).substr(("" + val).length);
      const apm = hourNum < 12 ? "上午" : "下午";
      this.text = `${timeStr[0]} ${weekDay} ${apm} ${hour}:${timeStr[1]}`;
    },
    start() {
      this.setT = setInterval(() => {
        this.parseDate();
      }, 1000);
    },
    end() {
      clearInterval(this.setT);
    },
  },
  beforeDestroy() {
    clearInterval(this.setT);
  },
};
</script>
