<template>
  <div class="current-time-warp">{{ currentTime }}</div>
</template>
<script setup>
import { ref, reactive, onMounted, watch, onUnmounted } from 'vue';
let currentTime = ref('');

const formatDateTime = () => {
  const now = new Date();
  // 获取各部分值
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0'); // JavaScript中月份从0开始，所以需要加1
  const day = String(now.getDate()).padStart(2, '0');

  // 星期几，注意返回的是0（周日）到6（周六）
  const weekDay = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'][now.getDay()];

  const hour = String(now.getHours()).padStart(2, '0');
  const minute = String(now.getMinutes()).padStart(2, '0');
  const second = String(now.getSeconds()).padStart(2, '0');

  // 格式化输出
  const formattedDate = `${year}-${month}-${day}\u00A0\u00A0\u00A0 ${weekDay}\u00A0\u00A0\u00A0 ${hour}:${minute}:${second}`;

  // console.log(formattedDate);
  return formattedDate;
};

let interval = ref(null);

const startTime = () => {
  interval.value = setInterval(() => {
    currentTime.value = formatDateTime();
  }, 1000);
};

const chearTime = () => {
  if (interval.value) {
    clearInterval(interval.value);
    interval.value = null;
  }
};

onMounted(() => {
  startTime();
});

onUnmounted(() => {
  chearTime();
});

defineExpose({
  startTime,
  chearTime,
});
</script>
<style lang="scss" scoped>
.current-time-warp {
  position: fixed;
  right: 16px;
  top: 24px;
  color: #add8f1;
  z-index: 2;
}
</style>
