import {
	data
} from "../tuniao-ui/libs/mixin/mixin"


class CACHE {
	constructor(data) {
		if (data === '' || data === null || data === undefined) {
			throw (new Error('请传入缓存name值:index | {name:index}'))
			return
		}
		if (typeof data === 'string') {
			this._name = data
			Object.defineProperty(this, '_name', {
				writable: false
			});
		} else {
			if (!data.name && !data._name) {
				throw (new Error('请传入缓存name值:index | {name:index}'))
				return
			}
			for (let i in data) {
				this[i] = data[i]
				const canWrite = i.slice(0, 1) !== '_'
				Object.defineProperty(this, i, {
					writable: canWrite,
					writable: canWrite
				});
			}
		}

	}
	isEmpty(){
		return Object.keys(this).length>=2?false:true;
	}
	get(key) {
		return this[key]
	}
	set(key, val) {
		this[key] = val
		uni.setStorageSync(this._name, this)
	}
	clear() {
		Object.keys(this).map(v => {
			if (v.slice(0, 1) !== '_') {
				this[v] = null
			}
		})
		uni.removeStorageSync(this._name)
	}
}

export const $cache_index = new CACHE({
	_name: 'CACHE_index',
	...uni.getStorageSync('CACHE_index')
})

export const $cache_video = new CACHE({
	_name: 'CACHE_video',
	...uni.getStorageSync('CACHE_video')
})

export const $cache_renwu = new CACHE({
	_name: 'CACHE_renwu',
	...uni.getStorageSync('CACHE_renwu')
})

export const $cache_chasingDrama = new CACHE({
	_name: 'CACHE_chasingDrama',
	...uni.getStorageSync('CACHE_chasingDrama')
})

export const $cache_user = new CACHE({
	_name: 'CACHE_user',
	...uni.getStorageSync('CACHE_user')
})

class CACHE_config extends CACHE {
	constructor(data) {
		super(data)
		for (let i in data) {
			if(i!=='_name'){
				uni.setStorageSync(i,data[i])
			}
		}
	}
	set(key, val) {
		this[key] = val
		uni.setStorageSync(this._name, this)
	}
	set(key, val) {
		this[key] = val
		uni.setStorageSync(key, val)
		uni.setStorageSync(this._name, this)
	}
	clear() {
		Object.keys(this).map(v => {
			if (v.slice(0, 1) !== '_') {
				this[v] = null
			}
		})
		uni.removeStorageSync(this._name)
	}
}
export const $cache_config = new CACHE_config({
	_name: 'CACHE_config',
	...uni.getStorageSync('CACHE_config')
})

const $cache={
	index:$cache_index,
	video:$cache_video,
	renwu:$cache_renwu,
	chasingDrama:$cache_chasingDrama,
	user:$cache_user,
	config:$cache_config
}
export function cacheClearAll() {
	for(let i in $cache){
		$cache[i].clear()
	}
}
export function cacheClear(arr){
	if(typeof arr==='string'&&$cache[arr]){
		$cache[arr].clear()
	}
	if(Array.isArray(arr)){
		for(let i in arr){
			const key=[arr[i]]
			if($cache[key]){
				$cache[key].clear()
			}
		}
	}
}