import React, { useRef, useState } from 'react';
import { useDrag, useDrop } from 'react-dnd';
import { Tag, Input, Popconfirm } 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, endChangePosition, edit, del }) => {
  const [isEdit, setIsEdit] = useState(false);
  const [inputValue, setInputValue] = useState('');
  const refInput = useRef();

  const handleEdit = () => {
    edit(id);
  };
  const handleInputChange = e => {
    setInputValue(e.target.value);
  };
  const handleInputConfirm = () => {
    setIsEdit(false);
    setInputValue('');
  };

  const handleClose = () => {
    del(id);
  };

  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) => {
      endChangePosition(); // 调用传入的方法完成交换
    },
  });

  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>
      <Popconfirm title="确定删除该分组吗?" onConfirm={handleClose} okText="确定" cancelText="取消">
        <CloseCircleOutlined className={styles['groupBox-body--tag__close']} />
      </Popconfirm>
    </Tag>
  );

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