import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
var _excluded = ["data", "params", "requestType", "getResponse", "getFullData", "includeCode", "showErrorMessage", "responseType"];
import _regeneratorRuntime from "@babel/runtime/regenerator";
import { isArray, forEach2ObjArr, isObject, reqStringify, isDate } from './utils';
import { default as Pfmessage } from '../../message';
// 序列化params
var paramsSerialize = function paramsSerialize(params) {
  var serializedParams = undefined;
  var jsonStringifiedParams = undefined;
  if (params) {
    if (isArray(params)) {
      jsonStringifiedParams = [];
      forEach2ObjArr(params, function (item) {
        if (item === null || typeof item === 'undefined') {
          jsonStringifiedParams.push(item);
        } else {
          jsonStringifiedParams.push(isObject(item) ? JSON.stringify(item) : item);
        }
      });
      serializedParams = reqStringify(jsonStringifiedParams);
    } else {
      jsonStringifiedParams = {};
      forEach2ObjArr(params, function (value, key) {
        var jsonStringifiedValue = value;
        if (value === null || typeof value === 'undefined') {
          jsonStringifiedParams[key] = value;
        } else if (isDate(value)) {
          jsonStringifiedValue = value.toISOString();
        } else if (isArray(value)) {
          jsonStringifiedValue = value;
        } else if (isObject(value)) {
          jsonStringifiedValue = JSON.stringify(value);
        }
        jsonStringifiedParams[key] = jsonStringifiedValue;
      });
      var tmp = 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 = _objectWithoutProperties(_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 = _objectSpread(_objectSpread({}, 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 = _objectSpread({
          Accept: 'application/json',
          'Content-Type': 'application/json;charset=UTF-8'
        }, init.headers);
        init.body = JSON.stringify(data);
      } else if (responseType === 'form') {
        init.headers = _objectSpread({
          Accept: 'application/json',
          'Content-Type': 'application/x-www-form-urlencodedw;charset=UTF-8'
        }, init.headers);
      } else {
        init.headers = _objectSpread({
          Accept: 'application/json'
        }, init.headers);
        init.body = data;
      }
    }
  }
  return fetch(_url, init).then( /*#__PURE__*/function () {
    var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(response) {
      var copy, dataJson, _ref3, code, _data2, _data, _dataJson;
      return _regeneratorRuntime.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 && Pfmessage.error(errorMessage);
    throw error;
  });
}
export default Request;