<template>
  <p class="text-clock">
    <i v-if="showIcon" class="icon icon-calendar-act"></i
    ><span>{{ text }}</span>
  </p>
</template>

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

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

      const hourNum = now.getHours();
      if (this.showApm) {
        const val = hourNum > 12 ? hourNum - 12 : hourNum;
        const hour = ("00" + val).substr(("" + val).length);
        const apm = hourNum < 12 ? "上午" : "下午";
        infos.push(apm);
        infos.push(`${hour}:${timeStr[1]}`);
      } else {
        const hour = ("00" + hourNum).substr(("" + hourNum).length);
        infos.push(`${hour}:${timeStr[1]}`);
      }

      this.text = infos.join(" ");
    },
    start() {
      this.setT = setInterval(() => {
        this.parseDate();
      }, 1000);
    },
    end() {
      clearInterval(this.setT);
    },
  },
  beforeDestroy() {
    clearInterval(this.setT);
  },
};
</script>

<style scoped>
.text-clock {
  margin: 0;
}
.text-clock i {
  margin-right: 10px;
  margin-top: -1px;
}
.text-clock span {
  display: inline-block;
  vertical-align: middle;
}
</style>
