import { encrypt, decrypt } from '@/common/crypto.js'

// 在开发环境下不需要加密数据
const encryptFlag = process.env.NODE_ENV === 'production'

// 预设字段头
const prefix = 'HEHE_'

// 缓存有效期 默认有效期为15天
const expiredTime = '15 * 24 * 60 * 60 * 1000'


// 从缓存中读取数据（期限）
export function setStorage(key, value, options = {}) {
	if (!options.expiredTime) {
		options.expiredTime = expiredTime
	}
	const nowTime = Date.now()
	// 加密
	if (encryptFlag) {
		value = encrypt(value)
	}
	const payload = {
		expiredTime: nowTime + options.expiredTime,
		data: value
	}
	key = prefix + key
	uni.setStorageSync(key, payload)
}

// 将数据添加到缓存中（期限）
export function getStorage(key) {
	key = prefix + key
	const nowTime = Date.now()
	const payload = uni.getStorageSync(key)
	if (nowTime > payload.expiredTime) {
		uni.removeStorageSync(key)
		return null
	}

	// 解密
	if (encryptFlag) {
		payload.data = decrypt(payload.data)
	}

	return payload.data
}

const install = Vue => {
	Vue.prototype.$setStorage = setStorage
	Vue.prototype.$getStorage = getStorage
}

export default install
