import { useUniStore } from './useUniStore';
import { sendSmsNoValidationNoToken, sendSmsNoToken, sendSms as sendSmsApi } from '@/api/modules/system';
import { EnumSmsApiType, EnumSmsType } from '@/common/enum';

type SmsApiType = EnumSmsApiType;
type SmsParams = {
  mobile: string;
  smsType?: EnumSmsType;
  uuid?: string;
  code?: string;
};

export const useSms = () => {
  const { setItem, getItem, removeItem } = useUniStore();

  // 状态常量定义
  const SMS_COUNTDOWN_TIME = import.meta.env.DEV ? 5 : 60; // 倒计时时长(秒)
  const STORAGE_KEYS = {
    LAST_TIME: 'ie-smsLastTime',
    WAIT_TIME: 'ie-smsWaitTime'
  };

  // 剩余等待时间 (-1表示未开始倒计时)
  const smsWaitTime = ref(-1);
  const smsIsSending = ref(false);
  const lastTime = ref(0);

  // 计算属性
  const isCountingDown = computed(() => {
    return smsWaitTime.value >= 0;
  });

  const smsTip = computed(() => {
    return isCountingDown.value ? `${smsWaitTime.value}秒后重新获取` : '获取验证码';
  });

  // 重置状态
  const resetState = () => {
    smsWaitTime.value = -1;
    smsIsSending.value = false;
    removeItem(STORAGE_KEYS.LAST_TIME);
    removeItem(STORAGE_KEYS.WAIT_TIME);
  };

  // 保存状态到本地存储
  const saveState = () => {
    try {
      lastTime.value = Date.now();
      setItem(STORAGE_KEYS.LAST_TIME, lastTime.value);
      setItem(STORAGE_KEYS.WAIT_TIME, smsWaitTime.value);
    } catch (error) {
      console.warn('保存短信倒计时状态失败:', error);
    }
  };

  // 倒计时
  const countDown = () => {
    // 已经延迟了1s才开始，所以只需要1s就可以结束了
    if (smsWaitTime.value > 1) {
      smsWaitTime.value--;
      saveState();
      setTimeout(countDown, 1000);
    } else {
      // 倒计时结束，重置状态
      resetState();
    }
  };

  // 启动倒计时
  const startCountdown = () => {
    smsWaitTime.value = SMS_COUNTDOWN_TIME;
    saveState();
    setTimeout(countDown, 1000);
  };

  // 验证手机号
  const validatePhone = (phone: string): boolean => {
    // 简单的手机号验证规则，可根据实际需求调整
    const phoneRegex = /^1[3-9]\d{9}$/;
    return phoneRegex.test(phone);
  };

  // 发送短信
  const sendSms = async (type: SmsApiType, params: SmsParams): Promise<{ success: boolean, error: any }> => {
    // 检查是否正在发送或倒计时中
    if (smsIsSending.value || isCountingDown.value) {
      return Promise.resolve({ success: false, error: null });
    }
    const { mobile, smsType, uuid, code } = params;
    // 验证手机号
    if (!validatePhone(mobile)) {
      console.warn('手机号格式不正确');
      return Promise.resolve({ success: false, error: null });
    }
    const smsParams = {
      mobile: mobile,
      smsType: smsType,
      uuid: uuid || '',
      code: code ? code + '' : ''
    };
    try {
      smsIsSending.value = true;
      return new Promise<{ success: boolean, error: any }>((resolve) => {
        switch (type) {
          case EnumSmsApiType.NO_VALIDATION_NO_TOKEN:
            sendSmsNoValidationNoToken(smsParams).then(res => {
              startCountdown();
              resolve({ success: true, error: null });
            }).catch(error => {
              console.error('发送短信请求失败:', error);
              resolve({ success: false, error: error });
            });
            break;
          case EnumSmsApiType.NO_TOKEN:
            sendSmsNoToken(smsParams).then(res => {
              startCountdown();
              resolve({ success: true, error: null });
            }).catch(error => {
              console.error('发送短信请求失败:', error);
              resolve({ success: false, error: error });
            });
            break;
          case EnumSmsApiType.NORMAL:
            sendSmsApi(smsParams).then(res => {
              startCountdown();
              resolve({ success: true, error: null });
            }).catch(error => {
              console.error('发送短信请求失败:', error);
              resolve({ success: false, error: error });
            });
            break;
          default:
            console.error('未知的短信发送类型:', type);
            resolve({ success: false, error: null });
            break;
        }
      });
    } catch (error) {
      console.error('发送短信失败:', error);
      return Promise.resolve({ success: false, error: error });
    } finally {
      smsIsSending.value = false;
    }
  };

  // 初始化
  const init = () => {
    try {
      const localLastTime = getItem(STORAGE_KEYS.LAST_TIME);
      const localWaitTime = getItem(STORAGE_KEYS.WAIT_TIME);

      // 检查是否有存储的倒计时状态
      if (localLastTime && localWaitTime) {
        const storedLastTime = Number(localLastTime);
        const storedWaitTime = Number(localWaitTime);

        // 确保解析的是有效数字
        if (!isNaN(storedLastTime) && !isNaN(storedWaitTime) && storedLastTime > 0) {
          const now = Date.now();
          // 计算剩余等待时间
          const duration = Math.max(0, storedWaitTime - Math.floor((now - storedLastTime) / 1000));

          if (duration > 0) {
            smsWaitTime.value = duration;
            lastTime.value = now - (storedWaitTime - duration) * 1000;
            setTimeout(countDown, 1000);
          } else {
            // 倒计时已结束，清理存储
            resetState();
          }
        } else {
          // 存储的数据无效，清理存储
          resetState();
        }
      }
    } catch (error) {
      console.warn('初始化短信倒计时状态失败:', error);
      resetState();
    }
  };

  return {
    init,
    sendSms,
    smsTip,
    smsWaitTime,
    smsIsSending,
    isCountingDown
  };
};