export default (grapesjs) => {
  grapesjs.plugins.add('sp-fix-5213', (editor, opts = {}) => {
    /**
     * 修复bug#5213：当算盘画布比例不是100%时，拖动鼠标改变组件大小时，鼠标会偏离组件框
     * 覆盖grapesjs/src/canvas/index.js中getMouseRelativePos方法
     * 增加scale计算
     * @param {Event} e
     * @return {Object}
     * @private
     */
    let startPos = {
      x: 0,
      y: 0
    };
    editor.Canvas.getMouseRelativePos = function(e, options) {
      var opts = options || {};
      var addTop = 0;
      var addLeft = 0;
      var subWinOffset = opts.subWinOffset;
      var doc = e.target.ownerDocument;
      var win = doc.defaultView || doc.parentWindow;
      var frame = win.frameElement;
      var yOffset = subWinOffset ? win.pageYOffset : 0;
      var xOffset = subWinOffset ? win.pageXOffset : 0;

      if (frame) {
        var frameRect = frame.getBoundingClientRect();
        addTop = frameRect.top || 0;
        addLeft = frameRect.left || 0;
      }

      if (e.type == "mousedown") {
        startPos = {
          x: e.clientX + addTop - yOffset,
          y: e.clientY + addLeft - xOffset
        };
      }
      const currentPos = {
        y: e.clientY + addTop - yOffset,
        x: e.clientX + addLeft - xOffset
      }
      let scale = 1;
      const $canvas = document.getElementsByClassName("gjs-cv-canvas__frames");
      if ($canvas.length > 0) {
        const transform = $canvas[0].style.transform;
        if (transform) {
          const setting = transform.split(' ').filter(val => val.indexOf('scale') > -1);
          if (setting.length > 0) {
            scale = setting[0].split('(')[1].split(')')[0];
          }
        }
      }
      return {
        y: (currentPos.y - startPos.y) / scale + startPos.y,
        x: (currentPos.x - startPos.x) / scale + startPos.x,
      };
    };
  })
}