import { login, getUserInfo, getKaptcha, refreshToken, loginOut } from "@/api/sys";
import { unifiedLogin, tokenLogin } 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: [],
    treeList: [],
    isReady: 0,
    routerName: "", //改变路由名称
    routerSeeName: "", //查看进度改变路由名称
    userName: getItem("USERNAME") || "",
    defaultDeptName: "甘肃省烟草专卖局"
  }),
  mutations: {
    setToken(state, token) {
      state.token = token;
      setItem(TOKEN, token);
    },
    setTreeList(state, list) {
      state.treeList = list;
    },
    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);
    },
    //保存当前deptId
    setName(state, routerName) {
      state.routerName = routerName;
      setItem("routerName", routerName);
    },
    setrouterSeeName(state, routerSeeName) {
      state.routerSeeName = routerSeeName;
      setItem("routerSeeName", routerSeeName);
    }
  },
  actions: {
    /*
     *登录请求动作
     */
    login(ctx, userInfo) {
      const { userName, password, kaptcha, loginType } = userInfo;
      return new Promise((resolve, reject) => {
        login({
          userName,
          password: Base64.encode(password),
          loginType,
          kaptcha
        }).then((data) => {
          // 解决出现验证后,刷新后,没有菜单的问题
          if (data && data.menuCodeSet) {
            this.commit("user/setToken", data.jwtToken);
            if (!data.jwtToken) console.log('8 token为空')
            this.commit("user/setDeptId", data.dept);
            this.commit("user/setUserName", data.userName);
            setItem("isOatuh", 0);
            setItem("USERNAME", data.userName);
            setItem("USERID", data.userId);
            setItem("PermissionsInfo", data.permissionsInfo);
            this.commit("user/setMenuList", data.menuList);
            setItem("menusPermission", data.menuCodeSet);
            this.commit("user/setUserInfo", {
              token: data.jwtToken,
              permission: {
                buttonPermission: ["removeTest", "viewTest"],
                menus: data.menuCodeSet
              },
              menuList: data.menuList,
              deptList: data.dept
            });
          }
          // 保存登录时间
          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);
              if (!data.jwtToken) console.log('token为空')
              this.commit("user/setDeptId", data.deptList);
              this.commit("user/setUserName", data.userName);
              setItem("USERNAME", data.userName);
              setItem("USERID", data.userId);
              setItem("PermissionsInfo", data.permissionsInfo);
              this.commit("user/setMenuList", data.menuList);
              setItem("menusPermission", data.menuCodeSet);
              setItem("isOatuh", 1);
              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);
          });
      });
    },
    /*
    *单点登录国家局平台
    */
    oatuhTokenLogin(ctx, userInfo) {
      const { userName, loginType, thridLogin, verifyCode } = userInfo;
      return new Promise((resolve, reject) => {
        tokenLogin({
          userName,
          loginType,
          thridLogin,
          verifyCode
        })
          .then((data) => {
            if (data && data.menuCodeSet) {
              this.commit("user/setToken", data.jwtToken);
              if (!data.jwtToken) console.log('8 token为空')
              this.commit("user/setDeptId", data.dept);
              this.commit("user/setUserName", data.userName);
              setItem("isOatuh", 0);
              setItem("USERNAME", data.userName);
              setItem("USERID", data.userId);
              setItem("PermissionsInfo", data.permissionsInfo);
              this.commit("user/setMenuList", data.menuList);
              setItem("menusPermission", data.menuCodeSet);
              this.commit("user/setUserInfo", {
                token: data.jwtToken,
                permission: {
                  buttonPermission: ["removeTest", "viewTest"],
                  menus: data.menuCodeSet
                },
                menuList: data.menuList,
                deptList: data.dept
              });
            }
            // 保存登录时间
            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);
            if (!data.jwtToken) console.log('1token为空')

            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;
    },
    setRouterName(ctx, name) {
      this.commit("user/setName", name);
    },
    setRouterSeeName(ctx, name) {
      this.commit("user/setrouterSeeName", name);
    },

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

    /*
     * 退出登录
     */
    async logout(ctx) {
      let params = {
        logoutType: "01"
      };
      const res = await loginOut(params);
      if (res) {
        resetRouter();
        this.commit("user/setToken", "");
        console.log('退出登录6')
        this.commit("user/setUserName", "admin");
        this.commit("user/setUserInfo", {});
        this.commit("permission/resetrouteReady", 0);
        const isOatuh = getItem("isOatuh");
        // window.localStorage.removeItem("token"); // 优化清空token的逻辑， 避免经常退出的问题2
        // removeAllItem();

        // 待补充 清理权限相关的配置
        if (isOatuh) {
          // router.push("/oatuh_login");
          window.location.href = `http://80.149.27.78:8001/login`;
        } else {
          router.push("/login");
        }
      }
    }
  }
};
