/*
 * @Author: yuananting
 * @Date: 2021-07-30 16:33:58
 * @LastEditors: yuananting
 * @LastEditTime: 2021-08-03 17:05:23
 * @Description: 任务中心-培训任务-新建-培训内容
 * @Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 * @@Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */
import React, { Component } from 'react';
import { Form, Input, Collapse, Dropdown, Menu } from 'antd';
import { sortableContainer, sortableElement, sortableHandle } from 'react-sortable-hoc';
import arrayMove from 'array-move';
import './TrainContent.less';
import RelatedCourseDrawer from './RelatedCourseDrawer';
import RelatedExamDrawer from './RelatedExamDrawer';
import ExpiredCourseList from './ExpiredCourseList';
import { LearningContentIcon } from '@/common/constants/academic/taskEnum';

const { Panel } = Collapse;

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

const SortableContentContainer = sortableContainer((props) => <div {...props}></div>);
const SortableContentItem = sortableElement((props) => <div {...props}>{props.contentitem}</div>);

const DragHandle = sortableHandle(() => <span className='icon iconfont drag-btn'>&#xe61e;</span>);

const courseStateShow = {
  UN_START: {
    title: '待开播',
  },
  STARTING: {
    title: '直播中',
  },
  FINISH: {
    title: '回放',
  },
  EXPIRED: {
    title: '未成功开课',
  },
};

const SortConvert = {
  1: '一',
  2: '二',
  3: '三',
  4: '四',
  5: '五',
  6: '六',
  7: '七',
  8: '八',
  9: '九',
  10: '十',
};

// const id = window.getParameterByName('id');
// const type = window.getParameterByName('type');

class TrainContent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dataSource: props.data,
      showCourseDrawer: false,
      showExamDrawer: false,
      selectedTaskIndex: 0,
      expiredCourseList: [], // 失效课程
      showStandardDetail: false, // 是否展开高级设置
    };
  }

  componentDidMount() {
    // if (type === 'edit') {
    //   this.getPlanDetail();
    //   this.getPlanCustomerState();
    // }
    // Bus.bind('editorLimit', (editorTextLength) => {
    //   setEditorTextLength(editorTextLength);
    // });
  }

  getPlanDetail = () => {
    PlanService.getTrainingPlanDetail({
      planId: id,
    }).then((res) => {
      const {
        planId,
        planName,
        enableState,
        operateType,
        operateIds,
        percentCompleteLive,
        percentCompleteVideo,
        percentCompletePicture,
        courseMediaVOS,
        trainingTaskList,
      } = res.result;
      let coverId;
      let coverUrl;
      let instro;
      let hasIntro = false;
      courseMediaVOS.map((item) => {
        switch (item.contentType) {
          case 'COVER':
            coverId = item.mediaContent;
            coverUrl = item.mediaUrl;
            break;
          case 'INTRO':
            hasIntro = true;
            instro = item.mediaContent;
            break;
          default:
            break;
        }
        return item;
      });
      let _selectOperatorList = [];
      if (operateIds) {
        _selectOperatorList = operateIds.map((item, index) => {
          let _item = {};
          _item.id = item;
          return _item;
        });
      }
      setTaskList(trainingTaskList);
      setBasicData({
        planId,
        planName,
        coverUrl: coverUrl || defaultCover,
        coverId,
        enableState,
        selectOperatorList: _selectOperatorList,
        instro,
        operateType,
        percentCompleteLive,
        percentCompleteVideo,
        percentCompletePicture,
      });
      setHasGetDetail(true);
    });
  };

  getPlanCustomerState = () => {
    PlanService.getTrainingCourseAutoCancel({
      planId: id,
    }).then((res) => {
      const expiredCourseList = res.result;
      this.setState({ expiredCourseList });
    });
  };

  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 className='type-option-text'>课程</span>
        </Menu.Item>
        <Menu.Item key='exam' onClick={() => this.setState({ showExamDrawer: true })}>
          <img className='type-option-icon' src='https://image.xiaomaiketang.com/xm/M4BEXnRWbb.png' />
          <span className='type-option-text'>考试</span>
        </Menu.Item>
        <Menu.Item key='homework'>
          <img className='type-option-icon' src='https://image.xiaomaiketang.com/xm/ypWQcFWnxB.png' />
          <span className='type-option-text'>实操作业</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);
        }
      );
    }
  };

  onContentSortEnd = ({ 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);
        }
      );
    }
  };

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

  renderStageInfo = (item, index) => {
    return (
      <div className='sort-stage-item'>
        <div className='item-info'>
          <span className='info-number'>{SortConvert[index + 1]}、</span>
          <Choose>
            <When condition={item.type === 'input'}>
              <Form>
                <Form.Item
                  initialValue={item.taskName}
                  validateTrigger={['onChange', 'onBlur']}
                  name={['stageName']}
                  rules={[
                    {
                      validator: (rule, value) => this.handleValidatorTaskName(rule, value),
                    },
                  ]}>
                  <Input
                    className='info-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>
            </When>
            <Otherwise>
              <span className='info-text'>{item.taskName}</span>
            </Otherwise>
          </Choose>
        </div>
        <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>
    );
  };

  renderStageItem = (item, index) => {
    return (
      <Collapse ghost>
        <Panel header={this.renderStageInfo(item, index)} key={index}>
          <SortableContentContainer useDragHandle disableAutoscroll helperClass='row-dragging' onSortEnd={(item) => this.onContentSortEnd(item, index)}>
            {item.courseList.map((contentItem, contentIndex) => (
              <SortableContentItem
                contentitem={this.renderContentItem(contentItem, contentIndex, index)}
                index={contentIndex}
                key={contentIndex}></SortableContentItem>
            ))}
          </SortableContentContainer>
          <Dropdown
            overlay={this.setTrianTypeOption()}
            onClick={() => {
              // this.showRelatedCourseModal(index);
            }}>
            <span className='add-content-btn'>+ 添加学习内容</span>
          </Dropdown>
        </Panel>
      </Collapse>
    );
  };

  renderContentItem = (record, index, parentIndex) => {
    const { courseState, courseName, courseType, courseChapterNum } = record;
    return (
      <div className='sort-content-item'>
        <div className='content-info'>
          <img className='type-option-icon' src={LearningContentIcon[courseType]} />
          <span className='content-name'>
            {parentIndex + 1}.{index + 1} {courseName}
          </span>
          {courseState === 'EXPIRED' && <span className='icon iconfont tip'>&#xe834;</span>}
          {courseType === 'LIVE' && <span className='extra-info'>{courseStateShow[record.courseState].title}</span>}
          {courseType === 'VOICE' && <span className='extra-info'>（共{courseChapterNum || 1}小节）</span>}
        </div>
        <div className='content-operate'>
          <span
            className='operate__item'
            onClick={() => {
              this.handleDeleteCourse(parentIndex, index);
            }}>
            <span className='icon iconfont'>&#xe6f6;</span>
            <span className='text'>删除</span>
          </span>
        </div>
        <DragHandle />
      </div>
    );
  };

  // 添加阶段
  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,
    });
  };

  onCloseExamDrawer = () => {
    this.setState({
      showExamDrawer: 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(
      {
        showCourseDrawer: false,
        dataSource: newData,
      },
      () => {
        this.props.onChange(newData);
      }
    );
  };

  render() {
    const { dataSource, showCourseDrawer, showExamDrawer, expiredCourseList, showStandardDetail } = this.state;
    return (
      <div className='train-content-page'>
        <div className='train-content__warp'>
          <SortableTaskContainer useDragHandle disableAutoscroll helperClass='row-dragging' onSortEnd={this.onTaskSortEnd}>
            {dataSource.map((item, index) => (
              <SortableTaskItem taskitem={this.renderStageItem(item, index)} index={index} key={index}></SortableTaskItem>
            ))}
          </SortableTaskContainer>
          <div className='add-stage-btn' onClick={() => this.addStage()}>
            + 添加阶段
          </div>
          {showCourseDrawer && <RelatedCourseDrawer data={dataSource} onClose={this.onCloseCourseDrawer} onSelect={this.confirmSelectCourse} />}
          {showExamDrawer && <RelatedExamDrawer onClose={this.onCloseExamDrawer} />}
        </div>
        <div className='expired-info__wrap'>
          <div className='module-title'>失效课程</div>
          <ExpiredCourseList expiredCourseList={expiredCourseList} />
        </div>
        <div className='finish-standard__warp'>
          <div className='module-title'>
            高级设置
            <span
              className={`icon iconfont ${showStandardDetail && 'rotate-arrow'}`}
              onClick={() => {
                this.setState({ showStandardDetail: !showStandardDetail });
              }}>
              &#xe614;
            </span>
          </div>
          {showStandardDetail && (
            <div className='detail-container'>
              <div className='title-text'>完成标准：</div>
              <div className='detail-box'>
                <div className='item-info'>
                  <img src={LearningContentIcon['LIVE']} />
                  <span>
                    直播课单个课程，学员学习进度达到
                    <Input
                      // value={percentCompleteLive}
                      onChange={(e) => {
                        // this.props.onChange('percentCompleteLive', e.target.value.replace(/\D/g, ''));
                      }}
                      // onBlur={(e) => this.percentCompleteBlur(e, 'percentCompleteLive')}
                      className='input-box'
                    />
                    %，即视为"已完成"学习
                  </span>
                </div>
                <div className='item-info'>
                  <img src={LearningContentIcon['VOICE']} />
                  <span>
                    线上课单个课节，学员学习进度达到
                    <Input
                      // value={percentCompleteVideo}
                      onChange={(e) => {
                        // this.props.onChange('percentCompleteVideo', e.target.value.replace(/\D/g, ''));
                      }}
                      // onBlur={(e) => this.percentCompleteBlur(e, 'percentCompleteVideo')}
                      className='input-box'
                    />
                    %，即课节视为"已完成"学习
                  </span>
                </div>
                <div className='item-info'>
                  <img src={LearningContentIcon['PICTURE']} />
                  <span>
                    图文课单个课程，学员学习进度达到
                    <Input
                      // value={percentCompletePicture}
                      onChange={(e) => {
                        // this.props.onChange('percentCompletePicture', e.target.value.replace(/\D/g, ''));
                      }}
                      // onBlur={(e) => this.percentCompleteBlur(e, 'percentCompletePicture')}
                      className='input-box'
                    />
                    %，即视为"已完成"学习
                  </span>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    );
  }
}

export default TrainContent;
