import cacheManager from "@/utils/cacheManager.js"

const TokenKey = 'Mta-UserCache'

export function useUserCache() {
	function saveCache() {
		let pageId, key, value;
		if (arguments.length === 3) {
			pageId = arguments[0];
			key = arguments[1];
			value = arguments[2];
		} else if (arguments.length === 2) {
			pageId = arguments[0];
			key = 'default';
			value = arguments[1];
		} else {
			console.log('saveCache 参数非法');
			return;
		}

		const auth = cacheManager.get('auth');
		// console.log('auth:', auth)
		if (!auth) {
			throw new Error('用户未登录！')
			return;
		}
		const userId = auth.userId;
		// console.log('userId:', userId)
		if (!userId) {
			throw new Error('数据异常用户Id异常！')
			return;
		}
		
		let pageData = uni.getStorageSync(TokenKey);
		if (!pageData) {
			pageData = {};
		}
		if (!pageData[userId]) {
			pageData[userId] = {};
		}
		if (!pageData[userId][pageId]) {
			pageData[userId][pageId] = {};
		}
		let oriVal = pageData[userId][pageId][key];
		if (oriVal !== null && !Array.isArray(oriVal) && typeof oriVal === 'object') {
			Object.assign(oriVal, value);
			pageData[userId][pageId][key] = oriVal;
		} else {
			pageData[userId][pageId][key] = value;
		}
		pageData[userId][pageId]['markTime'] = new Date().getTime();
		uni.setStorageSync(TokenKey, pageData)
	}

	function getCache() {
		let pageId, key;
		if (arguments.length === 2) {
			pageId = arguments[0];
			key = arguments[1];
		} else if (arguments.length === 1) {
			pageId = arguments[0];
			key = 'default';
		} else {
			console.log('getCache 参数非法');
			return;
		}

		const auth = cacheManager.get('auth');
		if (!auth) {
			throw new Error('用户未登录！')
			return;
		}
		const userId = auth.userId;
		if (!userId) {
			throw new Error('数据异常用户Id异常！')
			return;
		}

		let pageData = uni.getStorageSync(TokenKey);
		if (!pageData || !pageData[userId] || !pageData[userId][pageId]) {
			return null;
		}
		return pageData[userId][pageId][key];
	}

	function removeCache() {
		let pageId, key;
		if (arguments.length === 2) {
			pageId = arguments[0];
			key = arguments[1];
		} else if (arguments.length === 1) {
			pageId = arguments[0];
		} else {
			console.log('removeCache 参数非法');
			return;
		}

		const auth = cacheManager.get('auth');
		if (!auth) {
			throw new Error('用户未登录！')
			return;
		}
		const userId = auth.userId;
		if (!userId) {
			throw new Error('数据异常用户Id异常！')
			return;
		}

		if (pageId) {
			let pageData = uni.getStorageSync(TokenKey);
			if (!pageData) {
				return;
			}
			if (!pageData[userId]) {
				return;
			}
			if (arguments.length === 1) {
				delete pageData[userId][pageId];
				uni.setStorageSync(TokenKey, pageData)

			} else if (arguments.length === 2) {
				if (!pageData[userId][pageId]) {
					return;
				}
				delete pageData[userId][pageId][key];
				uni.setStorageSync(TokenKey, pageData)
			}
		}
	}

	return {
		saveCache,
		getCache,
		removeCache
	}
}