// 路由前置操作
import store from '@/store/index.js';
import {
  Message
} from 'element-ui';
import {
  getCookie,
  setCookie,
  dgTree
} from '@/utils/util.js';
import axios from '@/config/axios.js';
import {
  stDev,
  stProd,
  proPath
} from '@/config/config.js';

// 免登录白名单
const whiteList = ['/', '/login', '/download', '/page404', '/dingtalkTaskMobileEnd', '/dingtalkWorkFlowMobileEnd', '/luckDraw'];

/**
 * 当前路由取标题
 * @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
  console.log('开始了')
  router.beforeEach((to, from, next) => {
    //  面包屑
    if (document.domain.indexOf('steerinfo.com') > -1) {
      document.domain = 'steerinfo.com';
    }
    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 (to.query.ticket) {
      console.log('开始了2')
      setCookie('ticket', to.query.ticket, '', '/');
      let res = axios.get('pass/auth/ticket', {
        params: {
          ticket: to.query.ticket || '-5696372145848366561'
        }
      });
        res.then(res => {
            if (res.succeed) {
              DoneCookie(to, from, next, res.data.accessToken, flag)
            }
        }).catch(err => {
          console.log(err)
          Message('登陆账户异常, 请联系管理员')
        });
    } else {
      console.log('开始了3')
      DoneCookie(to, from, next, to.query.accessToken, flag)
    }
  });
}
function DoneCookie(to, from, next, accessToken, flag) {
  if (accessToken) {
    if (to.query.menuLeave) {
      setCookie('menuLeave', to.query.menuLeave, '', '/', '', '', true);
    } else {
      setCookie('menuLeave', '', '', '/', '', '', true);
    }
    setCookie('accessToken', accessToken, '', '/');
    store.dispatch('getLoginInfo').then(res => { // 拉取info
      if (res.code === '0') {
        setCookie('userId', res.data.user.userId);
        setCookie('loginId', res.data.user.userId); // 为配合bms取值添加
        setCookie('loginName', res.data.user.userCode);
        let info = JSON.parse(JSON.stringify(res.data.user));
        for (let k in info) {
          if (k === 'sysGroup' || k === 'sysCompanys' || k === 'sysRoles') {
            delete info[k];
          }
        }
        setCookie('userInfo', JSON.stringify(info));
        // 判断用户集团公司情况跳转
        let userInfo = res.data.user;
        // 超级管理员
        if (userInfo.userCode === 'admin') {
          if (userInfo.sysCompanys) {
            // 公司列表过多时cookie存放失败，存至localStorage
            // setCookie('companys', JSON.stringify(userInfo.sysCompanys));
            window.top.localStorage.setItem('sysGroup', JSON.stringify(userInfo.sysGroup));
            window.top.localStorage.setItem('companys', JSON.stringify(userInfo.sysCompanys));
            if (userInfo.hasOwnProperty('sysCompanys')) {
              window.top.localStorage.setItem('companyId', userInfo.sysCompanys[0].id);
            }
          }
          next({
            path: '/default'
          });
          // 普通用户
        } else {
          if (userInfo.hasOwnProperty('sysGroup') && userInfo.sysGroup !== '' && userInfo.sysGroup !== null && JSON.stringify(userInfo.sysGroup) !== '{}' && JSON.stringify(userInfo.sysGroup) !== '[]') {
            window.top.localStorage.setItem('sysGroup', JSON.stringify(userInfo.sysGroup));
            if (userInfo.hasOwnProperty('sysCompanys')) {
              window.top.localStorage.setItem('companys', JSON.stringify(userInfo.sysCompanys));
              window.top.localStorage.setItem('companyId', userInfo.sysCompanys[0].id);
              if (userInfo.sysCompanys.length > 1) {
                // 跳转选择集团公司页面
                next({
                  path: '/selectCompany'
                });
              } else {
                next({
                  path: '/default'
                });
              }
            } else {
              this.$message.error('后台返回数据缺少company信息，请联系开发人员！');
            }
          } else {
            this.$message.error('必须隶属一个集团！请先联系管理员添加集团信息!');
          }
        }
      } else {
        Message('登录已过期，请重新登录');
        setCookie('accessToken', '', -1, '/');
        setCookie('refreshToken', '', -1, '/');
        setCookie('workDate', '', -1);
        setCookie('appId', '', -1, '/');
        setCookie('ticket', '', -1, '/');
        setTimeout(() => {
          window.top.location.href = store.getters.ctx;
        }, 500)
      }
    }).catch(err => {
      console.log(err);
      Message('登录已过期，请重新登录');
      setCookie('accessToken', '', -1, '/');
      setCookie('refreshToken', '', -1, '/');
      setCookie('workDate', '', -1);
      setCookie('appId', '', -1, '/');
      setCookie('ticket', '', -1, '/');
      window.top.location.href = store.getters.ctx;
    });
  } else if (getCookie('accessToken')) { // 判断是否有token
    if (window.top.document.URL === window.document.URL && !window.top.localStorage.getItem('allPrivilege')) {
      let userInfo = JSON.parse(getCookie('userInfo'));
      setCookie('userId', userInfo.userId);
      let companyId = window.top.localStorage.getItem('companyId');
      let menuId = window.top.localStorage.getItem('activeMenu');
      // 查询所有注释掉
      // store.dispatch('getAllMenuUrl', { companyId: companyId });
      // store.dispatch('getOwnMenuUrl', { userId: userId, menuId: menuId });
      store.dispatch('getOwnMenuUrl', { companyId: companyId });
    }
    console.log('to.path: ' + to.path);
    if (to.path === '/login' || to.path === '/') {
      // 判断非本地模式登录页面不可访问
      if (document.location.origin.indexOf('steerinfo.com') !== -1) {
        next({
          path: '/page404'
        });
      } else {
        console.log('to.path:======= ');
        /**
        next({
          path: '/'
        }); */
        next();
      }
    } else {
      if (window.top.document.URL === window.document.URL && store.state.userInfo === null) { // 判断当前用户是否已拉取完路由信息
        store.dispatch('getUserInfo').then(res => { // 拉取info
          if (res.code === '0') {
            const userInfo = res.data;
            let appId = getCookie('appId');
            userInfo.appId = appId;
            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('appId', '', -1, '/');
            setCookie('workDate', '', -1);
            setCookie('ticket', '', -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('appId', '', -1, '/');
          setCookie('workDate', '', -1);
          setCookie('ticket', '', -1, '/');
          window.top.location.href = store.getters.ctx;
        });
      } else {
        next() // 当有用户权限的时候，说明所有可访问路由已生成 如访问没权限的全面会自动进入404页面
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单，直接进入
      // 判断非本地模式登录页面不可访问
      if ((to.path === '/login' || to.path === '/') && document.location.origin.indexOf('steerinfo.com') !== -1) {
        next({
          path: '/page404'
        });
      } else {
        next();
      }
    } else {
      Message('未登录');
      // next('/login'); // 否则全部重定向到登录页
      // window.location.href = '/views/index.html';
      setCookie('accessToken', '', -1, '/');
      setCookie('refreshToken', '', -1, '/');
      setCookie('workDate', '', -1);
      setCookie('appId', '', -1, '/');
      setCookie('ticket', '', -1, '/');
      window.top.location.href = store.getters.ctx;
    }
  }
}

export default routerBefore;
