/*
 * @Author: your name
 * @Date: 2022-04-21 15:50:48
 * @Description:
 * @FilePath: /zl-large-screen/src/components/CardItem/index.tsx
 */

import React, { useMemo, useRef, useEffect } from 'react';

import { ICardListITem } from '../../type/LargeScreenElement';

import './style.scss';

let timer = null; // 阻止双击两次触发mousedown
const CardItem: React.FC<ICardListITem> = (props) => {
  const {
    title,
    url,
    dragStart,
    titleStyle,
    item,
    doubleClick,
    sceneEvent,
    selected,
    cardMouseDown
  } = props;
  const dragDom = useRef<any>(null);
  const stopRef = useRef<any>(null);

  useEffect (() => {
    return () => {
      clearTimeout(timer);
    }
  },[])

  const drag = (e: React.DragEvent) => {
    e.dataTransfer.dropEffect = 'copy';
    e.dataTransfer.setData('text/plain', JSON.stringify(item));
    dragStart?.(e);
  };

  const stopDoubleMouseDown = (item)=> {
    if(!stopRef?.current){
      cardMouseDown?.(item);
      stopRef.current = true;
      timer = setTimeout(()=>{
        stopRef.current = false;
      }
      ,500)
    }
  }

  const MItem = useMemo(() => {
    return (
      <div
        ref={dragDom}
        className={`${selected ? 'active' : ''} zl-unit-card-item`}
        draggable={!sceneEvent} // 3D元件不可拖拽
        onDragStart={(e) => drag(e)}
        onDoubleClick={() => {
          !sceneEvent && doubleClick(item);
        }}
        onClick={() => {
          sceneEvent?.(item);
        }}
        onMouseDown={() => {
          stopDoubleMouseDown?.(item);
          
        }}
      >
        <div className="pop" />
        <div className="zl-large-screen-element-card-img">
          {url ? (
            <img src={url} alt={title} />
          ) : (
            <span style={{ ...titleStyle }}>{title}</span>
          )}
        </div>
        <p>{title}</p>
      </div>
    );
  }, [title, url,selected]);
  return MItem;
};
export default CardItem;
