import React, { useState, useEffect, useRef } from 'react';
import { Table } from 'antd';

import { HTML5Backend } from 'react-dnd-html5-backend';
import { DndProvider } from 'react-dnd';

import DraggableBodyRow from './DraggableBodyRow';

const DragTable = props => {
  const { columns, dataSource, dragCallBack, ItemTypes, editEventType, setSelectColor } = props;
  const [data, setData] = useState(null); // 分组后的数组
  const moving = useRef(false);
  const components = {
    body: {
      row: DraggableBodyRow,
    },
  };
  useEffect(() => {
    moving.current = false;
    if (dataSource.length > 0) {
      setData(dataSource);
    }
  }, [dataSource]);
  // 每次拖拽后返回
  useEffect(() => {
    if (ItemTypes === 'maintenance') {
      let moveState = moving.current;
      let val = { data, moveState };
      dragCallBack(val);
    } else {
      dragCallBack(data);
    }
  }, [data]);
  // 移动数组元素到指定位置
  const moveInArray = (arr, from, to) => {
    // 确保是有效数组
    if (Object.prototype.toString.call(arr) !== '[object Array]') {
      throw new Error('Please provide a valid array');
    }
    // 删除当前的位置
    let item = arr.splice(from, 1);
    // 确保还剩有元素移动
    if (!item.length) {
      throw new Error(`There is no item in the array at index ${from}`);
    }
    // 移动元素到指定位置
    arr.splice(to, 0, item[0]);
    return arr;
  };
  // 拖拽表格
  const moveRow = (dragIndex, hoverIndex) => {
    moving.current = true;
    setData(val => {
      let newData = JSON.parse(JSON.stringify(val));
      newData = moveInArray(newData, dragIndex, hoverIndex);
      return newData;
    });
  };
  return (
    <div>
      <DndProvider backend={HTML5Backend}>
        {ItemTypes === 'maintenance' ? (
          <Table
            bordered
            columns={columns}
            dataSource={data}
            components={components}
            onRow={(record, index) => ({
              index,
              ItemTypes,
              moveRow,
              onClick: () => props.onClick && props.onClick(record),
              onDoubleClick: event => {
                event.stopPropagation();
                setSelectColor(record.id);
                editEventType(record);
              }, // 双击
            })}
            {...props}
          />
        ) : (
          <Table
            bordered
            columns={columns}
            dataSource={data}
            components={components}
            onRow={(record, index) => ({
              index,
              ItemTypes,
              moveRow,
              onClick: () => props.onClick && props.onClick(record),
            })}
            {...props}
          />
        )}
      </DndProvider>
    </div>
  );
};

export default DragTable;
