import React, { useRef, useState } from 'react';
import { useDrag, useDrop } from 'react-dnd';
import { Tag, Input } from 'antd';
import { HolderOutlined, FormOutlined, CloseCircleOutlined } from '@ant-design/icons';
import styles from '../../style.less';

const ItemTypes = {
  CARD: 'card',
};
const DragTag = ({ text, id, index, changePosition }) => {
  const [isEdit, setIsEdit] = useState(false);
  const [inputValue, setInputValue] = useState('');
  const refInput = useRef();

  const handleEdit = () => {
    setIsEdit(true);
    setInputValue(text || '');
    const timer = setTimeout(() => {
      if (refInput.current) {
        refInput.current.focus();
      }
      clearTimeout(timer);
    }, 1);
  };
  const handleInputChange = e => {
    setInputValue(e.target.value);
  };
  const handleInputConfirm = () => {
    setIsEdit(false);
    setInputValue('');
  };

  const handleClose = () => {
    console.log('111 :>> ', 111);
  };

  const ref = useRef(null);
  // 因为没有定义收集函数，所以返回值数组第一项不要
  const [, drop] = useDrop({
    accept: ItemTypes.CARD,
    hover: (item, monitor) => {
      if (!ref.current) return;
      const dragIndex = item.index;
      const hoverIndex = index;
      if (dragIndex === hoverIndex) return; // 如果回到自己的坑，那就什么都不做
      changePosition(dragIndex, hoverIndex); // 调用传入的方法完成交换
      item.index = hoverIndex; // 将当前当前移动到Box的index赋值给当前拖动的box，不然会出现两个盒子疯狂抖动！
    },
    drop: (item, monitor) => {},
  });

  const [{ isDragging }, drag] = useDrag({
    type: ItemTypes.CARD,
    item: { id, index, type: ItemTypes.CARD },
    end: () => {},
    isDragging: monitor => index === monitor.getItem().index,
    collect: monitor => ({
      isDragging: monitor.isDragging(),
    }),
  });

  const inputRender = () => (
    <Input
      type="text"
      size="small"
      ref={refInput}
      className={styles['groupBox-body--tag-input']}
      value={inputValue}
      onChange={handleInputChange}
      onBlur={handleInputConfirm}
      onPressEnter={handleInputConfirm}
    />
  );

  const groupEditRender = () => (
    <Tag
      className={styles['groupBox-body--tag']}
      ref={drag(drop(ref))}
      style={{
        opacity: isDragging ? 0.3 : 1,
        display: isEdit ? 'none' : 'inline-block',
      }}
    >
      <HolderOutlined className={styles['groupBox-body--tag__move']} />
      <span className={styles['groupBox-body--tag__text']}>{text}</span>
      <span>
        <FormOutlined className={styles['groupBox-body--tag__edit']} onClick={handleEdit} />
      </span>
      <CloseCircleOutlined className={styles['groupBox-body--tag__close']} onClick={handleClose} />
    </Tag>
  );

  return (
    <>
      {isEdit && inputRender()}
      {groupEditRender()}
    </>
  );
};
export default DragTag;
