/*
 * @Author: zhangleyuan
 * @Date: 2021-02-20 16:45:51
 * @LastEditors: zhangleyuan
 * @LastEditTime: 2021-03-09 15:53:46
 * @Description: 描述一下
 * @@Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */
import React from 'react';
import { Table ,Button,Input,Form,Collapse,Modal } 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 { Panel } = Collapse;
const { confirm } = Modal;
const CourseType = {
  LIVE: {
    text: "直播课"
  },
  VOICE : {
    text:"视频课"
  },
  RECORD : {
    text:'录播课'
  }
};
const courseStateShow = {
  UN_START: {
    title: "待开课",
  },
  STARTING: {
    title: "上课中",
  },
  FINISH: {
    title: "已完成",
  },
  EXPIRED: {
    title: "未成功开课",
  },
};
const DragHandle = sortableHandle(() => (
  <span className="operate__item" >
    <span className="icon iconfont">&#xe7cd;</span>
    <span className="text">移动</span>
  </span>
));

const SortableItem = sortableElement(props => <tr {...props}/>);
const SortableContainer = sortableContainer(props => <tbody {...props} />);


const SortableTaskItem = sortableElement(props => <div {...props}>{props.taskItem}</div>)
const SortableTaskContainer =  sortableContainer(props => <div {...props}></div>);

