import { getStatusClassNames } from 'antd/lib/_util/statusUtils';
import React, { useState, useCallback, useEffect, useRef } from 'react';
import { useDrag, useDrop } from 'react-dnd';
import styles from './index.less';

const DraggableBodyRow = ({
  pickIndex,
  dragType,
  name,
  index,
  moveRow,
  className,
  style,
  tableType,
  ...restProps
}) => {
  useEffect(() => {}, []);
  const ref = useRef();
  // const
  const [{ isOver, canDrop, dropClassName }, drop] = useDrop({
    accept: 'DraggableBodyRow',
    canDrop: () => {
      // 组不能拖拽到字段上
      if (!tableType || (dragType === 'group' && tableType === 'field')) {
        return false;
      }
      if (dragType === 'field' && tableType === 'group' && pickIndex === index) {
        return false;
      }
      if (dragType === 'group' && index === 0) {
        return false;
      }
      return true;
    },
    collect: monitor => {
      const { index: dragIndex } = monitor.getItem() || {};

      let rowClass;
      // 拖拽体为字段时
      if (dragType === 'field') {
        if (tableType === 'group') {
          // 给字段拖拽到组
          rowClass = ` ${styles.dropOverGroup}`;
        } else {
          // 字段之间的拖拽
          rowClass =
            dragIndex < index ? ` ${styles.dropOverDownward}` : ` ${styles.dropOverUpward}`;
        }
      } else {
        // 拖拽提为组时
        if (index === 0 || dragIndex === index || tableType === 'field') {
          return {};
        }
        rowClass = dragIndex < index ? ` ${styles.dropOverDownward}` : ` ${styles.dropOverUpward}`;
      }
      // 字段不能拖拽到字段上
      if (dragIndex === index && tableType === 'field') {
        return {};
      }
      return {
        isOver: monitor.isOver(),
        canDrop: monitor.canDrop(),
        dropClassName: rowClass,
      };
    },
    drop: item => {
      moveRow(item.index, index, tableType, dragType);
    },
  });
  // 拖拽配置
  const [, drag] = useDrag({
    type: 'DraggableBodyRow',
    item: { index },
    canDrag: () => {
      if (dragType === 'group' && index === 0) {
        return false;
      }
      return true;
    },
    collect: monitor => ({ isDragging: monitor.isDragging() }),
  });
  drop(drag(ref));

  return (
    <tr
      ref={ref}
      className={`${className}${isOver ? dropClassName : ''}`}
      style={{ cursor: 'move', ...style }}
      {...restProps}
    />
  );
};

export default DraggableBodyRow;
