import {
  login,
  getUserInfo,
  getKaptcha,
  refreshToken,
  loginOut
} from "@/api/sys";
import {
  unifiedLogin
} from "@/api/user-manage";
import md5 from "md5";
import Base64 from "base-64";
import {
  setItem,
  getItem,
  removeAllItem
} from "@/utils/storage";
import {
  TOKEN
} from "@/constant";
import router, {
  resetRouter
} from "@/router";
import {
  setTimeStamp
} from "@/utils/auth";
import {
  TAGS_VIEW
} from "@/constant/index.js";
export default {
  namespaced: true,
  state: () => ({
    token: getItem(TOKEN) || "", // 先从localStorage里面取
    userInfo: {},
    deptList: [],
    deptId: "",
    menuList: [],
    isReady: 0,
    userName: getItem("USERNAME") || "",
    keepLiiveRoute: [], //需要缓存的路由
    activeId: '',//警组点击的唯一标识
    // keepLiiveRoute: ["lz/home"], //需要缓存的路由
  }),
  mutations: {
    setToken(state, token) {
      state.token = token;
      setItem(TOKEN, token);
    },
    setActiveId(state, activeId) {
      state.activeId = activeId;
    },
    setUserName(state, userName) {
      state.userName = userName;
    },
    setDeptList(state, deptList) {
      state.deptList = deptList;
    },
    setIsReady(state, deptList) {
      state.isReady++;
    },
    setMenuList(state, menuList) {
      state.menuList = menuList;
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo;
    },
    //保存当前deptId
    setDeptId(state, deptId) {
      state.deptId = deptId;
      setItem("deptId", deptId);
    },
    //保存路由
    setKeepLiiveRoute(state, val) {
      // state.keepLiiveRoute.push(val);
    },
    //删除缓存路由
    deleteKeepLiiveRoute(state, val) {
      // state.keepLiiveRoute = state.keepLiiveRoute.filter((item) => {
      //   return item != val;
      // });
    },
  },
  actions: {
    /*
     *登录请求动作
     */
    login(ctx, userInfo) {
      const {
        userName,
        password,
        kaptcha,
        type
      } = userInfo;
      return new Promise((resolve, reject) => {
        login({
          userName,
          password: Base64.encode(password),
          kaptcha,
          type
        })
          .then((data) => {
            if (data.deptList.length === 1) {
              this.commit("user/setToken", data.jwtToken);
              this.commit("user/setDeptId", data.deptList);
              this.commit("user/setUserName", data.userName);
              setItem('isOatuh', 0)
              setItem("USERNAME", data.userName);
              setItem("SFRH", data.sfrh);
              setItem("USERID", data.userId);
              setItem("PermissionsInfo", data.permissionsInfo);
              this.commit("user/setMenuList", data.menuList);
              setItem("menusPermission", data.menuCodeSet);
              setItem("idEntityCard", data.idEntityCard);
              this.commit("user/setUserInfo", {
                token: data.jwtToken,
                permission: {
                  buttonPermission: ["removeTest", "viewTest"],
                  menus: data.menuCodeSet
                },
                menuList: data.menuList,
                deptList: data.deptList
              });
            }
            // 保存登录时间
            setTimeStamp();
            resolve(data);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    /*
     *单点登录
     */
    oatuhLogin(ctx, userInfo) {
      const {
        token,
        systemId,
      } = userInfo;
      return new Promise((resolve, reject) => {
        unifiedLogin({
          token,
          systemId,
        })
          .then((data) => {
            if (data.deptList.length === 1) {
              this.commit("user/setToken", data.jwtToken);
              this.commit("user/setDeptId", data.deptList);
              this.commit("user/setUserName", data.userName);
              setItem("USERNAME", data.userName);
              setItem("SFRH", data.sfrh);
              setItem("USERID", data.userId);
              setItem("PermissionsInfo", data.permissionsInfo);
              this.commit("user/setMenuList", data.menuList);
              setItem("menusPermission", data.menuCodeSet);
              setItem('isOatuh', 1)
              setItem("idEntityCard", data.idEntityCard);
              this.commit("user/setUserInfo", {
                token: data.jwtToken,
                permission: {
                  buttonPermission: ["removeTest", "viewTest"],
                  menus: data.menuCodeSet
                },
                menuList: data.menuList,
                deptList: data.deptList
              });
            }
            // 保存登录时间
            setTimeStamp();
            resolve(data);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },

    refreshToken(ctx, parmas) {
      return new Promise((resolve, reject) => {
        refreshToken({
          deptId: parmas.deptId,
          authorization: parmas.jwtToken
        })
          .then((data) => {
            this.commit("user/setToken", "");
            this.commit("user/setToken", data.jwtToken);
            this.commit("user/setDeptList", data.deptList);
            this.commit("user/setUserName", data.userName);
            this.commit("user/setMenuList", data.menuList);
            this.commit("user/setUserInfo", {
              token: data.jwtToken,
              permission: {
                buttonPermission: ["removeTest", "viewTest"],
                menus: data.menuCodeSet
              },
              menuList: data.menuList,
              deptList: data.deptList
            });
            setItem("menusPermission", data.menuCodeSet);
            // 保存登录时间
            setTimeStamp();
            return resolve(data);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    /*
     * 获取图形验证码
     */
    async getKaptcha(ctx) {
      const res = await getKaptcha();
      return res;
    },

    /*
     * 获取用户信息
     */
    async getUserInfo(ctx) {
      const res = await getUserInfo();
      this.commit("user/setUserInfo", res);
      return res;
    },

    /*
     * 退出登录
     */
    async logout(ctx) {
      const res = await loginOut();
      if (res) {
        resetRouter();
        this.commit("user/setToken", "");
        this.commit("user/setUserName", "admin");
        this.commit("user/setUserInfo", {});
        this.commit("permission/resetrouteReady", 0);
        const isOatuh = getItem('isOatuh')
        this.commit("permission/deleteRouter");
        removeAllItem();
        // 待补充 清理权限相关的配置
        if (isOatuh) {
          window.location.href = `http://80.149.27.78:8001/login`;
        } else {
          router.push("/login");
        }
      }
    }
  }
};
