import { toRefs, onMounted, onUnmounted, reactive } from "vue";

export function useCurrentTime(): any {
  const date = reactive({
    nowTime: "",
    week: "",
    currentTime: "",
  });
  function getDate() {
    let nowTime = new Date();
    let yy = String(nowTime.getFullYear());
    let mm = timeNum(nowTime.getMonth() + 1);
    let dd = String(
      nowTime.getDate() < 10 ? "0" + nowTime.getDate() : nowTime.getDate()
    );
    date.nowTime = yy + "-" + mm + "-" + dd + "";
    date.week = "星期" + "日一二三四五六".charAt(nowTime.getDay());
    date.currentTime =
      timeNum(nowTime.getHours()) +
      ":" +
      timeNum(nowTime.getMinutes()) +
      ":" +
      timeNum(nowTime.getSeconds());
  }
  function timeNum(num: number) {
    if (num < 10) {
      return "0" + num;
    }
    return num;
  }

  let cid: string | number | NodeJS.Timeout | null | undefined = null;
  onMounted(() => {
    getDate();
    cid = setInterval(() => {
      getDate();
    }, 1000);
  });

  onUnmounted(() => cid && clearInterval(cid));

  return { ...toRefs(date) };
}
