import Router from "vue-router";
import router from "./index";
import axios from "axios";
import store from "../store";

// 解决ElementUI导航栏中的vue-router在3.0版本以上重复点菜单报错问题
const originalPush = Router.prototype.push;
Router.prototype.push = function push(location) {
    return originalPush.call(this, location).catch((err) => err);
};

// http://localhost:8082/?code=1&ticket=1
router.beforeEach(async (to, from, next) => {
    let {
        code,
        ticket
    } = to.query;

    if (code && ticket && to.name === "mainPage") {
        localStorage.clear();

        store.commit("getUserId", "");
        store.commit("getUsername", "");
        store.commit("getRoleCode", "");
        store.commit("getUseType", "");

        let result = await axios({
                method: "post",
                url: "/simulation/oauth/client/sign/single",
                data: {
                    code,
                    ticket,
                },
            })
            .then((res) => {
                if (res.code == 200 && !!res.info.access_token) {
                    localStorage.setItem(
                        "Authorization",
                        res.info.token_type + " " + res.info.access_token
                    );
                    localStorage.setItem(
                        "refreshToken",
                        res.info.refresh_token
                    );
                    localStorage.setItem("expiresTime", res.info.expires_time);
                    return true;
                } else {
                    alert(res.message || "网络异常");
                    return false;
                }
            })
            .catch((error) => {
                alert("网络异常!");
                return false;
            });

        if (result) {
            next({
                path: "/mainPage",
                // query: {
                //     code,
                //     ticket,
                // },
                replace: true,
            });
        } else {
            next({
                path: "/login",
            });
        }

        return;
    }

    if (to.fullPath === "/" || to.name === "*") {
        if (to.meta.login) {
            if (localStorage.getItem("Authorization")) {
                next({
                    path: "/mainPage",
                });
            } else {
                next({
                    path: "/login",
                });
            }
        } else {
            next({
                path: "/mainPage",
            });
        }
    } else {
        if (to.meta.login) {
            if (localStorage.getItem("Authorization")) {
                next();
            } else {
                next({
                    path: "/login",
                });
            }
        } else {
            next();
        }
    }
});