import {
    cacheStorage,
} from '@/utils'
import router from '_platform/router'

/**
 * 权限 store模块
 */
export default new Vuex.Store({
    state: {
        token: cacheStorage.getItem(process.env.VUE_APP_AUTH_TOKEN),
        // 当前用户信息
        user: cacheStorage.getItem(process.env.VUE_APP_AUTH_TOKEN) ? JSON.parse(cacheStorage.getItem(process.env.VUE_APP_USER)) : null,
    },
    getters: {

    },
    mutations: {
        setToken (state, token) {
            state.token = token
        },
        setUser (state, user) {
            state.user = user
        },
        /**
         * 登出
         * @param state
         */
        layout (state) {
            // 清除缓存， 认证token,用户信息,然后跳转到登录页面
            cacheStorage.clear()
            state.token = null
            state.user = null
            router.push({
                name: 'login'
            })
        }
    },
    actions: {
        setToken (context, token) {
            context.commit('setToken', token)
            cacheStorage.setItem(process.env.VUE_APP_AUTH_TOKEN, token)
        },
        setUser (context, user) {
            context.commit('setUser', user)
            cacheStorage.setItem(process.env.VUE_APP_USER, JSON.stringify(user))
        },
        logout (context) {
            context.commit('layout')
        },
    }
})
