/*
 * @Author: 吴文洁
 * @Date: 2020-08-05 10:07:47
 * @LastEditors: zhangleyuan
 * @LastEditTime: 2021-03-29 14:08:47
 * @Description: 线下课新增/编辑页
 * @Copyright: 杭州杰竞科技有限公司 版权所有
 */

import React from 'react';
import {
  Button,
  Input, 
  Radio, 
  message, 
  Modal, 
  Cascader, 
  Select, 
  Switch,
  TimePicker,
  InputNumber,
} from 'antd';
import $ from 'jquery';

import RangePicker from "@/modules/common/DateRangePicker";
import ShowTips from "@/components/ShowTips";
import Breadcrumbs from "@/components/Breadcrumbs";
import SelectStudent from '../modal/select-student';
import SelectPrepareFileModal from '../../prepare-lesson/modal/SelectPrepareFileModal';
import PreviewOfflineModal from './modal/PreviewOfflineModal';
import StoreService from "@/domains/store-domain/storeService";
import Service from '@/common/js/service';
import { randomString } from '@/domains/basic-domain/utils';
import User from '@/common/js/user';
import _ from "underscore";
import moment from 'moment';
import Upload from '@/core/upload';
import GraphicsEditor from '../components/GraphicsEditor';
import MultipleDatePicker from '@/components/MultipleDatePicker';
import './AddOfflineCourse.less';

const EDIT_BOX_KEY = Math.random();
const fieldNames  = { label: 'categoryName', value: 'id', children: 'sonCategoryList' };
const { Option } = Select;
//添加课程时课程默认的一些值
const whetherVisitorsJoin = 'NO'
const defaultCoverUrl = 'https://image.xiaomaiketang.com/xm/YNfi45JwFA.png';
let cutFlag = false;
const unitList = [
  { key: 'DAY', value: '天' },
  { key: 'HOUR', value: '小时' },
  { key: 'MINUTE', value: '分钟' },
]

class AddOfflineCourse extends React.Component {

  constructor(props) {
    super(props);

    const courseId = getParameterByName("id");
    const pageType = getParameterByName("type");

    this.state = {
      courseId,                        // 线下课ID,编辑的时候从URL上带过来
      pageType,                  // 页面类型: add->新建 edit->编辑
      imageFile: null,           // 需要被截取的图片
      courseName: null,        // 线下课名称
      courseMedia: '',
      introduce: '',
      coverId: null,             // 线下封面的recourceId
      coverUrl: defaultCoverUrl,            // 线下课封面
      studentList: [],           // 上课学员列表
      diskList: [],              // 机构可见磁盘目录
      selectedFileList: [],      // 已经从资料云盘中勾选的文件
      showCutModal: false,       // 是否显示截图弹窗
      showSelectVideoModal: false,
      studentModal: false,
      categoryName:null, //分类名称
      courseCatalogList:[], //分类列表
      categoryId:null, //分类的Id值
      whetherVisitorsJoin: 'NO', // 是否允许游客加入
      isContent: true,
      teacherList: [],
      teacherQuery: {
        size: 15,
        current: 1,
        nickName:null
      },
      calendarTime: [],
      offlineCourseType: 'ANY_DAY_POFFLINE',
      signInType: 'START_AGO',
      signOutType: 'START_LATER',
      quota: 1,
      signInTimeNum: 1,
      signOutEndTimeNum: 1,
      signOutStartTimeNum: 1,
      signInTimeUnit: 'MINUTE',
      signOutStartTimeUnit: 'MINUTE',
      signOutEndTimeUnit: 'MINUTE',
      whetherSetApply: 'YES',
      whetherSetSignIn: 'YES',
      whetherSetSignOut: 'YES',
    }
  }

  componentWillMount() {
    const { courseId, pageType } = this.state;
    this.getCourseCatalogList();
    this.getTeacherList();
    if (pageType === 'edit') {
      this.handleFetchScheudleDetail(courseId);
    }
  }

  initBus = () => {
    Bus.bind('offlineEditorImage', this.uploadImage)
    Bus.bind('offlineEditorVideo', this.uploadVideo)
  }

  removeBus = () => {
    Bus.unbind('offlineEditorImage', this.uploadImage)
    Bus.unbind('offlineEditorVideo', this.uploadVideo)
  }

  uploadImage = () => {
    this.setState({ showSelectImageModal: true })
  }

  uploadVideo = () => {
    this.setState({ showSelectVideoModal: true })
  }

