import api from '@/common/request.api.js'
import authtoken from "@/utils/auth.token.js"
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
	state: {
		token: authtoken.getToken(),
		hasLogin: false,
		userinfo: {}
	},
	mutations: {
		SET_TOKEN: (state, token) => {
			state.token = token
			authtoken.setToken(token)
		},
		SET_HASLOGIN: (state, hasLogin) => {
			state.hasLogin = hasLogin
		},
		SET_USERINFO: (state, userinfo) => {
			state.userinfo = userinfo
		}
	},
	getters: {
		token: state => state.token,
		hasLogin: state => state.hasLogin,
		userinfo: state => state.userinfo,
	},
	actions: {
		login({
			commit
		}, loginUserInfo) {
			return new Promise((resolve, reject) => {
				api.login(loginUserInfo).then(res => {
					console.log('login-result-info:', res)
					commit('SET_HASLOGIN', true)
					commit('SET_TOKEN', res.token)
					commit('SET_USERINFO', {
						userid: '123456',
						name: res.name
					})
					resolve(res)
				}).catch(err => {
					reject(err)
				})
			})
		},
		logined({
			commit
		}, loginUserInfo) {
			return new Promise((resolve, reject) => {
				commit('SET_HASLOGIN', true)
				commit('SET_TOKEN', loginUserInfo.token)
				commit('SET_USERINFO', {
					userid: '123456',
					name: loginUserInfo.name
				})
				resolve()
			})
		},
		logout({
			commit,
			state
		}) {
			return new Promise((resolve, reject) => {
				commit('SET_HASLOGIN', false)
				commit('SET_TOKEN', null)
				commit('SET_USERINFO', null)
				resolve()
			})
		}
	}
})

export default store
