/**
 * Created by rockyl on 2019-01-04.
 */

/**
 * 本地存储
 */
export default class LocalStorage {
	ID: string;

	constructor(ID: string) {
		this.ID = ID;
	}

	private getName(key: string, prefix: string = null): string {
		return (prefix || !this.ID || this.ID == '' ? prefix : this.ID) + '_' + key;
	}

	/**
	 * 获取数据
	 * @param key
	 * @param prefix
	 */
	getItem(key: string, prefix: string = null): string {
		return localStorage.getItem(this.getName(key, prefix));
	}

	/**
	 * 设置数据
	 * @param key
	 * @param value
	 * @param prefix
	 */
	setItem(key: string, value: string, prefix: string = null) {
		localStorage.setItem(this.getName(key, prefix), value);
	}

	/**
	 * 获取json数据对象
	 * @param key
	 * @param defaultObj
	 * @param prefix
	 */
	getItemObj(key: string, defaultObj: any = null, prefix: string = null): any {
		let result: any;
		try {
			result = JSON.parse(this.getItem(key, prefix));
		} catch (e) {

		}
		if (!result) {
			result = defaultObj;
		}
		return result;
	}

	/**
	 * 设置json数据对象
	 * @param key
	 * @param itemObj
	 * @param prefix
	 */
	setItemObj(key: string, itemObj: any, prefix: string = null) {
		this.setItem(key, JSON.stringify(itemObj), prefix);
	}
}
