import axios from 'axios';
import { request } from './request.js';
import Vue from 'vue';
import store from '@/store/index';

// 项目的部署路径
let project = '';
// 项目中配置的路由信息
let projectRoutes = [];
// 有权限访问的路由
let accessPath = [];
// 无权限的操作项
let itemPermission = {};
const origin = getOrigin();

function getOrigin() {
  let origin = window.location.origin;
  if (origin.indexOf('localhost') >= 0 || origin.indexOf('192.168') >= 0) {
    origin = 'https://four.gicdev.com';
  }
  return origin;
}

function getUserInfo() {
  return request({ url: '/gic-auth-web/get-login-user-info' });
}

function getGicMenu() {
  const getUserMenu = request({ url: '/gic-auth-web/login-user-menu' }).then(res => {
    accessPath = getProjectMenu(res.result || []);
  });
  const getUserOperation = request({ url: '/gic-auth-web/login-user-operation-item' }).then(res => {
    itemPermission = getItemPerm(res.result || []);
  });
  return Promise.all([ getUserMenu, getUserOperation ]);
}

async function getAppMenu(menuCode) {
  // 先根据menuCode获取应用ID
  // 然后根据应用ID判断是否是协作应用
  // 然后再通过是否是协作应用获取应用菜单和应用权限项
  let appId = '';
  await request({ url: '/gic-auth-web/get-app-by-code' }, { menuCode }).then(res => {
    appId = res.result;
  });
  const urlList = {
    menu: [ '/gic-auth-web/login-user-menu-of-app', '/gic-auth-web/login-collaborator-menu-of-app' ],
    opera: [ '/gic-auth-web/login-user-operation-item-of-app', '/gic-auth-web/login-collaborator-operation-item' ]
  };
  let identifier = 0; // 0: 非协作应用 1：协作应用

  await request({ url: '/application-center-web/business/cooperation-application/find-list' }).then(res => {
    const result = res.result || [];
    if (result.some(el => el.applicationId == appId)) {
      identifier = 1;
    }
  });
  const getUserMenu = request({ url: urlList.menu[identifier] }, { appId }).then(res => {
    accessPath = getProjectMenu(res.result || []);
    store.commit('updateRoutePath', res.result ? res.result[0].children : []); // warning: 与默认文件不同处  store中放入route信息
  });
  const getUserOperation = request({ url: urlList.opera[identifier] }, { appId }).then(res => {
    itemPermission = getItemPerm(res.result || []);
  });
  return Promise.all([ getUserMenu, getUserOperation ]);
}

function getProjectMenu(menu) {
  let result = [];
  menu.forEach(el => {
    if (el.projectUrlForWeb == project && 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) {
  console.log(to, from);
  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 });
    return next();
  };


  // 无权限访问
  if (process.env['NODE_ENV'] === 'development') { // eslint-disable-line
    // warning: 与默认文件不同处
    console.log('!!!无权限页面');
    return next();
  } else {
    if (projectRoutes.some(el => el == to.path) || accessPath.length == 0) {
      window.location.href = `${origin}/damo-system/no-access`;
    } else {
      Object.assign(axios.defaults.headers.common, { route: accessPath[0] });
      next(accessPath[0]);
    }
  }
}

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

let permission = function(config) {
  const { projectPath, isApp, writeRoute, router, routes, createApp, menuCode } = config;
  const fullLoading = Vue.prototype.$loading({
    lock: true,
    customClass: 'medium'
  });
  project = projectPath;
  window.addEventListener('load', async function() {
    // 获取菜单数据
    const path = window.location.pathname;
    if (path.indexOf('/login') == -1) {
      // 获取企业id，然后向请求头中添加sign、project、route三个参数
      // 其中route是动态参数，会在intercept中取to.path
      await getUserInfo().then(res => {
        const { enterpriseId } = res.result || {};
        Object.assign(axios.defaults.headers.common, {
          sign: enterpriseId,
          project: projectPath.replace(/^\//, ''),
          route: path.replace(projectPath, '')
        });
      });
      if (isApp) {
        await getAppMenu(menuCode);
      } else {
        await getGicMenu();
      }
    }
    if (Array.isArray(writeRoute)) {
      accessPath = accessPath.concat(writeRoute);
    }

    if (Array.isArray(routes)) {
      // 项目中路由文件配置的路径
      projectRoutes = flatRoutes(routes);
    }
    router.beforeEach(intercept);
    // 创建vue实例，渲染页面
    if (typeof createApp == 'function') {
      fullLoading.close();
      createApp();
    }
  });
};

export { permission, itemPerm };
