import store from '@/store/index';
const _ = require('lodash');
const jwt = require('jsonwebtoken');
let $dev_env = process.env.NODE_ENV === 'development';
import { Message } from 'element-ui';
export default (router) => {
  router.beforeEach((to, from, next) => {
    if (to.path.includes('dev')) {
      if (!$dev_env) next('/');
    }
    // 检查是不是登陆,登陆页面放过
    if (to.path === '/login') {
      next();
      return;
    }
    let user = store.state.user;
    if (!_.get(user, '_id')) {
      const str = sessionStorage.getItem('user');
      if (!str) next('/login');
      const obj = jwt.decode(str);
      store.commit('setUser', obj, { root: true });
      user = store.state.user;
    }
    // 首页你得让人进
    if (to.path === '/') {
      next();
      return;
    }
    // 检查是否有权限进入页面
    const menu = _.get(store, 'state.user.role.menu');
    const mode = _.get(menu, 'mode');
    if (mode === 'all') {
      next();
      return;
    }
    const can_in = _.get(menu, to.path);
    if (can_in) next();
    else {
      const keys = Object.keys(menu).filter((f) => f !== 'mode');
      let toPath = '';
      if (keys.includes('/')) toPath = '/';
      else toPath = _.head(keys);
      next(toPath);
      Message.error('您无权限访问该页面');
    }
  });
};
