import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/objectWithoutPropertiesLoose";
import _extends from "@babel/runtime/helpers/extends";
import _Button from "@alifd/next/es/button";
import _Message from "@alifd/next/es/message";
import _inheritsLoose from "@babel/runtime/helpers/inheritsLoose";
var _excluded = ["mode", "forceInline"];
import * as React from 'react';
import { Component, Fragment } from 'react';
import CustomIcon from '../../components/custom-icon';
import Sortable from './sortable';
import './style.less';
var _AliLowCodeEngine = AliLowCodeEngine,
  common = _AliLowCodeEngine.common;
var editorCabin = common.editorCabin,
  skeletonCabin = common.skeletonCabin;
var Title = editorCabin.Title;
var createSettingFieldView = skeletonCabin.createSettingFieldView,
  PopupContext = skeletonCabin.PopupContext;
/**
 * onItemChange 用于 ArraySetter 的单个 index 下的数据发生变化，
 * 因此 target.path 的数据格式必定为 [propName1, propName2, arrayIndex, key?]。
 *
 * @param target
 * @param value
 */
function onItemChange(target, index, item, props) {
  var targetPath = target === null || target === void 0 ? void 0 : target.path;
  if (!targetPath || targetPath.length < 2) {
    console.warn("[ArraySetter] onItemChange \u63A5\u6536\u7684 target.path <" + (targetPath || 'undefined') + "> \u683C\u5F0F\u975E\u6CD5\u9700\u4E3A [propName, arrayIndex, key?]");
    return;
  }
  var field = props.field;
  var path = field.path;
  if (path[0] !== targetPath[0]) {
    console.warn("[ArraySetter] field.path[0] !== target.path[0] <" + path[0] + " !== " + targetPath[0] + ">");
    return;
  }
  try {
    var fieldValue = field.getValue();
    fieldValue[index] = item.getValue();
    field === null || field === void 0 ? void 0 : field.setValue(fieldValue);
  } catch (e) {
    console.warn('[ArraySetter] extraProps.setValue failed :', e);
  }
}
;
export var ListSetter = /*#__PURE__*/function (_Component) {
  function ListSetter(props) {
    var _this;
    _this = _Component.call(this, props) || this;
    _this.state = {
      items: []
    };
    _this.scrollToLast = false;
    return _this;
  }
  _inheritsLoose(ListSetter, _Component);
  ListSetter.getDerivedStateFromProps = function getDerivedStateFromProps(props, state) {
    var items = [];
    var value = props.value,
      field = props.field;
    var valueLength = value && Array.isArray(value) ? value.length : 0;
    var _loop = function _loop(i) {
      var item = state.items[i];
      if (!item) {
        item = field.createField({
          name: i.toString(),
          setter: props.itemSetter,
          forceInline: 1,
          type: 'field',
          extraProps: {
            defaultValue: value[i],
            setValue: function setValue(target) {
              onItemChange(target, i, item, props);
            }
          }
        });
        item.setValue(value[i]);
      }
      items.push(item);
    };
    for (var i = 0; i < valueLength; i++) {
      _loop(i);
    }
    return {
      items: items
    };
  };
  var _proto = ListSetter.prototype;
  _proto.onSort = function onSort(sortedIds) {
    var _this$props = this.props,
      onChange = _this$props.onChange,
      oldValues = _this$props.value;
    var items = this.state.items;
    var values = [];
    var newItems = [];
    sortedIds.map(function (id, index) {
      var itemIndex = items.findIndex(function (item) {
        return item.id === id;
      });
      values[index] = oldValues[itemIndex];
      newItems[index] = items[itemIndex];
      return id;
    });
    onChange === null || onChange === void 0 ? void 0 : onChange(values);
  };
  _proto.onAdd = function onAdd(newValue) {
    var _this$props2 = this.props,
      itemSetter = _this$props2.itemSetter,
      field = _this$props2.field,
      onChange = _this$props2.onChange,
      _this$props2$value = _this$props2.value,
      value = _this$props2$value === void 0 ? [] : _this$props2$value;
    var values = value || [];
    var initialValue = itemSetter === null || itemSetter === void 0 ? void 0 : itemSetter.initialValue;
    var defaultValue = newValue ? newValue : typeof initialValue === 'function' ? initialValue(field) : initialValue;
    values.push(defaultValue);
    this.scrollToLast = true;
    onChange === null || onChange === void 0 ? void 0 : onChange(values);
  };
  _proto.onRemove = function onRemove(removed) {
    var _this$props3 = this.props,
      onChange = _this$props3.onChange,
      value = _this$props3.value;
    var items = this.state.items;
    var values = value || [];
    var i = items.indexOf(removed);
    items.splice(i, 1);
    values.splice(i, 1);
    var l = items.length;
    while (i < l) {
      items[i].setKey(i);
      i++;
    }
    removed.remove();
    var pureValues = values.map(function (item) {
      return typeof item === 'object' ? Object.assign({}, item) : item;
    });
    onChange === null || onChange === void 0 ? void 0 : onChange(pureValues);
  };
  _proto.componentWillUnmount = function componentWillUnmount() {
    this.state.items.forEach(function (field) {
      field.purge();
    });
  };
  _proto.render = function render() {
    var _this2 = this;
    var _this$props4 = this.props,
      hideDescription = _this$props4.hideDescription,
      _this$props4$extraPro = _this$props4.extraProps,
      extraProps = _this$props4$extraPro === void 0 ? {} : _this$props4$extraPro;
    var renderFooter = extraProps.renderFooter;
    var columns = null;
    var items = this.state.items;
    var scrollToLast = this.scrollToLast;
    this.scrollToLast = false;
    if (this.props.columns) {
      columns = this.props.columns.map(function (column) {
        return /*#__PURE__*/React.createElement(Title, {
          key: column.name,
          title: column.title || column.name
        });
      });
    }
    var lastIndex = items.length - 1;
    var content = items.length > 0 ? /*#__PURE__*/React.createElement("div", {
      className: "lc-setter-list-scroll-body"
    }, /*#__PURE__*/React.createElement(Sortable, {
      itemClassName: "lc-setter-list-card",
      onSort: this.onSort.bind(this)
    }, items.map(function (field, index) {
      return /*#__PURE__*/React.createElement(ArrayItem, {
        key: field.id,
        scrollIntoView: scrollToLast && index === lastIndex,
        field: field,
        onRemove: _this2.onRemove.bind(_this2, field)
      });
    }))) : /*#__PURE__*/React.createElement("div", {
      className: "lc-setter-list-notice"
    }, this.props.multiValue ? /*#__PURE__*/React.createElement(_Message, {
      type: "warning"
    }, "\u5F53\u524D\u9009\u62E9\u4E86\u591A\u4E2A\u8282\u70B9\uFF0C\u4E14\u503C\u4E0D\u4E00\u81F4\uFF0C\u4FEE\u6539\u4F1A\u8986\u76D6\u6240\u6709\u503C") : /*#__PURE__*/React.createElement(_Message, {
      type: "notice",
      size: "medium",
      shape: "inline"
    }, "\u6682\u65F6\u8FD8\u6CA1\u6709\u6DFB\u52A0\u5185\u5BB9"));
    return /*#__PURE__*/React.createElement("div", {
      className: "lc-setter-list lc-block-setter"
    }, !hideDescription && columns && items.length > 0 ? /*#__PURE__*/React.createElement("div", {
      className: "lc-setter-list-columns"
    }, columns) : null, content, /*#__PURE__*/React.createElement("div", {
      className: "lc-setter-list-add"
    }, !renderFooter ? /*#__PURE__*/React.createElement(_Button, {
      text: true,
      type: "primary",
      onClick: function onClick() {
        _this2.onAdd();
      }
    }, /*#__PURE__*/React.createElement("span", null, "\u6DFB\u52A0\u4E00\u9879 +")) : renderFooter(_extends({}, this.props, {
      onAdd: this.onAdd.bind(this)
    }))));
  };
  return ListSetter;
}(Component);
var ArrayItem = /*#__PURE__*/function (_Component2) {
  function ArrayItem() {
    var _this3;
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    _this3 = _Component2.call.apply(_Component2, [this].concat(args)) || this;
    _this3.shell = void 0;
    return _this3;
  }
  _inheritsLoose(ArrayItem, _Component2);
  var _proto2 = ArrayItem.prototype;
  _proto2.componentDidMount = function componentDidMount() {
    if (this.props.scrollIntoView && this.shell) {
      this.shell.parentElement.scrollIntoView({
        behavior: 'smooth',
        block: 'nearest'
      });
    }
  };
  _proto2.render = function render() {
    var _this4 = this;
    var _this$props5 = this.props,
      onRemove = _this$props5.onRemove,
      field = _this$props5.field;
    return /*#__PURE__*/React.createElement("div", {
      className: "lc-listitem",
      ref: function ref(_ref) {
        _this4.shell = _ref;
      }
    }, /*#__PURE__*/React.createElement("div", {
      className: "lc-listitem-body"
    }, createSettingFieldView(field, field.parent)), /*#__PURE__*/React.createElement("div", {
      className: "lc-listitem-actions"
    }, /*#__PURE__*/React.createElement(_Button, {
      size: "small",
      ghost: "light",
      onClick: onRemove,
      className: "lc-listitem-action"
    }, /*#__PURE__*/React.createElement(CustomIcon, {
      type: "icon-ic_delete"
    })), /*#__PURE__*/React.createElement(_Button, {
      draggable: true,
      size: "small",
      style: {
        cursor: "move"
      },
      ghost: "light",
      className: "lc-listitem-handler"
    }, /*#__PURE__*/React.createElement(CustomIcon, {
      type: "icon-ic_drag"
    }))));
  };
  return ArrayItem;
}(Component);
var TableSetter = /*#__PURE__*/function (_ListSetter2) {
  function TableSetter() {
    return _ListSetter2.apply(this, arguments) || this;
  }
  _inheritsLoose(TableSetter, _ListSetter2);
  return TableSetter;
}(ListSetter);
var ArraySetter = /*#__PURE__*/function (_Component3) {
  function ArraySetter() {
    var _this5;
    for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
      args[_key2] = arguments[_key2];
    }
    _this5 = _Component3.call.apply(_Component3, [this].concat(args)) || this;
    _this5.pipe = void 0;
    return _this5;
  }
  _inheritsLoose(ArraySetter, _Component3);
  var _proto3 = ArraySetter.prototype;
  _proto3.render = function render() {
    var _this6 = this;
    var _this$props6 = this.props,
      mode = _this$props6.mode,
      forceInline = _this$props6.forceInline,
      props = _objectWithoutPropertiesLoose(_this$props6, _excluded);
    var field = props.field,
      itemSetter = props.itemSetter;
    var columns;
    if ((itemSetter === null || itemSetter === void 0 ? void 0 : itemSetter.componentName) === 'ObjectSetter') {
      var _props, _props$config;
      var items = (_props = itemSetter.props) === null || _props === void 0 ? void 0 : (_props$config = _props.config) === null || _props$config === void 0 ? void 0 : _props$config.items;
      if (items && Array.isArray(items)) {
        columns = items.filter(function (item) {
          var _item$setter;
          return item.isRequired || item.important || ((_item$setter = item.setter) === null || _item$setter === void 0 ? void 0 : _item$setter.isRequired);
        });
        if (columns.length > 4) {
          columns = columns.slice(0, 4);
        }
      }
    }
    if (mode === 'popup' || forceInline) {
      var title = /*#__PURE__*/React.createElement(Fragment, null, "\u7F16\u8F91\uFF1A", /*#__PURE__*/React.createElement(Title, {
        title: field.title
      }));
      if (!this.pipe) {
        var width = 360;
        if (columns) {
          if (columns.length === 3) {
            width = 480;
          } else if (columns.length > 3) {
            width = 600;
          }
        }
        this.pipe = this.context.create({
          width: width
        });
      }
      this.pipe.send( /*#__PURE__*/React.createElement(TableSetter, _extends({
        key: field.id
      }, props, {
        columns: columns
      })), title);
      return /*#__PURE__*/React.createElement(_Button, {
        type: forceInline ? 'normal' : 'primary',
        onClick: function onClick(e) {
          _this6.pipe.show(e.target, field.id);
        }
      }, /*#__PURE__*/React.createElement(CustomIcon, {
        type: "icon-bianji",
        size: "small"
      }), forceInline ? title : '编辑数组');
    } else {
      var _columns;
      return /*#__PURE__*/React.createElement(ListSetter, _extends({}, props, {
        columns: (_columns = columns) === null || _columns === void 0 ? void 0 : _columns.slice(0, 4)
      }));
    }
  };
  return ArraySetter;
}(Component);
ArraySetter.contextType = PopupContext;
export { ArraySetter as default };