"use strict";

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

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

var _window$BSGlobal$tena, _window$BSGlobal$logi;

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

var tenantId = (_window$BSGlobal$tena = window.BSGlobal.tenantInfo) === null || _window$BSGlobal$tena === void 0 ? void 0 : _window$BSGlobal$tena.Id;
var userId = (_window$BSGlobal$logi = window.BSGlobal.loginUserInfo) === null || _window$BSGlobal$logi === void 0 ? void 0 : _window$BSGlobal$logi.Id;

var requestDomain = function requestDomain() {
  if (!window.location.hostname.match(/.work/)) return '';
  return "".concat(window.location.protocol, "//www.tita.gift");
};

exports.requestDomain = requestDomain;

function getToken() {
  return sessionStorage.getItem('DEMOFREE_TOKEN') || '';
}

function setToken(token) {
  sessionStorage.setItem('DEMOFREE_TOKEN', token);
}

var getJwtToken = function getJwtToken() {
  return _axios["default"].get("".concat(requestDomain(), "/api/v1/").concat(tenantId, "/").concat(userId, "/const/skynetToken")).then(function (res) {
    var _res$data;

    if ((_res$data = res.data) !== null && _res$data !== void 0 && _res$data.Data) {
      setToken(JSON.parse(res.data.Data.obj).token);
      return JSON.parse(res.data.Data.obj);
    }

    return false;
  });
};

exports.getJwtToken = getJwtToken;

var instance = _axios["default"].create({
  timeout: 10 * 1000
});

var beforeRequest = function beforeRequest(config) {
  config.headers['authorization'] = "Bearer ".concat(getToken());
  return config;
};

var beforeResponse = function beforeResponse(res) {
  var config = res.config;
  config.retry = 3;
  config.__retryCount = config.__retryCount || 0;

  if (res.data.code == 401) {
    // 401错误表示未登录授权或者token失效
    if (config.__retryCount <= config.retry) {
      config.__retryCount += 1;
      return getJwtToken().then(function () {
        return instance.request(res.config);
      });
    }

    return Promise.reject(res);
  }

  return res.data;
};

var requestError = function requestError(error) {
  return Promise.reject(error);
};

instance.interceptors.request.use(beforeRequest, requestError);
instance.interceptors.response.use(beforeResponse, function (error) {
  console.log({
    error: error
  });
});
var _default = instance;
exports["default"] = _default;