/*
 * @Author: zhangleyuan
 * @Date: 2021-02-20 16:45:51
 * @LastEditors: zhangleyuan
 * @LastEditTime: 2021-03-02 20:20:28
 * @Description: 描述一下
 * @@Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */
import React from 'react';
import { Table ,Button,Input,Form} from 'antd';
import { sortableContainer, sortableElement, sortableHandle} from 'react-sortable-hoc';
import { MenuOutlined } from '@ant-design/icons';
import arrayMove from 'array-move';
import RelatedCourseModal from '../modal/relatedCourseModal'
import { withRouter } from 'react-router-dom';
import './TrainingTask.less';

const DragHandle = sortableHandle(() => (
  <span style={{ cursor: 'pointer', color: '#999' }} >
    <span className="icon iconfont">&#xe7cd;</span>
    <span>移动</span>
  </span>
));
const SortableItem = sortableElement(props => <tr {...props} />);
const SortableContainer = sortableContainer(props => <tbody {...props} />);

class TrainingTask extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      dataSource:[],
      selectedTaskIndex:0,
      relatedCourseModalVisible:false
    };
  }
  componentDidMount(){

    console.log('data',this.props.data);
    
  }
  parseTaskColumns = ()=>{
      const columns = [
        {
          title: 'taskName',
          dataIndex: 'taskName',
          className: 'drag-visible',
          render: (val, record,index) => {
            return (
                <div>
                  {record.type==='text'?
                  <span>{val}</span>
                  : 
                  <Form>
                  <Form.Item  
                  validateTrigger={['onChange', 'onBlur']}
                  name={['taskName']}
                  rules={[
                    {
                      required: true,
                      message: "请输入任务名称",
                    },
                  ]}><Input defaultValue={record.taskName} style={{ width: 300 }} placeholder="请输入任务名称（20字以内）"  maxLength={20} onChange={(e) => { this.handleRenameTaskName(e,record)}} onBlur={(e)=>{this.handleTaskNameBlur(e,record)}}/></Form.Item></Form>}
                
                </div>
            )
          }
        },
        {
          title: '操作',
          key: 'operate',
          dataIndex: 'operate',
          width: '25%',
          render: (val, record,index) => {
              return (
                  <div className="operate">
                    <DragHandle />
                    <span className="operate__item">
                      <span className="icon iconfont">&#xe6f5;</span>
                      <span onClick={(e)=>{const { data }= this.props; record.type="input";this.props.onChange(data);}}>重命名</span>
                    </span>
                    <span className="operate__item"  onClick={()=>{this.handleDeleteTask(index)}} >
                      <span className="icon iconfont">&#xe6f6;</span>
                      <span>删除</span>
                    </span>
                  </div>
              )
          }
        }
    ];
    return columns;
  }
  parseCoursecolumns = (parentIndex)=>{
    const coursecolumns = [
      {
        title: 'courseName',
        dataIndex: 'courseName',
        className: 'drag-visible',
        render: (val, record) => {
          return (
              <div>
                {record.type==='input'?
                  <Form>
                  <Form.Item  
                  validateTrigger={['onChange', 'onBlur']}
                  name={['courseName']}
                  rules={[
                    {
                      required: true,
                      message: "请输入课程名称",
                    },
                  ]}>
                    <Input defaultValue={record.courseName} style={{ width: 300 }} placeholder="请输入任务名称（40字以内）"  maxLength={40} onChange={(e) => { this.handleRenameCourseName(e,record)}} onBlur={(e)=>{this.handleCourseNameBlur(e,record)}}/></Form.Item>
                    </Form>
                  :
                  <span>{record.courseName}</span>
                }
              </div>
          )
        }
      },
      {
        title: '操作',
        key: 'operate',
        dataIndex: 'operate',
        width: '25%',
        render: (val, record,index) => {
            return (
                <div className="operate">
                  <DragHandle />
                  <span className="operate__item">
                      <span className="icon iconfont">&#xe6f5;</span>
                      <span onClick={(e)=>{const { data } = this.props; record.type="input";this.props.onChange(data);}}>重命名</span>
                    </span>
                    <span className="operate__item" onClick={()=>{this.handleDeleteCourse(parentIndex,index)}}>
                      <span className="icon iconfont">&#xe6f6;</span>
                      <span>删除</span>
                    </span>
                </div>
            )
        }
      }
    ];
    return  coursecolumns
  }

  // onSortEnd = ({ oldIndex, newIndex }) => {
  //   const { dataSource } = this.state;
  //   if (oldIndex !== newIndex) {
  //     const newData = arrayMove([].concat(dataSource), oldIndex, newIndex).filter(el => !!el);
  //     console.log('Sorted items: ', newData);
  //     this.setState({ dataSource: newData });
  //   }
  // };

  // DraggableContainer = props => (
  //   <SortableContainer
  //     useDragHandle
  //     disableAutoscroll
  //     helperClass="row-dragging"
  //     onSortEnd={this.onSortEnd}
  //     {...props}
  //   />
  // );

  // DraggableBodyRow = ({ className, style, ...restProps }) => {
  //   const { dataSource } = this.state;
  //   // function findIndex base on Table rowKey props and should always be a right array index
  //   const index = dataSource.findIndex(x => x.index === restProps['data-row-key']);
  //   return <SortableItem className={className} index={index} {...restProps} style={style}/>;
  // };

  addTask = () => {
    const { data } = this.props;
    const taskObj={
      taskName: '',
      index:data.length,
      type:'input',
      courseList:[
      ]
    }
    const newData = [...data,taskObj];
    this.props.onChange(newData);
  }
  
  handleRenameTaskName = (e,record) => {
    const { value } = e.target;
    const { data } = this.props;
    record.taskName = value;
    this.props.onChange(data);
  }
  handleTaskNameBlur = (e,record)=>{
    const { value } = e.target;
    const {data}= this.props; 
    if(value){
      record.type="text";
      this.props.onChange(data);
    } 
  }

  handleRenameCourseName = (e,record) => {
    const { value } = e.target;
    const { data } = this.props;
    record.courseName = value;
    this.props.onChange(data);
  }

  handleCourseNameBlur = (e,record)=>{
    const { value } = e.target;
    const { data }= this.props;
    if(value){
      record.type="text";
      this.setState({data});
    } 
  }
  handleDeleteTask = (index)=>{
    const {data}= this.props;
    const newData=[...data];
    newData.splice(index,1);
    this.props.onChange(newData);
  }
  handleDeleteCourse = (parentIndex,index)=>{
    const {data}= this.props;
    const newData=[...data];
    const selectData = [...newData[parentIndex].courseList]
    selectData.splice(index,1)
    newData[parentIndex].courseList= selectData;
    this.props.onChange(newData);
    
  }
  showRelatedCourseModal = (index)=>{
    this.setState({
      selectedTaskIndex:index,
      relatedCourseModalVisible:true
    })
  }
  closeRelatedCourseModal = (index)=>{
    this.setState({
      relatedCourseModalVisible:false
    })
  }
  confirmSelectCourse = (selectList) =>{
    const {selectedTaskIndex}= this.state;
    const { data } = this.props
    const newData=[...data];
    const selectData = [...newData[selectedTaskIndex].courseList]
    const _selectData =[...selectData,...selectList];
    newData[selectedTaskIndex].courseList= _selectData;
    this.setState({
      relatedCourseModalVisible:false,
    },()=>{
      this.props.onChange(newData);
    })
  }
  
  render() {
    const { dataSource,selectedTaskIndex,relatedCourseModalVisible} = this.state;
    const { data } = this.props;
    return (
      <div  className="training-task">
        <Table
          pagination={false}
          dataSource={data}
          columns={this.parseTaskColumns()}
          rowKey="index"
          expandedRowRender={(record,index) => {
            if (record.courseList.length !== 0 ){
              return  <div>
                        <Table
                          pagination={false}
                          dataSource={record.courseList}
                          columns={this.parseCoursecolumns(index)}
                          rowKey="index"
                          // components={{
                          //   body: {
                          //     wrapper: this.DraggableContainer,
                          //     row: this.DraggableBodyRow,
                          //   },
                          // }}
                        />
                        <div><Button onClick={()=>{this.showRelatedCourseModal(index)}}><span>+</span><span>关联课程</span></Button></div>
                  </div>
            }else{
              return <div><Button onClick={()=>{this.showRelatedCourseModal(index)}}><span>+</span><span>关联课程</span></Button></div>;
            }

          }}
          // components={{
          //   body: {
          //     wrapper: this.DraggableContainer,
          //     row: this.DraggableBodyRow,
          //   },
          // }}
        />
        <div><Button onClick={()=>this.addTask()}><span>+</span><span>添加任务</span></Button></div>
        { relatedCourseModalVisible &&
          <RelatedCourseModal
            selectedTaskIndex={selectedTaskIndex}
            data={data}
            visible={relatedCourseModalVisible}
            onClose={this.closeRelatedCourseModal}
            onSelect={this.confirmSelectCourse}
          />
        }
      </div>
    );
  }
}

export default withRouter(TrainingTask)
