// 路由前置操作
import store from '@/store/index.js';
import {
  Message
} from 'element-ui';
import {
  getCookie,
  setCookie,
  dgTree
} from '@/utils/util.js';
// 免登录白名单
const whiteList = ['/', '/login'];

/**
 * 当前路由取标题
 * @param {Object} to 当前路由
 * @param {Array} constantRouterMap 路由map
 * @param {Array} menu 菜单树
 * @returns {String} 标题
 */
const titleFn = function (to, menu) {
  let title = '';
  if (to.meta && to.meta.title) {
    return to.meta.title;
  }
  //
  if (to.meta && to.meta.code) {
    //  查找标题
    let code = to.meta.code;
    dgTree(menu, '', item => {
      if (item.menuCode === code) {
        title = item.menuLabel;
      }
    });
  }
  return title;
}

/**
 * matched 添加标题名称
 * @param {Array} matched
 * @param {Array} menu 菜单树
 * @returns {Array} matched
 */
const breadcrumbFn = function (to, menu) {
  let code = to.meta.code;
  let list = [];
  let item = null;
  let data = [];
  let getPid = function (pId) {
    for (let ii of list) {
      if (ii.menuId === pId) {
        return ii;
      }
    }
    return null;
  }
  dgTree(menu, '', leaf => {
    list.push(leaf);
    if (leaf.menuCode === code) {
      item = leaf;
    }
  });
  let init = function (pId) {
    let itemPid = getPid(pId);
    if (itemPid) {
      data.push(itemPid);
      init(itemPid.pId);
    }
  }
  //
  if (item) {
    data.push(item);
    init(item.pId);
  }
  if (data.length > 1) {
    return data.reverse();
  }
  //
  to.matched.forEach(item => {
    dgTree(menu, '', leaf => {
      if (item.meta && item.meta.code === leaf.menuCode) {
        data.push(leaf);
      }
    });
  });
  return data;
}

//  路由前置操作
const routerBefore = function (router, constantRouterMap) {
  let flag = false
  router.beforeEach((to, from, next) => {
    //  面包屑
    console.log('进入路由', to.name)

    store.commit('breadcrumb', breadcrumbFn(to, store.state.routes));
    //  标题
    if (to.meta && !to.meta.title) {
      document.title = titleFn(to, store.state.routes) + ' ' + document.title.substr(document.title.indexOf('-'));
    } else {
      document.title = to.meta.title + ' ' + document.title.substr(document.title.indexOf('-'));
    }
    //
    if (getCookie('accessToken')) { // 判断是否有token
      if (window.top.document.URL === window.document.URL && !window.top.localStorage.getItem('ownPrivilege')) {
        store.dispatch('getOwnMenuUrl');
      }
      if (to.path === '/login') {
        next({
          path: '/'
        });
      } else {
        if (window.top.document.URL === window.document.URL && store.state.userInfo === null) { // 判断当前用户是否已拉取完路由信息
          // 前期无后台测试用
          // next();
          // /*
          store.dispatch('getUserInfo').then(res => { // 拉取info
            if (res.code === '0') {
              const userInfo = res.data;
              store.dispatch('generateRoutes', {
                userInfo
              }).then(() => { // 生成可访问的路由表
                // router.addRoutes(store.state.routes) // 动态添加可访问路由表
                if (flag) {
                  next()
                } else {
                  next({
                    ...to,
                    replace: true
                  })
                  flag = true
                }
                // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
                console.log('这是个什么东西', {
                  ...to,
                  replace: true
                })
              })
            } else {
              Message('登录已过期，请重新登录');
              // next('/login'); // 否则全部重定向到登录页
              // window.location.href = '/views/index.html';
              setCookie('accessToken', '', -1, '/');
              setCookie('refreshToken', '', -1, '/');
              setCookie('workDate', '', -1);
              window.top.location.href = store.getters.ctx;
            }
          }).catch(err => {
            console.log(err);
            Message('登录已过期，请重新登录');
            // next('/login'); // 否则全部重定向到登录页
            // window.location.href = '/views/index.html';
            setCookie('accessToken', '', -1, '/');
            setCookie('refreshToken', '', -1, '/');
            setCookie('workDate', '', -1);
            window.top.location.href = store.getters.ctx;
          });
          // */
        } else {
          next() // 当有用户权限的时候，说明所有可访问路由已生成 如访问没权限的全面会自动进入404页面
        }
      }
    } else {
      if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单，直接进入
        next();
      } else {
        Message('未登录');
        // next('/login'); // 否则全部重定向到登录页
        // window.location.href = '/views/index.html';
        setCookie('accessToken', '', -1, '/');
        setCookie('refreshToken', '', -1, '/');
        setCookie('workDate', '', -1);
        window.top.location.href = store.getters.ctx;
      }
    }
  });
}

export default routerBefore;
