import Vue from 'vue';
import { ACCESS_TOKEN } from '@/store/mutation-types';
import { welcome } from '@/utils/util';

const user = {
	state: {
		token: '',
		name: '',
		welcome: '',
		avatar: '',
		roles: [],
		info: {}
	},

	mutations: {
		SET_TOKEN: (state, token) => {
			state.token = token;
		},
		SET_NAME: (state, { name, welcome }) => {
			state.name = name;
			state.welcome = welcome;
		},
		SET_AVATAR: (state, avatar) => {
			state.avatar = avatar;
		},
		SET_ROLES: (state, roles) => {
			state.roles = roles;
		},
		SET_INFO: (state, info) => {
			state.info = info;
		}
	},

	actions: {
		// 登录
		Login({ commit }) {
			return new Promise(resolve => {
				const result = {
					id: '3DDbd2b1-e3F2-EbfA-52bD-D4cc1657C4Fb',
					name: 'Frank Smith',
					username: 'admin',
					password: '',
					avatar: 'https://gw.alipayobjects.com/zos/rmsportal/jZUIxmJycoymBprLOUbT.png',
					status: 1,
					telephone: '',
					lastLoginIp: '27.154.74.117',
					lastLoginTime: 1534837621348,
					creatorId: 'admin',
					createTime: 1497160610259,
					deleted: 0,
					roleId: 'admin',
					lang: 'zh-CN',
					token: '4291d7da9005377ec9aec4a71ea837f'
				};
				Vue.ls.set(ACCESS_TOKEN, result.token, 12 * 60 * 60 * 60 * 1000);
				commit('SET_TOKEN', result.token);
				resolve();
			});
		},

		// 获取用户信息
		GetInfo({ commit }) {
			return new Promise((resolve, reject) => {
				const response = MockUser.info();
				const result = response.result;
				if (result.role && result.role.permissions.length > 0) {
					const role = result.role;
					role.permissions = result.role.permissions;
					role.permissions.map(per => {
						if (per.actionEntitySet !== null && per.actionEntitySet.length > 0) {
							const action = per.actionEntitySet.map(action => {
								return action.action;
							});
							per.actionList = action;
						}
					});
					role.permissionList = role.permissions.map(permission => {
						return permission.permissionId;
					});
					commit('SET_ROLES', result.role);
					commit('SET_INFO', result);
				} else {
					reject(new Error('getInfo: roles must be a non-null array !'));
				}

				commit('SET_NAME', {
					name: result.name,
					welcome: welcome()
				});
				commit('SET_AVATAR', result.avatar);
				resolve({
					result
				});
			});
		},

		// 登出
		Logout({ commit }) {
			return new Promise(resolve => {
				commit('SET_TOKEN', '');
				commit('SET_ROLES', []);
				// localStorage.setItem('menuList', '');
				// localStorage.setItem('buttonList', '');
				Vue.ls.remove(ACCESS_TOKEN);
				resolve();
			});
		}
	}
};

export default user;
