import _regeneratorRuntime from "@babel/runtime/regenerator";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _extends from "@babel/runtime/helpers/esm/extends";
import { getToken } from "./token";
import { md5Http, random, getXWebTraceId } from './common';
import adapter from './axios-adapter.js';
import Toast from '../toast';
import bus from './bus';
var axios = window.axios; // const Toast = window.ksui && window.ksui.Toast

var TIMEOUT = 20000;

var getErrors = function getErrors() {
  var _ref;

  return _ref = {
    'Network Error': '网络错误，请检查网络'
  }, _ref["timeout of " + TIMEOUT + "ms exceeded"] = '请求超时，服务器未响应', _ref['Internal Server Error'] = '请求服务器错误', _ref['Request failed with status code 502'] = '请求服务器错误', _ref.api = '接口错误', _ref;
}; // axios实例


var isKSClient = navigator.userAgent.toLowerCase().indexOf('kuasheng-2.0') >= 0;
var options = {
  baseURL: '/router/rest',
  timeout: TIMEOUT,
  headers: {
    'format': 'JSON'
  }
};
options = isKSClient ? _extends({}, options, {
  adapter: adapter
}) : options;
var httpClient = axios.create(options);
httpClient.interceptors.request.use(function (config) {
  // headers对象中设置_tips属性，合并到config中并从headers中删除
  var $config = config.headers.$config;

  if ($config) {
    config.$config = _extends({}, $config);
    delete config.headers.$config;
  }

  bus.$emit('httpStart', config);
  return config;
});
httpClient.interceptors.response.use(function (res) {
  bus.$emit('httpEnd', res);

  if (String(res.data.code) === '0') {
    return res.data.data;
  } // options参数中有_tips属性不提示错误


  if (res.config.$config === undefined || res.config.$config._tips === undefined) {
    Toast(res.data.msg);
  }

  return Promise.reject(res);
}, function (error) {
  var msg = error.message || error.msg;
  var config = error._config || {};

  if (msg && (config.$config === undefined || config.$config._tips === undefined)) {
    var ERRORS = getErrors();
    error.message = ERRORS[msg] || msg || ERRORS.api;
    Toast(error.message);
  }

  return Promise.reject(error);
});
/**
 *
 * @param {string} method 开放平台的apiCode
 * @param {number | string} appkey 开放平台的appkey
 * @param {object} data
 * @param {object} options 其他配置
 */

var http = /*#__PURE__*/function () {
  var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(method, appkey, data, options) {
    var token, menu, user, res, now, headers, config;
    return _regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            if (options && options.timeout) {
              TIMEOUT = options.timeout;
            }

            token = getToken();
            menu = window.ksui.menu; // 先从window上获取user，没有再调跨声sdk获取

            user = window.ksui && window.ksui.user;

            if (user && user.id) {
              _context.next = 20;
              break;
            }

            if (!window.ks.getUserInfo) {
              _context.next = 19;
              break;
            }

            _context.prev = 6;
            _context.next = 9;
            return window.ks.getUserInfo();

          case 9:
            res = _context.sent;
            user = res.userInfo;
            _context.next = 17;
            break;

          case 13:
            _context.prev = 13;
            _context.t0 = _context["catch"](6);
            user = {
              id: ''
            };
            console.log(_context.t0);

          case 17:
            _context.next = 20;
            break;

          case 19:
            user = {
              id: ''
            };

          case 20:
            now = Date.now();
            headers = {
              method: method,
              appkey: appkey,
              token: token,
              timestamp: now,
              sign: md5Http(token, now, data),
              'X-menu-id': menu.id,
              webTraceId: user.id + "-" + now + "-" + random(4) + "-" + (menu.id || 'xxxx'),
              'x-webtrace-id': getXWebTraceId(user.id, menu.id, now)
            };

            if (options && options.headers) {
              headers = _extends({}, headers, options.headers);
            }

            config = _extends({
              url: "?" + method,
              method: 'POST',
              data: data
            }, options, {
              headers: headers
            });
            return _context.abrupt("return", httpClient(config));

          case 25:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, null, [[6, 13]]);
  }));

  return function http(_x, _x2, _x3, _x4) {
    return _ref2.apply(this, arguments);
  };
}(); // 换token


var token = function token(data) {
  var headers = {
    method: 'cas.oauth.ticketValidate',
    appkey: 10184
  };
  return httpClient({
    method: 'POST',
    data: data,
    headers: headers
  });
};

export { http, token };