import { globalEventHandler } from "./managers/eventmanager/eventManager";
import adaptivePageManager from './managers/adaptive';

import {
  boxRef,
  buttonGroupRef,
  customSVG,
  globalEventListener,
  headerRef,
  iframeRef,
  imgBase64Ref,
  rangeRef,
  spCode,
  textRef,
  pageAdaptor
} from "../configuration/constants";

export default (grapesjs) => {
  grapesjs.plugins.add("plugin-sp-common", (editor) => {
    const privateCls = [
      `.${textRef}`,
      `.${imgBase64Ref}`,
      `.${buttonGroupRef}`,
      `.${customSVG}`,
      `.${boxRef}`,
      `.${headerRef}`,
      `.${iframeRef}`,
      `.${rangeRef}`,
    ];

    editor.on("selector:add", (selector) => {
      if (privateCls.indexOf(selector.getFullName()) >= 0) {
        selector.set({ private: 1 });
      }
    });

    editor.on("component:mount", (model) => {
      const childrenSelectable = model.get("childrenSelectable");

      if (childrenSelectable === false) {
        model.view.$el.addClass("no-events");
        // setChildrenSelectable(model, childrenSelectable)
      }

      const style = model.getStyle();

      // 修正由于NaN引起的位置错误
      if (style.left && isNaN(parseFloat(style.left))) {
        model.addStyle({ left: "0px" });
      }

      if (style.top && isNaN(parseFloat(style.top))) {
        model.addStyle({ top: "0px" });
      }
    });

    editor.on('storage:start:load', function () {
      editor.StorageManager.setAutosave(false);
    });
    editor.on('storage:end:load', function () {
      setTimeout(function () {
        editor.getModel().set('changesCount', 0);
        editor.StorageManager.setStepsBeforeSave(1);
        editor.StorageManager.setAutosave(true);
      }, 2000);
    });

    editor.on("load", () => {
      const editorDoc = editor.Canvas.getDocument();
      if (!editorDoc.getAttribute) {
        editorDoc.getAttribute = function () {
          return null;
        };
      }
      // 画布加载完成后，在全局放置一个事件监听器，接收socket推送消息
      editor.getComponents().models.forEach((comp) =>
        comp.get("classes").forEach((clzz) => {
          if ([globalEventListener, pageAdaptor].indexOf(clzz.get("name")) > -1) {
            comp.remove();
          }
        })
      );

      // 全局事件监听
      editor.addComponents(
        `<script data-gjs-type="${spCode}" class="${globalEventListener}">${globalEventHandler.getJs()}</script>`
      );

      // 自适应
      editor.addComponents(
        `<script data-gjs-type="${spCode}" class="${pageAdaptor}">${adaptivePageManager.getJs()}</script>`
      );

      delete localStorage["frontpanel-data-cache"];
    });
    // 在组件被选中时，更新工具框位置，要加上frame的offset
    const canvasRectOffset = editor.Canvas.canvasRectOffset;
    editor.Canvas.canvasRectOffset = function (el, pos, opts = {}) {
      const { top, left } = canvasRectOffset.apply(this, [
        el,
        pos,
        opts,
      ]);
      const cvsView = editor.Canvas.getCanvasView().el;

      return {
        left: left + cvsView.scrollLeft,
        top: top + cvsView.scrollTop,
      };
    };
  });
}
