"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;
exports.getTicket = getTicket;
exports.refreshTicket = refreshTicket;
var _axios = _interopRequireDefault(require("axios"));
var _isObject = _interopRequireDefault(require("./isObject"));
var _getUrlParam2 = _interopRequireDefault(require("./getUrlParam"));
var _setCookie = _interopRequireDefault(require("./setCookie"));
var _getToken = _interopRequireDefault(require("./getToken"));
var _getSystemInfo = _interopRequireDefault(require("./getSystemInfo"));
var _pickBy = _interopRequireDefault(require("lodash/pickBy"));
var _utils = require("@vtx/utils");
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(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
// 默认30秒超时
var SECOND = 30;
var MILL_SECOND = 1000;
var t;
var _getUrlParam = (0, _getUrlParam2["default"])(),
  token = _getUrlParam.token;

// ticket 服务路径列表
var ticketFlag = ['/cloud/zhsw-jcss',
// 基础设施服务
'/cloud/zhsw-jcyj' // 监测预警服务
];

// 刷新 ticket
function refreshTicket() {
  ticketFlag.forEach(function (servicePath) {
    // 判断是否需要刷新 ticket
    var ticketFlag = sessionStorage.getItem("".concat(servicePath, "-ticket-flag")) === 'true';
    if (ticketFlag) {
      sessionStorage.setItem("".concat(servicePath, "-ticket-flag"), 'false');
      getTicket(servicePath);
    }
  });
}

// 获取相应服务的 ticket
function getTicket(servicePath) {
  http.get("".concat(servicePath, "/getTicket"), {
    body: {}
  }).then(function (res) {
    if ((res === null || res === void 0 ? void 0 : res.result) === 0) {
      sessionStorage.setItem("".concat(servicePath, "-ticket"), res.data);
    }
  });
}

// let retryRequests = []; //待重试的请求
// let isRefreshing = false; //是否正在刷新token
/**
 * 基于 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) {
      token = token || (0, _getToken["default"])();
      // 创建实例
      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: (0, _getUrlParam2["default"])('tenantId') || (0, _getSystemInfo["default"])('tenantId') || '',
          userId: (0, _getUrlParam2["default"])('userId') || (0, _getSystemInfo["default"])('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, _utils.trim)(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;
      var data = body;

      // 通过地址前两段得到相应的服务，例如: /cloud/zhsw-jcss
      var urlPaths = url.split('/');
      var servicePath = "/".concat([urlPaths[1], urlPaths[2]].join('/'));

      // 通过判断 ticket 标识及需要对应的服务传递 ticket
      if (headers !== null && headers !== void 0 && headers.ticket && ticketFlag.includes(servicePath)) {
        sessionStorage.setItem("".concat(servicePath, "-ticket-flag"), 'true');
        headers.ticket = sessionStorage.getItem("".concat(servicePath, "-ticket"));
      }
      return t.instance.post(url, data, {
        headers: headers ? headers : {}
      });
    }

    /**
     * 响应数据的处理
     * @param {*} response
     */
  }, {
    key: "_responseHandler",
    value: function _responseHandler(response) {
      var status = response.status,
        data = response.data,
        statusText = response.statusText;

      // 刷新 ticket
      refreshTicket();
      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 = http;
exports["default"] = _default;
//# sourceMappingURL=http.js.map
