var _excluded = ["safeArea", "portal", "draggable", "gap", "list", "onChange", "onDragEnd"];
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 _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
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 _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
import React, { useImperativeHandle, useRef, forwardRef } from 'react';
import { createPortal } from 'react-dom';
import getPosition from "./AssistiveTouch/getPosition";
import snapToEdge from "./AssistiveTouch/snapToEdge";
import getItemById from "./getItemById";

// 内库使用-start
import DOMUtil from "./../../utils/DOMUtil";
import SafeArea from "./../SafeArea";
import ActionSheet from "./../ActionSheet";
// 内库使用-end

/* 测试使用-start
import { DOMUtil, SafeArea, ActionSheet } from 'seedsui-react'
测试使用-start */

// 悬浮按钮
function FloatButton(_ref, ref) {
  var _ref$safeArea = _ref.safeArea,
    safeArea = _ref$safeArea === void 0 ? true : _ref$safeArea,
    portal = _ref.portal,
    draggable = _ref.draggable,
    _ref$gap = _ref.gap,
    gap = _ref$gap === void 0 ? {
      top: 8,
      right: 8,
      bottom: 8,
      left: 8
    } : _ref$gap,
    list = _ref.list,
    onChange = _ref.onChange,
    onDragEnd = _ref.onDragEnd,
    props = _objectWithoutProperties(_ref, _excluded);
  var rootRef = useRef(null);
  // 拖动信息
  var touchesRef = useRef({
    isDragging: false,
    startX: 0,
    startY: 0,
    currentLeft: 0,
    currentTop: 0
  });

  // Expose
  useImperativeHandle(ref, function () {
    return {
      rootDOM: rootRef.current,
      getRootDOM: function getRootDOM() {
        return rootRef.current;
      }
    };
  });

  // 获取图标
  function getIconNode(item) {
    if (typeof (item === null || item === void 0 ? void 0 : item.icon) === 'function') {
      return item.icon({
        item: item
      }) || null;
    }
    if ( /*#__PURE__*/React.isValidElement(item === null || item === void 0 ? void 0 : item.icon)) {
      return item.icon;
    }
    if (typeof (item === null || item === void 0 ? void 0 : item.icon) === 'string') {
      return /*#__PURE__*/React.createElement("i", {
        className: "float-button-icon ".concat(item.icon).concat(item.name ? ' m' : ' l')
      });
    }
    return null;
  }

  // 触摸开始
  function handleTouchStart(e) {
    e.stopPropagation();

    // 解决拖动时影响document弹性
    e.currentTarget.addEventListener('touchmove', DOMUtil.preventDefault, false);
    touchesRef.current.isDragging = true;
    var touch = e.touches[0];
    touchesRef.current.startX = touch.clientX;
    touchesRef.current.startY = touch.clientY;
    var pos = getPosition(e.currentTarget);
    touchesRef.current.currentLeft = pos.left;
    touchesRef.current.currentTop = pos.top;
    e.currentTarget.style.transition = 'none';
  }

  // 触摸移动
  function handleTouchMove(e) {
    e.stopPropagation();
    if (!touchesRef.current.isDragging) return;
    // e.preventDefault()
    var touch = e.touches[0];
    var deltaX = touch.clientX - touchesRef.current.startX;
    var deltaY = touch.clientY - touchesRef.current.startY;
    e.currentTarget.style.left = "".concat(touchesRef.current.currentLeft + deltaX, "px");
    e.currentTarget.style.top = "".concat(touchesRef.current.currentTop + deltaY, "px");
  }

  // 触摸结束
  function handleTouchEnd(e) {
    var _e$target, _e$target$closest, _e$changedTouches, _e$changedTouches2;
    e.stopPropagation();

    // 解除对move时的弹性对当前div的锁定
    e.currentTarget.removeEventListener('touchmove', DOMUtil.preventDefault, false);

    // 获取点击项的id
    var itemId = e.target.classList.contains('.float-button') ? (_e$target = e.target) === null || _e$target === void 0 ? void 0 : _e$target.id : (_e$target$closest = e.target.closest('.float-button')) === null || _e$target$closest === void 0 ? void 0 : _e$target$closest.id;
    var item = getItemById(list, itemId);
    if (!touchesRef.current.isDragging) {
      item && onChange && onChange(item);
      return;
    }
    touchesRef.current.isDragging = false;

    // 点击时不要修改位置
    var endX = (e === null || e === void 0 ? void 0 : e.clientX) || (e === null || e === void 0 || (_e$changedTouches = e.changedTouches) === null || _e$changedTouches === void 0 || (_e$changedTouches = _e$changedTouches[0]) === null || _e$changedTouches === void 0 ? void 0 : _e$changedTouches.clientX);
    var endY = (e === null || e === void 0 ? void 0 : e.clientY) || (e === null || e === void 0 || (_e$changedTouches2 = e.changedTouches) === null || _e$changedTouches2 === void 0 || (_e$changedTouches2 = _e$changedTouches2[0]) === null || _e$changedTouches2 === void 0 ? void 0 : _e$changedTouches2.clientY);
    var diffX = touchesRef.current.startX - endX;
    var diffY = touchesRef.current.startY - endY;
    if (Math.abs(diffX) < 5 && Math.abs(diffY) < 5) {
      item && onChange && onChange(item);
      return;
    }

    // 贴边
    snapToEdge(e.currentTarget, {
      gap: gap,
      onChange: typeof onDragEnd === 'function' ? function (pos) {
        onDragEnd({
          position: pos
        });
      } : undefined
    });
  }

  // 分组和非分组
  var groupList = [];
  var unGroupList = [];
  if (!Array.isArray(list) || !list.length) return null;
  var _iterator = _createForOfIteratorHelper(list),
    _step;
  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var item = _step.value;
      if (item.group === false) {
        unGroupList.push(item);
      } else {
        groupList.push(item);
      }
    }

    // DOM
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }
  var Node = /*#__PURE__*/React.createElement("div", _extends({
    ref: rootRef
  }, props, {
    className: DOMUtil.classNames('float-button-container', props === null || props === void 0 ? void 0 : props.className, SafeArea.getSafeAreaClassName(safeArea)),
    onTouchStart: draggable ? handleTouchStart : null,
    onTouchMove: draggable ? handleTouchMove : null,
    onTouchEnd: draggable ? handleTouchEnd : null
  }), list.map(function (item, index) {
    // 不能没有id
    if (!(item !== null && item !== void 0 && item.id)) {
      item.id = '' + index;
    }

    // 内容
    var Content = /*#__PURE__*/React.createElement(React.Fragment, null, getIconNode(item), item.name ? /*#__PURE__*/React.createElement("div", {
      className: "float-button-label"
    }, item.name) : null);

    // 分组
    if (Array.isArray(item.children) && item.children.length) {
      return /*#__PURE__*/React.createElement(ActionSheet.Combo, {
        key: item.id || index,
        id: item.id,
        list: item.children,
        className: DOMUtil.classNames('float-button', item.className),
        style: item.style,
        onClick: function onClick(e) {
          e.stopPropagation();
        },
        onChange: onChange
      }, Content);
    }
    // 未分组
    else {
      return /*#__PURE__*/React.createElement("div", {
        key: item.id || index,
        id: item.id,
        className: DOMUtil.classNames('float-button', item.className),
        style: item.style,
        onClick: draggable ? undefined : function (e) {
          onChange && onChange(item);
          e.stopPropagation();
        }
      }, Content);
    }
  }));
  if (!portal) {
    return Node;
  }
  return /*#__PURE__*/createPortal(Node, portal || document.getElementById('root'));
}
export default /*#__PURE__*/forwardRef(FloatButton);