/*
 * @Author: 吴文洁
 * @Date: 2020-08-05 10:07:47
 * @LastEditors: wufan
 * @LastEditTime: 2021-07-06 13:45:55
 * @Description: 线上课新增/编辑页
 * @Copyright: 杭州杰竞科技有限公司 版权所有
 */

import React from 'react'
import { Button, Input,  message, Modal, Cascader, Tooltip, Form, Popconfirm } from 'antd'
import { FileTypeIcon, FileVerifyMap } from '@/common/constants/academic/lessonEnum'
import ShowTips from '@/components/ShowTips'
import Breadcrumbs from '@/components/Breadcrumbs'
import moment from 'moment'
import AddVideoIntro from './components/AddVideoIntro'
import SelectStudent from '../modal/select-student'
import SelectPrepareFileModal from '../../prepare-lesson/modal/SelectPrepareFileModal'
import PreviewCourseModal from '../modal/PreviewCourseModal'
import StoreService from '@/domains/store-domain/storeService'
import CourseService from '@/domains/course-domain/CourseService'
import Service from '@/common/js/service'
import User from '@/common/js/user'
import _ from 'underscore'
import Upload from '@/core/upload'
import { randomString } from '@/domains/basic-domain/utils'
import $ from 'jquery'
import './AddVideoCourse.less'

const { TextArea } = Input;
const EDIT_BOX_KEY = Math.random()
const fieldNames = { label: 'categoryName', value: 'id', children: 'sonCategoryList' }

//添加课程时课程默认的一些值
const defaultShelfState = 'YES'
const defaultScheduleMedia = [
  {
    contentType: 'INTRO',
    mediaType: 'TEXT',
    mediaContent: '',
    key: EDIT_BOX_KEY
  }
]
const whetherVisitorsJoin = 'NO'

let cutFlag = false
class AddVideoCourse extends React.Component {
  constructor(props) {
    super(props)

    const id = getParameterByName('id')
    const pageType = getParameterByName('type')

    this.state = {
      id, // 线上课ID,编辑的时候从URL上带过来
      pageType, // 页面类型: add->新建 edit->编辑
      imageFile: null, // 需要被截取的图片
      courseName: null, // 线上课名称
      coverId: null, // 视频封面的recourceId
      coverUrl: null, // 线上课封面
      studentList: [], // 上课学员列表
      shelfState: 'YES', //是否开启学院展示
      scheduleMedia: [
        {
          // 线上课媒体资源
          contentType: 'INTRO',
          mediaType: 'TEXT',
          mediaContent: '',
          key: EDIT_BOX_KEY
        }
      ],
      diskList: [], // 机构可见磁盘目录
      selectedFileList: [], // 已经从资料云盘中勾选的文件
      showCutModal: false, // 是否显示截图弹窗
      showSelectFileModal: false,
      studentModal: false,
      categoryName: null, //分类名称
      courseCatalogList: [], //分类列表
      categoryId: null, //分类的Id值
      whetherVisitorsJoin: 'NO', // 是否允许游客加入
      showSelectCoverModal: false,
      cutImageBlob: null,
      introduce: '',
      courseChapterList:[
      ], // 课节列表
      videoType: "MP4",
    }
  }

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

  //获取分类列表
  getCourseCatalogList = () => {
    StoreService.getCourseCatalogList({ current: 1, size: 1000 }).then((res) => {
      this.setState({
        courseCatalogList: res.result.records
      })
    })
  }

