"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports["default"] = void 0;
var _dialog = _interopRequireDefault(require("@alifd/next/lib/dialog"));
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _icon = _interopRequireDefault(require("@alifd/next/lib/icon"));
var _button = _interopRequireDefault(require("@alifd/next/lib/button"));
var _inheritsLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose"));
var _react = _interopRequireWildcard(require("react"));
var _lowcodePluginBaseMonacoEditor = _interopRequireDefault(require("@alilc/lowcode-plugin-base-monaco-editor"));
var _lowcodeEngine = require("@alilc/lowcode-engine");
var _jsBeautify = require("js-beautify");
require("./index.less");
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { "default": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n["default"] = e, t && t.set(e, n), n; }
var SETTER_NAME = 'function-setter';
var defaultEditorOption = {
  width: '100%',
  height: '95%',
  options: {
    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 FunctionSetter = exports["default"] = /*#__PURE__*/function (_PureComponent) {
  function FunctionSetter() {
    var _this;
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    _this = _PureComponent.call.apply(_PureComponent, [this].concat(args)) || this;
    _this.emitEventName = '';
    _this.state = {
      isShowDialog: false
    };
    _this.bindEvent = function (eventName, paramStr) {
      _this.bindEventCallback(eventName, paramStr);
    };
    _this.bindFunction = function (isEdit) {
      var _this$props = _this.props,
        field = _this$props.field,
        value = _this$props.value,
        template = _this$props.template;
      var paramStr;
      var functionName;
      if (value) {
        paramStr = _this.parseFunctionParam(value.value);
        functionName = _this.parseFunctionName(value.value);
      }
      _lowcodeEngine.event.emit('eventBindDialog.openDialog', functionName || field.name, _this.emitEventName, paramStr, isEdit, functionName || field.name, {
        template: template
      });
    };
    _this.openDialog = function () {
      var _this$props$value = _this.props.value,
        value = _this$props$value === void 0 ? {} : _this$props$value;
      _this.setState({
        isShowDialog: true
      });
      _this.functionCode = value.value;
    };
    _this.closeDialog = function () {
      _this.setState({
        isShowDialog: false
      });
    };
    _this.removeFunctionBind = function () {
      var removeProp = _this.props.removeProp;
      removeProp();
    };
    _this.parseFunctionName = function (functionString) {
      var _functionString$split;
      // 因为函数格式是固定的，所以可以按照字符换去匹配获取函数名
      return (_functionString$split = functionString.split('this.')[1]) === null || _functionString$split === void 0 ? void 0 : _functionString$split.split('.')[0];
    };
    _this.parseFunctionParam = function (functionString) {
      // eslint-disable-next-line no-useless-escape
      var matchList = functionString.match(/\[([\s\S]*?)\]/g);
      if (matchList !== null && matchList !== void 0 && matchList.length) {
        var paramStr = matchList[0].substring(1, matchList[0].length - 1);
        if (paramStr == '') {
          return null;
        }
        return paramStr;
      }
    };
    /**
     * 渲染按钮(初始状态)
     */
    _this.renderButton = function () {
      return /*#__PURE__*/_react["default"].createElement(_button["default"], {
        size: "small",
        type: "normal",
        onClick: function onClick() {
          return _this.bindFunction();
        }
      }, "\u7ED1\u5B9A\u51FD\u6570");
    };
    _this.updateCode = function (newCode) {
      _this.functionCode = newCode;
    };
    _this.onDialogOk = function () {
      var onChange = _this.props.onChange;
      onChange({
        type: 'JSFunction',
        value: _this.functionCode
      });
      _this.closeDialog();
    };
    _this.focusFunctionName = function (functionName) {
      _lowcodeEngine.skeleton.showPanel('codeEditor');
      setTimeout(function () {
        _lowcodeEngine.event.emit('codeEditor.focusByFunction', {
          functionName: functionName
        });
      }, 300);
    };
    /**
     * 渲染绑定函数
     */
    _this.renderBindFunction = function () {
      var value = _this.props.value;

      // 解析函数名
      var functionName = _this.parseFunctionName(value.value);
      return /*#__PURE__*/_react["default"].createElement("div", {
        className: "function-container"
      }, /*#__PURE__*/_react["default"].createElement("img", {
        className: "funtion-icon",
        src: "https://gw.alicdn.com/tfs/TB1NXNhk639YK4jSZPcXXXrUFXa-200-200.png"
      }), /*#__PURE__*/_react["default"].createElement("span", {
        className: "function-name",
        onClick: function onClick() {
          return _this.focusFunctionName(functionName);
        }
      }, functionName), /*#__PURE__*/_react["default"].createElement(_icon["default"], {
        type: "set",
        size: "medium",
        className: "funtion-operate-icon",
        onClick: function onClick() {
          return _this.bindFunction(true);
        }
      }), /*#__PURE__*/_react["default"].createElement(_icon["default"], {
        type: "ashbin",
        size: "medium",
        className: "funtion-operate-icon",
        onClick: _this.removeFunctionBind
      }));
    };
    /**
     * 渲染编辑函数按钮(可直接编辑函数内容)
     */
    _this.renderEditFunctionButton = function () {
      return /*#__PURE__*/_react["default"].createElement("div", null, /*#__PURE__*/_react["default"].createElement(_button["default"], {
        size: "small",
        type: "primary",
        onClick: _this.openDialog
      }, /*#__PURE__*/_react["default"].createElement(_icon["default"], {
        type: "edit"
      }), "\u7F16\u8F91\u51FD\u6570"));
    };
    _this.bindEventCallback = function (eventName, paramStr) {
      var onChange = _this.props.onChange;
      onChange({
        type: 'JSFunction',
        value: "function(){ return this." + eventName + ".apply(this,Array.prototype.slice.call(arguments).concat([" + (paramStr || '') + "])) }"
      });
    };
    return _this;
  }
  (0, _inheritsLoose2["default"])(FunctionSetter, _PureComponent);
  var _proto = FunctionSetter.prototype;
  _proto.componentDidMount = function componentDidMount() {
    this.emitEventName = SETTER_NAME + "-" + this.props.field.id;
    _lowcodeEngine.event.on("common:" + this.emitEventName + ".bindEvent", this.bindEvent);
  };
  _proto.componentWillUnmount = function componentWillUnmount() {
    _lowcodeEngine.event.off(this.emitEventName + ".bindEvent", this.bindEvent);
  };
  _proto.render = function render() {
    var _this2 = this;
    var value = this.props.value;
    var isShowDialog = this.state.isShowDialog;
    var functionName = '';
    if (value && value.value) {
      functionName = this.parseFunctionName(value.value);
    }
    var renderFunction;
    if (value) {
      if (functionName) {
        renderFunction = this.renderBindFunction;
      } else {
        renderFunction = this.renderEditFunctionButton;
      }
    } else {
      renderFunction = this.renderButton;
    }
    return /*#__PURE__*/_react["default"].createElement("div", {
      className: "lc-function-setter"
    }, renderFunction(), value && value.value && /*#__PURE__*/_react["default"].createElement(_dialog["default"], {
      visible: isShowDialog,
      closeable: 'close',
      title: "\u51FD\u6570\u7F16\u8F91",
      onCancel: this.closeDialog,
      onOk: this.onDialogOk,
      onClose: function onClose() {
        _this2.closeDialog();
      }
    }, /*#__PURE__*/_react["default"].createElement("div", {
      style: {
        width: '500px',
        height: '400px'
      }
    }, /*#__PURE__*/_react["default"].createElement(_lowcodePluginBaseMonacoEditor["default"], (0, _extends2["default"])({
      value: (0, _jsBeautify.js_beautify)(value.value)
    }, defaultEditorOption, {
      language: 'javascript',
      onChange: function onChange(newCode) {
        return _this2.updateCode(newCode);
      }
    })))));
  };
  return FunctionSetter;
}(_react.PureComponent);
FunctionSetter.defaultProps = {
  value: undefined,
  type: 'string',
  defaultValue: '',
  hasClear: true,
  placeholder: '请点击选择 Icon',
  onChange: function onChange() {
    return undefined;
  }
};