"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getDataAndSetState = exports["default"] = void 0;
exports.getTicket = getTicket;
exports.refreshTicket = refreshTicket;
exports.resetRefreshTicket = resetRefreshTicket;
var _axios = _interopRequireDefault(require("axios"));
var _umi = require("umi");
var _isObject = _interopRequireDefault(require("lodash/isObject"));
var _pickBy = _interopRequireDefault(require("lodash/pickBy"));
var _message = _interopRequireDefault(require("antd/lib/message"));
var _utils = require("@vtx/utils");
var _PublicService = _interopRequireDefault(require("./PublicService"));
var _config = _interopRequireDefault(require("../config"));
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 MESSAGE_KEY = 'MESSAGE_KEY';
var t;
var _getUrlParam = (0, _utils.getUrlParam)(),
  token = _getUrlParam.token;

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

// 重置ticket
function resetRefreshTicket() {
  ticketFlag.forEach(function (servicePath) {
    sessionStorage.setItem("".concat(servicePath, "-ticket-flag"), 'true');
  });
  refreshTicket();
}

// 刷新 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 || _PublicService["default"].getToken();
      // 创建实例
      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: _PublicService["default"].getQueryString('tenantId') || _PublicService["default"].getSystemInfo('tenantId') || '',
          userId: _PublicService["default"].getQueryString('userId') || _PublicService["default"].getSystemInfo('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(_config["default"].apiPrefix + 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(_config["default"].apiPrefix + 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;
        _PublicService["default"].setCookie('token', _token);
        localStorage.setItem('token', _token);
      }

      //判断页面在不在iframe中
      var inIframe = window.top !== window;
      // 登录过期
      if (response.status === 401) {
        setTimeout(function () {
          _message["default"].error({
            content: '登录超时，请重新登录',
            key: MESSAGE_KEY,
            duration: 3
          });
          if (!inIframe && process.env.NODE_ENV !== 'development') {
            // 跳转到登录页
            window.location.href = "".concat(window.location.origin, "/#/");
          }
        }, 800);
      }
      if (status >= 200 && status < 300) {
        // 判断条件更据后期实际情况调整
        if (!data.result) {
          return data;
        } else {
          console.log('error3', error);
          // message.error({
          //     content: data.msg || '请求信息错误',
          //     key: MESSAGE_KEY,
          // });
          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 {
                _umi.history.push('/login');
              }
            } else {
              localStorage.setItem('isLogin', 'no');
              msg = '登录过期，请退出重新登录！';
            }
            break;
          default:
            msg = '请求错误，请检查或刷新重试！';
            break;
        }
        console.log('error1', error);
        _message["default"].error({
          content: msg,
          key: MESSAGE_KEY
        });
      } else {
        console.log('error2', error);
        _message["default"].error({
          content: '服务不可用',
          key: MESSAGE_KEY
        });
      }
    }

    // 获取实例
  }, {
    key: "getInstance",
    value: function getInstance() {
      return t.instance;
    }
  }]);
  return Http;
}();
var http = new Http();

/**
 * 获取数据并设置数据
 * @param request
 * @param setData
 * @param options
 * @returns {*}
 */
var getDataAndSetState = exports.getDataAndSetState = function getDataAndSetState(request, setData, options) {
  var url = request.url,
    method = request.method,
    params = request.params;
  var _ref = options || {},
    init = _ref.init,
    setLoading = _ref.setLoading;
  setLoading && setLoading(true);
  var _method = (method || 'get').toLowerCase();
  return http[_method](url, {
    body: _objectSpread({}, params)
  }).then(function (res) {
    var data;
    if ((res === null || res === void 0 ? void 0 : res.result) === 0 && res !== null && res !== void 0 && res.data) {
      data = res.data;
    }
    setData && setData(data || init);
    setLoading && setLoading(false);
    return data || init;
  })["catch"](function () {
    setData && setData(init);
    setLoading && setLoading(false);
    return init;
  });
};
var _default = exports["default"] = http;
//# sourceMappingURL=request.js.map
