/*
 * @Author: yuananting
 * @Date: 2021-07-05 10:49:01
 * @LastEditors: yuananting
 * @LastEditTime: 2021-07-05 11:02:04
 * @Description: 描述一下咯
 * @Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 * @@Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */
/*
 * @Author: zhangleyuan
 * @Date: 2021-02-20 16:45:51
 * @LastEditors: yuananting
 * @LastEditTime: 2021-07-01 17:16:50
 * @Description: 描述一下
 * @@Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */
import React from 'react';
import { Input, Form, Modal } from 'antd';
import { sortableContainer, sortableElement, sortableHandle } from 'react-sortable-hoc';

import arrayMove from 'array-move';
import RelatedCourseModal from '../modal/relatedCourseModal';
import { withRouter } from 'react-router-dom';
import './TrainingTask.less';

const { confirm } = Modal;
const CourseType = {
  LIVE: {
    text: '直播课',
  },
  VOICE: {
    text: '线上课',
  },
  RECORD: {
    text: '录播课',
  },
  PICTURE: {
    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) => {
    console.log('selectList', 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='plan-sort-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>
            <Choose>
              <When condition={record.type === 'input'}>
                <div className='task-name-con'>
                  <span className='number'>{index + 1}.</span>
                  <Form>
                    <Form.Item
                      initialValue={record.taskName}
                      validateTrigger={['onChange', 'onBlur']}
                      name={['taskName']}
                      rules={[
                        {
                          validator: (rule, value) => this.handleValidatorTaskName(rule, value),
                        },
                      ]}>
                      <Input
                        className='task-name-input'
                        style={{ width: 300 }}
                        placeholder='请输入任务名称（20字以内）'
                        maxLength={20}
                        onChange={(e) => {
                          this.handleRenameTaskName(e, record);
                        }}
                        onBlur={(e) => {
                          this.handleTaskNameBlur(e, record);
                        }}
                      />
                    </Form.Item>
                  </Form>
                </div>
              </When>
              <Otherwise>
                <div className='task-name-con'>
                  <span className='number'>{index + 1}.</span>
                  <span className='task-name'>{record.taskName}</span>
                </div>
              </Otherwise>
            </Choose>
          </div>
          <div className='operate'>
            <DragHandle />
            <span
              className='operate__item'
              onClick={() => {
                const { dataSource } = this.state;
                record.type = 'input';
                this.setState({ dataSource });
              }}>
              <span className='icon iconfont'>&#xe6f5;</span>
              <span className='text'>重命名</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((item, courseIndex) => (
                <SortableCourseItem courseitem={this.renderCourseItem(item, courseIndex, index)} index={courseIndex} key={courseIndex}></SortableCourseItem>
              ))}
            </SortableCourseContainer>

            <div className='add-course-con'>
              <Choose>
                <When condition={record.courseList.length > 19}>
                  <span
                    className='add-course-btn-disabled'
                    onClick={() => {
                      this.showRelatedCourseModal(index);
                    }}>
                    <span>+</span>
                    <span>关联课程</span>
                  </span>
                </When>
                <Otherwise>
                  <span
                    className='add-course-btn'
                    onClick={() => {
                      this.showRelatedCourseModal(index);
                    }}>
                    <span>+</span>
                    <span>关联课程</span>
                  </span>
                </Otherwise>
              </Choose>
            </div>
          </div>
        )}
      </div>
    );
  };
  renderCourseItem = (record, index, parentIndex) => {
    console.log(record);
    return (
      <div className='plan-course-sort-item'>
        <div className='course-info'>
          <span className='course-type'>{CourseType[record.courseType].text}</span>
          <Choose>
            <When condition={record.type === 'input'}>
              <Form>
                <Form.Item
                  initialValue={record.courseName}
                  validateTrigger={['onChange', 'onBlur']}
                  name={['courseName']}
                  rules={[
                    {
                      validator: (rule, value) => this.handleValidatorCourseName(rule, value),
                    },
                  ]}>
                  <Input
                    className='course-name-input'
                    style={{ width: 300 }}
                    placeholder='请输入课程名称（40字以内）'
                    maxLength={40}
                    onChange={(e) => {
                      this.handleRenameCourseName(e, record);
                    }}
                    onBlur={(e) => {
                      this.handleCourseNameBlur(e, record);
                    }}
                  />
                </Form.Item>
              </Form>
            </When>
            <Otherwise>
              <span className='course-name'>
                {parentIndex + 1}.{index + 1} {record.courseName}
              </span>
            </Otherwise>
          </Choose>

          {record.courseState === 'EXPIRED' && <span className='icon iconfont tip'>&#xe834;</span>}
          {record.courseType === 'LIVE' && <span className='course-state'>{courseStateShow[record.courseState].title}</span>}
          {record.courseType === 'VOICE' && <span>（共{record.courseChapterNum || 1}小节）</span>}
        </div>
        <div className='course-operate'>
          <DragHandle />

          <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;
    console.log('dataSource', dataSource);
    return (
      <div className='training-task'>
        <SortableTaskContainer useDragHandle disableAutoscroll helperClass='row-dragging' onSortEnd={this.onTaskSortEnd} className='plan-task-sort-container'>
          {dataSource.map((item, index) => (
            <SortableTaskItem taskitem={this.renderTaskItem(item, index)} index={index} key={index}></SortableTaskItem>
          ))}
        </SortableTaskContainer>

        <div className='add-task-con'>
          <Choose>
            <When condition={dataSource.length > 9}>
              <span className='add-task-btn-disabled'>
                <span>+</span>
                <span>添加任务</span>
              </span>
            </When>
            <Otherwise>
              <span className='add-task-btn' onClick={() => this.addTask()}>
                <span>+</span>
                <span>添加任务</span>
              </span>
            </Otherwise>
          </Choose>
        </div>
        {relatedCourseModalVisible && (
          <RelatedCourseModal
            selectedTaskIndex={selectedTaskIndex}
            data={dataSource}
            visible={relatedCourseModalVisible}
            onClose={this.closeRelatedCourseModal}
            onSelect={this.confirmSelectCourse}
          />
        )}
      </div>
    );
  }
}

export default withRouter(TrainingTask);
