import { login, getInfo, ldapLogin, loginDept } from "@/api/login";
import { getToken, setToken, removeToken } from "@/utils/auth";
// import { getTgInfoByUserId } from '@/api/adviser'
// import checkPermission from '@/utils/permission'
import { decrypt } from "@/utils/rsaEncrypt";
import { Message } from "element-ui";
import router from "@/router/routers";

export const setUserInfo = (res, commit) => {
  // 如果没有任何权限，则赋予一个默认的权限，避免请求死循环
  if (res.roles.length === 0) {
    commit("SET_ROLES", ["ROLE_SYSTEM_DEFAULT"]);
  } else {
    commit("SET_ROLES", res.roles);
  }
  commit("SET_USER", res);
};

const user = {
  state: {
    temporaryToken: "", // 多部门用户临时token
    token: getToken(),
    user: {},
    roles: [],
    // 第一次加载菜单时用到
    loadMenus: false,
    systemSafety: localStorage.getItem("systemSafety")
      ? JSON.parse(localStorage.getItem("systemSafety"))
      : {},
    whiteList: []
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      // eslint-disable-next-line no-param-reassign
      state.token = token;
    },
    SET_TEMPORARY_TOKEN: (state, token) => {
      // eslint-disable-next-line no-param-reassign
      state.temporaryToken = token;
    },
    // eslint-disable-next-line no-shadow
    SET_USER: (state, user) => {
      // eslint-disable-next-line no-param-reassign
      state.user = user;
    },
    SET_ROLES: (state, roles) => {
      // eslint-disable-next-line no-param-reassign
      state.roles = roles;
    },
    SET_LOAD_MENUS: (state, loadMenus) => {
      // eslint-disable-next-line no-param-reassign
      state.loadMenus = loadMenus;
    },
    SET_SYSTEM_SAFETY: (state, systemSafety) => {
      state.systemSafety = systemSafety;
      localStorage.setItem("systemSafety", JSON.stringify(systemSafety));
    },
    SET_WHITE_LIST: (state, whiteList) => {
      state.whiteList = whiteList;
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      debugger;
      // console.log('userInfo ==>', userInfo)
      const {
        loginName,
        rememberMe,
        captcha,
        uuid,
        deptId,
        ldapKey
      } = userInfo;
      const password = decrypt(userInfo.password);
      return new Promise((resolve, reject) => {
        let fn = loginName
          ? login(loginName, password, captcha, uuid)
          : ldapKey
          ? ldapLogin({ ldapKey })
          : loginDept({ deptId });
        fn.then(async res => {
          if (res && res.code === 0) {
            if (ldapKey && !res.data.user.id) {
              commit("SET_TEMPORARY_TOKEN", res.data.token);
            } else {
              setToken(res.data.token, rememberMe);
              commit("SET_TEMPORARY_TOKEN", "");
              commit("SET_TOKEN", res.data.token);
            }
            resolve(res);
          } else {
            Message({
              message: res.message,
              duration: 1500,
              type: "error"
            });
            reject(res);
          }
          console.log("res ==>", res);
        }).catch(error => {
          reject(error);
        });
      });
    },

    // 获取用户信息
    GetInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getInfo()
          .then(async res => {
            setUserInfo(res.data, commit);

            resolve(res.data);
          })
          .catch(error => {
            reject(error);
          });
      });
    },

    // 登出
    LogOut({ commit }) {
      return new Promise((resolve, reject) => {
        try {
          commit("SET_TOKEN", "");
          commit("SET_ROLES", []);
          commit("SET_SYSTEM_SAFETY", {});
          localStorage.setItem("isFirst", 0);
          removeToken();
          // location.href = `${window.config.webAuthUrl}?redirecturl=${
          //   location.origin
          // }/syzbadmin`;
          router.push("/login");
          resolve();
        } catch (error) {
          reject(error);
        }
      });
    },

    updateLoadMenus({ commit }) {
      return new Promise((resolve, reject) => {
        try {
          commit("SET_LOAD_MENUS", false);
          resolve();
        } catch (error) {
          reject(error);
        }
      });
    }
  }
};

export default user;
