/**
 * 用户基本信息
 */
import {
	getUserInfo,
	updateUserInfo
} from '@/api/user';

export default {
	state: () => ({
		userId: '',
		gender: '未知',
		avatar: 'http://gogs.chelvc.com/avatars/6',
		nickname: '默认用户',
		invitationCode: '', //邀请码
	}),
	mutations: {
		SET_USER_ID(state, userId) {
			state.userId = userId
		},
		SET_GENDER(state, gender) {
			state.gender = gender
		},
		SET_AVATAR(state, avatar) {
			state.avatar = avatar
		},
		SET_NICKNAME(state, nickname) {
			state.nickname = nickname
		},
		SET_INVITATIONCODE(state, invitationCode) {
			state.invitationCode = invitationCode;
		},
	},
	actions: {
		// 获取用户基本信息
		GetUserInfo({
			commit
		}) {
			return new Promise((resolve, reject) => {
				getUserInfo()
					.then(res => {
						commit('SET_USER_ID', res.data.id);
						commit('SET_GENDER', res.data.gender);
						commit('SET_AVATAR', res.data.avatar);
						commit('SET_NICKNAME', res.data.nickname);
						resolve(res);
					})
					.catch(err => {
						reject(err);
					});
			});
		},
		// 更新用户基本信息
		UpdateUserInfo({
			dispatch,
			commit
		}, payload) {
			return new Promise((resolve, reject) => {
				updateUserInfo(payload)
					.then(async res => {
						await dispatch('GetUserInfo')
						uni.showToast({
							title: '修改成功',
							icon: 'success',
						})
						resolve(res)
					})
					.catch(err => {
						uni.showToast({
							title: '修改失败',
							icon: 'error',
						})
						reject(err)
					})
			});
		}
	}
}