"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.getQueryByName = exports.getBasePath = exports["default"] = void 0;
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _request = _interopRequireDefault(require("@ywfe/request"));
var _jsonLogicJs = _interopRequireDefault(require("json-logic-js"));
var _antd = require("antd");
var ot = require('@ywfe/yw-transform');

/**
 * 生成查询参数
 * @param obj
 * @returns
 */
function stringify(obj) {
  var params = new URLSearchParams();
  for (var key in obj) {
    if (obj.hasOwnProperty(key) && obj[key] !== null && obj[key] !== undefined && obj[key] !== '') {
      params.append(key, obj[key]);
    }
  }
  return params.toString();
}

/**
 * 获取地址对应参数
 * @param name
 * @param search
 * @returns
 */
var getQueryByName = exports.getQueryByName = function getQueryByName(name, search) {
  var reg = new RegExp("(\\?|&)" + name + "=([^&]*)(&|$)", 'i');
  var searchParams = window.location.href;
  var values = reg.exec(search || searchParams);
  if (values != null) {
    return decodeURIComponent(values[2]) || '';
  }
  return '';
};
var basePathMap = new Map([['prod', 'https://gateway.ywwl.com'], ['test', 'https://test-gateway.ywwl.com'], ['test2', 'https://test2-gateway.ywwl.com'], ['dev', 'https://dev-gateway.ywwl.com']]);
// 获取host
var getBasePath = exports.getBasePath = function getBasePath() {
  var env = window.localStorage.getItem('env') || 'prod';
  return basePathMap.get(env);
};
var CONSTANTS = {
  // 运行时环境
  ENV: window.localStorage.getItem('env') || 'prod',
  BASEPATH: getBasePath()
};

