import axios from 'axios';

var WECOM_ROBOT_PREFIX = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=';
function getRobotWebhookUrl(key) {
  if (key.startsWith('http')) {
    return key;
  }
  return "".concat(WECOM_ROBOT_PREFIX).concat(key);
}
/**
 * 给机器人发消息的基本方法
 * @private
 * @param {object} config 输入信息
 * @param {string} config.webhookUrl webhook地址
 * @param {object} config.params 详细参数
 * @returns Promise
 * @example
 * ```ts
 * await sendToRobot({
 *   webhookUrl: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxx',
 *   params: {
 *     msgtype: 'markdown',
 *     markdown: { content: '## Hello World' },
 *   },
 * });
 * ```
 */
function sendToRobot(_ref) {
  var webhookUrl = _ref.webhookUrl,
    params = _ref.params;
  return new Promise(function (resolve, reject) {
    if (!webhookUrl) {
      reject(new Error('缺少 webhookUrl！'));
      return;
    }
    webhookUrl = parsePrefixChatId(webhookUrl);
    webhookUrl = getRobotWebhookUrl(webhookUrl);
    if (params.chatid) {
      params.chatid = parsePrefixChatId(params.chatid);
    }
    axios.post(webhookUrl, params).then(function (res) {
      var _a;
      if (((_a = res === null || res === void 0 ? void 0 : res.data) === null || _a === void 0 ? void 0 : _a.errcode) !== 0) {
        console.log('[sendToRobot] err: \n', res === null || res === void 0 ? void 0 : res.data);
        reject(res);
      } else {
        resolve(res);
      }
    })["catch"](function (err) {
      console.log('[sendToRobot] err: \n', err === null || err === void 0 ? void 0 : err.data);
      reject(err);
    });
  });
}
/**
 * 解析chatId，允许chatId头部带有其他前缀
 * 比如T_COMM_UPDATE___xxx，前缀可以用来表明chatId来自哪里
 * @ignore
 *
 */
function parsePrefixChatId(chatId) {
  var SEPARATOR = '___';
  if (chatId.indexOf(SEPARATOR) < 0) {
    return chatId;
  }
  return chatId.split(SEPARATOR)[1];
}

export { getRobotWebhookUrl, sendToRobot };
