"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;

var _axios = _interopRequireDefault(require("axios"));

var _qs = _interopRequireDefault(require("qs"));

var _isObject = _interopRequireDefault(require("lodash/isObject"));

var _pickBy = _interopRequireDefault(require("lodash/pickBy"));

var _antd = require("antd");

var _utils = require("@vtx/utils");

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

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }

// 默认30秒超时
var SECOND = 30;
var MILL_SECOND = 1000;

var _getUrlParam = (0, _utils.getUrlParam)(),
    token = _getUrlParam.token,
    tenantId = _getUrlParam.tenantId,
    userId = _getUrlParam.userId;
/**
 * 基于 axios 封装的请求封装
 * axios文档 http://www.axios-js.com/zh-cn/docs/
 * 支持 Get 和 Post 请求
 */


var Http = /*#__PURE__*/function () {
  function Http(options) {
    _classCallCheck(this, Http);

    // 创建axios实例
    this.instance = this._createAxios(options);
  } // 初始化


  _createClass(Http, [{
    key: "_createAxios",
    value: function _createAxios(options) {
      // 创建实例
      var instance = _axios["default"].create(_objectSpread({
        // `timeout` 指定请求超时的毫秒数(0 表示无超时时间)
        // 如果请求话费了超过 `timeout` 的时间，请求将被中断
        timeout: MILL_SECOND * SECOND,
        headers: {
          Authorization: token ? "Bearer ".concat(token) : '',
          'Cache-Control': 'no-cache',
          tenantId: tenantId
        }
      }, options));

      instance.interceptors.response.use(this._responseHandler, this._errorHandler);
      return instance;
    }
    /**
     * get 请求
     * @param {*} url
     * @param {*} options {body}
     */

  }, {
    key: "get",
    value: function get(url) {
      var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
      var _options$body = options.body,
          body = _options$body === void 0 ? {} : _options$body; // 过滤掉值为 '' || undefined || null 的对象属性

      var postData = (0, _isObject["default"])(body) ? (0, _pickBy["default"])((0, _utils.trim)(_objectSpread(_objectSpread({}, body), {}, {
        tenantId: tenantId
      })), function (value) {
        return value !== '' && value !== undefined && value !== null;
      }) : {};
      return this.instance.get(url, {
        params: _objectSpread({}, postData)
      });
    }
    /**
     * post 请求
     * @param {*} url
     * @param {*} options
     */

  }, {
    key: "post",
    value: function post(url) {
      var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
      var _options$body2 = options.body,
          body = _options$body2 === void 0 ? {} : _options$body2,
          _options$extraHeader = options.extraHeader,
          extraHeader = _options$extraHeader === void 0 ? {} : _options$extraHeader;
      var data = (0, _isObject["default"])(body) ? _qs["default"].stringify((0, _utils.trim)(body)) : (0, _utils.trim)(JSON.parse(body));

      if (extraHeader['Content-Type'] === 'application/json') {
        data = body;
      }

      return this.instance.post(url, data, {
        headers: extraHeader ? {
          operation: extraHeader.msg
        } : {}
      });
    }
    /**
     * 响应数据的处理
     * @param {*} response
     */

  }, {
    key: "_responseHandler",
    value: function _responseHandler(response) {
      var status = response.status,
          data = response.data,
          statusText = response.statusText;

      if (status >= 200 && status < 300) {
        if (data.result === 0) {
          return data;
        } else {
          _antd.message.error(data.msg || '请求信息错误');

          return;
        }
      }

      var error = new Error(statusText);
      error.response = response;
      throw error;
    }
    /**
     * 请求错误处理
     * @param {*} error
     */

  }, {
    key: "_errorHandler",
    value: function _errorHandler(error) {
      if (error.response) {
        var msg;

        switch (error.response.status) {
          case 404:
            msg = '接口请求不存在！错误码【404】。';
            break;

          case 500:
            msg = '服务端应用接口异常！错误码【500】。';
            break;

          default:
            msg = '请求错误，请检查或刷新重试！';
            break;
        }

        _antd.message.error(msg);
      } else {
        _antd.message.error('服务不可用');
      }
    } // 获取实例

  }, {
    key: "getInstance",
    value: function getInstance() {
      return this.instance;
    }
  }]);

  return Http;
}();

var http = new Http();
var _default = http;
exports["default"] = _default;
//# sourceMappingURL=request.js.map
