import _objectSpread from "@babel/runtime/helpers/objectSpread2";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import _isEqual from "lodash/isEqual";
import _cloneDeep from "lodash/cloneDeep";
import React, { useCallback, useState, useEffect, useRef } from "react";
import { connect } from "react-redux";
import { css } from "emotion";
import { Dropdown, Menu } from "@whalecloud/fdx";
import styled from "styled-components";
import { getPlugins } from "../../../plugins";
import { getActiveElement, getContent, getPage } from "../../selectors";
import { ReactComponent as BlockIcon } from "@svgr/webpack!../../assets/icons/block_icon.svg";
import { ReactComponent as ContainerIcon } from "@svgr/webpack!../../assets/icons/container_setting.svg";
import { ReactComponent as ExpandIcon } from "@svgr/webpack!../../assets/icons/expand_icon.svg";
import { ReactComponent as FoldIcon } from "@svgr/webpack!../../assets/icons/fold_icon.svg";
import { getNameofElement } from "../../utils";
import Draggable from "../../components/Draggable";
import { useHandlers } from "../../../hooks/useHandlers";
import { useStore } from 'react-redux';
import Droppable from "../../components/Droppable";
var title = /*#__PURE__*/css({
  color: '#fff',
  display: 'flex',
  alignItems: 'center',
  svg: {
    width: 16,
    marginRight: 5
  }
}, "label:title;");
var hover = /*#__PURE__*/css({
  background: 'rgba(37,157,219,.1)'
}, "label:hover;");
var ChildContainer = /*#__PURE__*/React.memo( /*#__PURE__*/styled("div", {
  target: "e1kjqkg00",
  label: "ChildContainer"
})({
  position: "relative",
  width: "100%"
}));

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

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

