import axios from 'axios';
import { name } from '../package.json';
// 整理路由
const routerObj = {};
const titleObj = {};
let baseUrl = process.env.VUE_APP_BASE_ROUTE_URL || process.env.BASE_URL || '';
let fullHost = location.host || '';
if (fullHost.indexOf('uat-') != -1) {
  fullHost = fullHost.replace('uat-', '');
}
if (fullHost.indexOf('http') == -1) {
  fullHost = (window.location.protocol || 'https:') + '//' + fullHost;
}
let rMode = 'history';
if (window.location.hash) {
  rMode = 'hash';
  baseUrl = baseUrl || location.pathname;
}
let projectName = name;
// 处理路由children
function allRouter(ele, spath) {
  for (var i = 0; i < ele.length; i++) {
    if (ele[i].path) {
      let key = '';
      if (spath && spath != '/') {
        key = spath + '/' + ele[i].path;
      } else {
        key = ele[i].path;
      }
      routerObj[key] = key;
      titleObj[key] = ele[i].meta && ele[i].meta.title;
      if (ele[i].children) {
        allRouter(ele[i].children, ele[i].path);
      }
    }
  }
}
// 处理路由
function handleAllRouter(parmsObj) {
  parmsObj.mode = parmsObj.mode || rMode;
  projectName = parmsObj.projectName || projectName;
  baseUrl = parmsObj.baseUrl || baseUrl || '';
  const fhost = parmsObj.fullHost || fullHost;
  if (baseUrl.substr(baseUrl.length - 1, 1) == '/') {
    baseUrl = baseUrl.substr(0, baseUrl.length - 1);
  }
  if (parmsObj.mode == 'hash') {
    baseUrl = baseUrl + '/#';
  }
  allRouter(parmsObj.routerConfig, '');
  const arr = [];
  for (var key in routerObj) {
    const optionObj = {};
    optionObj.url = routerObj[key];
    optionObj.fullPath = fhost + baseUrl + routerObj[key];
    optionObj.host = fhost;
    optionObj.title = titleObj[key];
    arr.push(optionObj);
  }

  sendAllRouterInfo(arr);
}
// 发送请求
function sendAllRouterInfo(data) {
  let url = '';
  if (process.env.NODE_ENV == 'development') {
    url = 'https://dev-sc.yunqueyi.com/basic-data/menuCode/upload';
  } else if (process.env.VUE_APP_ENV == 'uat') {
    url = 'https://sc.yunqueyi.com/basic-data/menuCode/upload';
  }
  if (!url) {
    return;
  }
  const obj = {
    projectName: projectName,
    menuCodeDtoList: data,
  };
  console.log(obj);
  axios({
    method: 'post',
    url: url,
    data: obj,
  })
    .then((res) => {
      console.log('请求接口成功了', res.data);
      return;
    })
    .catch((err) => {
      console.log('errerrerr', err);
      return;
    });
}
export default handleAllRouter;
