/*
 * @Author: 吴文洁
 * @Date: 2020-07-20 19:12:49
 * @Last Modified by: chenshu
 * @Last Modified time: 2021-05-25 16:11:25
 * @Description: 大班直播分享弹窗
 */

import React from 'react'
import { Modal, Button, message } from 'antd'
import domtoimage from 'dom-to-image'

import qrcode from '@/libs/qrcode/qrcode.js'
import User from '@/common/js/user'
import $ from 'jquery'
import _ from 'underscore'
import CourseService from '@/domains/course-domain/CourseService'

import './ShareLiveModal.less'

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

    this.state = {
      shareUrl: 'https://xiaomai5.com/liveShare?courseId=12',
    }
  }

  componentDidMount() {
    // 获取短链接
    this.handleConvertShortUrl()
  }

  handleConvertShortUrl = () => {
    const { longUrl } = this.props.data

    // 发请求
    CourseService.getQrcode({
      urls: [longUrl],
    }).then((res) => {
      const { result = [] } = res

      this.setState(
        {
          shareUrl: result[0].shortUrl,
        },
        () => {
          const qrcodeWrapDom = document.querySelector('#qrcodeWrap')
          const qrcodeNode = new qrcode({
            text: this.state.shareUrl,
            size: 98,
          })
          qrcodeWrapDom.appendChild(qrcodeNode)

          const qrcodeWrapDomDownload = document.querySelector('#qrcodeWrap-dowload')
          const qrcodeNodeDownLoad = new qrcode({
            text: this.state.shareUrl,
            size: 196,
          })
          qrcodeWrapDomDownload.appendChild(qrcodeNodeDownLoad)
        }
      )
    })
  }

  componentWillUnmount() {
    // 页面销毁之前清空定时器
    clearTimeout(this.timer)
  }

  // 下载海报
  handleDownloadPoster = () => {
    this.setState(
      {
        showImg: true,
        time: new Date().valueOf(),
      },
      () => {
        this.setState({ time: new Date().valueOf() }, () => {
          setTimeout(() => {
            let node = document.getElementById('poster-dowload')
            domtoimage.toPng(node).then((imgData) => {
              console.log(imgData)
              const download = document.createElement('a')
              const { courseName } = this.props.data
              $(download).attr('href', imgData).attr('download', `${courseName}.png`).get(0).click()
            })
          }, 1000)
        })
      }
    )
  }

  // 复制分享链接
  handleCopy = () => {
    const textContent = document.getElementById('shareUrl').innerText

    window.copyText(textContent)
    message.success('复制成功!')
  }

  render() {
    const { courseDivision, data, type, title } = this.props
    const { courseName, scheduleVideoUrl, courseMediaVOS, coverUrl } = data
    const { shareUrl, showImg, time } = this.state
    // 判断是否是默认图, 默认图不需要在URL后面增加字符串
    let coverImgSrc = '';
    switch (type) {
      case 'liveClass': // 直播课
        if (courseMediaVOS && courseMediaVOS.length > 0) {
          data.courseMediaVOS.map((item, index) => {
            if (item.contentType === 'COVER') {
              coverImgSrc = item.mediaUrl
            }
          })
        } else {
          coverImgSrc = 'https://image.xiaomaiketang.com/xm/Yip2YtFDwH.png';
        }
        break;
      case 'videoClass': // 视频课
        coverImgSrc = coverUrl || (courseDivision === 'internal' ? `${scheduleVideoUrl}?x-oss-process=video/snapshot,t_0,m_fast&anystring=anystring` : 'https://image.xiaomaiketang.com/xm/mt3ZQRxGKB.png')
        break;
      case 'graphicsClass': // 图文课
        coverImgSrc = coverUrl || 'https://image.xiaomaiketang.com/xm/wFnpZtp2yB.png';
        break;
      case 'offlineClass': // 线下课
          coverImgSrc = coverUrl || 'https://image.xiaomaiketang.com/xm/pxbWKsYA87.png';
        break;
    }

    return (
      <Modal
        title={`分享${title}`}
        width={680}
        visible={true}
        footer={null}
        maskClosable={false}
        closeIcon={<span className='icon iconfont modal-close-icon'>&#xe6ef;</span>}
        className='share-live-modal'
        onCancel={this.props.close}>
        <div className='left'>
          <div id='poster'>
            <div className='store-name'>
              <span className='text'>{User.getStoreName()}</span>
            </div>

            <div className='course-name-title'>{type === 'liveClass' ? `邀请你观看直播：` : `${courseName}开课啦`}</div>
            {type === 'liveClass' && <div class='live-couse-name'>{courseName}</div>}
            <Choose>
              <When condition={showImg}>
                <img crossOrigin='*' src={coverImgSrc + `?=${time}`} className='course-cover' alt='' />
              </When>
              <Otherwise>
                <img src={coverImgSrc + `?=${time}`} className='course-cover' alt='' />
              </Otherwise>
            </Choose>

            <div className='qrcode-wrap'>
              <div className='qrcode-wrap__left'>
                <div className='text'>长按识别二维码进入观看</div>
                <img className='finger' src='https://image.xiaomaiketang.com/xm/thpkWDwJsC.png' alt='' />
              </div>
              <div className='qrcode-wrap__right' id='qrcodeWrap'></div>
            </div>
          </div>
          <div id='poster-dowload'>
            <div className='store-name'>
              <span className='text'>{User.getStoreName()}</span>
            </div>
            <div className='course-name-title'>{type === 'videoClass' ? `${courseName}开课啦` : `邀请你观看直播：`}</div>
            {type === 'liveClass' && <div class='live-couse-name'>{courseName}</div>}
            <Choose>
              <When condition={showImg}>
                <img crossOrigin='*' src={coverImgSrc + `?=${time}`} className='course-cover' alt='' />
              </When>
              <Otherwise>
                <img src={coverImgSrc + `?=${time}`} className='course-cover' alt='' />
              </Otherwise>
            </Choose>

            <div className='qrcode-wrap'>
              <div className='qrcode-wrap__left'>
                <div className='text'>长按识别二维码进入观看</div>
                <img className='finger' src='https://image.xiaomaiketang.com/xm/thpkWDwJsC.png' alt='' />
              </div>
              <div className='qrcode-wrap__right' id='qrcodeWrap-dowload'></div>
            </div>
          </div>
        </div>
        <div className='right'>
          <div className='share-poster right__item'>
            <div className='title'>① 海报分享</div>
            {type === 'liveClass' && <div className='sub-title'>学员可通过微信扫描海报二维码，观看{title}</div>}
            {type === 'videoClass' && <div className='sub-title'>学员可通过微信识别二维码，报名观看{title}</div>}

            <div className='content' onClick={_.debounce(this.handleDownloadPoster, 1000, true)}>
              下载海报
            </div>
          </div>

          <div className='share-url right__item'>
            <div className='title'>② 链接分享</div>
            {type === 'liveClass' && <div className='sub-title'>学员可通过微信打开以下链接，观看{title}</div>}
            {type === 'videoClass' && <div className='sub-title'>学员可通过打开链接，报名观看{title}</div>}
            <div className='content url-content'>
              <div className='share-url' id='shareUrl'>
                {shareUrl}
              </div>
              <Button type='primary' onClick={this.handleCopy}>
                复制
              </Button>
            </div>
          </div>
        </div>
      </Modal>
    )
  }
}

export default ShareLiveModal
