/*
 * @Author: wangdengzhi
 * @Date: 2020-08-20 16:19:31
 * @Last Modified by: wangdengzhi
 * @Last Modified time: 2020-08-20 16:26:15
 * @description: 实现基于documentEvent的通信管道
 */
import { ICommand } from './types';
interface IMsg extends ICommand {
  headers: {
    reqId: string;
  };
}

class DocumentEventMessager {
  constructor() {}

  getCheckServiceType() {
    return 'common.requestFunctions';
  }

  // 实现webService如何去接收消息
  onReceiveMessage(messageHandler) {
    document.addEventListener('documentMessage', (e: any) => {
      e.detail && e.detail.headers && messageHandler(e.detail);
    });
  }

  // 实现webService如何去发送消息
  sendAction({ type, headers, data }: IMsg) {
    const event = new CustomEvent('documentMessage', {
      detail: { type, headers, data },
    });
    document.dispatchEvent(event);
  }
}

export default new DocumentEventMessager();
