import { login } from '@/api/user'
import { setToken } from '@/utils/auth'

const user = {
    state: {
        token: '',
        name: '',
        avatar: '',
        role: []
    },
    mutations: {
        SET_TOKEN: (state, token) => {
            state.token = token;
        },
        SET_NAME: (state, name) => {
            state.name = name;
        },
        SET_AVATAR: (state, avatar) => {
            state.avatar = avatar;
        },
        SET_ROLES: (state, roles) => {
            state.roles = roles;
        }
    },
    actions: {
        //登陆
        login({ commit }, userInfo) {
            const { username, password } = userInfo;
            return new Promise((resolve, reject) => {
                login({ username: username.trim(), password: password }).then(response => {
                    const { data } = response;
                    commit('SET_TOKEN', data.token);
                    setToken(data.token);
                    resolve(data);
                }).catch(error => {
                    console.log('登陆失败');
                    reject(error);
                })
            })
        },
    }
}
export default user