import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import smCrypto from "@/utils/smCrypto";
import router, {
  resetRouter
} from '@/router'

const state = {
  token: getToken(),
  name: '',
  loginName: '',
  avatar: '',
  roles: [],
  // 用户拥有的按钮资源
  btns: [],
  orgGroup: '',
  orgName: '',
  userId: ''
};

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles;
  },
  SET_BTNS: (state, btns) => {// 设置用户资源按钮
    state.btns = btns
  },
  SET_ORG_GROUP: (state, orgGroup) => {
    state.orgGroup = orgGroup
  },
  SET_ORGNAME: (state, orgName) => {
    state.orgName = orgName;
  },
  SET_LOGINNAME: (state, loginName) => {
    state.loginName = loginName;
  }
  ,
  SET_USERID: (state, userId) => {
    state.userId = userId;
  }
};

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo;
    commit('SET_LOGINNAME', username);
    return new Promise((resolve, reject) => {
      login({
        userName: username.trim(),
        passWord: smCrypto.doSm2Encrypt(password),
        logInType: "PASSWORD_LOGIN",
        device: "PC",
        systemType: "B"
      }).then(
        response => {
          const { data } = response;
          commit('SET_TOKEN', data.accessToken);
          setToken(data.accessToken);
          resolve();
        }).catch(error => {
          reject(error);
        });
    })
  },

  // get user info
  getUserInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        // const orgGroup = response.orgGroup;
        // const orgGroup = {
        //   "orgId": -1000,
        //   "orgGroupId": -1000,
        //   "orgGroupCode": "ROOT",
        //   "orgGroupName": "平台管理员"
        // }
        const data = response.data;
        const orgName = data.orgName;
        const roles = data.roleCodeList
        const orgGroup = data.orgId
        if (roles && roles.length > 0) {
          commit('SET_ROLES', roles)
        } else {
          reject('getInfo: roles must be a non-null array !')
        }
        //名称
        commit('SET_NAME', data.name);
        //按钮权限
        const btns = data.buttonCodeList;
        sessionStorage.setItem('userBtns', btns);
        //头像
        const avatar = data.avatar || 'https://testdgxcx-oss.gloria.com.cn/goelia-ai/avata.png';
        commit('SET_AVATAR', avatar);
        //用户名
        if (response.account) {
          commit('SET_LOGINNAME', response.account);
        }
        //组织名称
        commit('SET_ORGNAME', orgName);
        //组织角色
        if (orgGroup !== null && orgGroup !== '') {
          commit('SET_ORG_GROUP', orgGroup);
        }
        commit('SET_USERID', data.id);
        resolve(response);
      }).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', []);
        removeToken();
        resetRouter();
        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', []);
      removeToken();
      resolve();
    })
  },

  // dynamically modify permissions
  changeRoles({ commit, dispatch }, role) {
    return new Promise(async resolve => {
      const token = role + '-token';

      commit('SET_TOKEN', token);
      setToken(token);
      // by zjj
      const res = await dispatch('user/getUserInfo');
      let data = res.data.list; // router 连接
      // by zjj

      resetRouter();

      // generate accessible routes map based on roles
      const accessRoutes = await dispatch('permission/generateRoutes', data, {
        root: true
      });

      // dynamically add accessible routes
      router.addRoutes(accessRoutes);

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

      resolve()
    })
  }
};

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