import _objectSpread from "@babel/runtime/helpers/objectSpread2";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import React, { useCallback, useState } from "react";
import isEqual from "lodash/isEqual";
import { connect } from "../redux";
import { useHandler } from "../../hooks/useHandler";
import { getPlugin, getPlugins } from "../../plugins";
import { renderPlugins } from "../../plugins";
import { getElementProps, getElement } from "../selectors";
import Draggable from "./Draggable";
import { ElementContainer, typeStyle } from "./Element/ElementStyled";
import ElementReadOnly from "./Element/ElementReadOnly";
import tryRenderingPlugin from "./../../utils/tryRenderingPlugin";
import { judgeIfBlockStaticElement } from "../../utils/blockUtil";
import { ElementGroup } from "../../constant";
var commonPluginSettings = ["pb-editor-page-element-settings-save", "pb-editor-page-element-settings-clone", "pb-editor-page-element-settings-delete", "pb-editor-page-element-settings-switch-condition"];

var getElementPlugin = function getElementPlugin(element) {
  if (!element) {
    return null;
  }

  var plugins = getPlugins("pb-editor-page-element");
  return plugins.find(function (pl) {
    return pl.elementType === element.type;
  });
};

var getCommonPlugins = function getCommonPlugins(element) {
  var actionPluginSettings = [commonPluginSettings[1], commonPluginSettings[2]];

  if ((element === null || element === void 0 ? void 0 : element.type) === 'if') {
    actionPluginSettings = [commonPluginSettings[3], commonPluginSettings[2]];
  }

  var plugins = actionPluginSettings.map(function (pl) {
    return {
      plugin: getPlugin(pl),
      options: {}
    };
  });
  return plugins;
};

var getElementType = function getElementType(element) {
  var _element$data, _element$data$compone;

  if (typeof ((_element$data = element.data) === null || _element$data === void 0 ? void 0 : (_element$data$compone = _element$data.componentSettings) === null || _element$data$compone === void 0 ? void 0 : _element$data$compone.term) === 'boolean') {
    return 'term';
  }

  return element.type;
};

