import {
	getInfo,
	login,
	loginPhone,
	logout
} from '@/api/user'
import {
	getToken,
	removeToken,
	setToken
} from '@/utils/auth'
import {
	EventBus,
	Events
} from '@/utils/event-bus'
import store from '@/store'

const user = {
	state: {
		token: getToken(),
		user: {}
	},

	mutations: {
		SET_TOKEN: (state, token) => {
			state.token = token
			setToken(token)
		},
		SET_USER: (state, user) => {
			state.user = user
			// 触发菜单更新
			EventBus.$emit(Events.USER_INFO_UPDATE, {
				'user': user
			})
		},
		SET_PHONE: (state, phone) => {
			state.phone = phone
		}
	},

	actions: {
		// 短信登录
		loginPhone({
			commit,
			dispatch
		}, userInfo) {
			return new Promise((resolve, reject) => {
				loginPhone(userInfo).then(response => {
					const data = response.data
					commit('SET_TOKEN', data.token)
					commit('SHOW_LOADING')
					dispatch('getInfo')
					resolve()
				}).catch(error => {
					reject(error)
				})
			})
		},
		// 登录
		login({
			commit,
			dispatch,
			state
		}, userInfo) {
			userInfo.username = userInfo.username.trim()
			return new Promise((resolve, reject) => {
				login(userInfo).then(response => {
					const data = response.data
					commit('SET_TOKEN', data.token)
					commit('SHOW_LOADING')
					dispatch('getInfo')
					resolve()
				}).catch(error => {
					reject(error)
				})
			})
		},

		// 获取用户信息
		getInfo({
			commit,
			state
		}, params) {
			return new Promise((resolve, reject) => {
				params = params || {}
				getInfo(params).then(response => {
					const data = response.data
					commit('SET_USER', data)
					store.commit('HIDE_LOADING')
					resolve(response)
				}).catch(error => {
					reject(error)
					store.commit('HIDE_LOADING')
				})
			})
		},
		// 登出
		logout({
			commit,
			dispatch,
			state
		}) {
			return new Promise((resolve, reject) => {
				logout().then(() => {
					resolve()
					dispatch('fedLogOut')
				}).catch(error => {
					reject(error)
					dispatch('fedLogOut')
				})
			})
		},

		// 前端 登出
		fedLogOut({
			commit
		}) {
			return new Promise(resolve => {
				removeToken()
				commit('SET_TOKEN', '')
				resolve()
			})
		}
	}
}

export default user