/*
 * @Author: zhangleyuan
 * @Date: 2021-02-20 16:45:51
 * @LastEditors: zhangleyuan
 * @LastEditTime: 2021-03-11 18:27:36
 * @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 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(){
  
  }

  componentWillReceiveProps(nextProps) {
    
  }
  
  onTaskSortEnd = ({ oldIndex, newIndex }) => {
    const { dataSource } = this.state;

    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;
  
    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);})
    }

  };
  
  addTask = () => {
    const { dataSource } = this.state;
    const taskObj={
      taskName: '',
      index:dataSource.length,
      type:'input',
      open:true,
      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; 
    let input  = /^[\s]*$/;
    if(value && !input.test(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;
    let input  = /^[\s]*$/;
    if(value && !input.test(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);})
  }
  handleValidatorTaskName = (rule,value)=>{
    let input  = /^[\s]*$/;
    if (input.test(value) || !value){
      return Promise.reject(new Error('请输入任务名称'))
    }
    return  Promise.resolve()
  }
  handleValidatorCourseName = (rule,value)=>{
    let input  = /^[\s]*$/;
    if (input.test(value) || !value){
      return Promise.reject(new Error('请输入课程名称'))
    }
    return  Promise.resolve()
  }
  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={[
                          {
                            validator:(rule,value)=>this.handleValidatorTaskName(rule,value)
                          }
                        ]}>
                          <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={[
                      {
                        validator:(rule,value)=>this.handleValidatorCourseName(rule,value)
                      }
                    ]}>
                      <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">
       <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)
