import { ref } from 'vue';
import { lls } from '@/utils/storage';

export default function useSms(name = 'sms') {
  const defaultCodeWaitingTime = 60;
  const codeWaitingTime = ref(60);
  const isFetchingCode = ref(false);
  const codeContent = ref('获取验证码');
  const nameWaitTime = ref('');
  let tSetT: NodeJS.Timeout | null = null;

  function setWaitingTime(wt: string) {
    nameWaitTime.value = wt;
    const codetime = lls.get(wt);
    if (codetime) {
      const num = Math.floor((codetime.expire - new Date().getTime()) / 1000);
      if (num > 0) {
        codeWaitingTime.value = num;
        isFetchingCode.value = true;
        changeContent();
      }
    }
  }
  setWaitingTime(name);

  function changeContent() {
    if (!isFetchingCode.value) return;
    codeContent.value = `倒计时${codeWaitingTime.value}s`;

    const circleTime = (time: number) => {
      tSetT = setInterval(() => {
        if (time > 1) {
          time--;
          const expire = new Date().getTime() + time * 1000;
          lls.set(
            nameWaitTime.value,
            {
              time,
              expire,
            },
            expire
          );
          codeContent.value = `倒计时${time}s`;
        } else {
          clearSetContent();
        }
      }, 1e3);
    };
    circleTime(codeWaitingTime.value);
  }

  function clearSetContent() {
    codeWaitingTime.value = defaultCodeWaitingTime;
    lls.remove(nameWaitTime.value);
    codeContent.value = '获取验证码';
    isFetchingCode.value = false;
    if (tSetT) clearInterval(tSetT);
  }

  return {
    isFetchingCode,
    codeContent,
    changeContent,
  };
}
