/**
 * 存储管理工具
 */
import { encryptAES, decryptAES } from './crypto'

const ACCESS_TOKEN_KEY = "access_token"
const USER_INFO_KEY = "user_info"
const REMEMBERED_ACCOUNT_KEY = "remembered_account"

/**
 * 保存 AccessToken
 */
export const saveAccessToken = (token: string): void => {
    uni.setStorageSync(ACCESS_TOKEN_KEY, token)
}

/**
 * 获取 AccessToken
 */
export const getAccessToken = (): string | null => {
    const token = uni.getStorageSync(ACCESS_TOKEN_KEY)
    if (token != null) {
        const tokenStr = token as string
        if (tokenStr.length > 0) {
            return tokenStr
        }
    }
    return null
}

/**
 * 清除 AccessToken
 */
export const clearAccessToken = (): void => {
    uni.removeStorageSync(ACCESS_TOKEN_KEY)
}

/**
 * 保存用户信息
 */
export const saveUserInfo = (userInfo: UTSJSONObject): void => {
    uni.setStorageSync(USER_INFO_KEY, JSON.stringify(userInfo))
}

/**
 * 获取用户信息
 */
export const getUserInfo = (): UTSJSONObject | null => {
    const info = uni.getStorageSync(USER_INFO_KEY)
    if (info != null) {
        const infoStr = info as string
        if (infoStr.length > 0) {
            return JSON.parse(infoStr) as UTSJSONObject
        }
    }
    return null
}

/**
 * 清除用户信息
 */
export const clearUserInfo = (): void => {
    uni.removeStorageSync(USER_INFO_KEY)
}

/**
 * 保存记住的账号密码
 * 密码会使用 AES 加密后保存
 */
export const saveRememberedAccount = (username: string, password: string): void => {
    // 对密码进行 AES 加密
    const encryptedPassword = encryptAES(password)
    const data = {
        username: username,
        password: encryptedPassword
    }
    uni.setStorageSync(REMEMBERED_ACCOUNT_KEY, JSON.stringify(data))
}

/**
 * 获取记住的账号密码
 * 密码会自动解密
 */
export const getRememberedAccount = (): UTSJSONObject | null => {
    const data = uni.getStorageSync(REMEMBERED_ACCOUNT_KEY)
    if (data != null) {
        const dataStr = data as string
        if (dataStr.length > 0) {
            const jsonData = JSON.parse(dataStr) as UTSJSONObject
            // 解密密码
            const encryptedPassword = jsonData['password'] as string
            const decryptedPassword = decryptAES(encryptedPassword)
            // 返回解密后的数据
            return {
                username: jsonData['username'],
                password: decryptedPassword
            }
        }
    }
    return null
}

/**
 * 清除记住的账号密码
 */
export const clearRememberedAccount = (): void => {
    uni.removeStorageSync(REMEMBERED_ACCOUNT_KEY)
}

/**
 * 清除所有存储
 */
export const clearAll = (): void => {
    clearAccessToken()
    clearUserInfo()
}