// 请求接口
function createYwFetchHandler(config) {
  return /*#__PURE__*/function () {
    var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(options) {
      var requestConfig, basePath, paramsStr, response, params, _response;
      return _regenerator["default"].wrap(function _callee$(_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            requestConfig = (0, _extends2["default"])({}, options, {
              url: options.uri,
              method: options.method,
              data: options.params,
              headers: options.headers
            }, config); // todo basePath
            basePath = options.basePath || config.basePath;
            if (!(requestConfig.method === 'GET')) {
              _context.next = 10;
              break;
            }
            paramsStr = stringify(options.params);
            _context.next = 6;
            return _request["default"].get("" + basePath + options.uri + (paramsStr ? "?" + paramsStr : ''), {
              loginHost: config === null || config === void 0 ? void 0 : config.loginHost,
              timeout: options.timeout,
              headers: options.headers
            });
          case 6:
            response = _context.sent;
            return _context.abrupt("return", {
              data: response
            });
          case 10:
            if (!(requestConfig.method === 'POST')) {
              _context.next = 17;
              break;
            }
            params = options.params;
            if (options.headers['Content-type'] === 'multipart/form-data') {
              params = new FormData();
              Object.keys(options.params).forEach(function (key) {
                if (options.params[key] instanceof Array) {
                  options.params[key].forEach(function (item) {
                    params.append(key, item);
                  });
                  return;
                }
                params.append(key, options.params[key]);
              });
            }
            _context.next = 15;
            return _request["default"].post("" + basePath + options.uri, params, {
              loginHost: config === null || config === void 0 ? void 0 : config.loginHost,
              timeout: options.timeout,
              headers: options.headers
            });
          case 15:
            _response = _context.sent;
            return _context.abrupt("return", {
              data: _response
            });
          case 17:
            throw new Error('不支持的请求方法');
          case 18:
          case "end":
            return _context.stop();
        }
      }, _callee);
    }));
    return function (_x) {
      return _ref.apply(this, arguments);
    };
  }();
}
var appHelper = {
  constants: CONSTANTS,
  requestHandlersMap: {
    request: createYwFetchHandler({
      basePath: CONSTANTS.BASEPATH
    })
  },
  utils: {
    // 后面去掉
    transformData: function transformData(sourceData) {
      // 兼容原配置
      return sourceData;
    },
    // 函数转换
    transform: function transform(_ref2) {
      var source = _ref2.source,
        rules = _ref2.rules;
      return ot(source, rules);
    },
    // 逻辑转换
    apply: function apply(_ref3) {
      var source = _ref3.source,
        rules = _ref3.rules;
      return _jsonLogicJs["default"].apply(rules, source);
    },
    // 获取浏览器指定查询参数
    getQueryByName: getQueryByName,
    exportExcel: function exportExcel(url, params, noPre) {
      if (params === void 0) {
        params = {};
      }
      // const protectId = 'PRO_CUSTOMERSERVICE';
      // const env = getEnv();
      var data = Object.assign({}, params, {
        token: localStorage.getItem('token')
      });
      var paramsStr = data ? stringify(data) : '';
      var downloadUrl = "" + (noPre ? CONSTANTS.BASEPATH : '') + url + "?" + paramsStr;
      console.log("\u5BFC\u51FA\uFF1A" + downloadUrl);
      var id = "alink-" + new Date().getTime();
      var aDom = document.createElement('a');
      aDom.setAttribute('href', downloadUrl);
      aDom.setAttribute('target', '_blank');
      aDom.setAttribute('id', id);
      if (!document.getElementById(id)) {
        document.body.appendChild(aDom);
      }
      // 模拟点击
      aDom.click();
      // 删除这个假dom
      setTimeout(function () {
        document.body.removeChild(aDom);
      }, 0);
    }
  }
};
var getAppHelper = function getAppHelper(_ref4) {
  var history = _ref4.history,
    ywHistory = _ref4.ywHistory,
    state = _ref4.state,
    _ref4$utils = _ref4.utils,
    utils = _ref4$utils === void 0 ? {} : _ref4$utils,
    _ref4$constants = _ref4.constants,
    constants = _ref4$constants === void 0 ? {} : _ref4$constants;
  var _history = history || {
    push: function push(url, params, hash) {
      var paramsStr = params ? stringify(params) : '';
      var hashStr = hash ? "#" + hash : '';
      var searchStr = paramsStr || hashStr ? "?" + hashStr + paramsStr : '';
      ywHistory.push("" + url + searchStr);
    },
    open: function () {
      var _open = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(url, params, hash) {
        var newUrl, paramsStr, hashStr, res, searchStr;
        return _regenerator["default"].wrap(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              newUrl = url.replace(/\//g, '_');
              paramsStr = params ? stringify(params) : '';
              hashStr = hash ? "#" + hash : '';
              _context2.next = 5;
              return _request["default"].get(CONSTANTS.BASEPATH + "/ywwl-admin/desktop/module/info/query?resourceNameEn=" + url);
            case 5:
              res = _context2.sent;
              searchStr = paramsStr || hashStr ? "?" + hashStr + paramsStr : '';
              window.open("/" + res.moduleNameEn + "/" + res.moduleId + "/" + newUrl + searchStr);
            case 8:
            case "end":
              return _context2.stop();
          }
        }, _callee2);
      }));
      function open(_x2, _x3, _x4) {
        return _open.apply(this, arguments);
      }
      return open;
    }()
  };
  var hasPermission = function hasPermission(name) {
    var _state$permissions;
    return state === null || state === void 0 ? void 0 : (_state$permissions = state.permissions) === null || _state$permissions === void 0 ? void 0 : _state$permissions.includes(name);
  };
  return (0, _extends2["default"])({}, appHelper, {
    constants: (0, _extends2["default"])({}, appHelper.constants, constants),
    utils: (0, _extends2["default"])({}, appHelper.utils, {
      hasPermission: hasPermission
    }, utils),
    message: _antd.message,
    history: _history,
    state: state
  });
};
var _default = exports["default"] = getAppHelper;