import { login, logout } from "../../api/login";
import { adminUsersRead } from "../../api/personCenter/personCenter";
import { addAuth, removeAuth } from "../../utils/auth";
import Lockr from "lockr";

const user = {
    state: {
        userInfo: null, // 用户信息
        //TODO 用户权限
        allAuth: ['/home', '/school/manager'],
        actionList:[]
    },

    mutations: {
        SET_USERINFO: (state, userInfo) => {
            state.userInfo = userInfo;
        },
        SET_ALLAUTH: (state, allAuth) => {
            state.allAuth = allAuth
        }
        //TODO 用户权限
    },

    actions: {
        // 登录
        Login({ commit }, userInfo) {
            userInfo.Account = userInfo.Account.trim();
            return new Promise((resolve, reject) => {
                login(userInfo)
                    .then(data => {
                        let r = data.Data
                        let token = r.Token
                        delete r.Token
                        Lockr.set("Token", token);
                        Lockr.set("loginUserInfo", r);

                        //Lockr.set("authList", data.auth);

                        addAuth(token);
                        commit("SET_USERINFO", r);
                        // commit('SET_ALLAUTH', data.auth)
                        // TODO  完成登录 读取权限
                        resolve(data);
                    })
                    .catch(error => {
                        reject(error);
                    });
            });
        },

        // 获取权限
        getAuth({ commit }) {
            return new Promise((resolve, reject) => {
                //TODO 处理权限方法
            });
        },

        // 获取用户信息
        GetUserInfo({ commit, state }) {
            return new Promise((resolve, reject) => {
                adminUsersRead()
                    .then(response => {
                        let r = response.Data
                        delete r.Token
                        commit("SET_USERINFO", r);
                        resolve(response);
                    })
                    .catch(error => {
                        reject(error);
                    });

            });

        },

        // 登出
        LogOut({ commit }) {
            return new Promise((resolve, reject) => {
                // logout()
                //     .then(() => {
                //         /** flush 清空localStorage .rm('authKey') 按照key清除 */

                //     })
                //     .catch(error => {
                //         reject(error);
                //     });
                removeAuth();
                resolve();
            });
        }
    }
};

export default user;