import { ref, onUnmounted, computed } from "vue";
import dayjs from "dayjs";
import duration from "dayjs/plugin/duration";
dayjs.extend(duration);

export default function useCountDown() {
  let timer = null;
  let time = ref(0);
  // 格式化时间
  const formTime = computed(() => {
    let timeStr = dayjs.duration(new Date(time.value), "seconds");
    let formatStr = "DD天HH时mm分ss秒";
    if (timeStr.$d.years > 0) {
      formatStr = "YY年MM月DD天HH时mm分ss秒";
    } else if (timeStr.$d.months > 0) {
      formatStr = "MM月DD天HH时mm分ss秒";
    }
    return timeStr.format(formatStr);
  });
  const formTimeArr = computed(() => {
    let timeStr = dayjs.duration(new Date(time.value), "seconds");
    let formatStr = "DD-HH-mm-ss";
    let unitArr = ["天", "时", "分", "秒"];
    if (timeStr.$d.years > 0) {
      formatStr = "YY-MM-DD-HH-mm-ss";
      unitArr = ["年", "月", "天", "时", "分", "秒"];
    } else if (timeStr.$d.months > 0) {
      formatStr = "MM-DD-HH-mm-ss";
      unitArr = ["月", "天", "时", "分", "秒"];
    }
    const timeArr = timeStr.format(formatStr).split("-");
    return timeArr.map((item, index) => {
      return {
        unit: unitArr[index],
        text: item,
      };
    });
  });

  function startDownTime(startTime) {
    const currenTime = Math.floor(
      (new Date(dayjs(startTime)).getTime() - new Date().getTime()) / 1000
    );
    // 把传过来的数据给响应式数据
    time.value = currenTime > 0 ? currenTime : 0;
    // 格式化时间
    if (time.value > 0) {
      timer = setInterval(() => {
        time.value = Math.floor(
          (new Date(dayjs(startTime)).getTime() - new Date().getTime()) / 1000
        );
        if (time.value <= 0) {
          clearInterval(timer);
          // 其他业务逻辑
        }
      }, 200);
    }
  }

  // 如果存在，组件销毁调用清除定时器
  onUnmounted(() => {
    if (timer) {
      clearInterval(timer);
    }
  });
  return { formTime, startDownTime, formTimeArr };
}