  catalogChange = (value, categoryName) => {
    const changeValueLength = value.length
    switch (changeValueLength) {
      case 1:
        this.setState({ categoryId: value[0], categoryName })
        break
      case 2:
        this.setState({ categoryId: value[1], categoryName })
        break
      default:
        this.setState({ categoryId: null })
        break
    }
  }
  // 获取线上课详情
  handleFetchScheudleDetail = (courseId) => {
    CourseService.videoScheduleDetail({
      courseId
    }).then((res) => {
      const { result = {} } = res || {}
      const { courseName, shelfState, whetherVisitorsJoin, courseMediaVOS, categoryOneName, categoryTwoName, categoryId, courseChapterVOList =[] } = result
      let coverId
      let coverUrl
      let videoDuration
      let videoName
      let scheduleMedia = []
      let scheduleVideoUrl
      let hasIntro

      courseMediaVOS.map((item) => {
        switch (item.contentType) {
          case 'COVER':
            coverId = item.mediaContent
            coverUrl = item.mediaUrl
            break
          case 'INTRO':
            hasIntro = true
            this.getTextDetail('introduce', item.mediaUrl)
            break
          default:
            break
        }
        return item
      })

      let categoryName
      if (categoryTwoName) {
        categoryName = `${categoryOneName}-${categoryTwoName}`
      } else {
        categoryName = `${categoryOneName}`
      }

      const _courseChapterVOList = courseChapterVOList.map(item => {
        item.mediaName = item.name;
        item.mediaNameAlias = item.name;
        return item
      })

      this.setState({
        loadintroduce: !hasIntro,
        coverId,
        coverUrl,
        videoName,
        videoDuration,
        scheduleMedia,
        courseName,
        scheduleVideoUrl,
        shelfState,
        whetherVisitorsJoin,
        categoryName,
        categoryId,
        courseChapterList: _courseChapterVOList
      })
    })
  }

  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, scheduleMedia, courseChapterList, categoryId, shelfState, whetherVisitorsJoin } = this.state
    if (
      videoName ||
      videoDuration ||
      !courseChapterList.length ||
      !_.isEqual(scheduleMedia, defaultScheduleMedia) ||
      categoryId ||
      courseName ||
      coverId ||
      shelfState !== defaultShelfState ||
      whetherVisitorsJoin !== whetherVisitorsJoin
    ) {
      Modal.confirm({
        title: '确认要返回吗?',
        content: '返回后，本次编辑的内容将不被保存。',
        okText: '确认返回',
        cancelText: '留在本页',
        icon: <span className='icon iconfont default-confirm-icon'>&#xe6f4;</span>,
        onOk: () => {
          window.RCHistory.push({
            pathname: `/video-course`
          })
        }
      })
    } else {
      window.RCHistory.push({
        pathname: `/video-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 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, scheduleVideoUrl, courseName, scheduleMedia, videoDuration, introduce, courseChapterList, categoryName } = this.state

    const courseBasinInfo = {
      coverUrl,
      scheduleVideoUrl,
      courseName,
      videoDuration
    }
    const courseIntroInfo = {
      liveCourseMediaRequests: scheduleMedia,
      introduce,
      categoryName
    }

    const previewCourseModal = (
      <PreviewCourseModal
        type='videoCourse'
        courseBasicInfo={courseBasinInfo}
        courseIntroInfo={courseIntroInfo}
        close={() => {
          this.setState({
            previewCourseModal: null
          })
        }}
        courseChapterList={courseChapterList}
      />
    )

    this.setState({ previewCourseModal })
  }

  // 选择视频
  handleSelectVideo = (addFolderIds,selectedFileList) => {
    console.log("file-----",selectedFileList);

    this.setState({
      showSelectFileModal: false
    })

    let { courseChapterList } = this.state;
    let _courseChapterList = [...courseChapterList];

    selectedFileList.map((file,index) => {
    const { ossUrl, resourceId, folderName, folderFormat, folderSize } = file;

    const videoDom = document.createElement('video')
    videoDom.src = ossUrl
    videoDom.onloadedmetadata = () => {
      _courseChapterList.push({
        mediaContent: resourceId,
        contentType: 'SCHEDULE',
        mediaType: "VIDEO",
        mediaName: folderName.replace('.mp4',''),
        mediaNameAlias: folderName.replace('.mp4',''),
        videoDuration: videoDom.duration,
        id: resourceId,
        mediaUrl: ossUrl,
        sort: _courseChapterList.length
      })

      this.setState({
        size: folderSize,
        videoName: folderName,
        videoType: folderFormat,
        courseChapterList: _courseChapterList
      })
    }
    })
  }

    // 校验课节名称
    handleValidateChapterName = (chapterName)=> {
      let hasError = false;
      return new Promise((resolve) => {
        if(!chapterName) {
          this.setState({
            chapterNameValidateStatus: "error",
            chapterNameHelpMsg: '请输入课节名称'
          })
          hasError = true;
          resolve(false)
          return false
        }
  
        if(chapterName.length > 40) {
          this.setState({
            chapterNameValidateStatus: "error",
            chapterNameHelpMsg: '不要超过40字'
          })
          hasError = true;
          resolve(false)
          return false
        }
  
        if(!hasError){
          resolve(true)
          this.setState({
            chapterNameValidateStatus: "",
            chapterNameHelpMsg: ""
          })
        }
      })
    }

  // 保存
  handleSubmit = () => {
        //过期判断
        if (User.getExpirationTime() && moment().valueOf() > Number(User.getExpirationTime())) {
          Modal.warning({
            title:"服务已到期",
            content: "当前企业购买的小麦企学院服务已到期，如需继续使用学院功能，请尽快续费购买",
            okText: "我知道了"
          })
          return
        }
    const { instId, adminId } = window.currentUserInstInfo

    const {
      id,
      coverId,
      pageType,
      videoName,
      videoDuration,
      courseName,
      scheduleMedia,
      categoryId,
      shelfState,
      whetherVisitorsJoin,
      introduce,
      courseChapterList
    } = this.state

    const commonParams = {
      videoName,
      videoDuration,
      scheduleMedia: scheduleMedia.filter((item) => !!item.mediaContent),
      categoryId,
      courseName,
      coverId,
      operatorId: User.getStoreUserId(),
      storeId: User.getStoreId(),
      shelfState,
      whetherVisitorsJoin,
      courseType: 'VOICE',
      courseChapterList
    }
    // 校验必填字段:课程名称, 课程视频
    this.handleValidate(courseName, courseChapterList, categoryId, scheduleMedia).then((res) => {
      if (!res) return
      Upload.uploadTextToOSS(introduce, `${randomString()}.txt`, (introduceId) => {
        this.submitRemote({ id, pageType, commonParams: { ...commonParams, introduceId } })
      })
    })
  }

  submitRemote = ({ id, pageType, commonParams }) => {
    if (pageType === 'add') {
      Service.Hades('public/hades/createVideoSchedule', commonParams).then((res) => {
        if (!res) return
        message.success('新建成功')
        window.RCHistory.push({
          pathname: `/video-course`
        })
      })
    } else {
      const editParams = {
        courseId: id,
        ...commonParams
      }
      Service.Hades('public/hades/editVideoSchedule', editParams).then((res) => {
        if (!res) return
        message.success('保存成功')
        window.RCHistory.push({
          pathname: `/video-course`
        })
      })
    }
  }

  handleValidate = (courseName, courseChapterList, categoryId, scheduleMedia) => {
    return new Promise((resolve) => {
      if (!courseName) {
        message.warning('请输入课程名称')
        resolve(false)
        return false
      }
      if (!courseChapterList.length) {
        message.warning('请上传视频')
        resolve(false)
        return false
      }
      if (!categoryId) {
        message.warning('请选择课程分类')
        resolve(false)
        return false
      }
      const textMedia = scheduleMedia.filter((item) => item.mediaType === 'TEXT')
      for (let i = 0, len = textMedia.length; i < len; i++) {
        if (textMedia[i].mediaContentLength && textMedia[i].mediaContentLength.length > 1000) {
          message.warning(`第${i + 1}个文字简介的字数超过了1000个字`)
          resolve(false)
          return false
        }
      }
      resolve(true)
    })
  }
  handleSelectCover = (file) => {
    this.uploadImage(file)
  }

  //上传图片
  uploadImage = (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' })
  }

  handleRenameCourseChapter = (chapterId, isFromTextArea, value) => {
    let val = value && value.trim();

    this.handleValidateChapterName(val).then(res => {
      // 校验不通过不能点确定保存修改课节名称
      if (!res && !isFromTextArea) return;

      let { courseChapterList } = this.state; 
      let  _courseChapterList = [];
      _courseChapterList = courseChapterList.map((item,index)=>{
        if(item.id === chapterId){
          // 若是文本框编辑则修改的是视频别名，否则是点击确认修改视频本名
          if(isFromTextArea){
            item.mediaNameAlias = val;
          } else {
            item.mediaName = item.mediaNameAlias;
          }
        }
        return item
      })
      this.setState({
        courseChapterList: _courseChapterList
      })
    });

  }

  handleDeleteCourseChapter = (chapterId) => {
    console.log('chapterId---',chapterId);
    let { courseChapterList } = this.state; 
    let _courseChapterList = courseChapterList.filter((item,index) => {
        return item.id !== chapterId
    })
    this.setState({
      courseChapterList :_courseChapterList
    })
  }

  renderChapterTitle = (item) => {
    const { chapterNameValidateStatus, chapterNameHelpMsg} = this.state;

    return <div className="course-chapter-title-popover">
      <div className="tag-title">课节名称</div>
        <Form>
          <Form.Item
            validateStatus={chapterNameValidateStatus}
            help={chapterNameHelpMsg}
            >
          <TextArea
            value={item.mediaNameAlias}
            placeholder="请输入课节名称"
            maxLength={40}
            autoSize
            // autoSize={{ minRows: 1, maxRows: 3 }}
            style={{ width: '318px'}}
            onChange={(e) => {this.handleRenameCourseChapter(item.id, true, e.target.value) }}
          />
          </Form.Item>
          </Form>
      </div>
  }

    // 上下移动
    handleChangeIndex = (isUp, sortIndex) => {
      const { courseChapterList} = this.state;
  
      // 第一个上移和最后一个下移不能使用
      if((isUp && sortIndex === 0) || (!isUp && sortIndex === (courseChapterList.length -1))){
        return;
      }
  
      let _courseChapterList = [...courseChapterList];
      const temp =  courseChapterList[sortIndex];
  
      // 若上移
      if(isUp){
        _courseChapterList[sortIndex -1] = temp;
        _courseChapterList[sortIndex -1].sort = sortIndex -1;
        _courseChapterList[sortIndex] = courseChapterList[sortIndex - 1];
        _courseChapterList[sortIndex].sort = sortIndex;
      } else { // 若下移
        _courseChapterList[sortIndex + 1] = temp;
        _courseChapterList[sortIndex + 1].sort = sortIndex + 1;
        _courseChapterList[sortIndex] = courseChapterList[sortIndex + 1];
        _courseChapterList[sortIndex].sort = sortIndex;
      }
  
      this.setState({
        courseChapterList: _courseChapterList
      })
    }

  render() {
    const {
      pageType,
      courseName,
      coverUrl,
      scheduleMedia,
      showSelectFileModal,
      diskList,
      videoType,
      shelfState,
      categoryName,
      courseCatalogList,
      whetherVisitorsJoin,
      visible,
      showSelectCoverModal,
      hasImgReady,
      cutImageBlob,
      introduce,
      loadintroduce,
      id,
      courseChapterList,
      imageFile
    } = this.state

    const courseWareIcon = FileVerifyMap[videoType] ? FileTypeIcon[FileVerifyMap[videoType].type] : FileTypeIcon[videoType]
    const defaultCover = 'https://image.xiaomaiketang.com/xm/mt3ZQRxGKB.png';
    const isDefaultCover = coverUrl === defaultCover || coverUrl == null;

    return (
      <div className='page add-video-course-page'>
        <Breadcrumbs navList={pageType === 'add' ? '新建线上课' : '编辑线上课'} goBack={this.handleGoBack} />

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

          <div className='form'>
            <div className='course-name required'>
              <span className='label'>课程名称：</span>
              <Input
                value={courseName}
                placeholder='请输入线上课的名称（40字以内）'
                maxLength={40}
                style={{ width: 240 }}
                onChange={(e) => {
                  this.handleChangeForm('courseName', e.target.value)
                }}
              />
            </div>

            <div className='upload-video mt16'>
              <div className='content flex'>
                <span className='label required'>视频上传：</span>
              </div>
              <div className='sub-content'>
                <div className="btn-wrap">
                  <Button
                    onClick={() => {
                      if(courseChapterList.length >= 20) {
                        message.warning(`最多只能上传20个文件`);
                        return;
                      }
                      this.setState({
                        showSelectFileModal: true
                      })
                    }}>添加视频</Button>
                  <div className='course-ware--empty'>从资料云盘中选择视频</div>
                </div>
                <div className='tips'>视频数量限制20个，每个视频文件大小不超过2G</div>
              </div>
            </div>

            <If condition={courseChapterList.length > 0}>
                  <div className="course-chapter-list-wrap">
                    <div className="course-chapter-total">{`共${courseChapterList.length}个课节`}</div>
                    <div className='course-chapter-list' id="course-chapter-list">
                    {
                      _.map(courseChapterList,(item,index) => {
                        return <div className='course-ware' key={index}>
                              <div>{`0${index + 1 } `}</div>
                              <img className='course-ware__img' src={courseWareIcon} alt='' />
                              <div className='course-ware__name'>{item.mediaName && item.mediaName.length > 24 ? <Tooltip title={item.mediaName}>{item.mediaName}</Tooltip>:item.mediaName}</div>
                              <div className="course-chapter__opt" id={item.id}>
                                  <div className={`up ${Number(index) === 0 ? 'disabled':''}`} onClick={()=> this.handleChangeIndex(true,item.sort,item.id)}>上移</div>
                                  <div className="line">|</div>
                                  <div className={`down ${Number(index) === (courseChapterList.length - 1) ? 'disabled':''}`} onClick={()=> this.handleChangeIndex(false,item.sort,item.id)}>下移</div>
                                  <div className="line">|</div>
                                  <Popconfirm  
                                    placement="topLeft"
                                    className="course-chapter-tooltip" 
                                    title={this.renderChapterTitle(item)} 
                                    color='#fff' trigger="click" 
                                    overlayClassName="chapter-popover"
                                    getPopupContainer={() =>
                                      document.getElementById('course-chapter-list')
                                    }
                                    onConfirm={() => this.handleRenameCourseChapter(item.id,false,item.mediaNameAlias)}
                                    icon={null}
                                    maskClosable={false}
                                    >
                                  <div className="rename">重命名</div>
                                    </Popconfirm>
                                <div className="line">|</div>
                                <div className="delete" onClick={()=>this.handleDeleteCourseChapter(item.id)}>移除</div>
                              </div>
                        </div>
                      })
                    }

                  </div>
                  </div>
                  </If>

            <div className='cover-url flex mt16'>
              <div className='label'>课程封面：</div> 
              <div className='cover-url__wrap'>
                <div className='opt-btns'>
                  <div>
                    <Button
                      onClick={() => {
                        this.setState({ showSelectCoverModal: true })
                      }}>{`${pageType === 'add' && !coverUrl ? '上传' : '修改'}封面`}</Button>
                    <span
                      className={`span ${coverUrl ? 'defalut-span' : ''}`}
                      onClick={() => {
                        this.setState({
                          coverUrl: '',
                          coverId: ''
                        })
                      }}>
                      使用默认图
                    </span>
                  </div>
                  <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 || `https://image.xiaomaiketang.com/xm/mt3ZQRxGKB.png`} alt='' />
                </div>
              </div>
            </div>
            <div className='course-catalog required'>
              <span className='label'>课程分类：</span>
              {pageType === 'add' && (
                <Cascader
                  defaultValue={[]}
                  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
                  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='intro-info mt16'>
              <AddVideoIntro
                data={{
                  id,
                  liveCourseMediaRequests: scheduleMedia,
                  shelfState,
                  whetherVisitorsJoin,
                  introduce,
                  loadintroduce
                }}
                onChange={this.handleChangeForm}
              />
            </div>
          </div>
        </div>

        <div className="footer shrink-footer">
          <Button onClick={this.handleGoBack}>取消</Button>
          <Button onClick={this.handleShowPreviewModal}>预览</Button>
          <Button type='primary' onClick={_.debounce(() => this.handleSubmit(), 3000, true)}>
            保存
          </Button>
        </div>

        {/* 选择备课文件弹窗 */}
        {showSelectFileModal && (
          <SelectPrepareFileModal
            multiple={true}
            operateType='select'
            selectTypeList={['MP4']}
            accept='video/mp4'
            confirm={{
              title: '文件过大，无法上传',
              content: '为保障学员的观看体验，上传的视频大小不能超过2G'
            }}
            tooltip={'格式支持mp4，大小不超过2G'}
            isOpen={showSelectFileModal}
            diskList={diskList}
            addVideo={true}
            onClose={() => {
              this.setState({ showSelectFileModal: false })
            }}
            onSelect={this.handleSelectVideo}
          />
        )}
        {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.previewCourseModal}
      </div>
    )
  }
}

export default AddVideoCourse
