import {constant} from './constant'

// 存储变量名
let storageKey = 'storage_data'

// 存储节点变量名
let storageNodeKeys = [constant.avatar, constant.name, constant.roles, constant.permissions, constant.username]

const storage = {
  set: function(key:string, value:any):void {
    if (storageNodeKeys.indexOf(key) != -1) {
	  let data = ref(uni.getStorageSync(key));
      let tmp:UTSJSONObject|null = data.value!=='' && data.value!==null? uni.getStorageSync(storageKey) as UTSJSONObject|null : null
      let tmpJson:UTSJSONObject = (tmp != null ? JSON.parseObject(JSON.stringify(tmp)) : {}) as UTSJSONObject
	  tmpJson.set(key,value)
      uni.setStorageSync(storageKey, tmpJson)  
    }
  },
  get: function(key:string):any|null {
	let data = ref(uni.getStorageSync(key));  
    let storageData:UTSJSONObject|null = data.value!=='' && data.value!==null? uni.getStorageSync(storageKey) as UTSJSONObject|null : null
	if(storageData != null){
		let storeJson:UTSJSONObject=JSON.parseObject(JSON.stringify(storageData)) as UTSJSONObject
		return storeJson.get(key)
	}else{
		return null
	}
  },  
  cleanAll: function():void {	  
    uni.removeStorageSync(storageKey)
  },
  remove: function(key:string):void {
    let storageData:UTSJSONObject|null = uni.getStorageSync(storageKey) as UTSJSONObject|null
	if(storageData!=null){
		let storeMap=storageData.toMap()
		storeMap.delete(key)
		storageData=JSON.parseObject(JSON.stringify(storeMap)) as UTSJSONObject
		uni.setStorageSync(storageKey, storageData)
	}
    
  }
}

export default storage
