"use strict";

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

var _cloneDeep = _interopRequireDefault(require("lodash/cloneDeep"));

var _isEmpty = _interopRequireDefault(require("lodash/isEmpty"));

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

var _uuid = require("uuid");

var _constants = require("../../constants");

var _CompListPanel = _interopRequireDefault(require("./CompListPanel"));

require("./index.less");

var _PageCompList = _interopRequireDefault(require("./PageCompList"));

var _PropertyPanel = _interopRequireDefault(require("./PropertyPanel"));

var _QuickMenuBar = _interopRequireDefault(require("./QuickMenuBar"));

var _ViewArea = _interopRequireDefault(require("./ViewArea"));

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 _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

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 _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 _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 _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 _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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

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; }

/**
 * @class Designer
 * 主入口。
 */
var Designer = /*#__PURE__*/function (_Component) {
  _inherits(Designer, _Component);

  var _super = _createSuper(Designer);

  function Designer(props) {
    var _history;

    var _this;

    _classCallCheck(this, Designer);

    _this = _super.call(this, props);

    _defineProperty(_assertThisInitialized(_this), "cursor", {
      pc: 0,
      mobile: 0
    });

    _defineProperty(_assertThisInitialized(_this), "setPageData", function (pageData) {
      var trigger = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
      var _this$state = _this.state,
          MPageData = _this$state.MPageData,
          device = _this$state.device,
          selectedNode = _this$state.selectedNode;
      var newSelect = pageData.find(function (node) {
        return !(0, _isEmpty["default"])(selectedNode) && node.id === selectedNode.id;
      });

      _this.setState({
        MPageData: _objectSpread({}, MPageData, _defineProperty({}, device, pageData)),
        selectedNode: (0, _cloneDeep["default"])(newSelect)
      }); //修改history中的数据，用于redo和 undo


      trigger && _this.changeHistory(pageData);
    });

    _defineProperty(_assertThisInitialized(_this), "onSwitchDevice", function (device) {
      _this.setState(_objectSpread({}, _this.state, {
        device: device,
        selectedNode: null,
        addPanelVisible: false,
        animation: false
      }), function () {
        _this.setState({
          animation: true
        });
      });
    });

    _defineProperty(_assertThisInitialized(_this), "onAdd", function () {
      _this.setState({
        selectedNode: null,
        addPanelVisible: true
      });
    });

    _defineProperty(_assertThisInitialized(_this), "onAddPanelClose", function () {
      _this.setState({
        addPanelVisible: false
      });
    });

    _defineProperty(_assertThisInitialized(_this), "onPropsPanelClose", function () {
      _this.setState({
        selectedNode: null
      });
    });

    _defineProperty(_assertThisInitialized(_this), "componentScrollTop", function (data) {
      if (document.getElementById("view".concat(data.id))) {
        document.getElementById("view".concat(data.id)).scrollIntoView({
          behavior: 'smooth'
        });
      }
    });

    _defineProperty(_assertThisInitialized(_this), "addComponent", function (_ref) {
      var type = _ref.type,
          label = _ref.label,
          icon = _ref.icon;
      var _this$state2 = _this.state,
          MPageData = _this$state2.MPageData,
          device = _this$state2.device;
      var compInst = {
        type: type,
        id: (0, _uuid.v4)(),
        label: label,
        icon: icon
      };
      var newData = [].concat(_toConsumableArray(MPageData[device]), [compInst]);

      _this.setState({
        addPanelVisible: false,
        MPageData: _objectSpread({}, MPageData, _defineProperty({}, device, newData))
      }, function () {
        setTimeout(function () {
          // 定位到新增组件
          _this.componentScrollTop(compInst);

          var evt = new Event('component-click', {
            bubbles: false
          });
          evt.data = compInst;
          window.document.dispatchEvent(evt);
        }, 0);
      });

      _this.changeHistory(newData);
    });

    _defineProperty(_assertThisInitialized(_this), "onQuickMenuClick", function (code) {
      var _this$props = _this.props,
          onPublish = _this$props.onPublish,
          onSave = _this$props.onSave,
          onPreviews = _this$props.onPreviews;
      var _this$state3 = _this.state,
          device = _this$state3.device,
          MPageData = _this$state3.MPageData;
      var handleParams = {
        pageData: {
          id: (0, _uuid.v4)(),
          childNodes: MPageData[device]
        },
        device: device
      };

      switch (code) {
        case _constants.quickMenuCode.UNDO:
          _this.onUndo(1);

          break;

        case _constants.quickMenuCode.REDO:
          _this.onUndo(-1);

          break;

        case _constants.quickMenuCode.PUBLISH:
          onPublish(handleParams);
          break;

        case _constants.quickMenuCode.PREVIEW:
          onPreviews(handleParams);
          break;

        case _constants.quickMenuCode.SAVE:
          onSave(handleParams);
          break;

        case _constants.quickMenuCode.MODE_PC:
          _this.onSwitchDevice(_constants.deviceTypeMap.PC);

          break;

        case _constants.quickMenuCode.MODE_PHONE:
          _this.onSwitchDevice(_constants.deviceTypeMap.PHONE);

          break;
      }
    });

    _defineProperty(_assertThisInitialized(_this), "getTitles", function () {
      return [];
    });

    _defineProperty(_assertThisInitialized(_this), "renderHeader", function () {
      return /*#__PURE__*/_react["default"].createElement(_QuickMenuBar["default"], {
        language: _this.props.language,
        undoDisable: _this.getUndoDisable(),
        redoDisable: _this.getRedoDisable(),
        onBtnClick: _this.onQuickMenuClick,
        device: _this.state.device,
        onChangeDevice: _this.onSwitchDevice
      });
    });

    var _pageData = props.pageData,
        mobilePageData = props.mobilePageData,
        MParams = props.MParams;
    MParams && (window.MParams = MParams);
    var _MPageData = {
      pc: _pageData.childNodes || [],
      mobile: mobilePageData.childNodes || []
    };
    _this.state = {
      MPageData: _MPageData,
      device: _constants.deviceTypeMap.PHONE,
      history: (_history = {}, _defineProperty(_history, _constants.deviceTypeMap.PC, [_MPageData.pc]), _defineProperty(_history, _constants.deviceTypeMap.PHONE, [_MPageData.mobile]), _history),
      selectedNode: null,
      addPanelVisible: false,
      animation: true
    };
    return _this;
  }

  _createClass(Designer, [{
    key: "componentWillReceiveProps",
    value: function componentWillReceiveProps(nextProps) {
      var _history2;

      var pageData = nextProps.pageData,
          mobilePageData = nextProps.mobilePageData;
      this.setState({
        MPageData: {
          pc: pageData.childNodes || [],
          mobile: mobilePageData.childNodes || []
        },
        history: (_history2 = {}, _defineProperty(_history2, _constants.deviceTypeMap.PC, [pageData.childNodes || []]), _defineProperty(_history2, _constants.deviceTypeMap.PHONE, [mobilePageData.childNodes || []]), _history2)
      });
    }
  }, {
    key: "onComponentClick",
    value: function onComponentClick(data) {
      var _this$state4 = this.state,
          selectedNode = _this$state4.selectedNode,
          device = _this$state4.device;
      if (selectedNode && selectedNode.id === data.id) return;
      this.setState({
        selectedNode: (0, _cloneDeep["default"])(data)
      });
    }
  }, {
    key: "componentDidMount",
    value: function componentDidMount() {
      var _this2 = this;

      window.document.addEventListener('component-click', function (event) {
        _this2.onComponentClick(event.data);
      });
      window.document.addEventListener('property-update', function (event) {
        var _this2$state = _this2.state,
            MPageData = _this2$state.MPageData,
            device = _this2$state.device;
        var newPageData = JSON.parse(JSON.stringify(MPageData[device]));
        var findNode = newPageData.find(function (data) {
          return data.id === event.data.id;
        });

        _extends(findNode, event.data);

        _this2.setPageData(newPageData);
      });
    }
    /**
     * num = 1 表示undo 
     * num = -1 表示redo
     * @param {*} num 
     */

  }, {
    key: "onUndo",
    value: function onUndo(num) {
      var _this$state5 = this.state,
          device = _this$state5.device,
          history = _this$state5.history;
      var newCursorIndex = this.cursor[device] + num;
      this.cursor[device] = newCursorIndex;
      var newPageData = history[device][newCursorIndex];
      this.setPageData(newPageData, false);
    }
    /**
    * 修改历史模列表,用于 redo 和 undo
    * @param {*} pageData 
    */

  }, {
    key: "changeHistory",
    value: function changeHistory(pageData) {
      var _this$state6 = this.state,
          device = _this$state6.device,
          history = _this$state6.history;
      var index = this.cursor[device];
      history[device].splice(0, index, pageData);
      this.cursor[device] = 0;
      this.setState({
        history: _objectSpread({}, history)
      });
    }
    /**
     * 楼层 的 新增、删除、拷贝、顺序调整、属性修改时调用
     * @param {*} pageData 模版信息
     */

  }, {
    key: "getUndoDisable",
    value: function getUndoDisable() {
      var _this$state7 = this.state,
          history = _this$state7.history,
          device = _this$state7.device;
      return this.cursor[device] === history[device].length - 1;
    }
  }, {
    key: "getRedoDisable",
    value: function getRedoDisable() {
      var device = this.state.device;
      return this.cursor[device] === 0;
    }
  }, {
    key: "render",
    value: function render() {
      var _this$state8 = this.state,
          selectedNode = _this$state8.selectedNode,
          MPageData = _this$state8.MPageData,
          device = _this$state8.device,
          addPanelVisible = _this$state8.addPanelVisible,
          animation = _this$state8.animation,
          history = _this$state8.history;
      var _this$props2 = this.props,
          pagesManager = _this$props2.pagesManager,
          compSource = _this$props2.compSource,
          pageName = _this$props2.pageName;
      return /*#__PURE__*/_react["default"].createElement("div", {
        className: "designer-wrap"
      }, /*#__PURE__*/_react["default"].createElement(_PageCompList["default"], {
        pageData: MPageData[device],
        selected: selectedNode || {},
        setPageData: this.setPageData,
        renderPagesManage: pagesManager,
        onAdd: this.onAdd,
        pageName: pageName
      }), /*#__PURE__*/_react["default"].createElement(_CompListPanel["default"], {
        visible: addPanelVisible,
        onClose: this.onAddPanelClose,
        compSource: compSource[device],
        onAdd: this.addComponent
      }), /*#__PURE__*/_react["default"].createElement(_PropertyPanel["default"], {
        device: device,
        selectedNode: selectedNode || {},
        animation: animation,
        onClose: this.onPropsPanelClose,
        titles: this.getTitles()
      }), /*#__PURE__*/_react["default"].createElement(_ViewArea["default"], {
        device: device,
        pageData: MPageData[device],
        renderHeader: this.renderHeader,
        selected: selectedNode || {}
      }));
    }
  }]);

  return Designer;
}(_react.Component);

exports["default"] = Designer;
Designer.defaultProps = {
  onSave: function onSave() {},
  onPublish: function onPublish() {},
  onPreviews: function onPreviews() {},
  pageData: {},
  mobilePageData: {}
};