import globalVariable from "../global-variable";

/**
 * 本地存储工具类
 */
export class LocalStorageUtil {

    static setItem(key, value) {
        let v = null;
        if (typeof (value) == 'object') {
            v = JSON.stringify(value);
        } else {
            v = value;
        }
        try {
            key = globalVariable.localStoragePrefix + key;
            console.log('存储【' + key + '】值: ', v);
            uni.setStorageSync(key, v);
        } catch (e) {
            console.log('存储【' + key + '】失败');
        }
        return value
    }

    static getItem(key) {
        key = globalVariable.localStoragePrefix + key;
        let value = null;
        try {
            value = uni.getStorageSync(key);
            if (value) {
                value = JSON.parse(value);
            } else {
                return;
            }
            console.log('获取【' + key + '】值: ', value);
        } catch (e) {
            console.log('存储的值不是对象类型: ', value);
        }
        return value;
    }

    static removeItem(key) {
        try {
            key = globalVariable.localStoragePrefix + key;
            uni.removeStorageSync(key);
            console.log('移除【' + key + '】成功')
        } catch (e) {
            console.log('移除【' + key + '】失败')
        }
    }

    static setOrGetItem(key, value) {
        if (value && (JSON.stringify(value) + '') != '{}') {
            return this.setItem(key, value)
        } else {
            return this.getItem(key)
        }
    }

    static setOrGetQueryParams(page, params) {
        const _self = this
        // let className = page.__proto__.constructor.name;  // 返回上一级时手机端this还是子对象，导致返回上级页面时获取的是子页面的数据，导致错误。
        let className = page
        console.log(className + '导航参数---------------' + JSON.stringify(params))
        let result = _self.setOrGetItem(`navParams${className}`, params)
        if (!result) {
            result = {}
        }
        return result
    }
}
