(function (factory) {
  typeof define === 'function' && define.amd ? define(factory) :
  factory();
}((function () { 'use strict';

  function _typeof(obj) {
    if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
      _typeof = function (obj) {
        return typeof obj;
      };
    } else {
      _typeof = function (obj) {
        return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
      };
    }

    return _typeof(obj);
  }

  function _classCallCheck(instance, Constructor) {
    if (!(instance instanceof Constructor)) {
      throw new TypeError("Cannot call a class as a function");
    }
  }

  function _defineProperties(target, props) {
    for (var i = 0; i < props.length; i++) {
      var descriptor = props[i];
      descriptor.enumerable = descriptor.enumerable || false;
      descriptor.configurable = true;
      if ("value" in descriptor) descriptor.writable = true;
      Object.defineProperty(target, descriptor.key, descriptor);
    }
  }

  function _createClass(Constructor, protoProps, staticProps) {
    if (protoProps) _defineProperties(Constructor.prototype, protoProps);
    if (staticProps) _defineProperties(Constructor, staticProps);
    return Constructor;
  }

  function _inherits(subClass, superClass) {
    if (typeof superClass !== "function" && superClass !== null) {
      throw new TypeError("Super expression must either be null or a function");
    }

    subClass.prototype = Object.create(superClass && superClass.prototype, {
      constructor: {
        value: subClass,
        writable: true,
        configurable: true
      }
    });
    if (superClass) _setPrototypeOf(subClass, superClass);
  }

  function _getPrototypeOf(o) {
    _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
      return o.__proto__ || Object.getPrototypeOf(o);
    };
    return _getPrototypeOf(o);
  }

  function _setPrototypeOf(o, p) {
    _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
      o.__proto__ = p;
      return o;
    };

    return _setPrototypeOf(o, p);
  }

  function _assertThisInitialized(self) {
    if (self === void 0) {
      throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
    }

    return self;
  }

  function _possibleConstructorReturn(self, call) {
    if (call && (typeof call === "object" || typeof call === "function")) {
      return call;
    }

    return _assertThisInitialized(self);
  }

  // 消息对象类
  var Target =
  /*#__PURE__*/
  function () {
    function Target(target, name) {
      _classCallCheck(this, Target);

      var errMsg = '';

      if (arguments.length < 2) {
        errMsg = 'target error - target and name are both required';
      } else if (_typeof(target) != 'object') {
        errMsg = 'target error - target itself must be window object';
      } else if (typeof name != 'string') {
        errMsg = 'target error - target name must be string type';
      }

      if (errMsg) {
        throw new Error(errMsg);
      }

      this.target = target;
      this.name = name;
    }

    _createClass(Target, [{
      key: "send",
      value: function send(msgType, data, origin) {
        var msgInfo = {
          msgType: msgType,
          data: data
        };
        this.target.postMessage(msgInfo, origin);
      }
    }]);

    return Target;
  }();

  var Message =
  /*#__PURE__*/
  function () {
    /**
     *
     * @param {String} trustedOrigin 信任的域，可以在该域上接收或发送消息
     */
    function Message(trustedOrigin) {
      _classCallCheck(this, Message);

      this.targets = {};
      this.listenCallBack = null;
      this.trustedOrigin = trustedOrigin;
    }
    /**
     * @des 创建消息体发送/接收者
     */


    _createClass(Message, [{
      key: "addTarget",
      value: function addTarget(target, name) {
        var targetObj = new Target(target, name);
        this.targets[name] = targetObj;
      }
      /**
       * @des 广播消息
       * @param {String} msgType 消息类别
       * @param {Any} msg 消息内容
       * @param {String ?} targetOrigin  可以具体指定消息发送到哪个域(可选)。不指定，则用默认的trustedOrigin
       */

    }, {
      key: "send",
      value: function send(msgType) {
        var msg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
        var targetOrigin = arguments.length > 2 ? arguments[2] : undefined;
        var targets = this.targets;
        var origin = targetOrigin || this.trustedOrigin;
        var target;

        for (target in targets) {
          if (targets.hasOwnProperty(target)) {
            targets[target].send(msgType, msg, origin);
          }
        }
      }
      /**
       * @des 接收消息
       * @param {String | Boolean} msgType 消息类别，为String时，必须和发送消息的类别相同时，才会接受到。为Boolean，切为true，则会接收所有的消息
       * @param {Function ?} callback 回调函数，可选
       * @param {String ?} targetOrigin 指定只接收，哪个域的消息（可选）。不指定，默认接收trustedOrigin 的消息
       * @retrun 监听消息类型匹配成功时，若没有设置回调函数，则返回promise
       */

    }, {
      key: "listener",
      value: function listener(msgType, callback, targetOrigin) {
        var _this = this;

        this.listenCallBack = function (msg) {
          // 不是指定的的域，不接收消息
          var origin = targetOrigin || _this.trustedOrigin;
          if (msg.origin !== origin) return; // 参数格式校验

          if (_typeof(msg) == 'object' && msg.data) {
            msg = msg.data; // 接收指定类型消息

            if (typeof msgType === 'string') {
              if (msg.msgType === msgType) {
                callback(msg.data);
              } // 接收全部消息

            } else if (typeof msgType === 'boolean' && msgType) {
              callback(msg.data);
            }
          } else {
            throw new Error('传参格式错误');
          }
        };

        if ('addEventListener' in document) {
          window.addEventListener('message', this.listenCallBack, false);
        } else if ('attachEvent' in document) {
          window.attachEvent('onmessage', this.listenCallBack);
        }
      }
      /**
       * @des 注销
       */

    }, {
      key: "destroy",
      value: function destroy() {
        this.targets = {};

        if ('addEventListener' in document) {
          window.removeEventListener('message', this.listenCallBack, false);
        } else if ('attachEvent' in document) {
          window.detachEvent('onmessage', this.listenCallBack);
        }
      }
    }]);

    return Message;
  }();

  window.STCMessage = function () {
    // 消息前缀, 建议使用自己的项目名, 避免多项目之间的冲突
    // !注意 消息前缀应使用字符串类型
    // var prefix = '[PROJECT_NAME]',
    //   supportPostMessage = 'postMessage' in window;

    /**
     * @des 业务层
     */
    var STCMessage =
    /*#__PURE__*/
    function (_Message) {
      _inherits(STCMessage, _Message);

      function STCMessage() {
        var _this;

        var env = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'prod';

        _classCallCheck(this, STCMessage);

        var envMap = {
          dev: 'https://ts.keytop.cn/kosfront',
          prod: 'https://kos.keytop.cn/kosfront',
          dwyDev: 'http://220.160.111.118:25180',
          // 大物业的测试环境地址
          dwyProd: 'http://ktapps.keytop.cn' // 大物业的正试环境地址

        };
        var targetName;
        var trustedOrigin = envMap[env];

        if (env === 'dev' || env === 'prod') {
          targetName = 'inner';
        } else {
          targetName = 'wrap';
        }

        _this = _possibleConstructorReturn(this, _getPrototypeOf(STCMessage).call(this, trustedOrigin));

        _this.init(targetName);

        return _this;
      }

      _createClass(STCMessage, [{
        key: "init",
        value: function init(targetName) {
          var target;

          if (targetName === 'inner') {
            target = window.parent;
            self == top && (target = null);
          } else if (targetName === 'wrap') {
            target = document.querySelector('iframe') && document.querySelector('iframe').contentWindow;
          }

          target && this.addTarget(target, targetName); // 兼容没有iframe的时候，不添加消息体
        }
      }]);

      return STCMessage;
    }(Message);

    return STCMessage;
  }();

})));