  //获取分类列表
  getCourseCatalogList = ()=>{
    Service.Hades('public/hades/queryCategoryTree', { source: 0, tenantId: User.getStoreId(), count: false, userId: User.getUserId() }).then((res) => {
        this.setState({
          courseCatalogList: res.result.categoryList
        })
    });
  }
  
  catalogChange= (value, options) => {
    this.setState({ categoryId: _.last(value), categoryName: _.pluck(options, 'categoryName').join('-') })
  }
  // 获取线下课详情
  handleFetchScheudleDetail = (courseId) => {
    Service.Hades('public/hades/getOfflineCourseDetail',{
      courseId
    }).then((res) => {
      const { result = {} } = res || {};
      const {
        courseName,
        categoryId,
        offlinePlace,
        whetherVisitorsJoin,
        whetherSetApply,
        whetherSetSignIn,
        whetherSetSignOut,
        teacherId,
        teacherName,
        offlineCourseType,
        startTime,
        endTime,
        startTimeApply,
        endTimeApply,
        quota,
        calendarTime,
        courseMediaVOS,
        categoryName,
      } = result;
      let coverId;
      let coverUrl = this.state.coverUrl;
      let hasIntro = false;
      
      courseMediaVOS.map((item) => {
        switch (item.contentType){
          case "COVER":
            coverId = item.mediaContent;
            coverUrl = item.mediaUrl;
          break;
          case "SCHEDULE":
            this.getTextDetail('courseMedia', item.mediaUrl);
            break;
          case "INTRO":
            hasIntro = true;
            this.getTextDetail('introduce', item.mediaUrl);
            break;  
          default:
            break;
        }
        return item;
      })
      this.setState({
        loadintroduce: !hasIntro,
        coverId,
        coverUrl,
        categoryName,
        courseName,
        categoryId,
        offlinePlace,
        whetherVisitorsJoin,
        whetherSetApply,
        whetherSetSignIn,
        whetherSetSignOut,
        teacherId,
        teacherName,
        offlineCourseType,
        startTime,
        endTime,
        startTimeApply,
        endTimeApply,
        quota,
        calendarTime,
      });
    })
  }

  getTextDetail = (key, url) => {
    $.ajax({
      data: {},
      type: 'GET',
      url,
      contentType:'application/x-www-form-urlencoded; charset=UTF-8',
      success: (res) => {
        this.setState({ [key]: res, [`load${key}`]: true });
      }
    })
  }

  handleGoBack = () => {
    const {
      coverId,
      videoName,
      videoDuration,
      courseName,
      categoryId,
      whetherVisitorsJoin
    } = this.state;
    if(videoName || videoDuration || categoryId || courseName || coverId || whetherVisitorsJoin !== whetherVisitorsJoin ){
      Modal.confirm({
        title: '确认要返回吗?',
        content: '返回后，本次编辑的内容将不被保存。',
        okText: '确认返回',
        cancelText: '留在本页',
        icon: <span className="icon iconfont default-confirm-icon">&#xe6f4;</span>,
        onOk: () => {
          window.RCHistory.push({
            pathname: `/offline-course`,
          });
        }
      });
    }else{
      window.RCHistory.push({
        pathname: `/offline-course`,
      });
    }
  }

  // 修改表单
  handleChangeForm = (field, value, coverUrl) => {
    this.setState({
      [field]: value,
      coverUrl: coverUrl ? coverUrl : this.state.coverUrl
    });
  }
  
  // 显示选择学员弹窗
  handleShowSelectStuModal = () => {
    this.setState({ studentModal : true });

    const { studentList, selectedStuList } = this.state;
    // const _studentList = _.map(studentList, (item) => { 
    //   return item.studentId
    // })
    const studentModal = (
      <SelectStudent
        showTabs={true}
        type="videoCourse"
        onSelect={this.handleSelectStudent}
        after={true} //表明是不是上课后的状态
        studentList={studentList}
        close={() => {
          this.setState({
            studentModal: null,
          });
        }}
      />
    )
    this.setState({ studentModal });
  }

  handleSelectStudent = (studentIds) => {
    let studentList = [];
    _.each(studentIds, (item) => {
      studentList.push({ studentId: item });
    });
    // this.setState({ studentModal: null });
    this.setState({ studentList  });
    this.setState({ studentModal : false });
  }
  
