/*
 * @Author: yuananting
 * @Date: 2021-07-30 16:33:58
 * @LastEditors: yuananting
 * @LastEditTime: 2021-08-16 22:10:08
 * @Description: 任务中心-培训任务-新建-培训内容
 * @Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 * @@Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */
import React, { Component } from 'react';
import { Form, Input, Collapse, Dropdown, Menu, Modal } 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 ENUM from '../../enum';
import FormItem from 'antd/lib/form/FormItem';

const { Panel } = Collapse;
const { confirm } = Modal;

const SortableStageContainer = sortableContainer((props) => <div {...props}></div>);
const SortableStageItem = sortableElement((props) => <div {...props}>{props.stageitem}</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 = ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十'];

class TrainContent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      basicInfo: props.basicInfo,
      stageList: props.stageList,
      percentCompleteLive: props.percentCompleteLive,
      percentCompleteVideo: props.percentCompleteVideo,
      percentCompletePicture: props.percentCompletePicture,
      showCourseDrawer: false,
      showExamDrawer: false,
      selectedStageIndex: 0,
      type: window.getParameterByName('type'),
      showStandardDetail: false, // 是否展开高级设置
    };
  }

  componentDidMount() { }

  setTrianTypeOption = (index) => {
    return (
      <Menu>
        <Menu.Item key='course' onClick={() => this.setState({ showCourseDrawer: true, selectedStageIndex: index })}>
          <img className='type-option-icon' src={ENUM.LearningContentIcon['COURSE']} />
          <span className='type-option-text'>课程</span>
        </Menu.Item>
        <Menu.Item key='exam' onClick={() => this.setState({ showExamDrawer: true, selectedStageIndex: index })}>
          <img className='type-option-icon' src={ENUM.LearningContentIcon['EXAM']} />
          <span className='type-option-text'>考试</span>
        </Menu.Item>
        {/* <Menu.Item key='homework'>
          <img className='type-option-icon' src={ENUM.LearningContentIcon['HOMEWORK']} />
          <span className='type-option-text'>实操作业</span>
        </Menu.Item> */}
      </Menu>
    );
  };

  onStageSortEnd = ({ oldIndex, newIndex }) => {
    const { stageList } = this.state;

    if (oldIndex !== newIndex) {
      const _stageList = arrayMove([].concat(stageList), oldIndex, newIndex).filter((el) => !!el);
      this.setState(
        {
          stageList: _stageList,
        },
        () => {
          this.props.onChange('stageList', _stageList);
        }
      );
    }
  };

  onContentSortEnd = ({ oldIndex, newIndex }, parentIndex) => {
    const { stageList } = this.state;

    const _stageList = [...stageList];
    if (oldIndex !== newIndex) {
      _stageList[parentIndex].contentList = arrayMove([].concat(stageList[parentIndex].contentList), oldIndex, newIndex).filter((el) => !!el);
      this.setState(
        {
          stageList: _stageList,
        },
        () => {
          this.props.onChange('stageList', _stageList);
        }
      );
    }
  };

  handleRenameStageName = (value, item) => {
    const { stageList } = this.state;
    item.stageName = value;
    item.check = true;
    this.setState(
      {
        stageList,
      },
      () => {
        this.props.onChange('stageList', stageList);
      }
    );
  };

  handleStageNameBlur = (e, item, currentIndex) => {
    const { value } = e.target;
    const { stageList } = this.state;
    const sameStageName = stageList.filter((item, index) => {
      return item.stageName === value && index !== currentIndex;
    });
    if (sameStageName.length > 0) {
      return;
    }
    let input = /^[\s]*$/;
    if (value && !input.test(value)) {
      item.type = 'text';
      this.setState(
        {
          stageList,
        },
        () => {
          this.props.onChange('stageList', stageList);
        }
      );
    }
  };

  handleValidatorStageName = (value, currentIndex) => {
    const { stageList } = this.state;
    const sameStageName = stageList.filter((item, index) => {
      return item.stageName === value && index !== currentIndex;
    });
    let input = /^[\s]*$/;
    if (input.test(value) || !value) {
      return '请输入阶段名称';
    } else if (sameStageName.length > 0) {
      return '阶段名称已存在';
    }
    return false;
  };

  // 移除阶段
  handleDeleteStage = (index) => {
    return confirm({
      title: '删除阶段',
      content: '删除该阶段会连同课程、作业、考试一起删除，删除后不可恢复，是否仍要删除？',
      icon: <span className='icon iconfont default-confirm-icon'>&#xe839; </span>,
      okText: '删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        this.handleConfirmDeleteStage(index);
      },
    });
  };

  handleConfirmDeleteStage = (index) => {
    const { stageList } = this.state;
    const _stageList = [...stageList];
    _stageList.splice(index, 1);
    this.setState(
      {
        stageList: _stageList,
      },
      () => {
        this.props.onChange('stageList', _stageList);
      }
    );
  };

  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 { stageList } = this.state;
    const _stageList = [...stageList];
    const selectData = [..._stageList[parentIndex].contentList];
    selectData.splice(index, 1);
    _stageList[parentIndex].contentList = selectData;
    this.setState(
      {
        stageList: _stageList,
      },
      () => {
        this.props.onChange(_stageList);
      }
    );
  };

  renderStageInfo = (item, index) => {
    const { startCheck } = this.props;
    return (
      <div className='sort-stage-item'>
        <div className='item-info'>
          <span className='info-number'>{SortConvert[index]}、</span>
          <Choose>
            <When condition={item.type === 'input'}>
              <Form>
                <Form.Item
                  initialValue={item.stageName}
                  validateStatus={(item.check || startCheck) && this.handleValidatorStageName(item.stageName, index) ? 'error' : ''}
                  help={(item.check || startCheck) && this.handleValidatorStageName(item.stageName, index)}>
                  <Input
                    className='info-input'
                    style={{ width: 300 }}
                    placeholder='请输入阶段名称'
                    maxLength={20}
                    value={item.stageName}
                    onChange={(e) => {
                      this.handleRenameStageName(e.target.value, item);
                    }}
                    onBlur={(e) => {
                      this.handleStageNameBlur(e, item, index);
                    }}
                  />
                </Form.Item>
              </Form>
            </When>
            <Otherwise>
              <span className='info-text'>{item.stageName}</span>
            </Otherwise>
          </Choose>
        </div>
        <span className='item-operate'>
          <span
            className='operate__item'
            onClick={(e) => {
              if (item.type === 'input') return;
              const { stageList } = this.state;
              item.type = 'input';
              item.check = true;
              this.setState({ stageList });
              e.stopPropagation();
            }}>
            <span className='icon iconfont'>&#xe6f5;</span>
            <span className='text'>重命名</span>
          </span>
          <span
            className='operate__item'
            style={{ marginLeft: 16 }}
            onClick={(e) => {
              this.handleDeleteStage(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.contentList.map((contentItem, contentIndex) => (
              <SortableContentItem
                contentitem={this.renderContentItem(contentItem, contentIndex, index)}
                index={contentIndex}
                key={contentIndex}></SortableContentItem>
            ))}
          </SortableContentContainer>
          <Dropdown overlay={this.setTrianTypeOption(index)}>
            <span className={`add-content-btn ${item.contentList.length === 20 && 'disabled'}`}>+ 添加学习内容</span>
          </Dropdown>
        </Panel>
      </Collapse>
    );
  };

  renderContentItem = (record, index, parentIndex) => {
    const { courseState, contentName, contentType, courseType, courseChapterNum } = record;
    return (
      <div className='sort-content-item'>
        <div className='content-info'>
          <img className='type-option-icon' src={ENUM.LearningContentIcon[courseType || contentType]} />
          <span className='content-name'>
            {parentIndex + 1}.{index + 1} {contentName}
          </span>
          {courseState === 'EXPIRED' && <span className='icon iconfont tip'>&#xe834;</span>}
          {courseType === 'LIVE' && <span className='extra-info'>{courseStateShow[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 { stageList } = this.state;
    const stageObj = {
      stageName: '',
      type: 'input',
      contentList: [],
      check: false,
    };
    const _stageList = [...stageList, stageObj];
    this.setState(
      {
        stageList: _stageList,
      },
      () => {
        this.props.onChange('stageList', _stageList);
      }
    );
  };

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

  onCloseExamDrawer = () => {
    this.setState({
      showExamDrawer: false,
    });
  };

  confirmSelectCourse = (selectList) => {
    const { selectedStageIndex } = this.state;
    const { stageList } = this.state;
    const _stageList = [...stageList];
    const selectData = [..._stageList[selectedStageIndex].contentList];
    let _selectList = [];
    selectList.forEach((item) => {
      _selectList.push({
        contentId: item.courseId,
        contentName: item.courseName,
        contentType: 'COURSE',
        courseType: item.courseType,
        courseState: item.courseState,
      });
    });
    const _selectData = [...selectData, ..._selectList];
    _stageList[selectedStageIndex].contentList = _selectData;
    this.setState(
      {
        showCourseDrawer: false,
        stageList: _stageList,
      },
      () => {
        console.log('_stageList=============>', _stageList);
        this.props.onChange('stageList', _stageList);
      }
    );
  };

  confirmCreateExam = (examInfo) => {
    const { selectedStageIndex } = this.state;
    const { stageList } = this.state;
    const _stageList = [...stageList];
    const selectData = [..._stageList[selectedStageIndex].contentList];
    const _examInfo = {
      contentId: examInfo.examId,
      contentName: examInfo.examName,
      contentType: 'EXAM',
      paperId: examInfo.paperId,
    };
    selectData.push(_examInfo);
    _stageList[selectedStageIndex].contentList = selectData;
    this.setState(
      {
        showExamDrawer: false,
        stageList: _stageList,
      },
      () => {
        this.props.onChange('stageList', _stageList);
      }
    );
  };

  changePercentComplete = (e, field) => {
    let _percentComplete = 0;
    const value = e.target.value.replace(/\D/g, '');
    if (value > 100) {
      _percentComplete = 100;
    } else {
      if (value < 0) {
        _percentComplete = 0;
      } else {
        _percentComplete = value;
      }
    }
    this.setState(
      {
        [field]: _percentComplete,
      },
      () => {
        this.props.onChange(field, _percentComplete);
      }
    );
  };

  render() {
    const {
      stageList,
      showCourseDrawer,
      showExamDrawer,
      showStandardDetail,
      basicInfo,
      selectedStageIndex,
      percentCompleteLive,
      percentCompleteVideo,
      percentCompletePicture,
    } = this.state;

    const { startCheck } = this.props;

    const taskId = window.getParameterByName('taskId');

    return (
      <div className='train-content-page'>
        <div className='train-content__warp'>
          <SortableStageContainer useDragHandle disableAutoscroll helperClass='row-dragging' onSortEnd={this.onStageSortEnd}>
            {stageList.map((item, index) => (
              <SortableStageItem stageitem={this.renderStageItem(item, index)} index={index} key={index}></SortableStageItem>
            ))}
          </SortableStageContainer>
          {stageList.length < 10 && (
            <div className='add-stage-btn' onClick={() => this.addStage()}>
              + 添加阶段
            </div>
          )}
          {showCourseDrawer && (
            <RelatedCourseDrawer
              data={stageList}
              selectedStageIndex={selectedStageIndex}
              onClose={this.onCloseCourseDrawer}
              onSelect={this.confirmSelectCourse}
            />
          )}
          {showExamDrawer && <RelatedExamDrawer basicInfo={basicInfo} stageList={stageList} onClose={this.onCloseExamDrawer} onSave={this.confirmCreateExam} />}
        </div>

        {
         this.state.type === 'edit' &&  <ExpiredCourseList taskId={taskId} />
        }


        <div className='finish-standard__warp'>
          <div
            className='module-title'
            onClick={() => {
              this.setState({ showStandardDetail: !showStandardDetail });
            }}>
            高级设置
            <span className={`icon iconfont ${showStandardDetail && 'rotate-arrow'}`}>&#xe614;</span>
          </div>
          {showStandardDetail && (
            <div className='detail-container'>
              <div className='title-text'>完成标准：</div>
              <Form className='detail-box'>
                <div className='item-info'>
                  <span>
                    <img src={ENUM.LearningContentIcon['LIVE']} />
                  </span>
                  <span>
                    直播课单个课程，学员学习进度达到
                    <FormItem
                      validateStatus={startCheck && percentCompleteLive === '' ? 'error' : ''}
                      help={startCheck && percentCompleteLive === '' && '请输入完成标准'}>
                      <Input
                        value={percentCompleteLive}
                        onChange={(e) => {
                          this.changePercentComplete(e, 'percentCompleteLive');
                        }}
                        className='input-box'
                      />
                    </FormItem>
                    %，即视为"已完成"学习
                  </span>
                </div>
                <div className='item-info'>
                  <img src={ENUM.LearningContentIcon['VOICE']} />
                  <span>
                    线上课单个课节，学员学习进度达到
                    <FormItem
                      validateStatus={startCheck && percentCompleteVideo === '' ? 'error' : ''}
                      help={startCheck && percentCompleteVideo === '' && '请输入完成标准'}>
                      <Input
                        value={percentCompleteVideo}
                        onChange={(e) => {
                          this.changePercentComplete(e, 'percentCompleteVideo');
                        }}
                        className='input-box'
                      />
                    </FormItem>
                    %，即课节视为"已完成"学习
                  </span>
                </div>
                <div className='item-info'>
                  <img src={ENUM.LearningContentIcon['PICTURE']} />
                  <span>
                    图文课单个课程，学员学习进度达到
                    <FormItem
                      validateStatus={startCheck && percentCompletePicture === '' ? 'error' : ''}
                      help={startCheck && percentCompletePicture === '' && '请输入完成标准'}>
                      <Input
                        value={percentCompletePicture}
                        onChange={(e) => {
                          this.changePercentComplete(e, 'percentCompletePicture');
                        }}
                        className='input-box'
                      />
                    </FormItem>
                    %，即视为"已完成"学习
                  </span>
                </div>
              </Form>
            </div>
          )}
        </div>
      </div>
    );
  }
}

export default TrainContent;
