/*
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2020-07-31 11:41:34
 * @LastEditors: 无尘
 * @LastEditTime: 2020-09-21 15:42:03
 */
import { request } from './request.js';
import axios from 'axios';

// 项目中配置的路由信息
let projectRoutes = [];
// 有权限访问的路由
let accessPath = [];
// 无权限的操作项
let itemPermission = {};

function getGicMenu() {
  const getUserMenu = new Promise(resolve => {
    request({ url: '/hb-manage-web/list-staff-role-menu' }).then(res => {
      accessPath = getProjectMenu(res.result || []);
    }).finally(resolve);
  });
  const getUserOperation = new Promise(resolve => {
    request({ url: '/hb-manage-web/list-staff-role-opeation' }).then(res => {
      itemPermission = getItemPerm(res.result || []);
    }).finally(resolve);
  });
  return Promise.all([ getUserMenu, getUserOperation ]);
}

function getProjectMenu(menu) {
  let result = [];
  menu.forEach(el => {
    if (el.menuUrl) {
      result.push(el.menuUrl);
    }
    if (Array.isArray(el.children)) {
      result = result.concat(getProjectMenu(el.children));
    }
  });
  return result;
}

function getItemPerm(itemPerms) {
  let result = {};
  itemPerms.forEach(el => {
    result[el.menuCode] = true;
  });
  return result;
}

function flatRoutes(routes) {
  let result = [];
  routes.forEach(el => {
    if (Array.isArray(el.children)) {
      result = result.concat(flatRoutes(el.children));
    }
    result.push(el.path);
  });
  return result;
}

// 路由跳转拦截
function intercept(to, from, next) {
  const hasPerm = accessPath.some(el => {
    return el.indexOf('/#') >= 0 ? el == `/#${to.path}` : el == to.path;
  });
  // 有权限访问
  if (hasPerm) {
    Object.assign(axios.defaults.headers.common, {
      route: to.path.replace(/^\//, '')
    });
    return next();
  };
  // 无权限访问
  if (projectRoutes.some(el => el == to.path) || accessPath.length == 0) {
    next('/gic-error');
  } else {
    Object.assign(axios.defaults.headers.common, {
      route: accessPath[0].replace(/^\//, '')
    });
    next(accessPath[0]);
  }
}

// 操作项权限拦截（包括按钮、下拉列表选项、switch开关、复选框等等操作项）
function itemPerm(itemPermCode) {
  return !!itemPermission[itemPermCode];
}

let permission = function(config) {
  const { projectPath, whiteRoute, router, routes, createApp } = config;

  window.addEventListener('load', async function() {
    // 获取菜单数据
    // 获取权限数据
    const path = window.location.href;
    const hashName = window.location.hash;
    if (path.indexOf('/login') == -1 && path.indexOf('/gic-error') == -1) {
      Object.assign(axios.defaults.headers.common, {
        project: projectPath,
        route: hashName.includes('?') ? hashName.match(/(?<=\#\/).*?(?=\?)/)[0] : hashName.match(/(?<=\#\/).*/)[0]
      });
      await getGicMenu();
    }
    if (Array.isArray(whiteRoute)) {
      accessPath = accessPath.concat(whiteRoute);
    }
    if (Array.isArray(routes)) {
      // 项目中路由文件配置的路径
      projectRoutes = flatRoutes(routes);
    }
    router.beforeEach(intercept);
    // 创建vue实例，渲染页面
    if (typeof createApp == 'function') createApp();
  });
};

export { permission, itemPerm };
