import {
	api
} from '@/api/index'
import {
	getToken,
	setToken,
	removeToken
} from '@/utils/auth.js';

const user = {
	state: {
		// 用户认证token
		token: getToken(),
		// 用户ID
		userId: null,
		// 用户信息
		userInfo: {},
		// 测试信息
		testText: ''
	},

	mutations: {
		SET_TOKEN: (state, token) => {
			state.token = token
		},
		SET_USER_ID: (state, userId) => {
			state.userId = userId
		},
		SET_USERINFO: (state, userInfo) => {
			state.userInfo = userInfo
		},
		SET_TEST_TEXT: (state, testText) => {
			state.testText = testText
		},
	},

	actions: {
		// 用户登录
		Login({
			commit
		}, userInfo) {
			return new Promise(async (resolve, reject) => {
				// TODO: 用户登录处理，根据需求修改
				const res = await api.Login(userInfo);
				setToken(res.data.token);
				commit('SET_TOKEN', res.data.token);
				resolve(res);
			})
		},

		// 获取用户信息
		UserInfo({
			commit
		}) {
			return new Promise(async (resolve, reject) => {
				// TODO: 获取用户信息处理，根据需求修改
				try {
					const res = await getUserInfo();
					setUserId(res.data.userId);
					commit('SET_USER_ID', res.data.userId);
					commit('SET_USERINFO', res.data);
					resolve(res);
				} catch (e) {
					reject(e);
				}
			})
		},

		// 退出登录
		Logout({
			commit
		}) {
			return new Promise((resolve, reject) => {
				removeToken();
				removeUserId();
				commit('SET_TOKEN', null);
				commit('SET_USER_ID', null);
				resolve()
			})
		}

	}
}

export default user
