import { getConfig } from "@/utils";
import axios from "axios";
import { getCurrentSetting } from "@/api/tenant-user-controller";
import store from "@/store/index";
import router from "@/router";
import { Loading } from "element-ui";
import setup from "@/utils/setup";
import generateRoutes from "@/router/dynamicRouters";

// ! 初始一个loading当遮罩层
const loadingInstance = Loading.service({
  fullscreen: true,
  spinner: "none",
  background: "rgba(0, 0, 0, 0.8)",
});

store.commit("SET_APP_LOADING_MASK", loadingInstance);

export const getAccessToken = () => {
  return new Promise((resolve) => {
    if (process.env.VUE_APP_ENV === "development") {
      getConfig("accessToken").then((json) => {
        console.log(json);
        const accessToken = json.find((x) => x.name === "侯晓晨").value;
        localStorage.setItem("accessToken", accessToken.toString());
        resolve(accessToken);
      });
    } else {
      resolve(localStorage.getItem("accessToken"));
    }
  });
};

/**
 * * 自动登录获取dispatchToken
 */
export const permission = async () => {
  const accessToken = await getAccessToken();
  return new Promise((resolve, reject) => {
    axios
      .post(
        `${process.env.VUE_APP_API_ROOT}/identity/Desk/auto-login`,
        {},
        {
          headers: {
            "Content-Type": "multipart/form-data",
            // "skip-ip-validation":1,
            accessToken,
          },
        }
      )
      .then(async (res) => {
        const { status, data } = res;
        if (status === 200) {
          const {
            data: { dispatchToken },
          } = data;
          localStorage.setItem("dispatchToken", dispatchToken);
          // 获取配置
          const setting = await getCurrentSetting();
          store.commit("SET_APP_SETTING", setting);
          resolve(true);
        } else if (status === 401 || status === 403) {
          localStorage.setItem("dispatchToken", "");
          localStorage.setItem("userInfo", "");
          store.commit("showMessage", {
            type: "error",
            message: "未授权无效调度台用户",
            duration: 0,
          });
          store.commit("SET_SYS_USER_INFO", null);
          reject("未授权无效调度台用户");
        }
      })
      .catch((error) => {
        localStorage.setItem("dispatchToken", "");
        localStorage.setItem("userInfo", "");
        store.commit("showMessage", {
          type: "error",
          message: error.response.data.message,
          duration: 0,
        });
        store.commit("SET_SYS_USER_INFO", null);
        reject("未授权无效调度台用户");
        throw error;
      });
  });
};

router.beforeEach(async (to, from, next) => {
  if (to.path.toLowerCase().indexOf("voip") > -1) {
    loadingInstance.close();
  }
  await permission();
  if (store.getters.sysUserInfo === null || Object.keys(store.getters.sysUserInfo).length <= 0) {
    // * 判断当前用户是否已拉取完user_info信息
    try {
      // * 获取用户信息、启动调度客户端
      setup()
        .then((response) => {
          console.log("current user info ===", response);
          // * 储存用户信息
          localStorage.setItem("userInfo", JSON.stringify(response));
          store.commit("SET_SYS_USER_INFO", response);
          // * 根据用户角色判断调度台类型并储存
          const platformInfRole = [
            {
              value: "1",
              label: "指挥调度台",
              role: [
                "Company",
                "Urban",
                "SubUrb",
                "PoliceStation",
                "PopulationPoliceStation",
                "PopulationUrban",
                "PopulationSubUrb",
              ],
            },
            {
              value: "2",
              label: "内保调度台",
              role: ["Proprietor", "PoliceStation", "PopulationPoliceStation"],
            },
            {
              value: "3",
              label: "临保调度台",
              role: ["Company", "Urban", "SubUrb", "PoliceStation", "PopulationPoliceStation"],
              disabled: true,
            },
          ].filter((x) => x.role.includes(response.role));
          const defaultPlatform = platformInfRole[0].value;
          const storePlatform = localStorage.getItem("platform");
          if (platformInfRole.filter((x) => x.value === storePlatform).length <= 0) {
            localStorage.setItem("platform", defaultPlatform);
          }
          localStorage.setItem("userInfo", JSON.stringify(response));
          // * 根据调度台类型动态生成路由
          generateRoutes(localStorage.getItem("platform")).forEach((route) => {
            router.addRoute(route); // 生成该用户的新路由json操作完毕之后,调用vue-router的动态新增路由方法,将新路由添加
          });
        })
        .finally(() => {
          // ! 跳转路由
          next({ ...to, replace: true });
          loadingInstance.close();
        });
    } catch (err) {
      loadingInstance.close();
    }
  } else {
    // * 有用户信息直接进入
    next();
    loadingInstance.close();
  }
});