  // 显示预览弹窗
  handleShowPreviewModal = () => {
    const {
      coverUrl,
      courseName,
      startTime,
      endTime,
      introduce,
      categoryName,
      offlinePlace,
    } = this.state;

    const data = {
      coverUrl,
      courseName,
      startTime,
      endTime,
      categoryName,
      introduce,
      offlinePlace,
    }
    const previewOfflineModal = (
      <PreviewOfflineModal
        data={data}
        close={() => {
          this.setState({
            previewOfflineModal: null
          })
        }}
      />
    );

    this.setState({ previewOfflineModal });
  }

  handleSelectCover = (file)=> {
    this.uploadCoverImage(file);
  }
  
  //上传图片
  uploadCoverImage = (imageFile) => {
    const { folderName } = imageFile;
    const fileName = window.random_string(16) + folderName.slice(folderName.lastIndexOf("."));
    const self = this;
    this.setState(
      {
        visible: true,
      },
      () => {
        setTimeout(() => {
          const okBtnDom = document.querySelector("#headPicModal");
          const options = {
            size: [500, 282],
            ok: okBtnDom,
            maxZoom: 3,
            style: {
              jpgFillColor: "transparent",
            },
            done: function (dataUrl) {
              clearTimeout(self.timer);
              self.timer = setTimeout(() => {
                if ((self.state.rotate != this.rotate()) || (self.state.scale != this.scale())) {
                  const _dataUrl = this.clip()
                  const cutImageBlob = self.convertBase64UrlToBlob(_dataUrl);
                  self.setState({
                    cutImageBlob,
                    dataUrl: _dataUrl,
                    rotate: this.rotate(),
                    scale: this.scale()
                  })
                }

              }, 500)

              const cutImageBlob = self.convertBase64UrlToBlob(dataUrl);
              self.setState({
                cutImageBlob,
                dataUrl
              })
              setTimeout(() => {
                cutFlag = false;
              }, 2000);
            },
            fail: (failInfo) => {
              message.error("图片上传失败了，请重新上传");
            },
            loadComplete: function (img) {
              setTimeout(() => {
                const _dataUrl = this.clip()
                self.setState({
                  dataUrl: _dataUrl,
                  hasImgReady: true 
                })
              }, 100)

            },
          };
          const imgUrl = `${imageFile.ossUrl}?${new Date().getTime()}`
          if (!this.state.photoclip) {
            const _photoclip = new PhotoClip("#headPicModal", options);
            _photoclip.load(imgUrl);
            this.setState({
              photoclip: _photoclip,
            });
          } else {
            this.state.photoclip.clear();
            this.state.photoclip.load(imgUrl);
          }

        }, 200);
      }
    );
  };

  //获取resourceId
  getSignature = (blob, fileName) => {
    Upload.uploadBlobToOSS(blob, 'cover' + (new Date()).valueOf(),null,'signInfo').then((signInfo) => {
      this.setState({
        coverClicpPath:signInfo.fileUrl,
        coverId:signInfo.resourceId,
        visible: false
      },()=>this.updateCover())
    
    });
  };

  updateCover = () =>{
    const {coverClicpPath,coverId} = this.state
    this.setState({
      showSelectCoverModal: false,
      coverUrl:coverClicpPath,
      coverId:coverId
    })
  }

   // base64转换成blob
  convertBase64UrlToBlob = (urlData) => {
    const bytes = window.atob(urlData.split(",")[1]);
    const ab = new ArrayBuffer(bytes.length);
    const ia = new Uint8Array(ab);
    for (let i = 0; i < bytes.length; i++) {
      ia[i] = bytes.charCodeAt(i);
    }
    return new Blob([ab], { type: "image/png" });
  };

