function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
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 _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 _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure 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 _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 _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function _extends() { _extends = Object.assign ? Object.assign.bind() : 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 ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
import React, { useState, useEffect, memo, forwardRef } from 'react';
import { Button, Card, Dropdown, Flex, Form, Input, Modal, Radio } from 'antd';
import { MoreOutlined, SwapOutlined } from '@ant-design/icons';
import { DndContext, closestCenter, useSensor, useSensors, PointerSensor } from '@dnd-kit/core';
import { useSortable, SortableContext, verticalListSortingStrategy } from '@dnd-kit/sortable';
import { uuid } from "../../utils/index";
var commonStyle = {
  cursor: 'move',
  transition: 'transform 0.3s ease'
};

// 按钮组件
var DraggableButton = function DraggableButton(_ref) {
  var buttonItem = _ref.buttonItem,
    buttonList = _ref.buttonList,
    onEdit = _ref.onEdit;
  var id = buttonItem.id,
    _buttonItem$isMore = buttonItem.isMore,
    isMore = _buttonItem$isMore === void 0 ? false : _buttonItem$isMore,
    _buttonItem$children = buttonItem.children,
    children = _buttonItem$children === void 0 ? '' : _buttonItem$children,
    _buttonItem$buttonPro = buttonItem.buttonProps,
    buttonProps = _buttonItem$buttonPro === void 0 ? {} : _buttonItem$buttonPro;
  var _useSortable = useSortable({
      id: id
    }),
    listeners = _useSortable.listeners,
    setNodeRef = _useSortable.setNodeRef,
    transform = _useSortable.transform,
    transition = _useSortable.transition,
    isDragging = _useSortable.isDragging;
  var style = transform ? _objectSpread(_objectSpread({}, commonStyle), {}, {
    transform: "translate3d(".concat(transform.x, "px, ").concat(transform.y, "px, 0)"),
    transition: isDragging ? 'unset' : transition
  }) : commonStyle;

  // 防止拖拽时阻止点击事件
  var handleClick = function handleClick(e) {
    if (isDragging) {
      // 防止拖拽时触发点击事件
      e.stopPropagation();
      e.preventDefault();
      return;
    }

    // 触发编辑按钮
  };
  var menu = {
    items: buttonList.filter(function (item) {
      return !item.isMore;
    }).map(function (item) {
      return {
        key: item.id,
        label: item.children
      };
    }),
    onClick: function onClick(e) {
      var item = buttonList.find(function (item) {
        return item.id === e.key;
      });
      onEdit(item);
    }
  };
  return /*#__PURE__*/React.createElement("div", _extends({
    ref: setNodeRef
  }, listeners, {
    style: style
  }), isMore ? /*#__PURE__*/React.createElement(Dropdown, {
    menu: menu
  }, /*#__PURE__*/React.createElement(Button, {
    onClick: handleClick
  }, /*#__PURE__*/React.createElement(MoreOutlined, null))) : /*#__PURE__*/React.createElement(Button, _extends({
    style: style
  }, buttonProps, {
    onClick: function onClick() {
      return onEdit(buttonItem);
    }
  }), children));
};

// 主组件
var ButtonGroupEdit = /*#__PURE__*/forwardRef(function (props, ref) {
  var _useState = useState(props.buttonList),
    _useState2 = _slicedToArray(_useState, 2),
    buttonList = _useState2[0],
    setButtonList = _useState2[1]; // 左侧按钮列表
  var _useState3 = useState(props.buttonGroupList),
    _useState4 = _slicedToArray(_useState3, 2),
    buttonGroupList = _useState4[0],
    setButtonGroupList = _useState4[1]; // 右侧二维按钮组

  var sensors = useSensors(useSensor(PointerSensor, {
    activationConstraint: {
      distance: 5
    }
  }));
  var _useState5 = useState(false),
    _useState6 = _slicedToArray(_useState5, 2),
    isModalVisible = _useState6[0],
    setIsModalVisible = _useState6[1]; // Modal 控制显示状态
  var _useState7 = useState(null),
    _useState8 = _slicedToArray(_useState7, 2),
    currentButton = _useState8[0],
    setCurrentButton = _useState8[1]; // 当前要编辑按钮

  var _Form$useForm = Form.useForm(),
    _Form$useForm2 = _slicedToArray(_Form$useForm, 1),
    form = _Form$useForm2[0];
  useEffect(function () {
    setButtonList(props.buttonList);
    if (props.buttonList.length > 0) {
      // 如果按钮列表还有按钮  就在最后增加一个更多的按钮选项
      setButtonList([].concat(_toConsumableArray(buttonList), [{
        id: uuid(),
        isMore: true
      }]));
    } else {
      setButtonGroupList(props.buttonGroupList);
    }
  }, [props.buttonList, props.buttonGroupList]);

  // 增加一行按钮组
  var addRow = function addRow() {
    var newButton = {
      id: uuid(),
      children: "\u6309\u94AE".concat(uuid()),
      // 默认按钮文本
      buttonProps: {
        type: 'default'
      }
    };
    setButtonGroupList(function (prev) {
      return [].concat(_toConsumableArray(prev), [[newButton]]);
    });
  };
  useEffect(function () {
    if (currentButton) {
      var _currentButton$button;
      form.setFieldsValue({
        children: currentButton.children,
        type: (_currentButton$button = currentButton.buttonProps) === null || _currentButton$button === void 0 ? void 0 : _currentButton$button.type
      }); // 动态设置按钮名称
    }
  }, [currentButton, form]); // 每次 currentButton 改变时，更新表单值

  // 打开编辑Modal
  var handleEditButton = function handleEditButton(button) {
    setCurrentButton(button); // 设置当前编辑按钮
    setIsModalVisible(true); // 显示 Modal
  };

  // 关闭 Modal
  var handleCancel = function handleCancel() {
    setIsModalVisible(false);
    setCurrentButton(null); // 清空当前编辑的按钮
  };

  // 保存按钮修改
  var handleSave = function handleSave(values) {
    if (!currentButton) return;
    var updatedButton = _objectSpread(_objectSpread({}, currentButton), {}, {
      children: values.children,
      buttonProps: values
    });
    // 更新 buttonList
    setButtonList(function (prevList) {
      return prevList.map(function (item) {
        return item.id === currentButton.id ? _objectSpread(_objectSpread({}, item), updatedButton) : item;
      });
    });

    // 更新 buttonGroupList
    setButtonGroupList(function (prevGroupList) {
      return prevGroupList.map(function (row) {
        return row.map(function (item) {
          return item.id === currentButton.id ? _objectSpread(_objectSpread({}, item), updatedButton) : item;
        });
      });
    });
    handleCancel(); // 关闭 Modal
  };

  // 拖拽结束的处理函数
  var onDragEnd = function onDragEnd(event) {
    var _active$data, _over$data;
    var active = event.active,
      over = event.over;
    if (!over) return;
    var activeId = active.id;
    var overId = over.id;
    var activeContainerId = '';
    var overContainerId = '';
    if (active !== null && active !== void 0 && (_active$data = active.data) !== null && _active$data !== void 0 && _active$data.current) {
      activeContainerId = active.data.current.sortable.containerId;
    }
    if (over !== null && over !== void 0 && (_over$data = over.data) !== null && _over$data !== void 0 && _over$data.current) {
      overContainerId = over.data.current.sortable.containerId;
    }
    try {
      // 从 buttonList 拖拽到 buttonGroupList
      if (activeContainerId === 'list1' && overContainerId === 'list2') {
        var activeIndex = buttonList.findIndex(function (item) {
          return item.id === activeId;
        });
        if (activeIndex === -1) return;
        var movedItem = _objectSpread({}, buttonList[activeIndex]);
        // 找到目标位置
        var overRowIndex = buttonGroupList.findIndex(function (row) {
          return row.some(function (item) {
            return item.id === overId;
          });
        });
        if (overRowIndex === -1) return;
        var updatedGroupList = _toConsumableArray(buttonGroupList);
        updatedGroupList[overRowIndex].push(movedItem); // 将按钮添加到目标行
        // 更新状态
        var updatedButtonList = buttonList.filter(function (item) {
          return item.id !== activeId;
        }); // 删除拖拽的元素
        setButtonGroupList(updatedGroupList);
        setButtonList(updatedButtonList);
      }
      // 从 buttonGroupList 拖拽到 buttonList
      if (activeContainerId === 'list2' && overContainerId === 'list1') {
        var _buttonGroupList$_ove;
        var _overRowIndex = buttonGroupList.findIndex(function (row) {
          return row.some(function (item) {
            return item.id === overId;
          });
        });
        if (_overRowIndex === -1) return;
        var overColIndex = (_buttonGroupList$_ove = buttonGroupList[_overRowIndex]) === null || _buttonGroupList$_ove === void 0 ? void 0 : _buttonGroupList$_ove.findIndex(function (item) {
          return item.id === overId;
        });
        if (overColIndex === -1) return;
        var _buttonGroupList$_ove2 = buttonGroupList[_overRowIndex].splice(overColIndex, 1),
          _buttonGroupList$_ove3 = _slicedToArray(_buttonGroupList$_ove2, 1),
          _movedItem = _buttonGroupList$_ove3[0];
        setButtonGroupList(_toConsumableArray(buttonGroupList));
        setButtonList(function (prev) {
          return [].concat(_toConsumableArray(prev), [_movedItem]);
        });
      }

      // 同一个列表内的拖拽排序：在 buttonList 内拖拽排序
      if (activeContainerId === 'list1' && overContainerId === 'list1') {
        var _activeIndex = buttonList.findIndex(function (item) {
          return item.id === activeId;
        });
        var overIndex = buttonList.findIndex(function (item) {
          return item.id === overId;
        });
        if (_activeIndex === -1 || overIndex === -1) return;
        var updatedList = _toConsumableArray(buttonList);
        var _updatedList$splice = updatedList.splice(_activeIndex, 1),
          _updatedList$splice2 = _slicedToArray(_updatedList$splice, 1),
          _movedItem2 = _updatedList$splice2[0];
        updatedList.splice(overIndex, 0, _movedItem2);
        setButtonList(updatedList);
      }

      // 同一个列表内的拖拽排序：在 buttonGroupList 内拖拽排序
      if (activeContainerId === 'list2' && overContainerId === 'list2') {
        var _buttonGroupList$acti, _buttonGroupList$_ove4;
        var activeRowIndex = buttonGroupList.findIndex(function (row) {
          return row.some(function (item) {
            return item.id === activeId;
          });
        });
        var activeColIndex = (_buttonGroupList$acti = buttonGroupList[activeRowIndex]) === null || _buttonGroupList$acti === void 0 ? void 0 : _buttonGroupList$acti.findIndex(function (item) {
          return item.id === activeId;
        });
        var _overRowIndex2 = buttonGroupList.findIndex(function (row) {
          return row.some(function (item) {
            return item.id === overId;
          });
        });
        var _overColIndex = (_buttonGroupList$_ove4 = buttonGroupList[_overRowIndex2]) === null || _buttonGroupList$_ove4 === void 0 ? void 0 : _buttonGroupList$_ove4.findIndex(function (item) {
          return item.id === overId;
        });
        if (activeRowIndex === -1 || _overRowIndex2 === -1 || activeColIndex === -1 || _overColIndex === -1) return;
        var _updatedGroupList = _toConsumableArray(buttonGroupList);
        var _updatedGroupList$act = _updatedGroupList[activeRowIndex].splice(activeColIndex, 1),
          _updatedGroupList$act2 = _slicedToArray(_updatedGroupList$act, 1),
          _movedItem3 = _updatedGroupList$act2[0];
        _updatedGroupList[_overRowIndex2].splice(_overColIndex, 0, _movedItem3);
        setButtonGroupList(_updatedGroupList);
      }
    } catch (error) {
      console.error('拖拽结束时出错:', error);
    }
  };
  return /*#__PURE__*/React.createElement(Flex, {
    wrap: true,
    justify: "space-between",
    align: "center",
    gap: "middle"
  }, /*#__PURE__*/React.createElement(DndContext, {
    onDragEnd: onDragEnd,
    sensors: sensors,
    collisionDetection: closestCenter
  }, /*#__PURE__*/React.createElement(Card, {
    title: "\u6309\u94AE\u5217\u8868"
  }, /*#__PURE__*/React.createElement(SortableContext, {
    id: "list1",
    items: buttonList.map(function (item) {
      return item.id;
    }),
    strategy: verticalListSortingStrategy
  }, /*#__PURE__*/React.createElement(Flex, {
    gap: "middle",
    vertical: true
  }, buttonList.map(function (item) {
    return /*#__PURE__*/React.createElement(DraggableButton, {
      key: item.id,
      buttonItem: item,
      buttonList: buttonList,
      onEdit: handleEditButton
    });
  })))), /*#__PURE__*/React.createElement(Button, {
    type: "primary",
    icon: /*#__PURE__*/React.createElement(SwapOutlined, null)
  }), /*#__PURE__*/React.createElement(Card, {
    title: "\u8C03\u6574\u5217\u8868",
    style: {
      flex: 1
    }
  }, /*#__PURE__*/React.createElement(SortableContext, {
    id: "list2",
    items: buttonGroupList.flat().map(function (item) {
      return item.id;
    }),
    strategy: verticalListSortingStrategy
  }, /*#__PURE__*/React.createElement(Flex, {
    gap: "middle",
    vertical: true
  }, buttonGroupList.map(function (subItem, rowIndex) {
    return /*#__PURE__*/React.createElement(Card, null, /*#__PURE__*/React.createElement(Flex, {
      key: rowIndex,
      gap: "middle"
    }, subItem.map(function (item) {
      return /*#__PURE__*/React.createElement(DraggableButton, {
        key: item.id,
        buttonItem: item,
        buttonList: buttonList,
        onEdit: handleEditButton
      });
    })));
  }))))), /*#__PURE__*/React.createElement(Button, {
    type: "primary",
    onClick: addRow
  }, "\u65B0\u589E\u4E00\u884C"), /*#__PURE__*/React.createElement(Modal, {
    title: "\u7F16\u8F91\u6309\u94AE\u5C5E\u6027",
    open: isModalVisible,
    onCancel: handleCancel,
    footer: null
  }, currentButton && /*#__PURE__*/React.createElement(Form, {
    form: form,
    onFinish: handleSave
  }, /*#__PURE__*/React.createElement(Form.Item, {
    name: "children",
    label: "\u6309\u94AE\u540D\u79F0",
    rules: [{
      required: true,
      message: '请输入按钮名称'
    }]
  }, /*#__PURE__*/React.createElement(Input, {
    placeholder: "\u8BF7\u8F93\u5165\u6309\u94AE\u540D\u79F0"
  })), /*#__PURE__*/React.createElement(Form.Item, {
    name: "type",
    label: "\u6309\u94AE\u7C7B\u578B",
    rules: [{
      required: true,
      message: '请选择按钮类型'
    }]
  }, /*#__PURE__*/React.createElement(Radio.Group, null, /*#__PURE__*/React.createElement(Radio.Button, {
    value: "primary"
  }, "primary"), /*#__PURE__*/React.createElement(Radio.Button, {
    value: "dashed"
  }, "dashed"), /*#__PURE__*/React.createElement(Radio.Button, {
    value: "link"
  }, "link"), /*#__PURE__*/React.createElement(Radio.Button, {
    value: "text"
  }, "text"), /*#__PURE__*/React.createElement(Radio.Button, {
    value: "default"
  }, "default"))), /*#__PURE__*/React.createElement(Form.Item, null, /*#__PURE__*/React.createElement(Button, {
    type: "primary",
    htmlType: "submit"
  }, "\u4FDD\u5B58")))));
});
export default /*#__PURE__*/memo(ButtonGroupEdit);