import React from 'react'
import { Checkbox, Icon } from 'antd'
import { DragSource, DropTarget } from 'react-dnd'
import WithDragDropContext from './WithDragDropContext'
import styles from '../Table/tableBase.css'

function dragDirection (
  dragIndex,
  hoverIndex,
  initialClientOffset,
  clientOffset,
  sourceClientOffset
) {
  const hoverMiddleY = (initialClientOffset.y - sourceClientOffset.y) / 2
  const hoverClientY = clientOffset.y - sourceClientOffset.y
  if (dragIndex < hoverIndex && hoverClientY > hoverMiddleY) {
    return 'downward'
  }
  if (dragIndex > hoverIndex && hoverClientY < hoverMiddleY) {
    return 'upward'
  }
}

class BodyRow extends React.Component {
  render () {
    const {
      isOver,
      connectDragSource,
      connectDropTarget,
      moveRow,
      dragRow,
      clientOffset,
      sourceClientOffset,
      initialClientOffset,
      ...restProps
    } = this.props
    const style = { ...restProps.style, cursor: 'move' }

    let className = restProps.className
    if (isOver && initialClientOffset) {
      const direction = dragDirection(
        dragRow.index,
        restProps.index,
        initialClientOffset,
        clientOffset,
        sourceClientOffset
      )
      if (direction === 'downward') {
        className += ' drop-over-downward'
      }
      if (direction === 'upward') {
        className += ' drop-over-upward'
      }
    }
    return connectDragSource(
      connectDropTarget(
        <div
          {...restProps}
          className={className}
          style={style}
        />
      )
    )
  }
}

const rowSource = {
  beginDrag (props) {
    return {
      record: props.record,
      index: props.index
    }
  }
}

const rowTarget = {
  drop (props, monitor) {
    const dragData = monitor.getItem().record
    const hoverData = props.record

    // Don't replace items with themselves
    if (dragData.ID === hoverData.ID) return

    // Time to actually perform the action
    props.moveRow(dragData, hoverData)

    // Note: we're mutating the monitor item here!
    // Generally it's better to avoid mutations.
    // but it's good here for the sake of performance
    // to avoid expensive index searcher.
    monitor.getItem().record = hoverData
  }
}

const DragableBodyRow = DropTarget('row', rowTarget, (connect, monitor) => ({
  connectDropTarget: connect.dropTarget(),
  isOver: monitor.isOver(),
  sourceClientOffset: monitor.getSourceClientOffset()
}))(
  DragSource('row', rowSource, (connect, monitor) => ({
    connectDragSource: connect.dragSource(),
    dragRow: monitor.getItem(),
    clientOffset: monitor.getClientOffset(),
    initialClientOffset: monitor.getInitialClientOffset()
  }))(BodyRow)
)

class CustomFieldsManage extends React.Component {
  moveRow = (dragData, hoverData) => {
    let newData = JSON.parse(JSON.stringify(this.props.customCfg))
    let index = ''
    newData.forEach((item, key) => {
      if (item.ID === dragData.ID) {
        newData.splice(key, 1)
      }
      if (item.ID === hoverData.ID) {
        index = key
      }
    })
    newData.splice(index, 0, dragData)

    let initNum = 0
    let dataNumSort = {}
    newData.forEach(item => {
      if (item.num > initNum) {
        initNum = item.num
        dataNumSort[item.ID] = initNum
      } else {
        initNum = initNum + 1
        dataNumSort[item.ID] = initNum
      }
    })

    this.props.onChange('num', dataNumSort, dragData)
    // this.props.handleDrag(newData, index);
  };
  render () {
    const { customCfg, onChange } = this.props
    return (
      <WithDragDropContext>
        <div className={styles.tableFieldManage} onClick={e => e.stopPropagation()}>
          <div className={styles.fieldList}>
            {
              customCfg && customCfg.length
                ?
                customCfg.map((item, key) => {
                  return <DragableBodyRow className={styles.dragList} moveRow={this.moveRow} index={item.num} record={item} key={key}>
                    <div className={styles.dragCheck}>
                      <Checkbox defaultChecked={item.isCheck} onChange={e => onChange('check', (e && e.target ? e.target.checked : e), item)} disabled={item.isRequire} />
                    </div>
                    <div className={styles.dragLabel} title={item.title}>
                      <label>{item.title}</label>
                    </div>
                    <div className={styles.dragIcon}>
                      <Icon type='swap' />
                    </div>
                  </DragableBodyRow>
                })
                : null
            }
          </div>
          <div className={styles.pullFootBtn}>
            <div className={styles.rollback} onClick={this.props.clearCustomConfig}>
              <Icon type="rollback" />
            </div>
            <div className={styles.save} onClick={this.props.saveCustomConfig}>
              <Icon type="save" />
            </div>
          </div>
        </div>
      </WithDragDropContext>
    )
  }
}

export default CustomFieldsManage
