import { ref, Ref, onUnmounted } from 'vue';
/**
 * counter utils--验证码倒计时
 * @param duration
 * @returns
 */
export const useCounter = (duration = 60): [Ref<number>, any, () => void] => {
  let intervalTimer: any;
  onUnmounted(() => {
    clearInterval(intervalTimer);
  });
  const countDown = ref(0);
  const openInterval = () => {
    countDown.value = duration;
    intervalTimer = setInterval(() => {
      if (countDown.value > 0) {
        countDown.value -= 1;
      } else {
        clearInterval(intervalTimer);
        countDown.value = 0;
      }
    }, 1000);
  };
  const closeInterval = () => {
    if (intervalTimer) {
      clearInterval(intervalTimer);
    }
  };
  return [countDown, openInterval, closeInterval];
};
