"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = PageCompList;

var _fdx = require("@whalecloud/fdx");

var _classnames = _interopRequireDefault(require("classnames"));

var _immutabilityHelper = _interopRequireDefault(require("immutability-helper"));

var _react = _interopRequireWildcard(require("react"));

var _uuid = require("uuid");

var _Button = _interopRequireDefault(require("../../../common/Button"));

var _Iconfont = _interopRequireDefault(require("../../../common/Iconfont"));

require("./index.less");

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? Object(arguments[i]) : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys.push.apply(ownKeys, Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

var operTypeMap = {
  MOVE_UP: '1',
  MOVE_DOWN: '2',
  COPY: '3',
  DELETE: '4'
};

function PageCompList(_ref) {
  var selected = _ref.selected,
      setPageData = _ref.setPageData,
      pageData = _ref.pageData,
      onAdd = _ref.onAdd,
      renderPagesManage = _ref.renderPagesManage,
      pageName = _ref.pageName;

  var _useState = (0, _react.useState)(pageData || []),
      _useState2 = _slicedToArray(_useState, 2),
      components = _useState2[0],
      setComponents = _useState2[1];

  var _useState3 = (0, _react.useState)(''),
      _useState4 = _slicedToArray(_useState3, 2),
      dragId = _useState4[0],
      setDragId = _useState4[1];

  var _useState5 = (0, _react.useState)(selected || {}),
      _useState6 = _slicedToArray(_useState5, 2),
      selectedNode = _useState6[0],
      setSelectedNode = _useState6[1];

  var ref = (0, _react.useRef)();
  (0, _react.useEffect)(function () {
    setComponents(pageData || []);
  }, [pageData]);
  (0, _react.useEffect)(function () {
    setSelectedNode(selected || {});
  }, [selected]);
  var moveCard = (0, _react.useCallback)(function (dragNodeId, hoverNodeId) {
    var dragIndex = components.findIndex(function (comp) {
      return comp.id === dragNodeId;
    });
    var hoverIndex = components.findIndex(function (comp) {
      return comp.id === hoverNodeId;
    });
    setComponents(function (prevCards) {
      var newComps = (0, _immutabilityHelper["default"])(prevCards, {
        $splice: [[dragIndex, 1], [hoverIndex, 0, prevCards[dragIndex]]]
      });
      ref.current = newComps;
      return newComps;
    });
  }, [components]);

  var onDragStart = function onDragStart(e) {
    setDragId(e.currentTarget.dataset.nodeid);
  };

  var onDragEnter = function onDragEnter(e) {
    var hoverNodeId = e.currentTarget.dataset.nodeid;

    if (dragId === hoverNodeId) {
      return;
    }

    moveCard(dragId, hoverNodeId);
  };

  var onDragEnd = function onDragEnd() {
    setDragId('');
    setPageData(ref.current);
  };

  var onMenuClick = function onMenuClick(index, operType) {
    if (operType === operTypeMap.MOVE_UP) {
      setComponents(function (data) {
        var newComponents = _toConsumableArray(data);

        var temp = newComponents[index - 1];
        newComponents[index - 1] = newComponents[index];
        newComponents[index] = temp;
        ref.current = newComponents;
        return newComponents;
      });
    }

    if (operType === operTypeMap.MOVE_DOWN) {
      setComponents(function (data) {
        var newComponents = _toConsumableArray(data);

        var temp = newComponents[index + 1];
        newComponents[index + 1] = newComponents[index];
        newComponents[index] = temp;
        ref.current = newComponents;
        return newComponents;
      });
    }

    if (operType === operTypeMap.COPY) {
      setComponents(function (data) {
        var newComponents = _toConsumableArray(data);

        newComponents.splice(index + 1, 0, _objectSpread({}, newComponents[index], {
          id: (0, _uuid.v4)()
        }));
        ref.current = newComponents;
        return newComponents;
      });
    }

    if (operType === operTypeMap.DELETE) {
      setComponents(function (data) {
        var newComponents = _toConsumableArray(data);

        newComponents.splice(index, 1);
        ref.current = newComponents;
        return newComponents;
      });
    }

    setPageData(ref.current);
  };

  var componentScrollTop = function componentScrollTop(data) {
    if (document.getElementById("view".concat(data.id))) {
      document.getElementById("view".concat(data.id)).scrollIntoView({
        behavior: 'smooth'
      });
    }
  };

  var onCardClick = function onCardClick(event, data) {
    componentScrollTop(data); // 这里必须阻止事件冒泡，然后再触发自定义的事件

    event.preventDefault();
    event.stopPropagation();
    var evt = new Event('component-click', {
      bubbles: false
    });
    evt.data = data;
    window.document.dispatchEvent(evt);
    if (selectedNode && selectedNode.id === data.id) return;
    setSelectedNode(data);
  };

  var renderCard = function renderCard(comp, index) {
    var menu = /*#__PURE__*/_react["default"].createElement(_fdx.Menu, {
      onClick: function onClick(_ref2) {
        var item = _ref2.item;
        return onMenuClick(index, item.props.value);
      }
    }, index !== 0 && /*#__PURE__*/_react["default"].createElement(_fdx.Menu.Item, {
      value: "1",
      className: "menu_item"
    }, "Move Up"), index !== components.length - 1 && /*#__PURE__*/_react["default"].createElement(_fdx.Menu.Item, {
      value: "2",
      className: "menu_item"
    }, "Move Down"), /*#__PURE__*/_react["default"].createElement(_fdx.Menu.Item, {
      value: "3",
      className: "menu_item"
    }, "Copy"), /*#__PURE__*/_react["default"].createElement(_fdx.Menu.Item, {
      value: "4",
      className: "menu_item"
    }, "Delete"));

    var dragging = dragId === String(comp.id);
    var active = selectedNode && selectedNode.id === String(comp.id);
    return /*#__PURE__*/_react["default"].createElement("div", {
      key: "card".concat(comp.id),
      id: "card".concat(comp.id),
      "data-nodeid": comp.id,
      draggable: "true",
      className: (0, _classnames["default"])('card-wrap', {
        active: active
      }),
      onDragStart: onDragStart,
      onDragEnter: onDragEnter,
      onDragEnd: onDragEnd,
      onDragOver: function onDragOver(e) {
        e.preventDefault();
      },
      style: {
        opacity: dragging ? '0.4' : '1'
      }
    }, /*#__PURE__*/_react["default"].createElement("div", {
      className: "left",
      onClick: function onClick(e) {
        return onCardClick(e, comp);
      }
    }, /*#__PURE__*/_react["default"].createElement(_Iconfont["default"], {
      className: "comp-icon",
      type: comp.icon,
      size: "20px",
      color: active ? '#2F54EB' : ''
    }), /*#__PURE__*/_react["default"].createElement(_Iconfont["default"], {
      className: "drag-icon",
      type: "icon-drag",
      color: "#2F54EB",
      size: "20px"
    }), /*#__PURE__*/_react["default"].createElement("span", {
      className: "card-title ml16"
    }, index + 1, ". ", comp.title || comp.label)), /*#__PURE__*/_react["default"].createElement(_fdx.Dropdown, {
      overlay: menu,
      placement: "bottomRight",
      trigger: ['click']
    }, /*#__PURE__*/_react["default"].createElement(_Iconfont["default"], {
      className: "more-btn",
      type: "icon-more",
      size: "20px",
      style: {
        height: '40px'
      },
      color: "#2F54EB"
    })));
  };

  return /*#__PURE__*/_react["default"].createElement("div", {
    className: "page-comp-wrap"
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "page-comp-head"
  }, renderPagesManage), /*#__PURE__*/_react["default"].createElement("div", {
    className: "page-comp-list"
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "title mb16"
  }, pageName), /*#__PURE__*/_react["default"].createElement(_Button["default"], {
    type: "light",
    size: "large",
    icon: "icon-add",
    onClick: onAdd
  }, "Add Component"), /*#__PURE__*/_react["default"].createElement("div", {
    className: "list mt16"
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "inner-list"
  }, /*#__PURE__*/_react["default"].createElement("div", null, components.length > 0 && components.map(function (comp, i) {
    return renderCard(comp, i);
  }))))));
}