var WidgetTree = function WidgetTree(props) {
  var content = props.content,
      activeElement = props.activeElement,
      activateElement = props.activateElement,
      highlightElement = props.highlightElement,
      deactivateElement = props.deactivateElement,
      deleteElement = props.deleteElement,
      dragEnd = props.dragEnd,
      onReturn = props.onReturn;

  if (!content) {
    return null;
  }

  var _useState = useState([content.id]),
      _useState2 = _slicedToArray(_useState, 2),
      expandKeys = _useState2[0],
      setExpandKeys = _useState2[1];

  var _useState3 = useState([activeElement === null || activeElement === void 0 ? void 0 : activeElement.id]),
      _useState4 = _slicedToArray(_useState3, 2),
      selectedKeys = _useState4[0],
      setSelectedKeys = _useState4[1];

  var getChildLiClassName = function getChildLiClassName(key, ifSelect) {
    var className = "ant-tree-treenode-switcher-".concat(key === 'open' ? key : 'close');

    if (ifSelect) {
      className += " ant-tree-treenode-selected";
    }

    return className;
  };

  var getChildSpanClassName = function getChildSpanClassName(key) {
    var className = 'ant-tree-switcher';

    if (key === 'normal') {
      // 不支持展开
      className += " ant-tree-switcher-noop";
    } else {
      className += " ant-tree-switcher_".concat(key);
    }

    return className;
  };

  var getChildRightClassName = function getChildRightClassName(key, ifSelect) {
    var className = "relative ant-tree-node-content-wrapper ant-tree-node-content-wrapper-".concat(key);

    if (ifSelect) {
      className += " ant-tree-node-selected";
    }

    return className;
  };

  var getNodeKey = function getNodeKey(key, children) {
    if (!children || Array.isArray(children) && children.length <= 0) {
      return 'normal';
    }

    if (expandKeys.includes(key)) {
      return 'open';
    }

    return 'close';
  };

  var renderLeftIcon = function renderLeftIcon(key) {
    if (key === 'normal') {
      return null;
    }

    return key === 'open' ? /*#__PURE__*/React.createElement(ExpandIcon, null) : /*#__PURE__*/React.createElement(FoldIcon, null);
  };

  var renderContentIcon = function renderContentIcon(plugin) {
    var _ref = (plugin === null || plugin === void 0 ? void 0 : plugin.toolbar) || {},
        _ref$toolBarPreview = _ref.toolBarPreview,
        ToolBarPreview = _ref$toolBarPreview === void 0 ? /*#__PURE__*/React.createElement(ContainerIcon, null) : _ref$toolBarPreview;

    return ToolBarPreview;
  };

  var handleExpandNode = function handleExpandNode(id) {
    var keys = _cloneDeep(expandKeys);

    var index = keys.indexOf(id);

    if (index === -1) {
      keys.push(id);
    } else {
      keys.splice(index, 1);
    }

    setExpandKeys(keys);
  };

  var handleMouseOverNode = function handleMouseOverNode(id) {
    if ((activeElement === null || activeElement === void 0 ? void 0 : activeElement.id) !== id) {
      highlightElement({
        element: id
      });
    }
  };

  var handleSelectNode = function handleSelectNode(id) {
    if (selectedKeys[0] !== id) {
      setSelectedKeys([id]);
    }

    if (activeElement && activeElement.id === id) {
      return;
    }

    activateElement({
      element: id
    });
  };

  var handleDelete = useCallback(function (element) {
    if (element) {
      deleteElement({
        element: element
      });
      deactivateElement();
    }
  }, [deleteElement, deactivateElement]);
  var getMenu = useCallback(function (element) {
    return /*#__PURE__*/React.createElement(Menu, null, /*#__PURE__*/React.createElement(Menu.Item, {
      key: "1",
      onClick: function onClick() {
        handleDelete(element);
      }
    }, "Delete"));
  }, []);
  var store = useStore();

  var _useHandlers = useHandlers(props, {
    beginDrag: function beginDrag(_ref2) {
      var dragStart = _ref2.dragStart;
      return function (pro, mon, ele) {
        var data = {
          id: ele.id,
          type: ele.type,
          path: ele.path
        };
        setTimeout(function () {
          dragStart({
            element: data
          }, store);
        });
        return _objectSpread(_objectSpread({}, data), {}, {
          target: ele.target
        });
      };
    },
    handleDrop: function handleDrop(_ref3) {
      var dropElement = _ref3.dropElement;
      return function (source, direction, element, i) {
        var id = element.id,
            type = element.type;
        dropElement({
          source: source,
          target: {
            id: id,
            type: type,
            position: i
          }
        }, direction, store);
      };
    }
  }),
      beginDrag = _useHandlers.beginDrag,
      handleDrop = _useHandlers.handleDrop;

  var endDrag = React.useCallback(function (props, monitor) {// dragEnd({ element: monitor.getItem() });
  }, [dragEnd]);
  useEffect(function () {
    if (!selectedKeys.includes(activeElement === null || activeElement === void 0 ? void 0 : activeElement.id)) {
      setSelectedKeys([activeElement === null || activeElement === void 0 ? void 0 : activeElement.id]); // if (!expandKeys.includes(activeElement?.id)) {
      //   handleExpandNode(activeElement?.id);
      // }
    }
  }, [activeElement]);

  var mapTree = function mapTree() {
    var elements = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
    var parentElement = arguments.length > 1 ? arguments[1] : undefined;
    return elements.map(function (element, index) {
      var _element$elements = element.elements,
          childs = _element$elements === void 0 ? [] : _element$elements,
          id = element.id,
          type = element.type; // 当前元素plugin

      var plugin = getElementPlugin(type) || {};
      var expandNodeKey = getNodeKey(id, childs); // 是否选中

      var ifSelect = selectedKeys.includes(id);
      return /*#__PURE__*/React.createElement("li", {
        key: id,
        className: getChildLiClassName(expandNodeKey, ifSelect),
        role: "treeitem"
      }, /*#__PURE__*/React.createElement("span", {
        className: getChildSpanClassName(expandNodeKey),
        onClick: function onClick() {
          handleExpandNode(id);
        }
      }, renderLeftIcon(expandNodeKey)), /*#__PURE__*/React.createElement(Draggable, {
        target: plugin.target,
        element: _objectSpread(_objectSpread({}, element), {}, {
          target: plugin.target
        }),
        beginDrag: beginDrag,
        endDrag: endDrag
      }, function (_ref4) {
        var drag = _ref4.drag;
        var ref = useRef(null);
        return /*#__PURE__*/React.createElement("span", {
          ref: drag,
          className: getChildRightClassName(expandNodeKey, ifSelect),
          onMouseOver: function onMouseOver() {
            handleMouseOverNode(id);
          },
          onClick: function onClick() {
            onReturn(true);
            handleSelectNode(id);
          }
        }, /*#__PURE__*/React.createElement(Droppable, {
          id: element.id,
          dropRef: ref,
          type: parentElement.type,
          onDrop: function onDrop(source, direction) {
            return handleDrop(source, direction, parentElement, index);
          }
        }, function (_ref5) {
          var drop = _ref5.drop;
          return /*#__PURE__*/React.createElement(ChildContainer, {
            ref: drop(ref)
          }, /*#__PURE__*/React.createElement("span", {
            className: "ant-tree-iconEle ant-tree-icon__customize"
          }, renderContentIcon(plugin)), /*#__PURE__*/React.createElement(Dropdown, {
            overlay: getMenu(element),
            trigger: ['contextMenu']
          }, /*#__PURE__*/React.createElement("span", {
            className: "ant-tree-title"
          }, getNameofElement(element))));
        }));
      }), childs.length > 0 && /*#__PURE__*/React.createElement("ul", {
        className: "ant-tree-child-tree ant-tree-child-tree-".concat(expandNodeKey),
        style: {
          display: expandNodeKey !== 'open' ? 'none' : 'block'
        },
        role: "group"
      }, mapTree(childs, element)));
    });
  };

  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("ul", {
    className: "widget-tree ant-tree widget-tree ant-tree-block-node",
    role: "tree"
  }, /*#__PURE__*/React.createElement("span", {
    className: title
  }, /*#__PURE__*/React.createElement(BlockIcon, null), /*#__PURE__*/React.createElement("span", null, content.type)), mapTree(content.elements, content)));
};

var mapDispatchToProps = function mapDispatchToProps(dispatch) {
  return {
    highlightElement: function highlightElement(payload) {
      dispatch({
        type: 'ui/highlightElement',
        payload: payload
      });
    },
    activateElement: function activateElement(payload) {
      dispatch({
        type: 'ui/activateElement',
        payload: payload
      });
    },
    dragStart: function dragStart() {
      dispatch({
        type: 'ui/dragStart'
      });
    },
    dragEnd: function dragEnd() {
      dispatch({
        type: 'ui/dragEnd'
      });
    },
    dropElement: function dropElement(payload) {
      dispatch({
        type: 'appBuilder/dropElement',
        payload: payload
      });
    },
    deleteElement: function deleteElement(payload) {
      dispatch({
        type: 'appBuilder/deleteElement',
        payload: payload
      });
    },
    deactivateElement: function deactivateElement(payload) {
      dispatch({
        type: 'ui/deactivateElement',
        payload: payload
      });
    }
  };
};

export default connect(function (state) {
  var page = getPage(state) || {};
  var content = page.content ? getContent(state) : null;
  var activeElement = page.content ? getActiveElement(state) : null;
  return {
    content: content,
    activeElement: activeElement
  };
}, mapDispatchToProps, null, {
  areStatePropsEqual: _isEqual
})(WidgetTree);
//# sourceMappingURL=WidgetTree.js.map