import { login, getInfo } from "@/api/user";
import { getToken, setToken, removeToken } from "@/utils/auth";
import router, { resetRouter } from "@/router";
import { functionObj } from "@/utils/functionObj";

const state = {
  token: getToken(), //获取token值
  username: "", //获取用户名
  roles: [], //获取角色
  resource: [], //获取权限菜单
  buttons: [], //获取权限按钮
  orgId: "", //获取机构名称
  loginId: "", //登录账号
  orgType: "MSUP", //获取机构类型
  role: [],//获取角色
  userID: "FP0141",// 用户ID  //YH080   FP0001
};

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_USERNAME: (state, username) => {
    state.username = username;
  },
  SET_ORGID: (state, orgId) => {
    state.orgId = orgId;
  },
  SET_LOGINID: (state, loginId) => {
    state.loginId = loginId;
  },

  SET_ORGTYPE: (state, orgType) => {
    state.orgType = orgType;
  },
  SET_ROLE: (state, role) => {
    state.role = role;
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles;
  },
  SET_RESOURCE: (state, resource) => {
    state.resource = resource;
  },
  SET_BUTTONS: (state, buttons) => {
    state.buttons = buttons;
  },
  SET_USERID: (state, userID) => {
    state.userID = userID;
  }
};

const actions = {
  login({ commit }, userInfo) {
    const { username, password } = userInfo;
    return new Promise((resolve, reject) => {
      login({ loginId: username.trim(), pwd: password })
        .then(response => {
          const { data } = response;
          commit("SET_TOKEN", data.token);
          setToken(data.token);
          resolve();
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  getInfo({ commit, state }) {
    let token = state.token;
    return new Promise((resolve, reject) => {
      getInfo()
        .then(response => {
          const { data } = response;
          if (!data) {
            reject("请重新登录！！！");
          }
          // if (
          //   Array.isArray(data.permission.menus) &&
          //   data.permission.menus.length > 0
          // ) {
          //   commit("SET_RESOURCE", data.permission.menus);
          // }
          const buttonAuthList = [];
          let data1 = [];
          if (data.permission.menus) {

            // 数组对象去重
            function fn2(tempArr) {
              for (let i = 0; i < tempArr.length; i++) {
                for (let j = i + 1; j < tempArr.length; j++) {
                  if (tempArr[i].menuId == tempArr[j].menuId) {
                    tempArr.splice(j, 1);
                    j--;
                  };
                };
              };
              return tempArr;
            };

            var newMenus = fn2(data.permission.menus)
            newMenus.forEach(item1 => {
              functionObj.forEach(item2 => {
                if (
                  item1.menuId == item2.id &&
                  item2.menuType.toLowerCase() == "menu"
                ) {
                  item1 = {
                    parentId: item1.parentId,
                    sort: item1.sort,
                    remark: item1.menuName,
                    id: item2.id,
                    component: item2.component,
                    icon: item2.icon,
                    menuType: item2.menuType,
                    name: item2.name,
                    redirect: item2.redirect,
                    router: item2.router,
                    hidden: item2.hidden
                  };
                  data1.push(item1);
                }
                if (
                  item1.menuId == item2.id &&
                  item2.menuType.toLowerCase() == "button"
                ) {
                  item1 = {
                    id: item2.id,
                    menuType: item2.menuType,
                    remark: item1.menuName,
                    parentId: item1.parentId,
                    sort: item1.sort
                  };
                  data1.push(item1);
                }
              });
            });
          }
          data1.forEach(button => {
            if (button.menuType == "BUTTON") {
              buttonAuthList.push(button.id);
            }
          });
          commit("SET_ROLES", ["admin"]);
          commit("SET_USERNAME", data.title);
          commit("SET_ORGID", data.userContext.orgId);
          commit("SET_LOGINID", data.userContext.loginId);
          commit("SET_ORGTYPE", data.userContext.orgType);
          commit("SET_BUTTONS", buttonAuthList);
          commit("SET_RESOURCE", newMenus);
          commit("SET_ROLE", data.roles);
          commit("SET_USERID", data.userContext.userId);
          // data.roles = ["admin"];
          resolve(data);
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      // logout(state.token).then(() => {
      commit("SET_TOKEN", "");
      commit("SET_ROLES", []);
      commit("SET_BUTTONS", []);
      removeToken();
      resetRouter();

      // reset visited views and cached views
      // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
      dispatch("tagsView/delAllViews", null, { root: true });

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

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit("SET_TOKEN", "");
      commit("SET_ROLES", []);
      commit("SET_BUTTONS", []);
      removeToken();
      resolve();
    });
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + "-token";

    commit("SET_TOKEN", token);
    setToken(token);

    const { roles } = await dispatch("getInfo");

    resetRouter();

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch("permission/generateRoutes", roles, {
      root: true
    });
    // dynamically add accessible routes
    router.addRoutes(accessRoutes);

    // reset visited views and cached views
    dispatch("tagsView/delAllViews", null, { root: true });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
