/**
 * 缓存数据优化
 * var cache = require('utils/cache.js');
 * import cache from '../cache'
 * 使用方法 【
 *     一、设置缓存
 *         string    cache.put('k', 'string你好啊');
 *         json      cache.put('k', { "b": "3" }, 2);
 *         array     cache.put('k', [1, 2, 3]);
 *         boolean   cache.put('k', true);
 *     二、读取缓存
 *         默认值    cache.get('k')
 *         string    cache.get('k', '你好')
 *         json      cache.get('k', { "a": "1" })
 *     三、移除/清理  
 *         移除: cache.remove('k');
 *         清理：cache.clear(); 
 * 】
 * @type {String}
 */
module.exports = {
	/*
	 * 缓存前缀 
	 */
	postfix:'twinkly_',
	/**
	 * 设置缓存 
	 * @param  {[type]} k [键名]
	 * @param  {[type]} v [键值]
	 * @param  {[type]} e [过期时间：单位秒]
	 * @param  {[type]} s 异步回调
	 */
    set:function(k, v, e, s){
		var that=this;
		var e=e || 0;
		if(e>0) e=Date.parse(new Date()) + e*1000;
		if(v){
			
			if(typeof s == 'function'){
				wx.setStorage({
					key: k,
					data: v,
					success() {
						wx.setStorageSync(that.postfix + k, e)
						s();
					}
				});
			}else{
				wx.setStorageSync(that.postfix + k, e)
				wx.setStorageSync(k, v)
			}
		}else{
			that.remove(k);
		}
	},
	/**
	 * 获取缓存 
	 * @param  {[type]} k   [键名]
	 */
    get:function(k){
		var that=this,
		deadtime=wx.getStorageSync(that.postfix + k),
		data=wx.getStorageSync(k);
		if(deadtime>0){
			var now=Date.parse(new Date());
			if(deadtime<now){
				return data;
			}else{
				return false;
			}
		}else{
			return data;
		}
	},
	/**
	 * 清理指定缓存
	 * @return {[type]} [description]
	 */
    remove:function(k){
		var that=this;
		wx.removeStorageSync(that.postfix + k);
		wx.removeStorageSync(k);
	},
	/**
	 * 获取缓存并销毁
	 * @param  {[type]} k   [键名]
	 * @param  {[type]} def [获取为空时默认]
	 */
	getonce:function(k){
		var that=this;
		var data=that.get(k);
		that.remove(k);
		return data;
	},
	/**
	 * 清理所有缓存
	 * @return {[type]} [description]
	 */
    clear:function(){
		wx.clearStorageSync();
	}
}