  // 保存
  handleSubmit = () => {
    const {
      courseId,
      coverId,
      pageType,
      courseName,
      courseMedia,
      introduce,
      categoryId,
      offlinePlace,
      whetherVisitorsJoin,
      whetherSetApply,
      whetherSetSignIn,
      whetherSetSignOut,
      teacherId,
      coverUrl,
      offlineCourseType,
      startTime,
      endTime,
      startTimeApply,
      endTimeApply,
      quota,
      calendarTime,
      signInType,
      signInTimeNum,
      signInTimeUnit,
      signOutType,
      signOutStartTimeNum,
      signOutStartTimeUnit,
      signOutEndTimeNum,
      signOutEndTimeUnit,
    } = this.state;

    let coverObj ={
      contentType:'COVER',
      mediaContent: coverId,
      mediaType:'PICTURE',
      mediaUrl: coverUrl,
    }
    let scheduleMediaRequests = [];
    if(coverId){
      scheduleMediaRequests = [coverObj]
    }
    const commonParams = {
      categoryId,
      courseName,
      scheduleMediaRequests,
      storeId: User.getStoreId(),
      offlinePlace,
      whetherVisitorsJoin,
      whetherSetApply,
      whetherSetSignIn,
      whetherSetSignOut,
      teacherId,
      offlineCourseType,
      startTime,
      endTime,
      calendarTime,
    };

    if (whetherSetApply === 'YES') {
      commonParams.startTimeApply = startTimeApply;
      commonParams.endTimeApply = endTimeApply;
      commonParams.quota = quota;
    }

    if (whetherSetSignIn === 'YES') {
      commonParams.signInType = signInType;
      commonParams.signInTimeNum = signInTimeNum;
      commonParams.signInTimeUnit = signInTimeUnit;
    }

    if (whetherSetSignOut === 'YES') {
      commonParams.signOutType = signOutType;
      commonParams.signOutStartTimeNum = signOutStartTimeNum;
      commonParams.signOutStartTimeUnit = signOutStartTimeUnit;
      commonParams.signOutEndTimeNum = signOutEndTimeNum;
      commonParams.signOutEndTimeUnit = signOutEndTimeUnit;
    }

    // 校验必填字段:课程名称, 课程线下
    this.handleValidate({ courseName, courseMedia, categoryId }).then((res) => {
      if (!res) return;
      Upload.uploadTextToOSS(introduce, `${randomString()}.txt`, (introduceId) => {
        this.submitRemote({
          courseId,
          pageType,
          commonParams,
          introduceId,
        });
      }, () => message.warning('上传课程简介失败'));
    });
  }

  submitRemote = (data) => {
    const { courseId, pageType, commonParams, introduceId } = data;
    commonParams.introduceId = introduceId;
    if (pageType === 'add') {
      Service.Hades('public/hades/createOfflineCourse', commonParams).then((res) => {
        if (!res) return;
        message.success("新建成功");
        window.RCHistory.push({
          pathname: `/offline-course`,
        });
      })
    } else {
      const editParams = {
        courseId:courseId,
        ...commonParams,
      }
      Service.Hades('public/hades/updateOfflineCourse', editParams).then((res) => {
        if (!res) return;
        message.success("保存成功");
        window.RCHistory.push({
          pathname: `/offline-course`,
        });
      });
    }
  }

  handleValidate = (data) => {
    const { courseName, categoryId } = data;
    return new Promise((resolve) => {
      if (!courseName) {
        message.warning('请输入课程名称');
        resolve(false);
        return false
      }
      if(!categoryId){
        message.warning('请选择课程分类');
        resolve(false);
        return false
      }
      resolve(true);
    });
  }

  // 使用默认封面图
  handleResetCoverUrl = () => {
    const { coverUrl } = this.state;
    const isDefaultCover = coverUrl === defaultCoverUrl;
    // 如果已经是默认图的话，不做任何任何处理
    if (isDefaultCover) return;
    message.success('已替换为默认图');
    this.setState({ coverUrl: defaultCoverUrl });
  }

  // 滑动加载更多讲师列表
  handleScrollTeacherList = (e) => {
   const { hasNext } = this.state;
   const container = e.target;

   //判定元素是否滚动到底部
   const scrollToBottom = container &&  container.scrollHeight <= container.clientHeight + container.scrollTop;
   if (scrollToBottom && hasNext) {
     const { teacherQuery } = this.state;
     let _teacherQuery = teacherQuery;
     _teacherQuery.current = _teacherQuery.current + 1
     this.setState({
       teacherQuery:{..._teacherQuery}
     },()=>{this.getTeacherList(_teacherQuery.current)})
   }
  }
  
  getTeacherList(current = 1, selectList){
    const { teacherQuery,teacherList} = this.state;
    const _query = {
      ...teacherQuery,
      current,
      size:15
    };
    StoreService.getStoreUserBasicPage( _query).then((res) => {
        const { result = {} } = res;
        const { records = [], total = 0, hasNext } = result;
        const list = current > 1 ? teacherList.concat(records) : records;
        this.setState({
          hasNext,
          teacherList: list,
          teacherQuery:{..._query}
        })
    });
  }

  changeIntro = (value) => {
    this.setState({ introduce: value });
  }

  selectMultiDate = (calendarTime) => {
    const dateList = _.sortBy(calendarTime);
    this.setState({
      calendarTime: dateList,
    })
  }

