import React__default, { useState, useRef, useCallback, useMemo } from 'react';

function DragContent({
  children,
  style
}) {
  const [data, setData] = useState(null);
  const domRef = useRef(null);
  const onDrop = useCallback(event => {
    event.stopPropagation();
    const ydata = JSON.parse(event.dataTransfer.getData("DATA"));
    setData(ydata);
  }, []);
  const allowDrop = useCallback(e => e.preventDefault(), []);
  console.log(data);
  return /*#__PURE__*/React__default.createElement("div", {
    ref: domRef,
    onDrop: onDrop,
    onDragOver: allowDrop,
    style: style
  }, children);
}

function DragItem({
  children,
  dragData,
  dragId
}) {
  const DragId = useMemo(() => dragId || `dragId-${Math.random()}`, [dragId]);
  const [status, setStatus] = useState('noDrag');
  const [offset, setOffset] = useState([0, 0]);
  const domRef = useRef(null);
  const dragDomTemp = useRef(null);
  const onDragStart = useCallback(event => {
    const {
      pageX,
      pageY
    } = event;
    const {
      x,
      y
    } = domRef.current.getBoundingClientRect();
    const offsetX = pageX - x;
    const offsetY = pageY - y;
    dragDomTemp.current = domRef.current.cloneNode(true);
    domRef.current.after(dragDomTemp.current);

    //初始化缓存dom位置
    dragDomTemp.current.style.position = 'fixed';
    dragDomTemp.current.style.left = `${event.pageX - offsetX}px`;
    dragDomTemp.current.style.top = `${event.pageY - offsetY}px`;
    dragDomTemp.current.style.draggable = false;
    dragDomTemp.current.style.pointerEvents = 'none';
    setOffset([offsetX, offsetY]);
    setStatus('draging');
    event.dataTransfer.setDragImage(new Image(), 0, 0);
    event.dataTransfer.setData('DATA', JSON.stringify({
      ...dragData,
      DragId
    }));
  }, [DragId, dragData]);
  const onDragEnd = useCallback(() => {
    dragDomTemp.current.remove();
    setStatus('dragEnd');
  }, []);
  const onDrag = useCallback(e => {
    if (e.pageX === 0 && e.pageY === 0) {
      return;
    }
    if (e.pageX < offset[2] || e.pageY < offset[3]) {
      return;
    }
    dragDomTemp.current.style.position = 'fixed';
    dragDomTemp.current.style.left = `${e.pageX - offset[0]}px`;
    dragDomTemp.current.style.top = `${e.pageY - offset[1]}px`;
    // console.log(e.pageX, e.pageY, offset);
  }, [offset]);
  return /*#__PURE__*/React__default.createElement("div", {
    ref: domRef,
    onDragStart: onDragStart,
    onDrag: onDrag,
    id: DragId,
    draggable: true,
    onDragEnd: onDragEnd,
    style: {
      width: 'max-content',
      opacity: status === 'draging' ? 0.5 : 1
    }
  }, children);
}

const Drag = {
  DragBox: DragContent,
  DragItem
};

export { Drag as default };
//# sourceMappingURL=index.js.map
