/*
 * @Author: zhangleyuan
 * @Date: 2021-02-20 16:45:51
 * @LastEditors: zhangleyuan
 * @LastEditTime: 2021-03-08 17:39:37
 * @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:this.props.data,
      selectedTaskIndex:0,
      relatedCourseModalVisible:false
    };
  }
  componentWillMount(){
    // if (this.props.data) {
    //   const newData = [...this.props.data];
    //   this.setState({
    //     dataSource:newData,
    //   })
    // }
  }

  componentWillReceiveProps(nextProps) {
    
  }

  parseTaskColumns = ()=>{
      const columns = [
        {
          title: 'taskName',
          dataIndex: 'taskName',
          className: 'drag-visible',
          render: (val, record,index) => {
            return (
                <div>
                  {record.type==='input'?
                    <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>
                    : 
                    <span>{val}</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 { dataSource }= this.state; record.type="input";this.setState({dataSource})}}>重命名</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 { dataSource } = this.state; record.type="input";this.setState({dataSource})}}>重命名</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;

    console.log("oldIndex",oldIndex);
    console.log("newIndex",newIndex);

    if (oldIndex !== newIndex) {
      const newData = arrayMove([].concat(dataSource), oldIndex, newIndex).filter(el => !!el);
      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 { dataSource } = this.state;
    const taskObj={
      taskName: '',
      index:dataSource.length,
      type:'input',
      courseList:[
      ]
    }
    const newData = [...dataSource,taskObj];
    this.setState({
      dataSource:newData
    },()=>{this.props.onChange(newData);})
  }
  
  handleRenameTaskName = (e,record) => {
    const { value } = e.target;
    const { dataSource } = this.state;
    record.taskName = value;
    this.setState({
      dataSource,
    },()=>{this.props.onChange(dataSource);})
  }
  handleTaskNameBlur = (e,record)=>{
    const { value } = e.target;
    const { dataSource }= this.state; 
    if(value){
      record.type="text";
      this.setState({
        dataSource,
      },()=>{this.props.onChange(dataSource);})
    } 
  }

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

  handleCourseNameBlur = (e,record)=>{
    const { value } = e.target;
    const { dataSource }= this.state;
    if(value){
      record.type="text";
      this.setState({
        dataSource,
      },()=>{this.props.onChange(dataSource);})
    } 
  }
  handleDeleteTask = (index)=>{
    const {dataSource}= this.state;
    const newData=[...dataSource];
    newData.splice(index,1);
    this.setState({
      dataSource:newData,
    },()=>{this.props.onChange(newData);})
    
  }
  handleDeleteCourse = (parentIndex,index)=>{
    const {dataSource}= this.state;
    const newData=[...dataSource];
    const selectData = [...newData[parentIndex].courseList]
    selectData.splice(index,1)
    newData[parentIndex].courseList= selectData;
    this.setState({
      dataSource:newData,
    },()=>{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 { dataSource } = this.state
    const newData=[...dataSource];
    const selectData = [...newData[selectedTaskIndex].courseList]
    const _selectData =[...selectData,...selectList];
    newData[selectedTaskIndex].courseList= _selectData;
    this.setState({
      relatedCourseModalVisible:false,
      dataSource:newData,
    },()=>{
      this.props.onChange(newData);
    })
  }
  
  render() {
    const { dataSource,selectedTaskIndex,relatedCourseModalVisible} = this.state;

    const { data } = this.props;
    return (
      <div  className="training-task">
        <Table
          pagination={false}
          dataSource={dataSource}
          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={dataSource}
            visible={relatedCourseModalVisible}
            onClose={this.closeRelatedCourseModal}
            onSelect={this.confirmSelectCourse}
          />
        }
      </div>
    );
  }
}

export default withRouter(TrainingTask)
