import _regeneratorRuntime from '@babel/runtime/regenerator';
import { _ as __awaiter } from '../../tslib.es6-848120af.js';
import axios from 'axios';
import { getCredential } from './credential.mjs';

function getCustomEventQuery(_ref) {
  var startTime = _ref.startTime,
    endTime = _ref.endTime,
    projectId = _ref.projectId,
    _ref$env = _ref.env,
    env = _ref$env === void 0 ? 'production' : _ref$env;
  var envStr = '';
  if (env === 'production') {
    envStr = ' and "env"=\'production\' ';
  }
  return "select delta(count) as allCount from event_url_statistics where time >= ".concat(startTime, "s and time <= ").concat(endTime, "s and id='").concat(projectId, "' ").concat(envStr, " group by \"name\" slimit 1000");
}
function flattenEventData(data) {
  return data.reduce(function (acc, item) {
    var _a, _b, _c;
    var key = (_a = item.tags) === null || _a === void 0 ? void 0 : _a.name;
    if (!key) {
      return acc;
    }
    acc[key] = ((_c = (_b = item.values) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c[1]) || 0;
    return acc;
  }, {});
}
/**
 * 获取自定义事件数据
 * @ignore
 * @param {object} options 配置
 * @param {number} options.startTime 开始时间，格式如 1655282977
 * @param {number} options.endTime 结束时间，格式如 1655282977
 * @param {number} options.projectId 项目Id
 * @param {object} options.secretInfo 密钥信息
 * @param {string} [options.env] 环境，默认为production
 * @returns {Promise<object>} 自定义事件数据
 * @example
 *
 * getCustomEventData({
 *   startTime: 1665383837,
 *   endTime: 1665470227,
 *   projectId: 57706,
 *   secretInfo: {
 *     getPwdCode,
 *     encrypt,
 *     apiKey: '',
 *     loginName: '',
 *   },
 * }).then(resp => {
 *   console.log(resp)
 * })
 *
 * // 结果如下：
 *
 * {
 *   AI_PLAYER_EVENT_0: 7319,
 *   AI_PLAYER_EVENT_14: 14,
 *   AI_PLAYER_EVENT_300001: 6600,
 *   AI_PLAYER_EVENT_4: 10,
 *   LAUNCH_GAME_FAIL_QQ: 170,
 *   LAUNCH_GAME_FAIL_WX: 25,
 *   LAUNCH_GAME_SUC_GP_HELPER: 31,
 *   LAUNCH_GAME_SUC_QQ: 1179,
 * }
 */
function getCustomEventData(_ref2) {
  var startTime = _ref2.startTime,
    endTime = _ref2.endTime,
    projectId = _ref2.projectId,
    _ref2$env = _ref2.env,
    env = _ref2$env === void 0 ? 'production' : _ref2$env,
    secretInfo = _ref2.secretInfo;
  var _a, _b;
  return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
    var credential, result, res;
    return _regeneratorRuntime.wrap(function (_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          _context.next = 1;
          return getCredential(secretInfo);
        case 1:
          credential = _context.sent;
          _context.next = 2;
          return axios({
            method: 'POST',
            url: '/api/interface/monitor/queryData',
            data: {
              Namespace: 'TAM-v1',
              Query: getCustomEventQuery({
                startTime: startTime,
                endTime: endTime,
                projectId: projectId,
                env: env
              })
            },
            headers: Object.assign({}, credential)
          });
        case 2:
          result = _context.sent;
          res = [];
          try {
            /**
             * res格式为：
             * body: {
             *     Response: {
             *       RequestId: '22561d33ea8254619d56c05a-183c5c8b617',
             *       Result: '{"request_id":"22561d33ea8254619d56c05a-183c5c8b617","results":[]}'
             *     }
             *   },
             */
            res = JSON.parse(result.data.Response.Result) || {};
            /**
              * res：
              * {
              * 	"request_id": "22561d33ea8254619d56c05a-183c5c8b617",
              * 	"results": [{
              * 		"statement_id": 0,
              * 		"series": [{
              * 			"name": "event_url_statistics",
              * 			"tags": {
              * 				"name": "PAGE_INDEX"
              * 			},
              * 			"columns": ["time", "allCount"],
              * 			"values": [
              * 				[0, 13907]
              * 			]
              * 		}, {
              * 			"name": "event_url_statistics",
              * 			"tags": {
              * 				"name": "LAUNCH_GAME_SUC_WX"
              * 			},
              * 			"columns": ["time", "allCount"],
              * 			"values": [
              * 				[0, 94]
              * 			]
              * 		}, {
              * 			"name": "event_url_statistics",
              * 			"tags": {
              * 				"name": "PAGE_AI_ROOM"
              * 			},
              * 			"columns": ["time", "allCount"],
              * 			"values": [
              * 				[0, 1502]
              * 			]
              * 		}],
              * 		"total": 3
              * 	}]
              * }
              */
            res = ((_b = (_a = res === null || res === void 0 ? void 0 : res.results) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.series) || [];
          } catch (e) {}
          return _context.abrupt("return", flattenEventData(res));
        case 3:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
}
/**
 * 获取多个项目的自定义事件数据
 * @ignore
 * @param options 配置
 */
function getMultiCustomEventData(_ref3) {
  var startTime = _ref3.startTime,
    endTime = _ref3.endTime,
    _ref3$env = _ref3.env,
    env = _ref3$env === void 0 ? 'production' : _ref3$env,
    secretInfo = _ref3.secretInfo,
    projectIdMap = _ref3.projectIdMap;
  return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
    var res, projectIdList, _i, _projectIdList, projectId, list, _i2, _projectIdList2, _projectId, info, extraData;
    return _regeneratorRuntime.wrap(function (_context2) {
      while (1) switch (_context2.prev = _context2.next) {
        case 0:
          res = {};
          projectIdList = Object.keys(projectIdMap);
          if (projectIdList.length) {
            _context2.next = 1;
            break;
          }
          return _context2.abrupt("return");
        case 1:
          _i = 0, _projectIdList = projectIdList;
        case 2:
          if (!(_i < _projectIdList.length)) {
            _context2.next = 5;
            break;
          }
          projectId = _projectIdList[_i];
          _context2.next = 3;
          return getCustomEventData({
            startTime: startTime,
            endTime: endTime,
            projectId: +projectId,
            env: env,
            secretInfo: secretInfo
          });
        case 3:
          list = _context2.sent;
          res[projectId] = list;
        case 4:
          _i++;
          _context2.next = 2;
          break;
        case 5:
          _i2 = 0, _projectIdList2 = projectIdList;
        case 6:
          if (!(_i2 < _projectIdList2.length)) {
            _context2.next = 9;
            break;
          }
          _projectId = _projectIdList2[_i2];
          info = projectIdMap[_projectId];
          if (!info.extraProjectId) {
            _context2.next = 8;
            break;
          }
          _context2.next = 7;
          return getCustomEventData({
            startTime: startTime,
            endTime: endTime,
            projectId: info.extraProjectId,
            env: env,
            secretInfo: secretInfo
          });
        case 7:
          extraData = _context2.sent;
          res[_projectId].extraData = extraData;
        case 8:
          _i2++;
          _context2.next = 6;
          break;
        case 9:
          return _context2.abrupt("return", res);
        case 10:
        case "end":
          return _context2.stop();
      }
    }, _callee2);
  }));
}

export { getMultiCustomEventData };