  handleChangeDates = (dates) => {
    const data = {};
    if (_.isEmpty(dates)) {
      data.startTimeApply = undefined;
      data.endTimeApply = undefined;
    } else {
      data.startTimeApply = dates[0].valueOf();
      data.endTimeApply = dates[1].valueOf();
    }
    this.setState(data);
  }

  whetherVisitorsJoinChange = ()=>{
    if(this.state.whetherVisitorsJoin === "NO"){
      this.setState({ whetherVisitorsJoin: 'YES' });
    }else{
      this.setState({ whetherVisitorsJoin: 'NO' });
    }
  }

  render() {
    const {
      courseId,
      pageType,
      courseName,
      coverUrl,
      introduce,
      categoryName,
      courseCatalogList,
      whetherVisitorsJoin,
      loadintroduce,
      showSelectCoverModal,
      visible,
      hasImgReady,
      cutImageBlob,
      teacherName,
      teacherList,
      calendarTime,
      startTime,
      endTime,
      offlineCourseType,
      whetherSetApply,
      whetherSetSignIn,
      whetherSetSignOut,
      startTimeApply,
      endTimeApply,
      signInTimeUnit,
      signInTimeNum,
      signOutEndTimeNum,
      signOutEndTimeUnit,
      signOutStartTimeNum,
      signOutStartTimeUnit,
      signInType,
      signOutType,
      quota,
      offlinePlace,
    } = this.state;
    const isDefaultCover = coverUrl === defaultCoverUrl;
    return (
      <div className="page add-offline-course-page">
        <Breadcrumbs
          navList={pageType === "add" ? "新建线下课" : "编辑线下课"}
          goBack={this.handleGoBack}
        />

        <div className="box">
          <div className="show-tips">
            <ShowTips message="请遵守国家相关规定，切勿上传低俗色情、暴力恐怖、谣言诈骗、侵权盗版等相关内容，小麦企培保有依据国家规定及平台规则进行处理的权利" />
          </div>

          <div className="form">
            <div className="basic-info__wrap">
              <div className="title">基本信息</div>
              <div className="course-name">
                <span className="label"><span className="require">*</span>课程名称：</span>
                <Input
                  value={courseName}
                  placeholder="请输入线下课的名称（40字以内）"
                  maxLength={40}
                  style={{ width: 240 }}
                  onChange={(e) => { this.handleChangeForm('courseName', e.target.value)}}
                />
              </div>
              <div className="course-cover">
                <span className="label">封面图：</span>

                <div className="course-cover__wrap">
                  
                  <div className="img-content">
                  {
                    isDefaultCover && <span className="tag">默认图</span>
                  }
                    <img src={coverUrl} />
                  </div>
                  <div className="opt-btns">
                    <Button onClick={() => {
                      this.setState({
                        showSelectCoverModal: true
                      })
                    }}>上传图片</Button>
                    <span
                      className={`default-btn ${isDefaultCover ? 'disabled' : ''}`}
                      onClick={this.handleResetCoverUrl}
                    >使用默认图</span>
                    <div className="tips">建议尺寸1280*720px，图片支持jpg、jpeg、png格式。</div>
                  </div>
                </div>
              </div>
              <div className="course-catalog">
                <span className="label"><span className="require">*</span>课程分类：</span>
                { (pageType === 'add') && 
                  <Cascader
                    showSearch
                    defaultValue={categoryName ? [categoryName] : undefined} 
                    options={courseCatalogList} 
                    displayRender={	label => label.join('-')}  
                    fieldNames={fieldNames}
                    onChange={this.catalogChange}
                    style={{ width: 240 }}
                    placeholder="请选择课程分类" suffixIcon={<span className="icon iconfont" style={{ fontSize: '12px', color: '#BFBFBF' }}>&#xe835;</span>}
                  />
                }
                { (pageType === 'edit' && categoryName ) && 
                  <Cascader 
                    showSearch
                    defaultValue={[categoryName]} 
                    options={courseCatalogList} 
                    displayRender={	label => label.join('-')}  
                    fieldNames={fieldNames}
                    onChange={this.catalogChange}
                    style={{ width: 240 }}
                    placeholder="请选择课程分类"
                    suffixIcon={<span className="icon iconfont" style={{ fontSize: '12px', color: '#BFBFBF' }}>&#xe835;</span>}
                  />
                }
              </div>
              <div className="course-catalog">
                <span className="label"><span className="require">*</span>上课地点：</span>
                <Input
                  value={offlinePlace}
                  maxLength={40}
                  style={{ width: 240 }}
                  placeholder="请输入上课地点（40字以内）"
                  onChange={(e) => {
                    this.setState({ offlinePlace: e.target.value })
                  }}
                />
              </div>
              <div className="course-catalog" id="teacher">
                <span className="label"><span className="require">* </span>讲师：</span>
                <Select
                  placeholder="请选择讲师"
                  value={teacherName}
                  style={{ width: 240 }}
                  disabled={pageType === 'edit' ? true: false}
                  showSearch
                  allowClear
                  filterOption={(input, option) => option}
                  onPopupScroll={this.handleScrollTeacherList}
                  suffixIcon={<span className="icon iconfont" style={{fontSize:'12px',color:'#BFBFBF'}}>&#xe835;</span>}
                  onChange={(value,option) => {
                    if (option) {
                      this.setState({ teacherId: value, teacherType: option.children });
                    }else{
                      this.setState({ teacherId: value, teacherType: "" });
                    }
                  }}
                  onSearch={(value) => {
                    teacherQuery.nickName = value
                    this.setState({
                      teacherQuery
                    }, () => {
                      this.getTeacherList()
                    })
                  }}
                  onClear ={(value)=>{
                    this.setState({
                      teacherQuery:{
                        size: 15,
                        current: 1,
                        nickName:null
                      }
                    }, () => {
                      this.getTeacherList()
                    })
                  }
                }
                  getPopupContainer={() =>
                    document.getElementById("teacher")
                  }
                >
                  {_.map(teacherList, (item, index) => {
                    return (
                      <Option value={item.id} key={item.id}>{item.nickName}</Option>
                    );
                  })}
                </Select>
              </div>
              <div className="allow-tourist-join">
                <span className="label">观看设置：</span>
                <div className="content">
                  <div>
                    <Switch
                      checked={whetherVisitorsJoin === "YES" ? true : false}
                      onChange={this.whetherVisitorsJoinChange}
                    />
                  </div>  
                  <div>
                    <div className="desc">
                      <div>开启：允许未绑定手机号的用户观看</div>
                      <div>关闭：仅限绑定了手机号的用户可以进入观看图文课</div>
                    </div>
                  </div> 
                </div>
              </div>
              <div className="introduce">
                <span className="label">课程简介：</span>
                <div className="content">
                  <div className="intro-list">
                    <div className="intro-list__item introduce-editor">
                      {(!courseId || loadintroduce) &&
                        <GraphicsEditor
                          id="intro"
                          isIntro={true}
                          maxLimit={1000}
                          detail={{
                            content: introduce
                          }}
                          onChange={(val) => { this.changeIntro(val) }}
                        />
                      }
                    </div>
                  </div>
                </div>
              </div>
              <div className="title" style={{ marginTop: 24 }}>课程设置</div>
              <div className="day">
                <span className="label">
                  <span className="require">*</span>
                    上课日期：
                  </span>
                <div>
                  <div className='select-day'>
                    已选 <span className="mark-day">{isLongArr(calendarTime) ? calendarTime.length : 0}</span> 天
                  </div>
                  <MultipleDatePicker
                    selectDateList={calendarTime}
                    onSelect={this.selectMultiDate}
                    canSelectTodayBefore={false}
                  />
                </div>
                
              </div>
              
              <div className="hour" id="hour">
                <span className="label"><span className="require">*</span>上课时间：</span>
                <TimePicker
                  className="time-picker"
                  format="HH:mm"
                  value={startTime ? moment(startTime) : null}
                  placeholder="开始时间"
                  showNow={false}
                  style={{ width: 100, minWidth: 100}}
                  onSelect={(time) => {
                    this.setState({ startTime: time });
                  }}
                  getPopupContainer={() =>
                    document.getElementById("hour")
                  }
                />&nbsp;&nbsp;~&nbsp;&nbsp; 
                <TimePicker
                  className="time-picker"
                  format="HH:mm"
                  value={endTime ? moment(endTime) : null}
                  placeholder="结束时间"
                  showNow={false}
                  style={{ width: 100, minWidth: 100 }}
                  onSelect={(time) => {
                    this.setState({ endTime: time });
                  }}
                  getPopupContainer={() =>
                    document.getElementById("hour")
                  }
                />
              </div>
              <div className="course-catalog">
                <span className="label"><span className="require">* </span>用户上课方式：</span>
                <Radio.Group
                  style={{ display: 'inline-block' }}
                  value={offlineCourseType}
                  onChange={(e) => {
                    this.setState({ offlineCourseType: e.target.value });
                  }}
                  className="mt5"
                >
                  <Radio value="ANY_DAY_POFFLINE" className="mr-16">
                    <span style={{ color: "#333" }}>所选日期都要上课</span>
                  </Radio>
                  <Radio value="ALL_DAY_OFFLINE" className="mr-16">
                    <span style={{ color: "#333" }}>选择任意1天上课</span>
                  </Radio>
                </Radio.Group>
              </div>
              <div className="course-catalog">
                <span className="label">课程报名：</span>
                <div className="switch-box">
                  <div className="switch-item" key="1">
                    <Switch checked={whetherSetApply === 'YES'} onChange={(value) => this.setState({ whetherSetApply: value ? 'YES' : 'NO' })} />
                    <span className="switch-tip">开启后可设置课程报名时间，获取报名数据</span>
                  </div>
                  {whetherSetApply === 'YES' && <div className="switch-item" key="2">
                    <span className="switch-label">报名日期：</span>
                    <RangePicker
                      id="course_date_picker"
                      showTime={{ showTime: 'HH:mm' }}
                      allowClear={false}
                      value={startTimeApply ? [moment(startTimeApply), moment(endTimeApply)] : null }
                      format={"YYYY-MM-DD HH:mm"}
                      onChange={(dates) => { this.handleChangeDates(dates) }}
                      style={{ width: "calc(100% - 70px)" }}
                    />
                  </div>}
                  {whetherSetApply === 'YES' && <div className="switch-item" key="3">
                    <span className="switch-label">报名人数：最多</span>
                    <InputNumber
                      value={quota}
                      style={{ margin: '0 4px' }}
                      onChange={(value) => {
                        const number = (value + '').replace(/[^\d]/g, '');
                        this.setState({ quota: number })
                      }}
                    />
                    <span className="switch-label">人</span>
                  </div>}
                </div>
              </div>
              <div className="course-catalog">
                <span className="label">考勤签到：</span>
                <div className="switch-box">
                  <div className="switch-item" key="1">
                    <Switch checked={whetherSetSignIn === 'YES'} onChange={(value) => this.setState({ whetherSetSignIn: value ? 'YES' : 'NO' })} />
                    <span className="switch-tip">开启后可设置获取签到考勤数据</span>
                  </div>
                  {whetherSetSignIn === 'YES' && <div className="switch-item" key="2">
                    <span className="switch-label">签到时间：</span>
                    <Radio.Group
                      style={{ display: 'inline-block' }}
                      value={signInType}
                      onChange={(e) => {
                        this.setState({ signInType: e.target.value });
                      }}
                      className="mt5"
                    >
                      <Radio value="START_AGO" className="mr-16">
                        <span style={{ color: "#333" }}>课程开始前</span>
                      </Radio>
                      <Radio value="END_AGO" className="mr-16">
                        <span style={{ color: "#333" }}>课程结束前</span>
                      </Radio>
                    </Radio.Group>
                  </div>}
                  {whetherSetSignIn === 'YES' && <div className="switch-item" key="3">
                    <span className="switch-label">课程开始前</span>
                    <InputNumber
                      value={signInTimeNum}
                      style={{ margin: '0 4px' }}
                      onChange={(value) => {
                        const number = (value + '').replace(/[^\d]/g, '');
                        this.setState({ signInTimeNum: number });
                      }}
                    />
                    <Select
                      style={{ width: 72, marginRight: 4 }}
                      value={signInTimeUnit}
                      onChange={(value) => {
                        this.setState({ signInTimeUnit: value });
                      }}
                    >
                      {unitList.map(item => (
                        <Option value={item.key} key={item.key}>{item.value}</Option>
                      ))}
                    </Select>
                    <span className="switch-label">内可签到</span>
                  </div>}
                </div>
              </div>
              <div className="course-catalog">
                <span className="label">考勤签退：</span>
                <div className="switch-box">
                  <div className="switch-item" key="1">
                    <Switch checked={whetherSetSignOut === 'YES'} onChange={(value) => this.setState({ whetherSetSignOut: value ? 'YES' : 'NO' })} />
                    <span className="switch-tip">开启后可设置获取签退考勤数据</span>
                  </div>
                  {whetherSetSignOut === 'YES' && <div className="switch-item" key="2">
                    <span className="switch-label">签退时间：</span>
                    <Radio.Group
                      style={{ display: 'inline-block' }}
                      value={signOutType}
                      onChange={(e) => {
                        this.setState({ signOutType: e.target.value });
                      }}
                      className="mt5"
                    >
                      <Radio value="START_LATER" className="mr-16">
                        <span style={{ color: "#333" }}>课程开始后</span>
                      </Radio>
                      <Radio value="END_LATER" className="mr-16">
                        <span style={{ color: "#333" }}>课程结束后</span>
                      </Radio>
                    </Radio.Group>
                  </div>}
                  {whetherSetSignOut === 'YES' && <div className="switch-item" key="3">
                    <span className="switch-label">课程开始后</span>
                    <InputNumber
                      value={signOutStartTimeNum}
                      style={{ margin: '0 4px' }}
                      onChange={(value) => {
                        const number = (value + '').replace(/[^\d]/g, '');
                        this.setState({ signOutStartTimeNum: number });
                      }}
                    />
                    <Select
                      style={{ width: 72, marginRight: 4 }}
                      value={signOutStartTimeUnit}
                      onChange={(value) => {
                        this.setState({ signOutStartTimeUnit: value });
                      }}
                    >
                      {unitList.map(item => (
                        <Option value={item.key} key={item.key}>{item.value}</Option>
                      ))}
                    </Select>
                    <span className="switch-label">就可签退，截止签退时间为下课后</span>
                    <InputNumber
                      value={signOutEndTimeNum}
                      style={{ margin: '0 4px' }}
                      onChange={(value) => {
                        const number = (value + '').replace(/[^\d]/g, '');
                        this.setState({ signOutEndTimeNum: number });
                      }}
                    />
                    <Select
                      style={{ width: 72, marginRight: 4 }}
                      value={signOutEndTimeUnit}
                      onChange={(value) => {
                        this.setState({ signOutEndTimeUnit: value });
                      }}
                    >
                      {unitList.map(item => (
                        <Option value={item.key} key={item.key}>{item.value}</Option>
                      ))}
                    </Select>
                  </div>}
                </div>
              </div>
            </div>
          </div>
        </div>

        <div className="footer">
          <Button onClick={this.handleGoBack}>取消</Button>
          <Button onClick={this.handleShowPreviewModal}>预览</Button>
          <Button type="primary" onClick={_.debounce(() => this.handleSubmit(), 3000, true)}>保存</Button>
        </div>
        
        {showSelectCoverModal && 
          <SelectPrepareFileModal
            key="basic"
            operateType="select"
            multiple={false}
            accept="image/jpeg,image/png,image/jpg"
            selectTypeList={['JPG', 'JPEG', 'PNG']}
            tooltip='支持文件类型：jpg、jpeg、png'
            isOpen={showSelectCoverModal}
            onClose={() => {
              this.setState({ showSelectCoverModal: false })
            }}
            onSelect={this.handleSelectCover}
          />
        }
        <Modal
          title="设置图片"
          width={1080}
          visible={visible}
          maskClosable={false}
          closeIcon={<span className="icon iconfont modal-close-icon">&#xe6ef;</span>}
          onCancel={() => {
            this.setState({ visible: false });
          }}
          zIndex={10001}
          footer={[
            <Button
              key="back"
              onClick={() => {
                this.setState({ visible: false });
              }}
            >
              重新上传
            </Button>,
            <Button
              key="submit"
              type="primary"
              disabled={!hasImgReady}
              onClick={() => {
                if (!cutFlag) {
                  cutFlag = true;
                  this.refs.hiddenBtn.click();
                }
                this.getSignature(cutImageBlob);
              }}
            >
              确定
            </Button>,
          ]}
        >
          <div className="clip-box">
            <div
              id="headPicModal"
              ref="headPicModal"
              style={{
                width: "500px",
                height: "430px",
                marginBottom: 0,
              }}
            ></div>
            <div id="clipBtn" style={{ display: "none" }} ref="hiddenBtn"></div>
            <div className="preview-img">
              <div className="title">效果预览</div>
              <div id="preview-url-box" style={{width:500,height:282}}>
                <img src={this.state.dataUrl} style={{ width: '100%' }} alt="" />
              </div>
              <div className="tip-box">
                <div className="tip">温馨提示</div>
                <div className="tip">①预览效果图时可能存在延迟，单击左侧图片刷新即可</div>
                <div className="tip">②设置图片时双击可旋转图片，滚动可放大或缩小图片</div>
              </div>
            </div>
          </div>
        </Modal>
        { this.state.previewOfflineModal }
      </div>
    )
  }
}

export default AddOfflineCourse;
