import { loginByUsername, logout, getUserInfo, getPermissions, getOAuthTokeByCode } from "@/api/login";
import { getToken, setToken, removeToken, setUserName, removeUserName } from "@/utils/auth";

const { getSetting, getSettingBool } = window.systemParamsUtils;
const user = {
    state: {
        user: "",
        status: "",
        code: "",
        token: getToken(),
        name: "",
        avatar: "",
        introduction: "",
        roles: [],
        permissions: [],
        info: {},
        setting: {
            articlePlatform: []
        }
    },

    mutations: {
        SET_INFO: (state, info) => {
            state.info = info;
        },
        SET_CODE: (state, code) => {
            state.code = code;
        },
        SET_TOKEN: (state, token) => {
            state.token = token;
        },
        SET_INTRODUCTION: (state, introduction) => {
            state.introduction = introduction;
        },
        SET_SETTING: (state, setting) => {
            state.setting = setting;
        },
        SET_STATUS: (state, status) => {
            state.status = status;
        },
        SET_NAME: (state, name) => {
            state.name = name;
        },
        SET_AVATAR: (state, avatar) => {
            state.avatar = avatar;
        },
        SET_ROLES: (state, roles) => {
            state.roles = roles;
        },
        SET_PERMISSIONS: (state, permissions) => {
            state.permissions = permissions;
        }
    },

    actions: {
        // 用户名登录
        LoginByUsername({ commit }, userInfo) {
            const username = userInfo.username.trim();
            return new Promise((resolve, reject) => {
                loginByUsername(username, userInfo.password)
                    .then(({ data }) => {
                        setUserName(data.name);
                        resolve();
                    })
                    .catch(error => {
                        reject(error);
                    });
            });
        },

        // 获取用户信息
        GetUserInfo({ commit, state }) {
            return new Promise((resolve, reject) => {
                let params = {};
                if (getSettingBool("IS_OAUTH2")) {
                    params["access_token"] = getToken();
                    params["appCode"] = getSetting("APP_CODE");
                }
                getUserInfo(params)
                    .then(res => {
                        // const data = process.env.NEED_LOGIN ? res : userInfo;
                        const data = res.data;

                        //TODO 用户信息缓存，等用户信息出来后做
                        if (data.name === undefined) {
                            reject(data);
                        } else {
                            resolve(data);
                        }
                        commit("SET_INFO", data);
                        commit("SET_NAME", data.name);
                        commit("SET_PERMISSIONS", data.securityRights || []);
                        commit("SET_AVATAR", data.avatar);
                        setUserName(data.name);
                    })
                    .catch(error => {
                        reject(error);
                    });
            });
        },

        //oauth2登录方式获取token
        GetOAuthToken({ commit, state }, param) {
            return new Promise((resolve, reject) => {
                let params = {
                    grant_type: "authorization_code",
                    code: param.code,
                    redirect_uri: location.href.split("?")[0],
                    client_id: getSetting("CLIENT_ID"),
                    client_secret: getSetting("CLIENT_SECRET")
                };
                getOAuthTokeByCode(params)
                    .then(({ data }) => {
                        commit("SET_TOKEN", data.access_token);
                        setToken(data.access_token);
                        resolve(param.code);
                    })
                    .catch(error => {
                        reject(error);
                    });
            });
        },

        // 登出
        Logout({ commit, state }) {
            return new Promise((resolve, reject) => {
                logout({ redirectUrl: location.href })
                    .then(() => {
                        commit("SET_TOKEN", "");
                        commit("SET_ROLES", []);
                        removeToken();
                        removeUserName();
                        resolve();
                    })
                    .catch(error => {
                        reject(error);
                    });
            });
        },

        //oauth2登录方式退出
        LogoutOauth({ commit }, logoutUrl) {
            return new Promise(resolve => {
                commit("SET_TOKEN", "");
                commit("SET_NAME", "");
                removeToken();
                removeUserName();
                resolve();
                window.location.href = logoutUrl;
            });
        },

        // 前端 登出
        FedLogout({ commit }) {
            return new Promise(resolve => {
                commit("SET_TOKEN", "");
                commit("SET_NAME", "");
                removeToken();
                removeUserName();
                resolve();
            });
        },

        // 动态修改权限
        ChangeRoles({ commit, dispatch }, role) {
            return new Promise(resolve => {
                commit("SET_TOKEN", role);
                setToken(role);
                // commit("SET_Name", role);
                // setToken(role);
                getUserInfo(role).then(({ data }) => {
                    commit("SET_ROLES", data.roles);
                    commit("SET_NAME", data.name);
                    commit("SET_AVATAR", data.avatar);
                    commit("SET_INTRODUCTION", data.introduction);
                    dispatch("GenerateRoutes", data); // 动态修改权限后 重绘侧边菜单
                    resolve();
                });
            });
        }
    },
    getters: {
        user: state => state.info,
        token: state => state.token,
        avatar: state => state.avatar,
        name: state => state.name,
        introduction: state => state.introduction,
        status: state => state.status,
        roles: state => state.roles,
        setting: state => state.setting,
        permissions: state => state.permissions
    }
};

export default user;
