import { dateUtil } from '/@/utils/dateUtil';
import { reactive, toRefs } from 'vue';
import { tryOnMounted, tryOnUnmounted } from '@vueuse/core';

// intervalTime 间隔时间
export function useNow(immediate = true, intervalTime = 1000) {
  let timer: IntervalHandle;

  const state = reactive({
    year: 0,
    month: 0 as number | string,
    week: '',
    day: 0 as number | string,
    hour: '',
    minute: 0 as number | string,
    second: 0 as number | string,
    meridiem: '',
    // 毫秒
    timestamp: 0 as number,
  });

  const update = () => {
    const now = dateUtil();

    const h = now.format('HH');
    const m = now.format('mm');
    const s = now.get('s');

    state.year = now.get('y');
    state.month = now.get('M') + 1 > 9 ? now.get('M') + 1 : '0' + (now.get('M') + 1);
    state.week = '星期' + ['日', '一', '二', '三', '四', '五', '六'][now.day()];
    state.day = now.get('date') > 9 ? now.get('date') : '0' + now.get('date');
    state.hour = h;
    state.minute = m;
    state.second = s;

    state.meridiem = now.format('A');

    state.timestamp = dateUtil().valueOf();
  };

  function start() {
    update();
    clearInterval(timer);
    timer = setInterval(() => update(), intervalTime);
  }

  function stop() {
    clearInterval(timer);
  }

  tryOnMounted(() => {
    immediate && start();
  });

  tryOnUnmounted(() => {
    stop();
  });

  return {
    ...toRefs(state),
    start,
    stop,
  };
}
