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

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

import { RangePicker, CourseCatalogSelect } from '@/modules/common'
import ShowTips from '@/components/ShowTips'
import Breadcrumbs from '@/components/Breadcrumbs'
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 ImgClipModal from '@/components/ImgClipModal'
import './AddOfflineCourse.less'
import Bus from '@/core/bus'

const { Option } = Select
const defaultCoverUrl = 'https://image.xiaomaiketang.com/xm/pxbWKsYA87.png'
const unitList = [
  { key: 'HOUR', value: '小时' },
  { key: 'MINUTE', value: '分钟' },
]

class AddOfflineCourse extends React.Component {
  constructor(props) {
    super(props)

    const courseId = window.getParameterByName('id')
    const pageType = window.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, // 是否显示截图弹窗
      studentModal: false,
      categoryName: null, //分类名称
      categoryList: [],
      courseCatalogList: [], //分类列表
      categoryId: null, //分类的Id值
      whetherVisitorsJoin: 'NO', // 是否允许游客加入
      isContent: true,
      teacherList: [],
      teacherQuery: {
        size: 15,
        current: 1,
        nickName: null,
      },
      calendarTime: [],
      offlineCourseType: 'ALL_DAY_OFFLINE',
      signInType: 'START_AGO',
      signOutType: 'START_LATER',
      oldQuta: null,
      quota: null,
      signInTimeNum: null,
      signOutEndTimeNum: null,
      signOutStartTimeNum: null,
      signInTimeUnit: 'MINUTE',
      signOutStartTimeUnit: 'MINUTE',
      signOutEndTimeUnit: 'MINUTE',
      whetherSetApply: 'YES',
      whetherSetSignIn: 'YES',
      whetherSetSignOut: 'YES',
      isEditDisablie: false,
      startTime: new Date().getTime() + 300000, // 批量开始时分
      endTime: new Date().getTime() + 300000, // 批量结束时分
    }
  }

  componentWillMount() {
    const { courseId, pageType } = this.state
    this.getCourseCatalogList()
    this.getTeacherList()
    if (pageType === 'edit') {
      this.handleFetchScheudleDetail(courseId)
    }
    Bus.bind('editorLimit', (editorTextLength) => {
      this.setState({
        editorTextLength,
      })
    })
  }

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

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

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

  //获取分类列表
  getCourseCatalogList = () => {
    Service.Hades('public/hades/queryCategoryTree', { source: 0, tenantId: User.getStoreId(), count: false, userId: User.getUserId() }).then((res) => {
      const { categoryList = [] } = res.result
      this.setState({
        categoryList,
        courseCatalogList: this.renderTreeNodes(categoryList),
      })
    })
  }

  renderTreeNodes = (data) => {
    let newTreeData = data.map((item) => {
      item.title = item.categoryName
      item.value = item.id
      item.key = item.id
      if (item.sonCategoryList) {
        item.children = this.renderTreeNodes(item.sonCategoryList)
      }
      return item
    })
    return newTreeData
  }

  checkDetail = (courseId) => {
    return Service.Hades('public/hades/getOfflineCourseDetail', {
      courseId,
    }).then((res) => {
      const { courseState } = res.result
      return courseState === 'UN_START'
    })
  }

  // 获取线下活动详情
  handleFetchScheudleDetail = (courseId) => {
    return 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,
        signInTimeNum,
        signInTimeUnit,
        signOutStartTimeNum,
        signOutStartTimeUnit,
        signOutEndTimeNum,
        signOutEndTimeUnit,
        signInType,
        signOutType,
        whetherHaveApply,
      } = 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: quota < 0 ? null : quota,
        oldQuta: quota,
        calendarTime,
        signInTimeNum,
        signInTimeUnit,
        signOutStartTimeNum,
        signOutStartTimeUnit,
        signOutEndTimeNum,
        signOutEndTimeUnit,
        signInType,
        signOutType,
        isEditDisablie: whetherHaveApply === 'YES',
      })
    })
  }

  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`,
      })
    }
  }

  // 显示预览弹窗
  handleShowPreviewModal = () => {
    const {
      coverUrl,
      courseName,
      teacherName,
      startTime,
      endTime,
      introduce,
      categoryName,
      offlinePlace,
      whetherSetApply,
      startTimeApply,
      endTimeApply,
      whetherSetSignIn,
      whetherSetSignOut,
      signInType,
      signOutType,
      signInTimeNum,
      signInTimeUnit,
      signOutStartTimeNum,
      signOutStartTimeUnit,
      signOutEndTimeNum,
      signOutEndTimeUnit,
    } = this.state

    const data = {
      coverUrl,
      courseName,
      teacherName,
      startTime,
      endTime,
      categoryName,
      introduce,
      offlinePlace,
      whetherSetApply,
      startTimeApply,
      endTimeApply,
      whetherSetSignIn,
      whetherSetSignOut,
      signInType,
      signOutType,
      signInTimeNum,
      signInTimeUnit,
      signOutStartTimeNum,
      signOutStartTimeUnit,
      signOutEndTimeNum,
      signOutEndTimeUnit,
    }
    const previewOfflineModal = (
      <PreviewOfflineModal
        data={data}
        close={() => {
          this.setState({
            previewOfflineModal: null,
          })
        }}
      />
    )

    this.setState({ previewOfflineModal })
  }

  handleSelectCover = (file) => {
    this.setState({
      visible: true,
      imageFile: file,
    })
  }

  //获取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,
    })
  }

  preSubmit = () => {
    //过期判断
    if (User.getExpirationTime() && moment().valueOf() > Number(User.getExpirationTime())) {
      Modal.warning({
        title: '服务已到期',
        content: '当前企业购买的小麦企学院服务已到期，如需继续使用学院功能，请尽快续费购买',
        okText: '我知道了',
      })
      return
    }
    const { courseId } = this.state
    if (courseId) {
      this.checkDetail(courseId).then((bool) => (bool ? this.handleSubmit() : message.warning('课程已开始，无法继续编辑')))
    } else {
      this.handleSubmit()
    }
  }

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

    let coverObj = {
      contentType: 'COVER',
      mediaContent: coverId,
      mediaType: 'PICTURE',
      mediaUrl: coverUrl,
    }
    let scheduleMediaRequests = []
    if (coverId) {
      scheduleMediaRequests = [coverObj]
    }

    // 编辑且使用默认图时不传
    if (pageType === 'edit' && coverUrl === defaultCoverUrl) {
      scheduleMediaRequests = []
    }
    const commonParams = {
      categoryId,
      courseName,
      scheduleMediaRequests,
      storeId: User.getStoreId(),
      offlinePlace,
      whetherVisitorsJoin,
      whetherSetApply,
      whetherSetSignIn,
      whetherSetSignOut,
      teacherId,
      offlineCourseType,
      startTime,
      endTime,
      calendarTime,
      editorTextLength,
      // isMore,
    }

    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
      if (commonParams.signOutType === 'START_LATER') {
        commonParams.signOutStartTimeNum = signOutStartTimeNum
        commonParams.signOutStartTimeUnit = signOutStartTimeUnit
      }
      commonParams.signOutEndTimeNum = signOutEndTimeNum
      commonParams.signOutEndTimeUnit = signOutEndTimeUnit
    }

    // 校验必填字段:课程名称, 课程线下
    this.handleValidate(commonParams).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) => {
    return new Promise((resolve) => {
      if (!data.courseName) {
        message.warning('请输入课程名称')
        resolve(false)
      } else if (!data.categoryId) {
        message.warning('请选择课程分类')
        resolve(false)
      } else if (!data.offlinePlace) {
        message.warning('请输入上课地点')
        resolve(false)
      } else if (!data.teacherId) {
        message.warning('请选择讲师')
        resolve(false)
      } else if (_.isEmpty(data.calendarTime)) {
        message.warning('请选择上课日期')
        resolve(false)
      } else if (!data.startTime || !data.endTime) {
        message.warning('请选择上课时间')
        resolve(false)
      } else if (moment(moment(data.calendarTime[0]).format('YYYY-MM-DD') + moment(data.startTime).format(' HH:mm')).valueOf() < Date.now()) {
        message.warning('上课时间不能早于现在')
        resolve(false)
      } else if (data.startTime >= data.endTime) {
        message.warning('上课结束时间不能早于上课开始时间')
        resolve(false)
      } else if (data.whetherSetApply === 'YES' && !data.startTimeApply) {
        message.warning('请选择报名时间')
        resolve(false)
      } else if (data.whetherSetApply === 'YES' && data.startTimeApply >= data.endTimeApply) {
        message.warning('报名结束时间需大于报名开始时间')
        resolve(false)
      } else if (
        data.whetherSetApply === 'YES' &&
        data.endTimeApply > moment(moment(data.calendarTime[0]).format('YYYY-MM-DD') + moment(data.endTime).format(' HH:mm:ss')).valueOf()
      ) {
        message.warning('报名结束时间需小于上课开始时间')
        resolve(false)
      } else if (data.whetherSetSignIn === 'YES' && !data.signInTimeNum) {
        message.warning('请输入签到时间')
        resolve(false)
      } else if (data.whetherSetSignOut === 'YES' && ((data.signOutType === 'START_LATER' && !data.signOutStartTimeNum) || !data.signOutEndTimeNum)) {
        message.warning('请输入签退时间')
        resolve(false)
      } else if (data.editorTextLength > 1000) {
        message.warning('课程简介超过字数限定')
        resolve(false)
      } else {
        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 = [], 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].startOf('minute').valueOf() + 59000
    }
    this.setState(data)
  }

  whetherVisitorsJoinChange = () => {
    const { whetherSetApply, whetherVisitorsJoin } = this.state
    if (whetherSetApply == 'NO') {
      message.warning('关闭报名无法获取手机号!')
      return
    }
    if (this.state.whetherVisitorsJoin === 'NO') {
      this.setState({ whetherVisitorsJoin: 'YES' })
    } else {
      this.setState({ whetherVisitorsJoin: 'NO' })
    }
  }

  handleChangeCatalogList = (value, label) => {
    this.setState({ categoryId: value, categoryName: label[0] })
  }

  render() {
    const {
      courseId,
      pageType,
      courseName,
      coverUrl,
      introduce,
      categoryId,
      courseCatalogList,
      whetherVisitorsJoin,
      loadintroduce,
      showSelectCoverModal,
      visible,
      teacherId,
      teacherList,
      calendarTime,
      startTime,
      endTime,
      offlineCourseType,
      whetherSetApply,
      whetherSetSignIn,
      whetherSetSignOut,
      startTimeApply,
      endTimeApply,
      signInTimeUnit,
      signInTimeNum,
      signOutEndTimeNum,
      signOutEndTimeUnit,
      signOutStartTimeNum,
      signOutStartTimeUnit,
      signInType,
      signOutType,
      oldQuta,
      quota,
      offlinePlace,
      isEditDisablie,
      imageFile,
    } = 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.setState({ courseName: e.target.value })
                  }}
                />
              </div>
              <div className='course-cover'>
                <span className='label'>封面图：</span>

                <div className='course-cover__wrap'>
                  <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或16:9。封面图最大5M，支持jpg、jpeg和png。</div>
                  </div>
                  <div className='img-content'>
                    {isDefaultCover && <span className='tag'>默认图</span>}
                    <img src={coverUrl} />
                  </div>
                </div>
              </div>
              <div className='course-catalog'>
                <span className='label special'>
                  <span className='require'>*</span>课程分类：
                </span>
                <CourseCatalogSelect
                  value={categoryId}
                  onChange={(value, label) => {
                    this.handleChangeCatalogList(value, label)
                  }}
                />
                {/* <TreeSelect
                  showSearch
                  treeNodeFilterProp='title'
                  style={{ width: 240 }}
                  dropdownStyle={{ maxHeight: 300, overflow: 'auto' }}
                  treeData={courseCatalogList}
                  placeholder='请选择课程类型'
                  allowClear
                  value={categoryId}
                  treeDefaultExpandAll
                  onChange={(value, label) => {
                    this.handleChangeCatalogList(value, label)
                  }}
                /> */}
              </div>
              <div className='course-catalog'>
                <span className='label special'>
                  <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 special'>
                  <span className='require'>* </span>讲师：
                </span>
                <Select
                  placeholder='请选择讲师'
                  value={teacherId}
                  style={{ width: 240 }}
                  showSearch
                  allowClear
                  filterOption={(input, option) => option}
                  dropdownClassName='offline-dropdown-box'
                  onPopupScroll={this.handleScrollTeacherList}
                  suffixIcon={
                    <span className='icon iconfont' style={{ fontSize: '12px', color: '#BFBFBF' }}>
                      &#xe835;
                    </span>
                  }
                  onChange={(value, option) => {
                    if (option) {
                      this.setState({ teacherId: value, teacherName: option.children })
                    } else {
                      this.setState({ teacherId: value, teacherName: '' })
                    }
                  }}
                  onSearch={(value) => {
                    let _teacherQuery = { ...this.state.teacherQuery }
                    _teacherQuery.nickName = value
                    this.setState(
                      {
                        teacherQuery: _teacherQuery,
                      },
                      () => {
                        this.getTeacherList()
                      }
                    )
                  }}
                  onClear={(value) => {
                    this.setState(
                      {
                        teacherQuery: {
                          size: 15,
                          current: 1,
                          nickName: null,
                        },
                      },
                      () => {
                        this.getTeacherList()
                      }
                    )
                  }}
                  getPopupContainer={() => document.getElementById('teacher')}>
                  {_.map(teacherList, (item) => {
                    return (
                      <Option value={item.id} key={item.id}>
                        {item.nickName}
                      </Option>
                    )
                  })}
                </Select>
              </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'>{window.isLongArr(calendarTime) ? calendarTime.length : 0}</span> 天
                  </div>
                  <MultipleDatePicker disabled={isEditDisablie} selectDateList={calendarTime} onSelect={this.selectMultiDate} canSelectTodayBefore={false} />
                </div>
              </div>

              <div className='hour' id='hour'>
                <span className='label'>
                  <span className='require'>*</span>上课时间：
                </span>
                <TimePicker
                  disabled={isEditDisablie}
                  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
                  disabled={isEditDisablie}
                  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'
                  disabled={isEditDisablie}>
                  <Radio value='ALL_DAY_OFFLINE' className='mr-16'>
                    <span style={{ color: '#333' }}>所选日期都要上课</span>
                  </Radio>
                  <Radio value='ANY_DAY_POFFLINE' 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
                      disabled={isEditDisablie}
                      checked={whetherSetApply === 'YES'}
                      onChange={(value) => {
                        this.setState({
                          whetherSetApply: value ? 'YES' : 'NO',
                          startTimeApply: undefined,
                          endTimeApply: undefined,
                          quota: null,
                          whetherVisitorsJoin: value ? whetherVisitorsJoin : 'YES',
                        })
                      }}
                    />
                    <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)
                        }}
                        renderExtraFooter={() => (
                          <If condition={calendarTime[0]}>
                            <div style={{ position: 'absolute', bottom: 8, cursor: 'pointer' }}>
                              <span
                                onClick={() =>
                                  this.setState({
                                    startTimeApply: moment(`${moment(calendarTime[0]).format('YYYY-MM-DD')} ${moment(startTime).format('HH:mm')}`)
                                      .subtract(1, 'days')
                                      .valueOf(),
                                    endTimeApply:
                                      moment(`${moment(calendarTime[0]).format('YYYY-MM-DD')} ${moment(startTime).format('HH:mm')}`).valueOf() - 1000,
                                  })
                                }
                                style={{
                                  color: '#2966FF',
                                  border: '1px solid #2966FF',
                                  padding: '2px 8px',
                                  borderRadius: '2px',
                                  marginRight: 8,
                                }}>
                                上课前1天
                              </span>
                              <span
                                onClick={() =>
                                  this.setState({
                                    startTimeApply: moment(`${moment(calendarTime[0]).format('YYYY-MM-DD')} ${moment(startTime).format('HH:mm')}`)
                                      .subtract(2, 'days')
                                      .valueOf(),
                                    endTimeApply:
                                      moment(`${moment(calendarTime[0]).format('YYYY-MM-DD')} ${moment(startTime).format('HH:mm')}`).valueOf() - 1000,
                                  })
                                }
                                style={{
                                  color: '#2966FF',
                                  border: '1px solid #2966FF',
                                  padding: '2px 8px',
                                  borderRadius: '2px',
                                  marginRight: 8,
                                }}>
                                上课前2天
                              </span>
                              <span
                                onClick={() =>
                                  this.setState({
                                    startTimeApply: moment(`${moment(calendarTime[0]).format('YYYY-MM-DD')} ${moment(startTime).format('HH:mm')}`)
                                      .subtract(3, 'days')
                                      .valueOf(),
                                    endTimeApply:
                                      moment(`${moment(calendarTime[0]).format('YYYY-MM-DD')} ${moment(startTime).format('HH:mm')}`).valueOf() - 1000,
                                  })
                                }
                                style={{
                                  color: '#2966FF',
                                  border: '1px solid #2966FF',
                                  padding: '2px 8px',
                                  borderRadius: '2px',
                                  marginRight: 8,
                                }}>
                                上课前3天
                              </span>
                            </div>
                          </If>
                        )}
                      />
                    </div>
                  )}
                  {whetherSetApply === 'YES' && (
                    <div className='switch-item' key='3'>
                      <span className='switch-label'>
                        报名人数
                        <Tooltip title='报名一旦开始，报名人数不支持减少'>
                          <span style={{ margin: '0 4px', color: '#999' }} className='icon iconfont'>
                            &#xe7c4;
                          </span>
                        </Tooltip>
                        ：最多
                      </span>
                      <InputNumber
                        value={quota}
                        min={oldQuta || 1}
                        max={100000}
                        precision={0}
                        style={{ margin: '0 4px', width: 90 }}
                        disabled={oldQuta < 0}
                        onChange={(value) => {
                          this.setState({ quota: value })
                        }}
                      />
                      <span className='switch-label'>人</span>
                      <span className='switch-tip'>未填写时默认为不限制</span>
                    </div>
                  )}
                </div>
              </div>
              <div className='allow-tourist-join'>
                <span className='label'>观看设置：</span>
                <div className='content'>
                  <Switch checked={whetherVisitorsJoin === 'NO' ? true : false} onChange={this.whetherVisitorsJoinChange} />
                  <div className='desc'>
                    {whetherVisitorsJoin === 'NO' ? '已开启，仅限绑定了手机号的学员报名线下活动' : '已关闭，允许未绑定手机号的学员报名线下活动'}
                  </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',
                          signInType: 'START_AGO',
                          signInTimeNum: null,
                          signInTimeUnit: 'MINUTE',
                        })
                      }}
                    />
                    <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'>课程{signInType === 'START_AGO' ? '开始' : '结束'}前</span>
                      <InputNumber
                        value={signInTimeNum}
                        min={1}
                        max={signInTimeUnit === 'MINUTE' ? 1440 : 24}
                        precision={0}
                        style={{ margin: '0 4px', width: 90 }}
                        onChange={(value) => {
                          this.setState({ signInTimeNum: value })
                        }}
                      />
                      <Select
                        style={{ width: 72, marginRight: 4 }}
                        value={signInTimeUnit}
                        onChange={(value) => {
                          const data = { signInTimeUnit: value }
                          if (value === 'HOUR' && signInTimeNum > 24) {
                            data.signInTimeNum = 24
                          }
                          this.setState(data)
                        }}>
                        {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',
                          signOutType: 'START_LATER',
                          signOutStartTimeNum: null,
                          signOutStartTimeUnit: 'MINUTE',
                          signOutEndTimeNum: null,
                          signOutEndTimeUnit: 'MINUTE',
                        })
                      }}
                    />
                    <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'>课程{signOutType === 'START_LATER' ? '开始' : '结束'}后</span>
                      {signOutType === 'START_LATER' && (
                        <InputNumber
                          value={signOutStartTimeNum}
                          min={1}
                          max={signOutStartTimeUnit === 'MINUTE' ? 1440 : 24}
                          precision={0}
                          style={{ margin: '0 4px', width: 90 }}
                          onChange={(value) => {
                            this.setState({ signOutStartTimeNum: value })
                          }}
                        />
                      )}
                      {signOutType === 'START_LATER' && (
                        <Select
                          style={{ width: 72, marginRight: 4 }}
                          value={signOutStartTimeUnit}
                          onChange={(value) => {
                            const data = { signOutStartTimeUnit: value }
                            if (value === 'HOUR' && signOutStartTimeNum > 24) {
                              data.signOutStartTimeNum = 24
                            }
                            this.setState(data)
                          }}>
                          {unitList.map((item) => (
                            <Option value={item.key} key={item.key}>
                              {item.value}
                            </Option>
                          ))}
                        </Select>
                      )}
                      {signOutType === 'START_LATER' && <span className='switch-label'>就可签退，截止签退时间为下课后</span>}
                      <InputNumber
                        value={signOutEndTimeNum}
                        min={1}
                        max={signOutEndTimeUnit === 'MINUTE' ? 1440 : 24}
                        precision={0}
                        style={{ margin: '0 4px', width: 90 }}
                        onChange={(value) => {
                          this.setState({ signOutEndTimeNum: value })
                        }}
                      />
                      <Select
                        style={{ width: 72, marginRight: 4 }}
                        value={signOutEndTimeUnit}
                        onChange={(value) => {
                          const data = { signOutEndTimeUnit: value }
                          if (value === 'HOUR' && signOutEndTimeNum > 24) {
                            data.signOutEndTimeNum = 24
                          }
                          this.setState(data)
                        }}>
                        {unitList.map((item) => (
                          <Option value={item.key} key={item.key}>
                            {item.value}
                          </Option>
                        ))}
                      </Select>
                      {signOutType !== 'START_LATER' && <span className='switch-label'>内可签退</span>}
                    </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.preSubmit(), 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}
          />
        )}
        {visible && (
          <ImgClipModal
            visible={visible}
            imgUrl={imageFile.ossUrl}
            onConfirm={this.getSignature}
            onClose={() => {
              this.setState({ visible: false })
            }}
          />
        )}
        {this.state.previewOfflineModal}
      </div>
    )
  }
}

export default AddOfflineCourse
