"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));
var _utils = require("./utils");
var _message = _interopRequireDefault(require("../../message"));
var _excluded = ["data", "params", "requestType", "getResponse", "getFullData", "includeCode", "showErrorMessage", "responseType"];
// 序列化params
var paramsSerialize = function paramsSerialize(params) {
  var serializedParams = undefined;
  var jsonStringifiedParams = undefined;
  if (params) {
    if ((0, _utils.isArray)(params)) {
      jsonStringifiedParams = [];
      (0, _utils.forEach2ObjArr)(params, function (item) {
        if (item === null || typeof item === 'undefined') {
          jsonStringifiedParams.push(item);
        } else {
          jsonStringifiedParams.push((0, _utils.isObject)(item) ? JSON.stringify(item) : item);
        }
      });
      serializedParams = (0, _utils.reqStringify)(jsonStringifiedParams);
    } else {
      jsonStringifiedParams = {};
      (0, _utils.forEach2ObjArr)(params, function (value, key) {
        var jsonStringifiedValue = value;
        if (value === null || typeof value === 'undefined') {
          jsonStringifiedParams[key] = value;
        } else if ((0, _utils.isDate)(value)) {
          jsonStringifiedValue = value.toISOString();
        } else if ((0, _utils.isArray)(value)) {
          jsonStringifiedValue = value;
        } else if ((0, _utils.isObject)(value)) {
          jsonStringifiedValue = JSON.stringify(value);
        }
        jsonStringifiedParams[key] = jsonStringifiedValue;
      });
      var tmp = (0, _utils.reqStringify)(jsonStringifiedParams);
      serializedParams = tmp;
    }
  }
  return serializedParams;
};
var defaultInit = {
  method: 'GET',
  credentials: 'include'
};
function Request(url, options) {
  var _options$method;
  var _ref = options || {},
    data = _ref.data,
    params = _ref.params,
    _ref$requestType = _ref.requestType,
    requestType = _ref$requestType === void 0 ? 'json' : _ref$requestType,
    getResponse = _ref.getResponse,
    getFullData = _ref.getFullData,
    includeCode = _ref.includeCode,
    _ref$showErrorMessage = _ref.showErrorMessage,
    showErrorMessage = _ref$showErrorMessage === void 0 ? true : _ref$showErrorMessage,
    responseType = _ref.responseType,
    _init = (0, _objectWithoutProperties2.default)(_ref, _excluded);
  var _url = url;
  var serializedParams = paramsSerialize(params);
  if (serializedParams) {
    var urlSign = url.indexOf('?') !== -1 ? '&' : '?';
    _url = "".concat(url).concat(urlSign).concat(serializedParams);
  }
  var init = (0, _objectSpread2.default)((0, _objectSpread2.default)({}, defaultInit), _init);
  init.method = (options === null || options === void 0 ? void 0 : (_options$method = options.method) === null || _options$method === void 0 ? void 0 : _options$method.toUpperCase()) || 'GET';
  if (['POST', 'PUT', 'PATCH', 'DELETE'].includes(init.method)) {
    var dataType = Object.prototype.toString.call(data);
    if (dataType === '[object, Object]' || dataType === '[object, Array]') {
      if (responseType === 'json') {
        init.headers = (0, _objectSpread2.default)({
          Accept: 'application/json',
          'Content-Type': 'application/json;charset=UTF-8'
        }, init.headers);
        init.body = JSON.stringify(data);
      } else if (responseType === 'form') {
        init.headers = (0, _objectSpread2.default)({
          Accept: 'application/json',
          'Content-Type': 'application/x-www-form-urlencodedw;charset=UTF-8'
        }, init.headers);
      } else {
        init.headers = (0, _objectSpread2.default)({
          Accept: 'application/json'
        }, init.headers);
        init.body = data;
      }
    }
  }
  return fetch(_url, init).then( /*#__PURE__*/function () {
    var _ref2 = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee(response) {
      var copy, dataJson, _ref3, code, _data2, _data, _dataJson;
      return _regenerator.default.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              if (!(response.status >= 200 && response.status < 300)) {
                _context.next = 16;
                break;
              }
              if (!(responseType === 'blob')) {
                _context.next = 3;
                break;
              }
              return _context.abrupt("return", response);
            case 3:
              copy = response.clone();
              _context.next = 6;
              return copy.json();
            case 6:
              dataJson = _context.sent;
              _ref3 = dataJson || {}, code = _ref3.code, _data2 = _ref3.data;
              if (!(code === '0' || includeCode !== null && includeCode !== void 0 && includeCode.includes(code))) {
                _context.next = 13;
                break;
              }
              _data = getFullData ? dataJson : _data2;
              return _context.abrupt("return", getResponse ? {
                data: _data,
                response: copy
              } : _data);
            case 13:
              throw dataJson;
            case 14:
              _context.next = 20;
              break;
            case 16:
              _context.next = 18;
              return response.clone().json();
            case 18:
              _dataJson = _context.sent;
              throw _dataJson;
            case 20:
            case "end":
              return _context.stop();
          }
        }
      }, _callee);
    }));
    return function (_x) {
      return _ref2.apply(this, arguments);
    };
  }()).catch(function (error) {
    var errorMessage = typeof error === 'string' ? error : error !== null && error !== void 0 && error.message ? error === null || error === void 0 ? void 0 : error.message : false;
    showErrorMessage && errorMessage && _message.default.error(errorMessage);
    throw error;
  });
}
var _default = Request;
exports.default = _default;