import baseUtil from '../../../utils/base';
import strRender from '../../../utils/strRender';
import messager from '../common/messager';
import emitManager from '../common/emitManager';
import { silenceLogger } from '../../../common/logger';

let nowEventId = Date.now() + 10000; // 事件回调唯一标识

export default {
  /**
   * @typedef {Object} ExtraOpt
   * @property {boolean} parseResponse 是否转换响应参数
   * @property {Object} extraDispatch 额外发送信息
   */
  /**
   * 调用方法并绑定事件
   * @param {string} moduleName 模块名
   * @param {string} topic API名
   * @param {object} opts 传参1
   * @param {Function} cb 传参2
   * @param {ExtraOpt} extraOpt 额外配置
   */
  onEvent(moduleName, topic, opts, cb, extraOpt) {
    if (baseUtil.isFun(opts)) {
      cb = opts;
      opts = null;
    }

    const { parseResponse = true, extraDispatch = {} } = extraOpt || {}
    const { callback: optCallback } = opts || {};
    const callback = cb || optCallback || function () { };
    const cbName = `${topic}_${nowEventId++}`;
    const params = { cbName, ...(extraDispatch || {}) };
    if (opts) {
      params.options = { ...opts, callback: '' };
    }

    const type = strRender.getEventNameFromTopic(topic);
    const eventType = strRender.genEventType(moduleName, type, opts);

    silenceLogger.debug('onEvent', topic, cbName, eventType, parseResponse);
    emitManager.on(cbName, callback, eventType, parseResponse);
    return messager.dispatch(topic, params)
    // .then(res => {
    //   const data = (baseUtil.isObject(res) && res) || {};
    //   data._hyEventId = cbName;
    //   return data;
    // });
  },

  /**
   * 注销事件监听
   * @param {string} topic 
   * @param {object} opts 
   */
  offEvent(moduleName, topic, opts, cb) {
    if (baseUtil.isFun(opts)) {
      cb = opts;
      opts = null;
    }

    const { _hyEventId, callback: optCallback, ...params } = opts || {};
    const type = strRender.getEventNameFromTopic(topic);
    const eventType = strRender.genEventType(moduleName, type, params);
    
    silenceLogger.debug('offEvent', topic, eventType);
    emitManager.off(_hyEventId, cb || optCallback, eventType);
    return messager.dispatch(topic, params);
  },

  /**
   * 普通事件调用，没返回值或返回的不是 Promise
   * @param {*} moduleName 模块名
   * @param {*} topic 方法名
   * @param {...any} params 传参
   */
  callEventSync(moduleName, topic, ...params) {
    return messager.emit(topic, ...params);
  },

  /**
   * 异步事件调用，返回 Promise
   * @param {*} moduleName 模块名
   * @param {*} topic 方法名
   * @param {...any} params 传参
   */
  callEvent(moduleName, topic, ...params) {
    return messager.dispatch(topic, ...params);
  }
}