'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.PFetchNoContext = exports.FFetch = exports.GFetch = exports.PFetch = undefined;

var _qs = require('qs');

var _qs2 = _interopRequireDefault(_qs);

var _StringUtils = require('../utils/StringUtils');

var _MenuHelper = require('../utils/MenuHelper');

var _CacheService = require('../service/CacheService');

var _MxFetch = require('../utils/MxFetch');

var _MxFetch2 = _interopRequireDefault(_MxFetch);

var _config = require('../../config');

var _config2 = _interopRequireDefault(_config);

var _SessionStorage = require('../service/SessionStorage');

var _LocalStorage = require('../service/LocalStorage');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * Created by baoyinghai on 10/18/16.
 */
var getHeader = function getHeader(url, isUpload) {
  var queryStr = location.href.split('?p=', 2)[1];
  var query = queryStr && _qs2.default.parse(atob(queryStr));
  var menuIds = Object.assign({}, (0, _SessionStorage.getRecMenuId)(), query);
  var menuItem = (0, _MenuHelper.getMenuItemByFunc)(function (item) {
    return (item.actionLink || item.domainLink) === '/' + url;
  }, (0, _LocalStorage.getMenuClobal)());
  if (menuItem && menuItem.menuCode) {
    menuIds.enterMenuId = menuItem.menuCode;
    (0, _SessionStorage.saveEnterMenuId)(menuItem.menuCode);
    if (!menuIds.processMenuId && (menuItem.actionLink.indexOf('ApplyList/render') !== -1 || menuItem.actionLink.indexOf('ReviewList/render') !== -1)) {
      (0, _SessionStorage.saveProcessMenuCode)(menuItem.actionLink.indexOf('ApplyList/render') !== -1 ? 'BPMApply.QueryToDo' : 'BPMReview.QueryToDo');
    }
  }
  if (isUpload) {
    return {
      'Accept': 'application/json',
      // 'Authorization': 'Basic  ' + getToken(),
      'MX-MainMenuId': menuIds.enterMenuId,
      'MX-ProcessSubMenuId': menuIds.processMenuId
    };
  }
  return {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    // 'Authorization': 'Basic  ' + getToken(),
    'MX-MainMenuId': menuIds.enterMenuId,
    'MX-ProcessSubMenuId': menuIds.processMenuId
  };
};

/* eslint-disable */
var process = function process(_promise) {
  return new Promise(function (resolve, reject) {
    _promise.then(function (response) {
      return response.text();
    }).then(function (response) {
      if (response === '') {
        resolve({});
      } else {
        var json = null;
        try {
          json = JSON.parse(response);
        } catch (e) {
          reject({ message: '系统异常' });
          console.error('不合法的JSON字符串:', response);
        }
        console.log('返回结果: ', json);
        if (json.msgContent || json.errMsg || json.message || json.code === 'version upgrade' || json.code == 404 || json.code == 500) {
          // ex === 5000 表示需要二次确认
          if (json.ex === 5000) {
            resolve({ needConfirm: true, msgContent: json.msgContent });
          } else {
            reject(json);
          }
        } else {
          resolve(json);
        }
      }
    }).catch(function (errorData) {
      reject(errorData);
    });
  });
};
var rawFetch = function rawFetch(url, param) {
  /* eslint-disable no-console */
  console.log('=========> 数据请求 <=========');
  console.log('请求地址: ', url);
  console.log('请求参数: ', param);
  // if (url.indexOf('http') < 0) {
  //   url = CbaseProcessUrl + url;
  // };
  // return process(MxFetch.fetch(Config.Host + url, param, 6180));
  return process(_MxFetch2.default.fetch((0, _StringUtils.trimStartAndEnd)(_config2.default.Host + url), param));
};
/* eslint-disable */
var PFetch = exports.PFetch = function PFetch(url, param) {
  var headers = getHeader(url);
  return rawFetch((0, _StringUtils.trimStart)(url, '/'), {
    method: 'POST',
    headers: headers,
    body: JSON.stringify(param)
  });
};
/* eslint-disable */
var GFetch = exports.GFetch = function GFetch(url, param) {
  var headers = getHeader(url);
  return rawFetch(url + (param ? '?' + _qs2.default.stringify(param) : ''), {
    method: 'GET',
    headers: headers
  });
};
// export const FFetch = (url, param) => {
//   const headers = getHeader(url, true);
//   return rawFetch(trimStart(url, '/'), {
//     method: 'POST',
//     headers,
//     body: param
//   });
// };

var FFetch = exports.FFetch = function FFetch(options) {
  options.headers = getHeader(options.action, true);
  options.action = _config2.default.Host + (0, _StringUtils.trimStart)(options.action, '/');
  return process(_MxFetch2.default.upload(options));
};

/* eslint-disable */
var PFetchNoContext = exports.PFetchNoContext = function PFetchNoContext(url, param) {
  var headers = getHeader(url);
  console.log('=========> 数据请求 <=========');
  console.log('请求地址: ', url);
  console.log('请求参数: ', param);
  // TODO: relative path
  return process(_MxFetch2.default.fetch('/' + (0, _StringUtils.trimStart)(url, '/'), {
    method: 'POST',
    headers: headers,
    body: JSON.stringify(param)
  }));
};

exports.default = {
  PFetch: PFetch,
  GFetch: GFetch,
  FFetch: FFetch,
  PFetchNoContext: PFetchNoContext
  // Upload
};