import {isAllNull} from "js-fast-way"
import website from '@/config/index'

//获取缓存
export const getStorage = (key, debug = false) => {
    let obj = uni.getStorageSync(website.key + '-' + key), content;
    if (isAllNull(obj)) {
        return '';
    }
    try {
        obj = JSON.parse(obj);
    } catch {
        return obj;
    }
    if (debug) {
        return obj;
    }
    if (obj.dataType === 'string') {
        content = obj.content;
    } else if (obj.dataType === 'number') {
        content = Number(obj.content);
    } else if (obj.dataType === 'boolean') {
        content = Boolean(obj.content);
    } else if (obj.dataType === 'object') {
        content = obj.content;
    }
    return content ?? '';
}

//保存缓存
export const setStorage = (key, value) => {
    try {
        uni.setStorageSync(website.key + '-' + key, JSON.stringify({
            dataType: typeof (value),
            content: value ?? '',
            datetime: new Date().getTime()
        }));
    } catch (e) {
        uni.showToast({
            title: '本地数据缓存失败',
            icon: 'none'
        });
    }
}

//删除缓存
export const delStorage = (key) => {
    try {
        uni.removeStorageSync(website.key + '-' + key);
    } catch {
    }
}


//清理缓存
export const clearStorage = () => {
    try {
        uni.clearStorageSync();
    } catch {}
}
