/*
 * @Author: yuananting
 * @Date: 2021-07-30 16:33:58
 * @LastEditors: yuananting
 * @LastEditTime: 2021-08-02 11:14:47
 * @Description: 任务中心-培训任务-新建-培训内容
 * @Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 * @@Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */
import React, { Component } from 'react';

import { Form, Button, Input, Space, DatePicker, Radio, Tag, Col, message, Tooltip, Collapse, Dropdown, Menu, Drawer } from 'antd';
import { sortableContainer, sortableElement, sortableHandle } from 'react-sortable-hoc';
import arrayMove from 'array-move';
import './TrainContent.less';
import RelatedCourseDrawer from './RelatedCourseDrawer';

const { Panel } = Collapse;

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

const DragHandle = sortableHandle(() => <span className='drag-btn'>::</span>);

class TrainContent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dataSource: props.data,
      showCourseDrawer: false,
    };
  }

  setTrianTypeOption = () => {
    return (
      <Menu>
        <Menu.Item key='course' onClick={() => this.setState({ showCourseDrawer: true })}>
          <img className='type-option-icon' src='https://image.xiaomaiketang.com/xm/6C2GjSpnDp.png' />
          <span>课程</span>
        </Menu.Item>
        <Menu.Item key='exam'>
          <img className='type-option-icon' src='https://image.xiaomaiketang.com/xm/M4BEXnRWbb.png' />
          <span>考试</span>
        </Menu.Item>
        <Menu.Item key='homework'>
          <img className='type-option-icon' src='https://image.xiaomaiketang.com/xm/ypWQcFWnxB.png' />
          <span>实操作业</span>
        </Menu.Item>
      </Menu>
    );
  };

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

  handleRenameTaskName = (e, item) => {
    const { value } = e.target;
    const { dataSource } = this.state;
    item.taskName = value;
    this.setState(
      {
        dataSource,
      },
      () => {
        this.props.onChange(dataSource);
      }
    );
  };
  handleTaskNameBlur = (e, item) => {
    const { value } = e.target;
    const { dataSource } = this.state;
    let input = /^[\s]*$/;
    if (value && !input.test(value)) {
      item.type = 'text';
      this.setState(
        {
          dataSource,
        },
        () => {
          this.props.onChange(dataSource);
        }
      );
    }
  };

  handleValidatorTaskName = (rule, value) => {
    let input = /^[\s]*$/;
    if (input.test(value) || !value) {
      return Promise.reject(new Error('请输入任务名称'));
    }
    return Promise.resolve();
  };

  renderTaskInfo = (item, index) => {
    return (
      <div className='sort-task-item'>
        <Choose>
          <When condition={item.type === 'input'}>
            <div className='task-name-con'>
              {/* <span className='number'>{index + 1}.</span> */}
              <Form>
                <Form.Item
                  initialValue={item.taskName}
                  validateTrigger={['onChange', 'onBlur']}
                  name={['taskName']}
                  rules={[
                    {
                      validator: (rule, value) => this.handleValidatorTaskName(rule, value),
                    },
                  ]}>
                  <Input
                    className='task-name-input'
                    style={{ width: 300 }}
                    placeholder='请输入阶段名称'
                    maxLength={20}
                    onChange={(e) => {
                      this.handleRenameTaskName(e, item);
                      e.stopPropagation();
                    }}
                    onBlur={(e) => {
                      this.handleTaskNameBlur(e, item);
                      e.stopPropagation();
                    }}
                  />
                </Form.Item>
              </Form>
            </div>
          </When>
          <Otherwise>
            <div className='task-name-con'>
              {/* <span className='number'>{index + 1}.</span> */}
              <span className='task-name'>{item.taskName}</span>
            </div>
          </Otherwise>
        </Choose>
        <span className='item-operate'>
          <span
            className='operate__item'
            onClick={(e) => {
              const { dataSource } = this.state;
              item.type = 'input';
              this.setState({ dataSource });
              e.stopPropagation();
            }}>
            <span className='icon iconfont'>&#xe6f5;</span>
            <span className='text'>重命名</span>
          </span>
          <span
            className='operate__item'
            style={{ marginLeft: 16 }}
            onClick={(e) => {
              this.handleDeleteTask(index);
              e.stopPropagation();
            }}>
            <span className='icon iconfont'>&#xe6f6;</span>
            <span className='text'>删除</span>
          </span>
        </span>
        <DragHandle />
      </div>
    );
  };

  renderTaskItem = (item, index) => {
    return (
      <Collapse ghost>
        <Panel header={this.renderTaskInfo(item, index)} key={index}>
          {/* {renderTaskItem(props.iteminfo, props.index)} */}
          <Dropdown
            overlay={this.setTrianTypeOption()}
            className='add-course-btn'
            onClick={() => {
              // this.showRelatedCourseModal(index);
            }}>
            <span>+ 关联课程</span>
          </Dropdown>
        </Panel>
      </Collapse>
    );
  };

  // 添加阶段
  addStage = () => {
    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);
      }
    );
  };

  onCloseCourseDrawer = () => {
    this.setState({
      showCourseDrawer: false,
    });
  };

  render() {
    const { dataSource, showCourseDrawer } = this.state;
    return (
      <div className='train-content__warp'>
        <SortableTaskContainer useDragHandle disableAutoscroll helperClass='row-dragging' onSortEnd={this.onTaskSortEnd}>
          {dataSource.map((item, index) => (
            <SortableTaskItem taskitem={this.renderTaskItem(item, index)} index={index} key={index}></SortableTaskItem>
          ))}
        </SortableTaskContainer>
        <div className='add-task-btn' onClick={() => this.addStage()}>
          + 添加阶段
        </div>
        <RelatedCourseDrawer data={dataSource} onClose={this.onCloseCourseDrawer} visible={showCourseDrawer} />
      </div>
    );
  }
}

export default TrainContent;
