import Taro from '@tarojs/taro';

// storage key
export const JWT = '_jujwt'; // jwt
export const JWTEXPIRE = 24 * 3600; // jwt  过期时间
export const OPENDATA = '_d' // 微信开放数据 openid unionId sessionKey
export const WXUSERINFO = '_wu' // 微信GetUserInfo 数据
export const USERINFO = '_u' // 用户信息
export const TASKKEY = "_task" // 任务key

// 同步设置缓存
export function SetData(key, data, t = 0) {
    if (t > 0) {
        let time = (new Date()).getTime()
        time = Number(String(time).substr(0, 10))
        t = time + t
    }
    let storage = {
        expire: t,
        _data: data
    }
    return Taro.setStorageSync(key, storage)

}

// 异步设置缓存
export function SetAsyncData(key, data, t = 0) {
    if (t > 0) {
        let time = (new Date()).getTime()
        time = Number(String(time).substr(0, 10))
        t = time + t
    }
    let storage = {
        expire: t,
        _data: data
    }
    return Taro.setStorage({
        key: key,
        data: storage
    })

}

// 取出缓存  -- _jujwt
export function GetData(key) {
    let storage = Taro.getStorageSync(key)
    if (!storage) {
        return null
    }
    if (storage.expire > 0) {
        let time = (new Date()).getTime()
        time = Number(String(time).substr(0, 10))
        if (time > storage.expire) {
            DelData(key)
            return null
        }
    }
    return storage._data
}

// 删除缓存
export function DelData(key) {
    return Taro.removeStorage({
        key: key
    })
}

export function CleanData(key) {
    return Taro.clearStorage()
}
