import { logout } from "@/api/login";
import { setLoginedUser, getLoginedUser, removeLoginedUser } from "@/utils/auth";
import _ from "lodash"
let loginedUser = getLoginedUser()
const user = {
    state: _.assign({
        accessToken: ""
    }, loginedUser),

    mutations: {
        SET_USER: (state, user) => {
            for(var k in user){
                state[k] = user[k]
            }
        },
        REMOVE_USER: (state, user) => {
            for(var k in state){
                delete state[k]
            }
        },
    },

    actions: {
        SetLoginUser({ commit, state }, user) {
            user = _.assign({}, getLoginedUser(), user)
            setLoginedUser(user)
            commit('SET_USER', user)
        },
        // 登出
        LogOut({ commit, state }) {
            return new Promise((resolve, reject) => {
                logout({
                    token: state.user.accessToken
                })
                    .then(() => {
                        commit('REMOVE_USER', '')
                        removeLoginedUser()
                        resolve();
                    })
                    .catch(error => {
                        reject(error);
                    });
            });
        },
    }
};

export default user;
