import userApi from '@/api/modules/user.js'

const user = {
	state: {
		tokenObj: {
			token: '',
			date: 0
		},
		jpcjUserInfo: {

		},
		userInfo: '',
		name: '',
		avatar: '',
		roles: [],
		permissions: [],
		lightConfig: {
			interval: 5,
			directives: 5,
			isTipSound: false,
			type: 0,
			typelist: [{
				name: "随机抽取多条指令"
			}, {
				name: "随机抽取一个组合"
			}]
		}
	},
	mutations: {
		SET_TOKENOBJ: (state, tokenObj) => {
			state.tokenObj = tokenObj
		},
		//jpcjUserInfo
		SET_JPCJUSERINFO(state, jpcjUserInfo) {
			state.jpcjUserInfo = jpcjUserInfo
		},
		REFRESH_TOKEN(state) {
			if (state.tokenObj.token !== '')
				state.tokenObj.date = new Date().getTime()
		},
		SET_USERINFO: (state, userInfo) => {
			state.userInfo = userInfo
		},
		SET_NAME: (state, name) => {
			state.name = name
		},
		SET_AVATAR: (state, avatar) => {
			state.avatar = avatar
		},
		SET_ROLES: (state, roles) => {
			state.roles = roles
		},
		SET_PERMISSIONS: (state, permissions) => {
			state.permissions = permissions
		},
		SET_LIGHTCONFIG: (state, lightConfig) => {
			state.lightConfig = lightConfig
		}
	},
	actions: {
		/**
		 * 用户登录储存token
		 * @param {Object} store
		 */
		async Login(store) {
			wx.showLoading({
				title: '登陆中...',
			})
			let res = await userApi.login()
			if (res.data) {
				store.commit('SET_TOKENOBJ', {
					token: res.data.token,
					date: new Date().getTime()
				})
			}

			// store.commit('SET_JPCJUSERINFO',res.data.jpcjUserInfo)
			wx.hideLoading()
			return res
		},
		async getToken(store) {
			let tokenObj = store.state.tokenObj
			if (new Date().getTime() - tokenObj.date < 1000 * 60 * 28) {
				return tokenObj.token
			} else {
				let res = await store.dispatch("Login")
				if (res.data) {
					store.commit('SET_TOKENOBJ', {
						token: res.data.token,
						date: new Date().getTime()
					})
				}

				return res.data&&res.data.token
			}
		},
		/**
		 * 获取用户信息
		 * @param {Object} store
		 */
		async GetInfo(store) {
			let res = await userApi.getInfo()
			uni.setStorageSync("userInfo", res.data);
			store.commit('SET_USERINFO', res.data)
			return res
		}
	}
}

export default user