const SortableCourseItem = sortableElement(props => <div {...props}>{props.courseItem}</div>)
const SortableCourseContainer =  sortableContainer(props => <div {...props}></div>);
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);
      console.log("newData",newData)
      
      this.setState({ dataSource: [...newData] });
      
    }
  };
  onTaskSortEnd = ({ 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,
      },()=>{this.props.onChange(newData);})
    }
  };
  onCourseSortEnd = ({ oldIndex, newIndex },parentIndex) => {
    
    const { dataSource } = this.state;
    
    console.log("parentIndex",parentIndex);
    console.log("dataSource",dataSource);
    console.log("dataSource",dataSource[parentIndex].courseList);
    const _dataSource = [...dataSource];
    if (oldIndex !== newIndex) {
      _dataSource[parentIndex].courseList = arrayMove([].concat(dataSource[parentIndex].courseList), oldIndex, newIndex).filter(el => !!el);
      this.setState({
        dataSource:_dataSource,
      },()=>{this.props.onChange(_dataSource);})
    }

  };
  
  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',
      open:false,
      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)=>{
    return confirm({
      title: "删除任务",
      content: "删除该任务会同步删除任务下的课程，是否仍要删除？",
      icon: (
        <span className="icon iconfont default-confirm-icon">&#xe839; </span>
      ),
      okText: "删除",
      okType: "danger",
      cancelText: "取消",
      onOk: () => {
        this.handleConfirmDeleteTask(index);
      },
    });
  
  }
  handleConfirmDeleteTask = (index)=>{
    const {dataSource}= this.state;
    const newData=[...dataSource];
    newData.splice(index,1);
    this.setState({
      dataSource:newData,
    },()=>{this.props.onChange(newData);})
  }
  
  handleDeleteCourse = (parentIndex,index)=>{
    return confirm({
      title: "删除课程",
      content: "确定删除该课程吗？",
      icon: (
        <span className="icon iconfont default-confirm-icon">&#xe839; </span>
      ),
      okText: "删除",
      okType: "danger",
      cancelText: "取消",
      onOk: () => {
        this.handleConfirmDeleteCourse(parentIndex,index);
      },
    });
  }
  handleConfirmDeleteCourse = (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);
    })
  }
  openOrCloseTask = (index)=>{
    const {dataSource}= this.state;
    const newData=[...dataSource];
    newData[index].open = !newData[index].open;
    this.setState({
      dataSource:newData,
    },()=>{this.props.onChange(newData);})
  }
  renderTaskItem = (record,index)=>{
    return  <div className="task-item">
              <div className="task-con">
                <div className="task-instro">
                  <span onClick={()=>this.openOrCloseTask(index)}>
                    {record.open?
                      <span className="icon iconfont open-icon">&#xe82d;</span>:
                      <span className="icon iconfont  open-icon">&#xe835;</span>
                    }
                  </span>
                  {record.type==='input'?
                    <div className="task-name-con">
                      <span className="number">{index + 1}.</span>
                      <Form>
                        <Form.Item  
                        validateTrigger={['onChange', 'onBlur']}
                        name={['taskName']}
                        rules={[
                          {
                            required: true,
                            message: "请输入任务名称",
                          },
                        ]}>
                          <Input  className="task-name-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>
                      : 
                      <div className="task-name-con">
                        <span className="number">{index + 1}.</span>
                        <span className="task-name">{record.taskName}</span>
                      </div>
                  }
                </div>
                <div className="operate">
                    <DragHandle />
                    <span className="operate__item">
                      <span className="icon iconfont">&#xe6f5;</span>
                      <span className="text" onClick={()=>{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 className="text">删除</span>
                    </span>
                </div>
              </div>
              {record.open &&
                <div className="course-box">
                  <SortableCourseContainer 
                    useDragHandle
                    disableAutoscroll
                    helperClass="row-dragging"
                    onSortEnd={(record)=>this.onCourseSortEnd(record,index)} >
                    {record.courseList.map((courseItem, courseIndex) =>
                      <SortableCourseItem courseItem={this.renderCourseItem(courseItem,courseIndex,index)} index={courseIndex}>
                      </SortableCourseItem>
                    )}
                  </SortableCourseContainer>

                  <div className="add-course-con">
                    {record.courseList.length>19?
                      <span className="add-course-btn-disabled" onClick={()=>{this.showRelatedCourseModal(index)}}><span>+</span><span>关联课程</span></span>
                      :
                      <span className="add-course-btn" onClick={()=>{this.showRelatedCourseModal(index)}}><span>+</span><span>关联课程</span></span>
                    }
                   
                  </div>
                </div>
              }
            </div>
    }
  renderCourseItem = (record,index,parentIndex)=>{
    return <div className="course-item">
              <div className="course-info">
                <span className="course-type">{CourseType[record.courseType].text}</span>
                {record.type==='input'?
                  <Form>
                    <Form.Item  
                    validateTrigger={['onChange', 'onBlur']}
                    name={['courseName']}
                    rules={[
                      {
                        required: true,
                        message: "请输入课程名称",
                      },
                    ]}>
                      <Input className="course-name-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 className="course-name">{parentIndex + 1}.{index + 1}{record.courseName}</span>
                }
                {record.courseState === "EXPIRED" &&
                  <span className="icon iconfont tip">&#xe834;</span>
                }
                { record.courseType==="LIVE" &&
                  <span className="course-state">{courseStateShow[record.courseState].title}</span>
                }
               
              </div>
              <div className="operate">
                <DragHandle />
                <span className="operate__item">
                  <span className="icon iconfont">&#xe6f5;</span>
                  <span  className="text" 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  className="text">删除</span>
                </span>
              </div>
          </div>
  }
  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,
            },
          }}
        /> */}
        
       <SortableTaskContainer  
          useDragHandle
          disableAutoscroll
          helperClass="row-dragging"
          onSortEnd={this.onTaskSortEnd} 
        >
          {dataSource.map((item, index) =>
            <SortableTaskItem taskItem={this.renderTaskItem(item,index)} index={index}>
            </SortableTaskItem>
          )}
       </SortableTaskContainer>
       
        <div className="add-task-con">
          {dataSource.length > 9 ?
          <span className="add-task-btn-disabled"><span>+</span><span>添加任务</span></span>
          :
          <span className="add-task-btn" onClick={()=>this.addTask()}><span>+</span><span>添加任务</span></span>
          }
        </div>
        { relatedCourseModalVisible &&
          <RelatedCourseModal
            selectedTaskIndex={selectedTaskIndex}
            data={dataSource}
            visible={relatedCourseModalVisible}
            onClose={this.closeRelatedCourseModal}
            onSelect={this.confirmSelectCourse}
          />
        }
      </div>
    );
  }
}

export default withRouter(TrainingTask)
