function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
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 _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 ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
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(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
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(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
import React, { useEffect, useMemo, useState } from 'react';
import { useSortable } from '@dnd-kit/sortable';
import { DndContext } from '@dnd-kit/core';
import { Tooltip } from 'antd';
import DotsSix from '@pisell/icon/es/DotsSix';
import { getText } from "../../../locales";
import { CSS } from '@dnd-kit/utilities';
import { EyeOutlined, EyeInvisibleOutlined, WarningOutlined } from '@ant-design/icons';
import { SortableContext, verticalListSortingStrategy, arrayMove } from '@dnd-kit/sortable';
import { restrictToVerticalAxis, restrictToParentElement } from '@dnd-kit/modifiers';
import classNames from 'classnames';
import "./index.less";
var prefix = 'pisell-lowcode';
var TreeItem = function TreeItem(props) {
  var id = props.id,
    item = props.item,
    depth = props.depth,
    sensors = props.sensors,
    childrenProps = props.childrenProps,
    lists = props.lists,
    expandedKeys = props.expandedKeys,
    onChange = props.onChange;
  var _useSortable = useSortable({
      id: id
    }),
    attributes = _useSortable.attributes,
    listeners = _useSortable.listeners,
    setNodeRef = _useSortable.setNodeRef,
    transform = _useSortable.transform,
    transition = _useSortable.transition,
    isDragging = _useSortable.isDragging;
  var _useState = useState(window.innerWidth < 600),
    _useState2 = _slicedToArray(_useState, 2),
    isMobile = _useState2[0],
    setIsMobile = _useState2[1];
  var style = {
    transform: CSS.Transform.toString(transform && _objectSpread(_objectSpread({}, transform), {}, {
      scaleY: 1
    })),
    transition: transition
  };
  var rowKey = useMemo(function () {
    return (childrenProps === null || childrenProps === void 0 ? void 0 : childrenProps.rowKey) || 'id';
  }, [childrenProps === null || childrenProps === void 0 ? void 0 : childrenProps.rowKey]);
  var handleDragEnd = function handleDragEnd(event) {
    var active = event.active,
      over = event.over;
    if (!over || !active || !lists.length) return;
    try {
      var _active$id, _over$id;
      var _active$id$split = active === null || active === void 0 ? void 0 : (_active$id = active.id) === null || _active$id === void 0 ? void 0 : _active$id.split('-'),
        _active$id$split2 = _slicedToArray(_active$id$split, 2),
        activeParentId = _active$id$split2[0],
        activeId = _active$id$split2[1];
      var _over$id$split = over === null || over === void 0 ? void 0 : (_over$id = over.id) === null || _over$id === void 0 ? void 0 : _over$id.split('-'),
        _over$id$split2 = _slicedToArray(_over$id$split, 2),
        overParentId = _over$id$split2[0],
        overId = _over$id$split2[1];
      var parentIndex = lists.findIndex(function (item) {
        return item[rowKey] == activeParentId;
      });
      if (activeId !== overId && activeParentId === overParentId && parentIndex !== -1) {
        var activeIndex = item.children.findIndex(function (item) {
          return item[rowKey] == activeId;
        });
        var overIndex = item.children.findIndex(function (item) {
          return item[rowKey] == overId;
        });

        // 移动数据
        if (activeIndex !== -1 && overIndex !== -1) {
          var _lists$parentIndex;
          var newChildren = arrayMove((_lists$parentIndex = lists[parentIndex]) === null || _lists$parentIndex === void 0 ? void 0 : _lists$parentIndex.children, activeIndex, overIndex);
          var _lists = [].concat(_toConsumableArray(lists.slice(0, parentIndex)), [_objectSpread(_objectSpread({}, lists === null || lists === void 0 ? void 0 : lists[parentIndex]), {}, {
            children: newChildren
          })], _toConsumableArray(lists.slice(parentIndex + 1)));
          onChange && onChange(_toConsumableArray(_lists));
        }
      }
    } catch (error) {}
  };

  /**
   * @title: 点击切换眼睛
   * @description:
   * @param {any} e
   * @return {*}
   * @Author: WangHan
   * @Date: 2024-07-19 22:43
   */
  var handleShow = function handleShow(e) {
    e.stopPropagation(); // 阻止事件冒泡
    e.preventDefault(); // 阻止默认行为
    var index = lists === null || lists === void 0 ? void 0 : lists.findIndex(function (node) {
      return node[rowKey] === item[rowKey];
    });
    if (index !== -1) {
      lists[index].show = !lists[index].show;
      onChange === null || onChange === void 0 ? void 0 : onChange(_toConsumableArray(lists));
    }
  };
  var onSelect = function onSelect() {
    var _item$children;
    if (depth === 0 && (_item$children = item.children) !== null && _item$children !== void 0 && _item$children.length) {
      var key = item[rowKey];
      (childrenProps === null || childrenProps === void 0 ? void 0 : childrenProps.onHiddenChange) && (childrenProps === null || childrenProps === void 0 ? void 0 : childrenProps.onHiddenChange(key));
    }
  };
  var renderChildren = useMemo(function () {
    var _item$children2;
    var showChildren = (item === null || item === void 0 ? void 0 : (_item$children2 = item.children) === null || _item$children2 === void 0 ? void 0 : _item$children2.length) > 0 && (expandedKeys === null || expandedKeys === void 0 ? void 0 : expandedKeys.includes(item[rowKey]));
    var _isAvailableTab = (childrenProps === null || childrenProps === void 0 ? void 0 : childrenProps.tabKey) === 'available';
    return showChildren && /*#__PURE__*/React.createElement(SortableContext, {
      items: item.children.map(function (child) {
        return "".concat(item[rowKey], "-").concat(child[rowKey]);
      }),
      strategy: verticalListSortingStrategy
    }, item.children.map(function (child) {
      return _isAvailableTab && child !== null && child !== void 0 && child.is_available || !_isAvailableTab ? /*#__PURE__*/React.createElement(TreeItem, {
        id: "".concat(item[rowKey], "-").concat(child[rowKey]),
        key: "".concat(item[rowKey], "-").concat(child[rowKey]),
        item: child,
        lists: lists,
        depth: depth + 1,
        childrenProps: childrenProps
      }) : null;
    }));
  }, [item.children, expandedKeys, rowKey, lists, childrenProps === null || childrenProps === void 0 ? void 0 : childrenProps.tabKey, isDragging]);

  // 右侧图标
  var rightIcon = useMemo(function () {
    // 右侧子级图标
    var hiddenRightIcon = childrenProps === null || childrenProps === void 0 ? void 0 : childrenProps.hiddenRightIcon;
    return !hiddenRightIcon ? /*#__PURE__*/React.createElement("div", {
      className: classNames("".concat(prefix, "-drag-sort-tree-icon")),
      onClick: handleShow
    }, item.show ? /*#__PURE__*/React.createElement(EyeOutlined, null) : /*#__PURE__*/React.createElement(EyeInvisibleOutlined, null)) : null;
  }, [childrenProps === null || childrenProps === void 0 ? void 0 : childrenProps.hiddenRightIcon, item === null || item === void 0 ? void 0 : item.show, lists]);

  // 警告图标
  var warningIcon = useMemo(function () {
    var hiddenWarningIcon = childrenProps === null || childrenProps === void 0 ? void 0 : childrenProps.hiddenWarningIcon;
    return !hiddenWarningIcon && !(item !== null && item !== void 0 && item.is_available) ? /*#__PURE__*/React.createElement("div", {
      className: classNames("".concat(prefix, "-drag-sort-tree-item-icon"))
    }, /*#__PURE__*/React.createElement(Tooltip, {
      title: getText('drag-sort-tree-unavailable-today-tip'),
      color: "#ffffff",
      overlayInnerStyle: {
        color: '#344054'
      }
    }, /*#__PURE__*/React.createElement(WarningOutlined, {
      style: {
        color: '#FF2020'
      }
    }))) : null;
  }, [childrenProps === null || childrenProps === void 0 ? void 0 : childrenProps.hiddenWarningIcon, item === null || item === void 0 ? void 0 : item.is_available]);
  var handleWindowResize = function handleWindowResize() {
    // 获取当前窗口的宽度
    var windowWidth = window.innerWidth;
    setIsMobile(windowWidth < 600);
  };
  useEffect(function () {
    window.addEventListener('resize', handleWindowResize);
    return function () {
      window.removeEventListener('resize', handleWindowResize);
    };
  }, []);
  return /*#__PURE__*/React.createElement(DndContext, {
    sensors: sensors,
    modifiers: [restrictToVerticalAxis, restrictToParentElement],
    onDragEnd: handleDragEnd
  }, /*#__PURE__*/React.createElement("div", _extends({
    ref: setNodeRef,
    style: style
  }, attributes, !isMobile ? listeners : {}), /*#__PURE__*/React.createElement("div", {
    className: classNames("".concat(prefix, "-drag-sort-tree"), childrenProps === null || childrenProps === void 0 ? void 0 : childrenProps.className, isMobile ? "".concat(prefix, "-drag-sort-phone-tree") : ''),
    style: {
      paddingLeft: !depth ? '10px' : "".concat(depth * 40, "px"),
      cursor: isDragging ? 'grabbing' : 'grab'
    },
    onClick: onSelect
  }, /*#__PURE__*/React.createElement("div", {
    className: classNames("".concat(prefix, "-drag-sort-tree-item"))
  }, !(childrenProps !== null && childrenProps !== void 0 && childrenProps.hiddenDraggableIcon) ? /*#__PURE__*/React.createElement(DotsSix, _extends({}, isMobile ? listeners : {}, {
    className: classNames("".concat(prefix, "-drag-sort-tree-item-dot-icon")),
    style: {
      left: isMobile ? !depth ? '-14px' : '12px' : 0
    }
  })) : null, /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefix, "-drag-sort-tree-title")
  }, (childrenProps === null || childrenProps === void 0 ? void 0 : childrenProps.titleRender) || (item === null || item === void 0 ? void 0 : item.title))), !depth ? rightIcon : warningIcon), renderChildren));
};
export default TreeItem;