var Element = function Element(props) {
  var buildMode = props.buildMode,
      dragEnd = props.dragEnd,
      element = props.element,
      active = props.active,
      _props$className = props.className,
      className = _props$className === void 0 ? "" : _props$className,
      _props$containerClass = props.containerClassName,
      containerClassName = _props$containerClass === void 0 ? "" : _props$containerClass,
      _props$text = props.text,
      text = _props$text === void 0 ? "" : _props$text;
  var plugin = getElementPlugin(element);

  if (!plugin) {
    return null;
  }

  var renderedPlugin = tryRenderingPlugin(function () {
    return plugin.render({
      element: element,
      buildMode: buildMode,
      text: text
    });
  });

  if (judgeIfBlockStaticElement(element) && element.type !== 'document') {
    // block内的静态元素仅作展示
    return /*#__PURE__*/React.createElement(ElementReadOnly, Object.assign({}, props, {
      renderedPlugin: renderedPlugin
    }));
  }

  var _useState = useState(null),
      _useState2 = _slicedToArray(_useState, 2),
      highlightId = _useState2[0],
      setHighlightId = _useState2[1];

  var beginDrag = useHandler(props, function (_ref) {
    var dragStart = _ref.dragStart,
        element = _ref.element;
    return function () {
      var data = {
        id: element.id,
        type: element.type,
        path: element.path
      };
      setTimeout(function () {
        dragStart({
          element: data
        });
      });
      return _objectSpread(_objectSpread({}, data), {}, {
        target: plugin.target
      });
    };
  });
  var endDrag = React.useCallback(function (props, monitor) {// dragEnd({ element: monitor.getItem() });
  }, [dragEnd]);
  var onDblClick = useHandler(props, function (_ref2) {
    var element = _ref2.element,
        checkLayoutSave = _ref2.checkLayoutSave,
        fetchUIMetaData = _ref2.fetchUIMetaData,
        globalUpdate = _ref2.globalUpdate,
        currentProject = _ref2.currentProject;
    return function () {
      var _element$data2, _element$data2$blockS;

      if (element.type === "document" && (_element$data2 = element.data) !== null && _element$data2 !== void 0 && (_element$data2$blockS = _element$data2.blockSettings) !== null && _element$data2$blockS !== void 0 && _element$data2$blockS.isBlock) {
        var name = element.name; // 双进保存当前页进入目标block

        checkLayoutSave(function () {
          fetchUIMetaData({
            fileName: "".concat(name, ".xml"),
            projectName: currentProject
          }, function (data) {
            globalUpdate({
              selectedBlockData: data,
              currentBlock: name,
              editorMode: 'block',
              currentPage: '',
              currentAction: '',
              currentCommonSql: ''
            });
          });
        });
      }
    };
  });
  var onClick = useHandler(props, function (_ref3) {
    var element = _ref3.element,
        active = _ref3.active,
        activateElement = _ref3.activateElement;
    return function () {
      if (element.type === "document") {
        return;
      }

      if (!active) {
        activateElement({
          element: element.id
        });
      }
    };
  });
  var onMouseOver = useHandler(props, function (_ref4) {
    var element = _ref4.element;
    return function (e) {
      var _element$data3, _element$data3$blockS;

      if (element.type === 'document' && !((_element$data3 = element.data) !== null && _element$data3 !== void 0 && (_element$data3$blockS = _element$data3.blockSettings) !== null && _element$data3$blockS !== void 0 && _element$data3$blockS.isBlock)) {
        return;
      }

      e.stopPropagation();
      e.preventDefault();
      setHighlightId(element.id);
    };
  });
  var actions = getCommonPlugins(element); // const renderDraggable = useCallback(({ drag }) => {
  //   const elementType = getElementType(element);
  //   return (
  //     <div ref={drag} className={"type " + typeStyle}>
  //       <div className="background" onClick={onClick} onDoubleClick={onDblClick} />
  //       <div className={"element-holder"}>
  //         {renderPlugins("pb-editor-page-element-action", { element, plugin })}
  //         <div onClick={onClick}>
  //           <span>{getNameofElement(element)}</span>
  //           {elementType !== 'term' && actions.map(({ plugin: pl, options }, index) => {
  //             return (
  //               <div
  //                 key={pl.name + "-" + index}
  //                 style={{ position: "relative" }}
  //               >
  //                 {pl.renderAction({ options, element })}
  //               </div>
  //             );
  //           })}
  //         </div>
  //       </div>
  //     </div>
  //   );
  // }, [getNameofElement(element)])

  var renderDraggable = useHandler(props, function (_ref5) {
    var element = _ref5.element;
    return function (_ref6) {
      var drag = _ref6.drag;
      var elementType = getElementType(element);
      return /*#__PURE__*/React.createElement("div", {
        ref: drag,
        className: "type " + typeStyle
      }, /*#__PURE__*/React.createElement("div", {
        className: "background",
        onClick: onClick
      }), /*#__PURE__*/React.createElement("div", {
        className: "element-holder"
      }, renderPlugins("pb-editor-page-element-action", {
        element: element,
        plugin: plugin
      }), /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("span", {
        onClick: onClick
      }, plugin.elementType), elementType !== 'term' && actions.map(function (_ref7, index) {
        var pl = _ref7.plugin,
            options = _ref7.options;
        return /*#__PURE__*/React.createElement("div", {
          key: pl.name + "-" + index,
          style: {
            position: "relative"
          }
        }, pl.renderAction({
          options: options,
          element: element
        }));
      }))));
    };
  });
  var getElementClassName = useCallback(function () {
    var _plugin$toolbar;

    if ([ElementGroup['CONTAINER'], ElementGroup['LAYOUT']].includes(plugin === null || plugin === void 0 ? void 0 : (_plugin$toolbar = plugin.toolbar) === null || _plugin$toolbar === void 0 ? void 0 : _plugin$toolbar.group)) {
      // 容器组件内部需要padding间隔
      if (element.elements.length <= 0 || ['if', 'row'].includes(plugin.elementType)) {
        return 'webiny-pb-page-element-container-empty';
      }

      return '';
    }

    return 'webiny-pb-page-element-container-empty';
  }, [element]);
  return /*#__PURE__*/React.createElement(ElementContainer, {
    id: element.id,
    onMouseOver: onMouseOver,
    highlightId: highlightId,
    active: active,
    className: "webiny-pb-page-element-container ".concat(getElementClassName(), " ").concat(containerClassName)
  }, /*#__PURE__*/React.createElement("div", {
    className: ["innerWrapper", className].filter(function (c) {
      return c;
    }).join(" ")
  }, /*#__PURE__*/React.createElement(Draggable, {
    target: plugin.target,
    beginDrag: beginDrag,
    endDrag: endDrag
  }, renderDraggable), renderedPlugin));
};

