/**
 * 记住密码功能
 * 使用 localStorage 存储加密后的用户名和密码
 */

// 存储key
const REMEMBER_KEY = 'remembered_credentials'

// 简单加密（实际项目中应使用更安全的加密方式）
const encode = (str: string): string => {
  return btoa(encodeURIComponent(str))
}

// 简单解密
const decode = (str: string): string => {
  try {
    return decodeURIComponent(atob(str))
  } catch {
    return ''
  }
}

/**
 * 保存的凭证接口
 */
export interface RememberedCredentials {
  username: string
  password: string
  rememberPassword: boolean
}

/**
 * 保存登录凭证
 */
export const saveCredentials = (username: string, password: string, remember: boolean) => {
  if (remember) {
    const credentials = {
      u: encode(username),
      p: encode(password),
      r: true
    }
    localStorage.setItem(REMEMBER_KEY, JSON.stringify(credentials))
  } else {
    // 如果不记住密码，清除已保存的凭证
    localStorage.removeItem(REMEMBER_KEY)
  }
}

/**
 * 获取保存的登录凭证
 */
export const getRememberedCredentials = (): RememberedCredentials | null => {
  try {
    const saved = localStorage.getItem(REMEMBER_KEY)
    if (!saved) return null

    const credentials = JSON.parse(saved)
    return {
      username: decode(credentials.u),
      password: decode(credentials.p),
      rememberPassword: credentials.r
    }
  } catch {
    return null
  }
}

/**
 * 清除保存的登录凭证
 */
export const clearRememberedCredentials = () => {
  localStorage.removeItem(REMEMBER_KEY)
}

/**
 * 检查是否有保存的凭证
 */
export const hasRememberedCredentials = (): boolean => {
  return localStorage.getItem(REMEMBER_KEY) !== null
}
