"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;
var _axios = _interopRequireDefault(require("axios"));
var _isObject = _interopRequireDefault(require("./isObject"));
var _getVtxToken = _interopRequireDefault(require("@vtx/utils/lib/getVtxToken"));
var _trim = _interopRequireDefault(require("@vtx/utils/lib/trim"));
var _setCookie = _interopRequireDefault(require("./setCookie"));
var _pickBy = _interopRequireDefault(require("lodash/pickBy"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); 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, _toPropertyKey(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; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
// 默认30秒超时
var SECOND = 30;
var MILL_SECOND = 1000;
var t;

/**
 * 基于 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);
    t = this;
  }
  // 初始化
  _createClass(Http, [{
    key: "_createAxios",
    value: function _createAxios(options) {
      var _ref = (0, _getVtxToken["default"])() || {},
        token = _ref.token,
        tenantId = _ref.tenantId,
        userId = _ref.userId;
      // 创建实例
      var instance = _axios["default"].create(_objectSpread({
        // `timeout` 指定请求超时的毫秒数(0 表示无超时时间)
        // 如果请求话费了超过 `timeout` 的时间，请求将被中断
        timeout: MILL_SECOND * SECOND,
        headers: {
          Authorization: token ? "Bearer ".concat(token) : '',
          'Cache-Control': 'no-cache',
          'content-type': 'application/json;charset=UTF-8',
          tenantId: tenantId,
          userId: userId
        }
      }, 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,
        headers = options.headers;
      // 过滤掉值为 '' || undefined || null 的对象属性
      var postData = (0, _isObject["default"])(body) ? (0, _pickBy["default"])((0, _trim["default"])(body), function (value) {
        return value !== '' && value !== undefined && value !== null;
      }) : {};
      return t.instance.get(url, {
        headers: _objectSpread({}, headers),
        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$headers = options.headers,
        headers = _options$headers === void 0 ? {} : _options$headers;
      return t.instance.post(url, body, {
        headers: headers ? headers : {}
      });
    }

    /**
     * 响应数据的处理
     * @param {*} response
     */
  }, {
    key: "_responseHandler",
    value: function _responseHandler(response) {
      var status = response.status,
        data = response.data,
        statusText = response.statusText;
      var tokenInfo = response.headers['ACCESS-TOKEN'] || response.headers['access-token'];
      if (tokenInfo) {
        tokenInfo = JSON.parse(tokenInfo);
        var token = tokenInfo.access_token;
        (0, _setCookie["default"])('token', token);
        localStorage.setItem('token', token);
      }
      if (status >= 200 && status < 300) {
        // 判断条件更据后期实际情况调整
        if (!data.result) {
          return data;
        } else {
          console.log(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;
          case 401:
            if (process.env.MENU) {
              if (window.location.hash.indexOf('login') !== -1) {
                msg = '请求错误，请检查或刷新重试！';
              } else {
                // history.push('/login');
              }
            } else {
              localStorage.setItem('isLogin', 'no');
              msg = '登录过期，请退出重新登录！';
            }
            break;
          default:
            msg = '请求错误，请检查或刷新重试！';
            break;
        }
        console.log(msg);
      } else {
        console.log('服务不可用');
      }
    }

    // 获取实例
  }, {
    key: "getInstance",
    value: function getInstance() {
      return t.instance;
    }
  }]);
  return Http;
}();
var http = new Http();
var _default = exports["default"] = http;
//# sourceMappingURL=http.js.map