var mapDispatchToProps = function mapDispatchToProps(dispatch) {
  return {
    dragStart: function dragStart() {
      dispatch({
        type: 'ui/dragStart'
      });
    },
    dragEnd: function dragEnd() {
      dispatch({
        type: 'ui/dragEnd'
      });
    },
    highlightElement: function highlightElement(payload) {
      dispatch({
        type: 'ui/highlightElement',
        payload: payload
      });
    },
    activateElement: function activateElement(payload) {
      dispatch({
        type: 'ui/activateElement',
        payload: payload
      });
    },
    checkLayoutSave: function checkLayoutSave(callback) {
      dispatch({
        type: 'globalUI/checkLayoutSave'
      }).then(function () {
        callback();
      });
    },
    fetchUIMetaData: function fetchUIMetaData(payload, callback) {
      dispatch({
        type: 'lowcodeTree/getUIMetaData',
        payload: payload
      }).then(function (returnData) {
        if (returnData) {
          callback(returnData);
        }
      });
    },
    globalUpdate: function globalUpdate(payload) {
      dispatch({
        type: 'globalUI/save',
        payload: payload
      });
    },
    dropElement: function dropElement(payload) {
      dispatch({
        type: 'appBuilder/dropElement',
        payload: payload
      });
    }
  };
};

export default connect(function (state, props) {
  var _state$appBuilder$con = state.appBuilder.config,
      config = _state$appBuilder$con === void 0 ? {} : _state$appBuilder$con;
  return _objectSpread(_objectSpread({}, getElementProps(state, props)), {}, {
    element: getElement(state, props.id),
    currentProject: config.currentProject,
    buildMode: config.buildMode || 'PC'
  });
}, mapDispatchToProps, null, {
  areStatePropsEqual: isEqual
})( /*#__PURE__*/React.memo(Element, function (prev, next) {
  var _prev$element, _next$element;

  if (((_prev$element = prev.element) === null || _prev$element === void 0 ? void 0 : _prev$element.id) === ((_next$element = next.element) === null || _next$element === void 0 ? void 0 : _next$element.id)) {
    var _prev$element2, _next$element2, _prev$element3, _next$element3;

    if (prev.active !== next.active) {
      return false;
    }

    if (!isEqual((_prev$element2 = prev.element) === null || _prev$element2 === void 0 ? void 0 : _prev$element2.data, (_next$element2 = next.element) === null || _next$element2 === void 0 ? void 0 : _next$element2.data)) {
      return false;
    }

    if (!isEqual((_prev$element3 = prev.element) === null || _prev$element3 === void 0 ? void 0 : _prev$element3.elements, (_next$element3 = next.element) === null || _next$element3 === void 0 ? void 0 : _next$element3.elements)) {
      return false;
    }

    return true;
  }

  return false;
}));
//# sourceMappingURL=Element.js.map