import Vue from "vue";
import Vuex from "vuex";
import Cookies from "js-cookie";
import layoutStore from "./modules/layout/index";
import { defaultRouter } from "@/router/index";
import { encryptLoginPassword } from "@/utils";
import { Message } from "element-ui";

import request from "@/api/index";
import router from "@/router/index";
import { addrouters, addRoutersAdmin, addroutersPersonal, csAddrouters } from "@/router/index";
Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    token: "",
    csCode: localStorage.getItem("csCode") || "",
    info: localStorage.getItem("info")
      ? JSON.parse(localStorage.getItem("info"))
      : "", // 每次刷新都要通过token请求个人信息来筛选动态路由
    routers: [], //左侧菜单
    addRouters:
      localStorage.getItem("addRouters") &&
        localStorage.getItem("addRouters") != "undefined"
        ? JSON.parse(localStorage.getItem("addRouters"))
        : [], //动态路由
    tokenSources: new Map(), //正在请求接口（切换取消请求）
  },
  mutations: {
    setToken(state, token) {
      state.token = token;
    },
    setCode(state, code) {
      state.csCode = code;
      localStorage.setItem("csCode", code);
    },
    setInfo(state, data) {
      state.info = { ...data };
      localStorage.setItem("info", JSON.stringify(data));
    },
    setRouters: (state, routers) => {
      let addrouterList = []
      if (state.info.showRole == 'ROLE_PERSONAL') {
        addrouterList = [...addroutersPersonal]
      } else if (state.info.showRole == 'ROLE_PINGTAI') {
        addrouterList = [...addRoutersAdmin]
      } else {
        if (state.csCode) {
          addrouterList = [...csAddrouters]
        } else {
          addrouterList = [...addrouters]
        }

      }
      let aRouters = addrouterList.filter((item) => {
        let path = item.children[0]?.path.replace("/", "");
        return routers?.includes(path);
      });

      state.addRouters = aRouters; // 保存动态路由用来addRouter
      state.routers = defaultRouter.concat(aRouters); // 所有有权限的路由表，用来生成菜单列表
      localStorage.setItem("addRouters", JSON.stringify(routers));
    },
    setTokenSources(state, data) {
      if (data instanceof Array) {
        state.tokenSources.set(data[0], data[1]);
      } else {
        state.tokenSources = new Map();
      }
    },
    delTokenSources(state, data) {
      state.tokenSources.delete(data);
    },
  },
  actions: {
    Login({ state, commit }, params) {
      let loginForm = {};
      loginForm.username = params.username;
      loginForm.password = encryptLoginPassword(params.password);
      request
        .login({ ...loginForm })
        .then((res) => {
          let response = res;
          if (response.status == 0) {
            const userInfo = { ...response.data };
            if (userInfo.permissions && userInfo.permissions.length) {
              userInfo.showRoleName = response.data.permissions[0]?.roleName;
              userInfo.showRole = response.data.permissions[0]?.role;
              commit("setToken", "isLogin");
              commit("setInfo", { ...userInfo });
              commit("setRouters", [
                ...userInfo.permissions[0]?.authorityRouter,
              ]);
              state.addRouters.forEach((res) => {
                router.addRoute(res);
              });
              router.addRoute({
                path: "*",
                redirect: "/404",
                hidden: true,
                children: [],
              });
              if (params.url) {
                window.location.href = params.url;
              } else {
                router.push({ path: "/" });
              }
            } else {
              Message({
                message: "该账号暂无权限，请联系管理员~",
                type: "error",
                duration: 3 * 1000,
              });
            }
          }
        })
        .catch((err) => {
          Message({
            message: err,
            type: "error",
            duration: 3 * 1000,
          });
        });
    },
    CSLogin({ state, commit }, code) {
      request
        .ssoLogin({ code: code })
        .then((res) => {
          let response = res;
          if (response.status == 0) {
            const userInfo = { ...response.data };
            if (userInfo.permissions && userInfo.permissions.length) {
              userInfo.showRoleName = response.data.permissions[0]?.roleName;
              userInfo.showRole = response.data.permissions[0]?.role;
              commit("setToken", "isLogin");
              commit("setCode", code);
              commit("setInfo", { ...userInfo });
              commit("setRouters", [
                ...userInfo.permissions[0]?.authorityRouter,
              ]);
              state.addRouters.forEach((res) => {
                router.addRoute(res);
              });
              router.addRoute({
                path: "*",
                redirect: "/404",
                hidden: true,
                children: [],
              });
              router.push({ path: "/" });

            } else {
              Message({
                message: "该账号暂无权限，请联系管理员~",
                type: "error",
                duration: 3 * 1000,
              });
            }
          } else {
            Message({
              message: response.info,
              type: "error",
              duration: 3 * 1000,
            });
          }
        })
        .catch(() => { });
    },
    permissions({ state, commit }, role) {
      commit("setToken", "isLogin");
      let userInfo = state.info;
      let authorityRouterObj = userInfo.permissions.filter((item) => {
        return item.role == role;
      });
      userInfo.showRoleName = authorityRouterObj[0]?.roleName;
      userInfo.showRole = authorityRouterObj[0]?.role;
      commit("setInfo", userInfo);
      commit("setRouters", [...authorityRouterObj[0]?.authorityRouter]);
      state.addRouters.forEach((res) => {
        router.addRoute(res);
      });
      router.addRoute({
        path: "*",
        redirect: "/404",
        hidden: true,
        children: [],
      });
      router.push({ path: "/" });
      window.location.reload()
    },
  },
  getters: {
    addRouters: (state) => state.addRouters,
    token: (state) => state.token,
    code: (state) => state.csCode,
    info: (state) => state.info,
    routers: (state) => state.routers,
    logoShow: (state) => state.layoutStore.logoShow,
    isCollapse: (state) => state.layoutStore.isCollapse,
    uniquerouter: (state) => state.layoutStore.uniquerouter,
    tabnavBox: (state) => state.layoutStore.tabnavBox,
    rightNav: (state) => state.layoutStore.rightNav,
  },
  modules: {
    layoutStore,
  },
});

export default store;
