/*
 * @Author: 吴文洁
 * @Date: 2020-08-05 10:07:47
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-07-08 19:32:50
 * @Description: 图文课新增/编辑页
 * @Copyright: 杭州杰竞科技有限公司 版权所有
 */

import React from 'react'
import { Button, Input, message, Modal } from 'antd'
import $ from 'jquery'
import moment from 'moment'
import { CourseCatalogSelect } from '@/modules/common'
import ShowTips from '@/components/ShowTips'
import Breadcrumbs from '@/components/Breadcrumbs'
import AddGraphicsIntro from './components/AddGraphicsIntro'
import SelectStudent from '../modal/select-student'
import SelectPrepareFileModal from '../../prepare-lesson/modal/SelectPrepareFileModal'
import PreviewGraphicsModal from '../modal/PreviewGraphicsModal'
import Service from '@/common/js/service'
import { randomString } from '@/domains/basic-domain/utils'
import User from '@/common/js/user'
import _ from 'underscore'
import Upload from '@/core/upload'
import ImgClipModal from '@/components/ImgClipModal'
import './AddGraphicsCourse.less'
import Bus from '@/core/bus'

//添加课程时课程默认的一些值
const defaultShelfState = 'YES'
const defaultCover = 'https://image.xiaomaiketang.com/xm/wFnpZtp2yB.png'

class AddGraphicsCourse 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, // 图文课名称
      courseMedia: '',
      introduce: '',
      courseMediaId: null, // 图文课链接
      coverId: null, // 图文封面的recourceId
      coverUrl: defaultCover, // 图文课封面
      studentList: [], // 上课学员列表
      shelfState: 'YES', //是否开启学院展示
      selectedFileList: [], // 已经从资料云盘中勾选的文件
      showCutModal: false, // 是否显示截图弹窗
      showSelectVideoModal: false,
      studentModal: false,
      categoryName: '',
      categoryId: null, //分类的Id值
      whetherVisitorsJoin: 'NO', // 是否允许游客加入
    }
  }

  componentWillMount() {
    const { id, pageType } = this.state
    if (pageType === 'edit') {
      this.handleFetchScheudleDetail(id)
    }
    Bus.bind('editorLimit', (editorTextLength, editorType) => {
      this.setState({
        [editorType]: editorTextLength,
      })
    })
  }

  initBus = () => {
    Bus.bind('graphicsEditorImage', this.uploadImage)
    Bus.bind('graphicsEditorVideo', this.uploadVideo)
  }

  removeBus = () => {
    Bus.unbind('graphicsEditorImage', this.uploadImage)
    Bus.unbind('graphicsEditorVideo', this.uploadVideo)
  }

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

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

  // 获取图文课详情
  handleFetchScheudleDetail = (courseId) => {
    Service.Hades('public/hades/mediaCourseDetail', {
      courseId,
    }).then((res) => {
      const { result = {} } = res || {}
      const { courseName, shelfState, whetherVisitorsJoin, courseMediaVOS, categoryId } = 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,
        courseName,
        shelfState,
        whetherVisitorsJoin,
        categoryId,
      })
    })
  }

  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, courseMediaId, categoryId, shelfState, whetherVisitorsJoin } = this.state
    if (
      videoName ||
      videoDuration ||
      courseMediaId ||
      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: `/graphics-course`,
          })
        },
      })
    } else {
      window.RCHistory.push({
        pathname: `/graphics-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 })
  }

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

  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, courseMedia, introduce, categoryName } = this.state

    const courseBasinInfo = {
      coverUrl,
      courseName,
      categoryName,
    }
    const courseIntroInfo = {
      courseMedia,
      introduce,
    }
    const previewGraphicsModal = (
      <PreviewGraphicsModal
        courseBasicInfo={courseBasinInfo}
        courseIntroInfo={courseIntroInfo}
        close={() => {
          this.setState({
            previewGraphicsModal: null,
          })
        }}
      />
    )

    this.setState({ previewGraphicsModal })
  }

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

  //获取resourceId
  getSignature = (blob) => {
    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,
    })
  }

  // 保存
  handleSubmit = () => {
    //过期判断
    if (User.getExpirationTime() && moment().valueOf() > Number(User.getExpirationTime())) {
      Modal.warning({
        title: '服务已到期',
        content: '当前企业购买的小麦企学院服务已到期，如需继续使用学院功能，请尽快续费购买',
        okText: '我知道了',
      })
      return
    }
    const { id, coverId, pageType, courseName, courseMedia, introduce, categoryId, shelfState, whetherVisitorsJoin } = this.state

    const commonParams = {
      categoryId,
      courseName,
      coverId,
      operatorId: User.getStoreUserId(),
      storeId: User.getStoreId(),
      shelfState,
      whetherVisitorsJoin,
      courseType: 'PICTURE',
    }
    // 校验必填字段:课程名称, 课程图文
    this.handleValidate(courseName, courseMedia, categoryId).then((res) => {
      if (!res) return
      Upload.uploadTextToOSS(
        courseMedia,
        `${randomString()}.txt`,
        (courseMediaId) => {
          Upload.uploadTextToOSS(
            introduce,
            `${randomString()}.txt`,
            (introduceId) => {
              this.submitRemote({
                id,
                pageType,
                commonParams,
                courseMediaId,
                introduceId,
              })
            },
            () => message.warning('上传课程简介失败')
          )
        },
        () => message.warning('上传课程内容失败')
      )
    })
  }

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

  handleValidate = (courseName, courseMedia, categoryId) => {
    const { graphicsCourseIntor, graphicsCourseContent } = this.state
    return new Promise((resolve) => {
      if (!courseName) {
        message.warning('请输入课程名称')
        resolve(false)
        return false
      }
      if (!courseMedia) {
        message.warning('请输入课程内容')
        resolve(false)
        return false
      }
      if (!categoryId) {
        message.warning('请选择课程分类')
        resolve(false)
        return false
      }

      if (graphicsCourseContent > 1000) {
        message.warning('课程内容超过字数限定')
        resolve(false)
        return
      }

      if (graphicsCourseIntor > 1000) {
        message.warning('课程简介超过字数限定')
        resolve(false)
        return
      }
      resolve(true)
    })
  }

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

  render() {
    const {
      id,
      pageType,
      courseName,
      coverUrl,
      courseMedia,
      introduce,
      imageFile,
      shelfState,
      whetherVisitorsJoin,
      loadcourseMedia,
      loadintroduce,
      showSelectCoverModal,
      visible,
      categoryId,
    } = this.state
    // 已选择的上课学员数量
    // 当前是否使用的是默认图片
    const isDefaultCover = coverUrl === defaultCover

    return (
      <div className='page add-graphics-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='cover-url flex mt16'>
              <div className='label'>封面图：</div>
              <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 required'>
              <span className='label'>课程分类：</span>
              <CourseCatalogSelect
                value={categoryId}
                onChange={(value, label) => {
                  this.handleChangeCatalogList(value, label)
                }}
              />
            </div>
            <div className='intro-info mt16'>
              <AddGraphicsIntro
                data={{
                  id,
                  courseMedia,
                  introduce,
                  shelfState,
                  whetherVisitorsJoin,
                  loadcourseMedia,
                  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>

        {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.previewGraphicsModal}
      </div>
    )
  }
}

export default AddGraphicsCourse
