import config from '@/config/index.config.js'

import {
	getToken,
	setToken,
	removeToken,
	getUserInfo,
	setUserInfo,
	removeUserInfo
} from '@/utils/auth'

import {
	login,
	getInfo
} from '@/api/login.js';

const baseUrl = config.requestUrl

const user = {
	state: {
		token: getToken(),
		userInfo: getUserInfo() ? JSON.parse(getUserInfo()) : {},
	},
	mutations: {
		SET_TOKEN: (state, token) => {
			state.token = token
		},
		SET_USER_INFO: (state, userInfo) => {
			state.userInfo = userInfo;
			setUserInfo(JSON.stringify(userInfo))
		}
	},

	actions: {
		// 本地登录
		Login({
			commit,
			dispatch
		}, params) {
			return new Promise((resolve, reject) => {
				login(params).then(res => {
					setToken(res.token)
					commit('SET_TOKEN', res.token)
					dispatch('GetInfo') //调取用户信息
					resolve()
				}).catch(error => {
					reject(error)
				})
			})
		},
		// 本地登录获取用户信息
		GetInfo({
			commit,
			state
		}) {
			return new Promise((resolve, reject) => {
				getInfo().then(res => {
					const user = res.data
					commit('SET_USER_INFO', JSON.stringify(user))
					resolve(res)
				}).catch(error => {
					reject(error)
				})
			})
		},
		
		LogOut({commit,state}){
			// TODO:调用退出登录接口
			commit('SET_TOKEN','');
			commit('SET_USER_INFO', JSON.stringify(user))
		},
	}
}

export default user