import _extends from "@babel/runtime/helpers/extends";
import _inheritsLoose from "@babel/runtime/helpers/inheritsLoose";
import * as React from 'react';
import { Component } from 'react';
import MonacoEditor from '@alilc/lowcode-plugin-base-monaco-editor';
import './index.less';
var defaultParams = '{\n \t"type":"click" \n}';
// 模板变量占位
var tempPlaceHolder = '${extParams}';
var tempPlaceHolderReg = /\$\{extParams\}/g;
var propEventsReg = /(this\.)?props\.[a-zA-Z0-9\-_]+/;
var _AliLowCodeEngine = AliLowCodeEngine,
  event = _AliLowCodeEngine.event,
  project = _AliLowCodeEngine.project,
  skeleton = _AliLowCodeEngine.skeleton;
var _Next = Next,
  Dialog = _Next.Dialog,
  Search = _Next.Search,
  Input = _Next.Input,
  Balloon = _Next.Balloon,
  Icon = _Next.Icon,
  Switch = _Next.Switch,
  Message = _Next.Message;
var defaultEditorOption = {
  height: '319px',
  width: '100%',
  readOnly: false,
  automaticLayout: true,
  folding: true,
  // 默认开启折叠代码功能
  lineNumbers: 'on',
  wordWrap: 'off',
  formatOnPaste: true,
  fontSize: 12,
  tabSize: 2,
  scrollBeyondLastLine: false,
  fixedOverflowWidgets: false,
  snippetSuggestions: 'top',
  minimap: {
    enabled: false
  },
  scrollbar: {
    vertical: 'auto',
    horizontal: 'auto'
  }
};
var SystemEventNameMap = {
  componentDidMount: true,
  constructor: true,
  componentWillMount: true,
  shouldComponentUpdate: true,
  componentDidUpdate: true,
  render: true,
  componentWillUnmount: true
};
var HelpTip = function HelpTip(props) {
  var children = props.children,
    className = props.className,
    _props$align = props.align,
    align = _props$align === void 0 ? 't' : _props$align,
    _props$style = props.style,
    style = _props$style === void 0 ? {} : _props$style,
    _props$iconStyle = props.iconStyle,
    iconStyle = _props$iconStyle === void 0 ? {} : _props$iconStyle,
    _props$size = props.size,
    size = _props$size === void 0 ? 'xs' : _props$size;
  var icon = /*#__PURE__*/React.createElement(Icon, {
    style: iconStyle,
    size: size,
    type: "help"
  });
  var bConfig = {
    align: align,
    className: className,
    style: style,
    closable: false,
    needAdjust: true,
    shouldUpdatePosition: true,
    trigger: icon
  };
  return /*#__PURE__*/React.createElement(Balloon, bConfig, children);
};
var EventBindDialog = /*#__PURE__*/function (_Component) {
  function EventBindDialog() {
    var _this;
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    _this = _Component.call.apply(_Component, [this].concat(args)) || this;
    _this.eventList = [
      // {
      //   name: 'getData',
      // },
      // {
      //   name: 'deleteData',
      // },
      // {
      //   name: 'initData',
      // },
      // {
      //   name: 'editData',
      // },
      // {
      //   name: 'submitData',
      // },
    ];
    _this.relatedEventName = '';
    _this.bindEventName = '';
    _this.state = {
      visiable: false,
      setterName: 'event-setter',
      selectedEventName: '',
      eventName: '',
      paramStr: '',
      configEventData: null,
      useParams: false
    };
    _this.openDialog = function (bindEventName, relatedEventName, isEdit) {
      _this.relatedEventName = relatedEventName;
      _this.bindEventName = bindEventName;
      _this.initEventName(isEdit);
    };
    _this.closeDialog = function () {
      _this.setState({
        visiable: false
      });
    };
    _this.initEventName = function (isEdit) {
      var eventName = _this.relatedEventName;
      if (!isEdit) {
        _this.eventList.forEach(function (item) {
          if (item.name === eventName) {
            eventName = eventName + "_new";
          }
        });
      }
      _this.setState({
        eventName: eventName,
        selectedEventName: isEdit ? eventName : '',
        visiable: true
      });
    };
    _this.onInputChange = function (eventName) {
      _this.setState({
        eventName: eventName
      });
    };
    _this.onSelectItem = function (eventName) {
      _this.setState({
        selectedEventName: eventName
      });

      // 为空是新建事件
      if (eventName === '') {
        _this.initEventName();
      } else {
        _this.setState({
          selectedEventName: eventName,
          eventName: eventName
        });
      }
    };
    _this.onSearchEvent = function () {};
    _this.onChange = function (checked) {
      _this.setState({
        useParams: checked
      });
    };
    /**
     * 将paramStr包装成一个js对象，防止monaco格式报错
     */
    _this.formatParmaStr = function (paramStr) {
      if (!paramStr) {
        return defaultParams;
      } else {
        return paramStr;
      }
    };
    _this.pickupFunctionName = function (codeStr) {
      return codeStr.substr(0, codeStr.indexOf('('));
    };
    _this.removeSpace = function (str) {
      return str.replace(/\s*/g, '');
    };
    _this.formatTemplate = function (template, eventName, useParams) {
      var formatTemp;
      if (template) {
        var functionName = _this.pickupFunctionName(template);
        formatTemp = template.replace(new RegExp("^s*" + functionName), eventName);
        if (useParams) {
          formatTemp = formatTemp.replace(tempPlaceHolderReg, 'extParams');
        } else {
          var leftIndex = formatTemp.indexOf('(');
          var rightIndex = formatTemp.indexOf(')');
          // 提取括号中的参数列表
          var paramList = formatTemp.substr(leftIndex + 1, rightIndex - (leftIndex + 1)).split(',');
          paramList.map(function (item, index) {
            if (_this.removeSpace(item) === tempPlaceHolder) {
              paramList.splice(index, 1);
            }
            return item;
          });

          // 重新join进去

          formatTemp = formatTemp.substr(0, leftIndex) + "(" + paramList.join(',') + ")" + formatTemp.substr(rightIndex + 1, formatTemp.length);
        }
      }
      return formatTemp;
    };
    _this.formatEventName = function (eventName) {
      // 支持绑定this.props.xxxx
      if (propEventsReg.test(eventName)) {
        return eventName.replace(/(this\.)|(\s+)/, '');
      }
      var newEventNameArr = eventName.split('');
      var index = eventName.indexOf('.');
      if (index >= 0) {
        newEventNameArr[index + 1] = newEventNameArr[index + 1].toUpperCase();
      }
      return newEventNameArr.join('').replace(/\./, '');
    };
    _this.onOk = function () {
      var editor = _this.props.editor;
      var _this$state = _this.state,
        setterName = _this$state.setterName,
        eventName = _this$state.eventName,
        paramStr = _this$state.paramStr,
        _this$state$configEve = _this$state.configEventData,
        configEventData = _this$state$configEve === void 0 ? {} : _this$state$configEve,
        useParams = _this$state.useParams;
      var formatEventName = _this.formatEventName(eventName);
      if (SystemEventNameMap[formatEventName]) {
        Message.error('不可以绑定到系统内置函数,请修改函数名以后重新绑定');
        return;
      }
      event.emit(setterName + ".bindEvent", formatEventName, useParams ? paramStr : undefined, _this.bindEventName);

      // 选中的是新建事件 && 注册了sourceEditor面板
      if (_this.state.selectedEventName == '' && !propEventsReg.test(formatEventName)) {
        // 判断面板是否处于激活状态
        skeleton.showPanel('codeEditor');
        var formatTemp = _this.formatTemplate(configEventData.template, formatEventName, useParams);
        setTimeout(function () {
          event.emit('codeEditor.addFunction', {
            functionName: formatEventName,
            template: formatTemp
          });
        }, 200);
      }
      _this.closeDialog();
    };
    _this.onChangeEditor = function (paramStr) {
      _this.setState({
        paramStr: paramStr
      });
    };
    return _this;
  }
  _inheritsLoose(EventBindDialog, _Component);
  var _proto = EventBindDialog.prototype;
  _proto.componentDidMount = function componentDidMount() {
    var _this2 = this;
    var config = this.props.config;
    event.on("common:" + config.pluginKey + ".openDialog", function (relatedEventName, setterName, paramStr, isEdit, bindEventName, configEventData) {
      _this2.setState({
        setterName: setterName,
        paramStr: _this2.formatParmaStr(paramStr),
        configEventData: configEventData,
        useParams: !!paramStr
      });
      var schema = project.exportSchema();
      var pageNode = schema.componentsTree[0];
      if (pageNode.methods) {
        _this2.eventList = [];
        for (var key in pageNode.methods) {
          _this2.eventList.push({
            name: key
          });
        }
      }
      _this2.openDialog(bindEventName, relatedEventName, isEdit);
    });
  };
  _proto.render = function render() {
    var _this3 = this,
      _lowcodeSetterSwitch;
    var _this$state2 = this.state,
      selectedEventName = _this$state2.selectedEventName,
      eventName = _this$state2.eventName,
      visiable = _this$state2.visiable,
      paramStr = _this$state2.paramStr,
      useParams = _this$state2.useParams;
    // console.log('selectedEventName:' + selectedEventName);
    return /*#__PURE__*/React.createElement(Dialog, {
      visible: visiable,
      title: "\u4E8B\u4EF6\u7ED1\u5B9A",
      onClose: this.closeDialog,
      onCancel: this.closeDialog,
      onOk: function onOk() {
        return _this3.onOk();
      }
    }, /*#__PURE__*/React.createElement("div", {
      className: "event-dialog-body"
    }, /*#__PURE__*/React.createElement("div", {
      className: "dialog-left-container"
    }, /*#__PURE__*/React.createElement("div", {
      className: "dialog-small-title"
    }, "\u4E8B\u4EF6\u9009\u62E9"), /*#__PURE__*/React.createElement("div", {
      className: "dialog-left-context"
    }, /*#__PURE__*/React.createElement("ul", {
      className: "event-type-container"
    }, /*#__PURE__*/React.createElement("li", {
      className: "select-item"
    }, "\u5185\u7F6E\u51FD\u6570"), /*#__PURE__*/React.createElement("li", {
      className: "select-item select-item-active"
    }, "\u7EC4\u4EF6\u4E8B\u4EF6")), /*#__PURE__*/React.createElement("div", {
      className: "event-select-container"
    }, /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(Search, {
      className: "event-search-box",
      shape: "simple"
    }), /*#__PURE__*/React.createElement("ul", {
      className: "event-list"
    }, /*#__PURE__*/React.createElement("li", {
      className: selectedEventName == '' ? 'select-item select-item-active' : 'select-item',
      onClick: function onClick() {
        return _this3.onSelectItem('');
      }
    }, "\u65B0\u5EFA\u4E8B\u4EF6"), this.eventList.map(function (item, index) {
      return /*#__PURE__*/React.createElement("li", {
        key: index,
        className: selectedEventName == item.name ? 'select-item select-item-active' : 'select-item',
        onClick: function onClick() {
          return _this3.onSelectItem(item.name);
        }
      }, item.name);
    })))))), /*#__PURE__*/React.createElement("div", {
      className: "dialog-right-container"
    }, /*#__PURE__*/React.createElement("div", {
      className: "dialog-small-title"
    }, "\u4E8B\u4EF6\u540D\u79F0", ((_lowcodeSetterSwitch = window.lowcodeSetterSwitch) === null || _lowcodeSetterSwitch === void 0 ? void 0 : _lowcodeSetterSwitch.enablePropsEvents) && /*#__PURE__*/React.createElement(HelpTip, {
      iconStyle: {
        marginLeft: 4
      }
    }, "\u5982\u9700\u7ED1\u5B9A props \u5C5E\u6027\uFF0C\u53EF\u901A\u8FC7 props.xxx \u8FDB\u884C\u7ED1\u5B9A")), /*#__PURE__*/React.createElement("div", {
      className: "event-input-container"
    }, /*#__PURE__*/React.createElement(Input, {
      style: {
        width: '100%'
      },
      value: eventName,
      onChange: this.onInputChange
    })), /*#__PURE__*/React.createElement("div", {
      className: "dialog-small-title"
    }, "\u6269\u5C55\u53C2\u6570\u8BBE\u7F6E", ' ', /*#__PURE__*/React.createElement(HelpTip, null, "\u6269\u5C55\u53C2\u6570\u505A\u4E3A\u5355\u72EC\u7684\u4E00\u4E2Ajson\u683C\u5F0F\u5165\u53C2\u8FFD\u52A0\u5728\u539F\u6709\u900F\u4F20\u53C2\u6570\u4E4B\u540E \u5982:onClick (event,extParams)"), /*#__PURE__*/React.createElement(Switch, {
      checked: useParams,
      size: "small",
      style: {
        marginLeft: '10px'
      },
      autoWidth: true,
      checkedChildren: "\u542F\u7528",
      unCheckedChildren: "\u5173\u95ED",
      onChange: this.onChange
    })), /*#__PURE__*/React.createElement("div", {
      className: "editor-container"
    }, /*#__PURE__*/React.createElement(MonacoEditor, _extends({
      value: paramStr
    }, defaultEditorOption, {
      language: 'json',
      onChange: function onChange(newCode) {
        return _this3.onChangeEditor(newCode);
      }
    })), !useParams && /*#__PURE__*/React.createElement("div", {
      className: "mask"
    })))));
  };
  return EventBindDialog;
}(Component);
export { EventBindDialog as default };