import MD5 from './md5.js' 
export default {
	/**
	 * 保存数据
	 * @param {Object} key 键
	 *  @param {Object} value 值
	 * @param {Object} time 缓存时间 单位s
	 */
	set(key,value,time){ 
		if(typeof time !='undefined' && time >0){
			let time_key = key+'---time';
			let nowTime = new Date().getTime();
			let overTime = nowTime + time*1000;
			localStorage.setItem(time_key,overTime);
		}
		localStorage.setItem(key,JSON.stringify(value));
	},
	get(key){
		//判断是否有时间
		let time_key = key+'---time';
		let overTime =localStorage.getItem(time_key); 
		if(overTime){
			let nowTime = new Date().getTime();
			//console.log(key,overTime,nowTime)
			if(nowTime >= overTime){
				//时间结束 清楚
				localStorage.removeItem(time_key)
				localStorage.removeItem(key);
				return null;
			}
		}
		let result =localStorage.getItem(key);
		if(result){
			return JSON.parse(result)
		}
		return null;
	},
	/**
	 * 加密保存
	 * @param {Object} key 
	 * @param {Object} value
	 * @param {Object} time 存储时间 s 秒
	 */
	setEncrypt(key,value,time){
		let _time = new Date().getTime();
		let _data = JSON.stringify(value);
		let _random = parseInt(Math.random() * 10000);
		let _verify = MD5(_time+'') + MD5(_data) + MD5(_random+"");
		let save={
			data:_data,
			time:_time,
			random:_random
		}
		if(time && time >0){ 
			let end= parseInt(time)*1000 + parseInt(_time);
			
			_verify += MD5(end+'');
			save['end']=end;
		}
		_verify = MD5(_verify);
		save['verify']=_verify;
		localStorage.setItem(key,JSON.stringify(save))
	},
	getEncrypt(key){
		let save = localStorage.getItem(key);
		if(!save){
			return null;
		}
		let {time,data,random,end,verify} = JSON.parse(save);
		if(!time || !data || !random ||!verify){
			return null;
		}
		let _verify = MD5(time+'') + MD5(data) + MD5(random+"");
		if(end){
			_verify += MD5(end+"")
		}
		if(MD5(_verify)!=verify){
			console.log("数据污染")
			return null;
		}
		if(end && end < new Date().getTime()){
			console.log("过期了")
			return null;
		}
		return JSON.parse(data);		
	}
}