import React from "react";

const ShowItem = ({ basicUrl, type, x, y, ...otherInfo }) => {
  switch (type) {
    case 'image':
      return (
        <img
          draggable={false}
          key={otherInfo.key}
          src={basicUrl + otherInfo.path}
          style={{
            // border: '1px solid red',
            cursor: 'pointer',
            width: otherInfo.w,
            height: otherInfo.h,
          }}
        />
      );
    case 'text':
      return (
        <p
          draggable={false}
          key={otherInfo.key}
          style={{
            // border: '1px solid red',
            cursor: 'pointer',
            fontSize: otherInfo?.fontSize ? otherInfo.fontSize + 'px' : undefined,
            fontFamily: otherInfo?.fontFamily ? otherInfo.fontFamily : undefined,
            fontWeight: otherInfo?.fontStyle ? otherInfo.fontStyle : undefined,
            color: otherInfo?.color ? otherInfo.color : undefined,
          }}
        >
          {otherInfo.word}
        </p>
      );
  }
};


export const dragEventList = (setOtherProps, otherProps) => {
  let draggedRef = null;
  document.addEventListener(
    'dragstart',
    function(event) {
      // 保存拖动元素的引用(ref.)
      draggedRef = event.target;
      // 使其半透明
      event.target.style.opacity = 0.5;
    },
    false,
  );
  document.addEventListener(
    'dragend',
    (event) => {
      // 重置透明度
      event.target.style.opacity = '';
    },
    false,
  );

  /* 放下目标节点时触发事件 */
  document.addEventListener(
    'dragover',
    (event) => {
      // 阻止默认动作
      event.preventDefault();
    },
    false,
  );
  document.addEventListener(
    'drop',
    (event) => {
      // 阻止默认动作（如打开一些元素的链接）
      event.preventDefault();
      // 将拖动的元素到所选择的放置目标节点中
      if (event.target.id === 'dropZone') {
        let left = event.offsetX;
        if (left > event.target.offsetWidth - draggedRef.offsetWidth - 10) {
          console.log('拖拽到了图片区域外部,不能进行拖拽');
          return false;
        }
        let top = event.offsetY;
        let key = draggedRef?.dataset?.mes || draggedRef?.parentNode?.dataset?.mes;
        let item = otherProps.signConfig.find((g) => {
          return g.key === key;
        });
        if(!item){
          return false;
        }
        // left = left - (item.x /2 );
        // top = top - (item.y / 2);
        item.x = left;
        item.y = top;
        console.log(left, top);
        setOtherProps({
          ...otherProps,
          signConfig: otherProps.signConfig,
        })
        draggedRef.style.left = left; // `${left}px`;
        draggedRef.style.top = top; // `${top}px`;
      }
      return true;
    },
    false,
  );
}

export default ShowItem
