import { login } from '@/api/user'
import md5 from 'js-md5';
import router from '@/router/index'
export const user = {
    namespaced: true,
    state: {
        userInfo: {
            uuid: "",
            nickName: "",
            headerImg: "",
            authority: "",
        },
        token: "",
    },
    mutations: {
        setUserInfo(state, userInfo) {
            // 这里的 `state` 对象是模块的局部状态
            state.userInfo = userInfo
        },
        setToken(state, token) {
            // 这里的 `state` 对象是模块的局部状态
            state.token = token
        },
        LoginOut(state) {
            state.userInfo = {}
            state.token = ""
            localStorage.uid = ""
            localStorage.token = ""
            sessionStorage.clear()
            router.push({ name: 'login', replace: true })
        },
        ResetUserInfo(state, userInfo = {}) {
            state.userInfo = {...state.userInfo,
                ...userInfo
            }
        }
    },
    actions: {
        async LoginIn({ commit, dispatch, rootGetters, getters }, loginInfo) {
			let param = Object.assign( {}, loginInfo )
			let mpass = param.password.replace(/(^\s*)|(\s*$)/g, "");
            param.password = md5( mpass );
            const res = await login(param)
            if (res.code == 200) {
                commit('setUserInfo', res.data)
                commit('setToken', res.data.token)
                await dispatch('router/SetAsyncRouter', {}, { root: true })
                const asyncRouters = rootGetters['router/asyncRouters']
                router.addRoutes(asyncRouters)
	
                router.push({ name: 'exam_train' })
             
                return true
            }
        },
        async LoginOut({ commit }) {
            commit("LoginOut")
        }
    },
    getters: {
        userInfo(state) {
            return state.userInfo
        },
        token(state) {
            return state.token
        },

    }
}