import React, { useState, useRef } from "react";
import { useDrag } from "ahooks";
export default function DragItem({
  children,
  onDragStart,
  onDragEnd,
  title
}: {
  children: any;
  onDragStart: () => void;
  onDragEnd: () => void;
  title: string;
}) {
  const dragRef = useRef(null);

  const [dragging, setDragging] = useState(false);

  // 创建一个canvas元素，将图片绘制到canvas上，然后获取canvas的dataURL作为拖拽时的图片
  const canvas = document.createElement("canvas");
  canvas.width = title.length * 10 + 20;
  canvas.height = 30;
  const ctx = canvas.getContext("2d");
  if(ctx) {
    // 设置背景色为蓝色
    ctx.fillStyle = "#4096ff";
    ctx.fillRect(0, 0, canvas.width, 30);
    ctx.fillStyle = "#fff";
    ctx.fillText(title, 10, 20);
  }
  
  const dataUrl = canvas.toDataURL("image/png");

  useDrag("", dragRef, {
    dragImage: {
      image: dataUrl,
    },
    onDragStart: () => {
      onDragStart();
      setDragging(true);
    },
    onDragEnd: () => {
      onDragEnd();
      setDragging(false);
    },
  });

  return (
    <div
      ref={dragRef}
      style={{
        opacity: dragging ? 0.7 : 1,
      }}
    >
      {children}
    </div>
  );
}
