/**
 * 存储管理对象
 * 目标：将现有系统的所有需要存储的数据，统一管理
 *
 * @author terrfly
 * @site https://www.jeequan.com
 * @date 2022/04/13 07:18
 */
import appConfig from '@/config/appConfig.js'

const model = {
	// 获取和放置token
	token: (val, isDelete = false) => {
		if (isDelete) {
			appConfig.tokenVal = ''
			return uni.removeStorageSync(appConfig.tokenKey)
		}

		if (val) {
			// 有值，为放置
			appConfig.tokenVal = val
			uni.setStorageSync(appConfig.tokenKey, val)
		} else {
			// 否则为获取

			if (!appConfig.tokenVal) {
				//缓存取不到，获取应用本地信息
				appConfig.tokenVal = uni.getStorageSync(appConfig.tokenKey)
			}
			return appConfig.tokenVal
		}
	},

	// 已经登录的用户记录
	loggedInUser: (addUserName = null, removeUserName = null) => {
		let key = 'loggedInUserList'

		// 删除
		if (removeUserName) {
			let nameList = uni.getStorageSync(key) || []
			if (nameList.length <= 0) {
				//不存在数据
				return false
			}

			let hasUserIndex = nameList.indexOf(removeUserName)
			if (hasUserIndex >= 0) {
				nameList.splice(hasUserIndex, 1) //删除
				uni.setStorageSync(key, nameList)
			}

			return false
		}

		// 有新插入的记录
		if (addUserName) {
			let nameList = uni.getStorageSync(key) || []

			let hasUser = false
			for (let i = 0; i < nameList.length; i++) {
				if (nameList[i] == addUserName) {
					hasUser = true
				}
			}

			// 包含记录
			if (hasUser) {
				return false
			}

			// 最多存储 5 个
			if (nameList.length >= 5) {
				nameList.splice(0, 1) //删除第一个
			}
			nameList.push(addUserName)
			uni.setStorageSync(key, nameList)

			//获取
		} else {
			return uni.getStorageSync(key) || [] //默认空数组
		}
	},

	// 用户信息
	userInfo: (currentUserInfo) => {
		if (currentUserInfo) {
			// 仅保存基础数据
			let saveUser = {
				sysUserId: currentUserInfo.userNo,
				userType: currentUserInfo.userType,
				isEpUuser: currentUserInfo.userType === 3, //是否拓展员
				state: currentUserInfo.state,
				inviteCode: currentUserInfo.inviteCode,
				inviteCodeUrl: currentUserInfo.inviteCodeUrl,
				agtInviteCodeUrl: currentUserInfo.agtInviteCodeUrl,
                entIdList: currentUserInfo.entIdList,
			}
			uni.setStorageSync('currentUserInfo', saveUser) // 改变存储
		}

		return uni.getStorageSync('currentUserInfo')
	},

	// 项目环境变量：（测试、 生产的切换）
	env: (envMode) => {
		if (envMode) {
			uni.setStorageSync('currentEnvEnum', envMode) // 改变存储
		}
		return uni.getStorageSync('currentEnvEnum')
	},
	// 工作工具样式
	toolStyle: (style) => {
		if (style) {
			uni.setStorageSync('toolStyle', style) // 改变存储
		}
		return uni.getStorageSync('toolStyle')
	},
  uploadImgSize: (uploadImgSize) => {
    if (uploadImgSize) {
        uni.setStorageSync("uploadImgSize", uploadImgSize) // 存储 上传 图片大小限制
    }
  return uni.getStorageSync("uploadImgSize")
  },
}

export default model
