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 = ownKeys.concat(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); 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 } }); 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; } 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; }

/* eslint-disable */
import { message, Spin } from '@whalecloud/fdx'; // import { Steps } from 'intro.js-react';
// import 'intro.js/introjs.css';

import isEmpty from 'lodash/isEmpty';
import React, { Component } from 'react';
import { v4 as uuidv4 } from 'uuid';
import { acceptTypes, componentMap, propertyPanelMap } from '../../core/component-types';
import PCDesigner from '../../core/designer/PCDesigner';
import PhoneDesigner from '../../core/designer/PhoneDesigner';
import { delNode, findNode, insertNode, moveNode, updateAllNode, updateNode } from '../../utils/treeUtil';
import MainArea from '../MainArea';
import PropertyPanelContainer from '../PropertyPanelContainer';
import SideBar from '../SideBar';
import TopBar from '../TopBar';
import DragAndDropHOC from './DragAndDropHOC';
import './index.less';
/**
 * @class MGenerator
 * 主入口。
 */

var MGenerator = /*#__PURE__*/function (_Component) {
  _inherits(MGenerator, _Component);

  var _super = _createSuper(MGenerator);

  // 点击组件副本
  // copy数据
  // 当前pid
  // 当前位置
  // 允许复制标示
  function MGenerator(props) {
    var _this;

    _classCallCheck(this, MGenerator);

    _this = _super.call(this, props);

    _defineProperty(_assertThisInitialized(_this), "clickData", {});

    _defineProperty(_assertThisInitialized(_this), "copyData", {});

    _defineProperty(_assertThisInitialized(_this), "destPid", '');

    _defineProperty(_assertThisInitialized(_this), "destIndex", '');

    _defineProperty(_assertThisInitialized(_this), "allow", false);

    _defineProperty(_assertThisInitialized(_this), "getTitles", function () {
      var childNodes = _this.state.MPageData[_this.state.renderer].childNodes;
      var filterNodes = childNodes ? childNodes.filter(function (node) {
        return node.pageModuleName;
      }) : [];
      return filterNodes.map(function (node) {
        return node.pageModuleName;
      });
    });

    _defineProperty(_assertThisInitialized(_this), "isAllow", function (item) {
      var allNodes = _this.state.MPageData[_this.state.renderer].childNodes || [];
      var findNodes = allNodes.find(function (node) {
        return node.type === 'MPageTitle';
      });

      if (item.type === 'MPageTitle' && findNodes) {
        message.error('No more can be created');
        return false;
      }

      return true;
    });

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

    var _props$pageData = props.pageData,
        pageData = _props$pageData === void 0 ? {} : _props$pageData,
        _props$mobilePageData = props.mobilePageData,
        mobilePageData = _props$mobilePageData === void 0 ? {} : _props$mobilePageData,
        _props$leftSiderBarCo = props.leftSiderBarConfig,
        leftSiderBarConfig = _props$leftSiderBarCo === void 0 ? [] : _props$leftSiderBarCo,
        _props$mobileLeftSide = props.mobileLeftSiderBarConfig,
        mobileLeftSiderBarConfig = _props$mobileLeftSide === void 0 ? [] : _props$mobileLeftSide,
        _props$receiveCompone = props.receiveComponent,
        receiveComponent = _props$receiveCompone === void 0 ? {} : _props$receiveCompone,
        MParams = props.MParams;
    MParams && (window.MParams = MParams);
    var MPageData = {
      pc: pageData,
      mobile: mobilePageData
    };
    var MLeftSiderBarConfig = {
      pc: leftSiderBarConfig,
      mobile: mobileLeftSiderBarConfig
    };
    _this.state = {
      componentMap: componentMap,
      propertyPanelMap: propertyPanelMap,
      MPageData: MPageData,
      MLeftSiderBarConfig: MLeftSiderBarConfig,
      propertyInstance: null,
      renderer: 'pc',
      loading: false,
      deviceType: 'iPhone',
      historyList: {
        pc: [MPageData.pc],
        mobile: [MPageData.mobile]
      },
      selectedNode: null
    };
    return _this;
  }
  /**
   * 向 MagicBox 注册一个组件
   * @param {*} name
   * @param {*} component
   * @param {*} panel
   */


  _createClass(MGenerator, [{
    key: "registerComponnet",
    value: function registerComponnet(name, component, panel) {
      var _this$state = this.state,
          componentMap = _this$state.componentMap,
          propertyPanelMap = _this$state.propertyPanelMap;
      if (componentMap[name]) console.warn("Coponent ".concat(name, " has already exists."));
      component && (componentMap[name] = component);
      panel && (propertyPanelMap[name] = panel);
      this.setState(_objectSpread({}, this.state, {
        componentMap: componentMap,
        propertyPanelMap: propertyPanelMap,
        modalVisible: false
      }));
    }
  }, {
    key: "componentWillReceiveProps",
    value: function componentWillReceiveProps(nextProps) {
      var _nextProps$pageData = nextProps.pageData,
          pageData = _nextProps$pageData === void 0 ? {} : _nextProps$pageData,
          _nextProps$mobilePage = nextProps.mobilePageData,
          mobilePageData = _nextProps$mobilePage === void 0 ? {} : _nextProps$mobilePage,
          _nextProps$leftSiderB = nextProps.leftSiderBarConfig,
          leftSiderBarConfig = _nextProps$leftSiderB === void 0 ? [] : _nextProps$leftSiderB,
          _nextProps$mobileLeft = nextProps.mobileLeftSiderBarConfig,
          mobileLeftSiderBarConfig = _nextProps$mobileLeft === void 0 ? [] : _nextProps$mobileLeft;
      var MPageData = {
        pc: _objectSpread({
          index: 0,
          id: uuidv4(),
          pid: -1,
          isSelected: false,
          childNodes: []
        }, pageData),
        mobile: _objectSpread({
          index: 0,
          id: uuidv4(),
          pid: -1,
          isSelected: false,
          childNodes: []
        }, mobilePageData)
      };
      var MLeftSiderBarConfig = {
        pc: _toConsumableArray(leftSiderBarConfig),
        mobile: _toConsumableArray(mobileLeftSiderBarConfig)
      };
      this.setState({
        MPageData: MPageData,
        MLeftSiderBarConfig: MLeftSiderBarConfig
      });
    }
  }, {
    key: "componentWillMount",
    value: function componentWillMount() {
      var _this2 = this;

      var receiveComponent = this.props.receiveComponent;

      if (!isEmpty(receiveComponent)) {
        console.warn(receiveComponent);
        Object.keys(receiveComponent).map(function (v) {
          acceptTypes.push(v);

          _this2.registerComponnet(v, receiveComponent[v][0], receiveComponent[v][1]);
        });
      }

      window.acceptTypes = acceptTypes;
    }
  }, {
    key: "componentDidMount",
    value: function componentDidMount() {
      var _arguments = arguments,
          _this3 = this;

      window.document.addEventListener('keydown', function (e) {
        var e = event || window.event || _arguments.callee.caller.arguments[0];

        if (e.target.nodeName !== 'INPUT') {
          if (e.keyCode == 86 && (navigator.platform.match('Mac') ? e.metaKey : e.ctrlKey)) {
            if (_this3.copyData.type === 'MPlotArea') {
              return;
            }

            if (!_this3.allow) {
              return;
            }

            var item = _objectSpread({}, _this3.copyData, {
              id: uuidv4(),
              pid: uuidv4()
            });

            insertNode(_this3.state.MPageData[_this3.state.renderer], item, _this3.destPid, _this3.destIndex);

            _this3.setState(_objectSpread({}, _this3.state), function () {
              _this3.changePageData(_this3.state.MPageData[_this3.state.renderer]);
            });
          } else if (e.keyCode == 67 && (navigator.platform.match('Mac') ? e.metaKey : e.ctrlKey)) {
            _this3.copyData = _this3.clickData;
          } else if (e.keyCode == 83 && (navigator.platform.match('Mac') ? e.metaKey : e.ctrlKey)) {
            e.preventDefault();
            alert('你按下了ctrl+S');
          } else if (e.keyCode == 46) {
            _this3.onDelComponent();
          }
        }
      });
      window.document.addEventListener('component-click', function (event) {
        if (event.data && event.data.type) {
          if (event.data.type === 'MCol') {
            _this3.allow = true;
            _this3.destPid = event.data.id;
            _this3.destIndex = event.data.index;
          } else if (event.data.type === 'MRow') {
            _this3.allow = false;
            _this3.destPid = event.data.id;
            _this3.destIndex = event.data.index;
          } else {
            _this3.allow = false;
            _this3.clickData = event.data;
          }
        }

        if (_this3.state.selectedNode && _this3.state.selectedNode.id === event.data.id) return;
        updateAllNode(_this3.state.MPageData[_this3.state.renderer], {
          isSelected: false
        });
        _this3.state.selectedNode = event.data;
        updateNode(_this3.state.MPageData[_this3.state.renderer], _this3.state.selectedNode.id, {
          isSelected: true
        });
        var Clazz = _this3.state.propertyPanelMap[event.data.type];
        var newInstance = Clazz && React.createElement(Clazz, _objectSpread({}, event.data, {
          titles: _this3.getTitles(),
          renderer: _this3.state.renderer
        }));

        _this3.setState(_objectSpread({}, _this3.state, {
          propertyInstance: newInstance
        }));
      });
      window.document.addEventListener('property-update', function (event) {
        updateNode(_this3.state.MPageData[_this3.state.renderer], event.data.id, event.data);

        _this3.setState(_objectSpread({}, _this3.state, {
          loading: true
        }), function () {
          setTimeout(function () {
            message.success('Save successfully');

            _this3.setState({
              loading: false
            });
          }, 500);

          _this3.changePageData(_this3.state.MPageData[_this3.state.renderer]);
        });
      });
      /* 30秒自动保存 */

      var autoSave = this.props.autoSave;
      this.time = null;
      autoSave && (this.timer = setInterval(function () {
        autoSave({
          pageData: _this3.state.MPageData[_this3.state.renderer],
          type: _this3.state.renderer,
          deviceType: _this3.state.deviceType
        });
      }, 30000));
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      clearInterval(this.timer);
    }
  }, {
    key: "onViewData",
    value: function onViewData(event) {}
  }, {
    key: "onDelComponent",
    value: function onDelComponent(event) {
      var _this4 = this;

      if (this.state.selectedNode) {
        var node = this.state.selectedNode;

        if (node && node.pid === -1) {
          console.warn("Try deleting root node, id=".concat(node.id, "."));
          return;
        }

        node && delNode(this.state.MPageData[this.state.renderer], node.pid, node.index);
        this.state.selectedNode = null;
        this.setState(_objectSpread({}, this.state, {
          propertyInstance: null
        }), function () {
          _this4.changePageData(_this4.state.MPageData[_this4.state.renderer]);
        });
      }
    }
  }, {
    key: "onPublish",
    value: function onPublish() {
      var onPublish = this.props.onPublish;
      onPublish && onPublish({
        pageData: this.state.MPageData[this.state.renderer],
        type: this.state.renderer,
        deviceType: this.state.deviceType
      });
    }
  }, {
    key: "onSave",
    value: function onSave() {
      var onSave = this.props.onSave;
      onSave && onSave({
        pageData: this.state.MPageData[this.state.renderer],
        type: this.state.renderer,
        deviceType: this.state.deviceType
      });
    }
  }, {
    key: "onPreview",
    value: function onPreview(event) {
      var onPreviews = this.props.onPreviews;
      onPreviews && onPreviews({
        pageData: this.state.MPageData[this.state.renderer],
        MParams: window.MParams,
        type: this.state.renderer,
        deviceType: this.state.deviceType
      });
    }
  }, {
    key: "isValidDest",
    value: function isValidDest(item, destPid, destIndex) {
      if (!item.pid) return true; // new added node

      var itemData = findNode(this.state.MPageData[this.state.renderer], item.id);

      if (!itemData) {
        return false;
      } // try dropping to self or descendant node


      var isInvalid = false;

      function isDescendant(node) {
        if (isInvalid) {
          return;
        }

        if (node.id === destPid) {
          isInvalid = true;
        }

        node.childNodes && node.childNodes.map(function (n, index) {
          isDescendant(n);
        });
      }

      isDescendant(itemData);
      return !isInvalid;
    }
  }, {
    key: "onDrop",
    value: function onDrop(item, destPid, destIndex) {
      var _this5 = this;

      console.log(item, 333);

      if (item.pid) {
        // move tree node
        item = moveNode(this.state.MPageData[this.state.renderer], item.pid, item.index);
        item && insertNode(this.state.MPageData[this.state.renderer], item, destPid, destIndex);
      } else {
        // insert new node
        if (!this.isAllow(item)) {
          return;
        }

        item = _objectSpread({}, item, {
          id: uuidv4(),
          pid: uuidv4()
        });
        console.log(item, 3334);
        insertNode(this.state.MPageData[this.state.renderer], item, destPid, destIndex);
      }

      this.setState(_objectSpread({}, this.state), function () {
        _this5.changePageData(_this5.state.MPageData[_this5.state.renderer]);
      });
    }
  }, {
    key: "onHover",
    value: function onHover(item, destPid, destIndex) {}
    /* 历史数据 */
    // historyList = { pc: [], mobile: [] }

  }, {
    key: "changePageData",
    value: function changePageData(data) {
      var nPageData = JSON.parse(JSON.stringify(data));
      this.state.historyList[this.state.renderer].push(nPageData);
      this.state.historyList[this.state.renderer] = this.state.historyList[this.state.renderer].slice(-20);
      this.index[this.state.renderer] = this.state.historyList[this.state.renderer].length - 1;
    }
  }, {
    key: "changeProperty",
    value: function changeProperty(data) {}
  }, {
    key: "undo",
    value: function undo() {
      this.index[this.state.renderer] = this.index[this.state.renderer] === 0 ? 0 : this.index[this.state.renderer] - 1;
      var undoPageData = JSON.parse(JSON.stringify(this.state.historyList[this.state.renderer][this.index[this.state.renderer]]));
      this.state.MPageData[this.state.renderer] = undoPageData;
      this.setState({
        MPageData: this.state.MPageData
      });
    }
  }, {
    key: "redo",
    value: function redo() {
      this.index[this.state.renderer] = this.index[this.state.renderer] === this.state.historyList[this.state.renderer].length - 1 ? this.index[this.state.renderer] : this.index[this.state.renderer] + 1;
      var redoPageData = JSON.parse(JSON.stringify(this.state.historyList[this.state.renderer][this.index[this.state.renderer]]));
      this.state.MPageData[this.state.renderer] = redoPageData;
      this.setState({
        MPageData: this.state.MPageData
      });
    }
  }, {
    key: "onSwitchRenderer",
    value: function onSwitchRenderer(renderer) {
      this.copyData = {};
      this.setState(_objectSpread({}, this.state, {
        renderer: renderer,
        propertyInstance: null
      }));
    }
  }, {
    key: "onChangeSelect",
    value: function onChangeSelect(deviceType) {
      this.setState({
        deviceType: deviceType
      });
    }
  }, {
    key: "render",
    value: function render() {
      var _this6 = this;

      var _this$state2 = this.state,
          stepsEnabled = _this$state2.stepsEnabled,
          steps = _this$state2.steps,
          initialStep = _this$state2.initialStep,
          pointShow = _this$state2.pointShow,
          pointX = _this$state2.pointX,
          pointY = _this$state2.pointY;
      return /*#__PURE__*/React.createElement("div", {
        className: "mgenerator"
      }, /*#__PURE__*/React.createElement(Spin, {
        tip: "Loading...",
        spinning: this.state.loading
      }, /*#__PURE__*/React.createElement(TopBar, {
        undo: this.undo.bind(this),
        redo: this.redo.bind(this),
        onViewData: this.onViewData.bind(this),
        onDelComponent: this.onDelComponent.bind(this),
        onPreview: this.onPreview.bind(this),
        onSave: this.onSave.bind(this),
        onPublish: this.onPublish.bind(this),
        switchRenderer: this.onSwitchRenderer.bind(this),
        onChangeSelect: this.onChangeSelect.bind(this)
      }), /*#__PURE__*/React.createElement("div", {
        className: "mainContainer"
      }, /*#__PURE__*/React.createElement(DragAndDropHOC, null, /*#__PURE__*/React.createElement(SideBar, {
        showIntro: MParams && MParams.showIntro,
        pageData: this.state.MPageData[this.state.renderer],
        leftSiderBarConfig: this.state.MLeftSiderBarConfig[this.state.renderer]
      }), /*#__PURE__*/React.createElement(MainArea, null, function () {
        if (_this6.state.renderer === 'pc') {
          return /*#__PURE__*/React.createElement(PCDesigner, {
            componentMap: _this6.state.componentMap,
            pageData: _this6.state.MPageData[_this6.state.renderer],
            onHover: _this6.onHover.bind(_this6),
            onDrop: _this6.onDrop.bind(_this6),
            isValidDest: _this6.isValidDest.bind(_this6)
          });
        }

        if (_this6.state.renderer === 'mobile') {
          return /*#__PURE__*/React.createElement(PhoneDesigner, {
            deviceType: _this6.state.deviceType,
            componentMap: _this6.state.componentMap,
            pageData: _this6.state.MPageData[_this6.state.renderer],
            onHover: _this6.onHover.bind(_this6),
            onDrop: _this6.onDrop.bind(_this6),
            isValidDest: _this6.isValidDest.bind(_this6)
          });
        }

        return /*#__PURE__*/React.createElement(React.Fragment, null);
      }())), /*#__PURE__*/React.createElement(PropertyPanelContainer, {
        type: this.state.propertyInstance && this.state.propertyInstance.props && this.state.propertyInstance.props.type,
        changeProperty: this.changeProperty.bind(this)
      }, this.state.propertyInstance))));
    }
  }]);

  return MGenerator;
}(Component);

export { MGenerator };