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

import React from 'react';
import { Modal, Input, Button, message } from 'antd';
import domtoimage from 'dom-to-image';
import html2canvas from 'html2canvas';
import qrcode from "@/libs/qrcode/qrcode.js";
import User from '@/common/js/user';
import $ from 'jquery';
import CourseService from "@/domains/course-domain/CourseService";

import './ShareLiveModal.less';

const  storeName = User.getStoreName();
const DEFAULT_COVER = 'https://image.xiaomaiketang.com/xm/YNfi45JwFA.png';

class ShareLiveModal extends React.Component {

  constructor(props) {
    super(props);
    
    this.state = {
      shareUrl: 'https://xiaomai5.com/liveShare?courseId=12'
    }
  }
  
  componentDidMount() {
    // 获取短链接
    this.handleConvertShortUrl();
  //   const { needStr, data, type } = this.props;
  //   const { courseName, coverUrl = DEFAULT_COVER, scheduleVideoUrl } = data;
  //   const { shareUrl ,time} = this.state;

  //   // 判断是否是默认图, 默认图不需要在URL后面增加字符串
  //   const isDefaultCover = coverUrl === DEFAULT_COVER;

  //   let coverImgSrc = coverUrl;
  //   if(type === 'videoClass'){
  //     if(!coverUrl || isDefaultCover){
  //       coverImgSrc = `${scheduleVideoUrl}?x-oss-process=video/snapshot,t_0,m_fast&anystring=anystring`
  //     }
  //   }else{
  //     data.courseMediaVOS.map((item,index)=>{
  //       if( item.contentType === "COVER"){
  //         coverImgSrc = item.mediaUrl;
  //       }    
  //     })
  //   }
  //   let image = new Image()
  //   image.src =coverImgSrc + '?v=' + Math.random()
  //   image.crossOrigin = "*"
  //   image.onload = ()=>{
  //     let imgData = getBase64Image(image)
  //    this.setState({imgData}) 
  //   }

  //  function getBase64Image (img) {
  //     let canvas = document.createElement("canvas")
  //     canvas.width = img.width
  //     canvas.height = img.height
  //     let ctx = canvas.getContext("2d")
  //     ctx.drawImage(img, 0, 0, img.width, img.height)
  //     let dataURL = canvas.toDataURL("image/png")
  //     return dataURL
  //   }
 
  }

  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);
      });
    })
  }

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

  // 下载海报
  handleDownloadPoster = () => {
    this.setState({
      showImg:true,
      time:new Date().valueOf()
    },()=>{
      this.setState({time:new Date().valueOf()},()=>{
        let node = document.getElementById('poster');
        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();
            // this.props.close()
          })
      })
    })
  
    
  }
  
  // 复制分享链接
  handleCopy = () => {
    const textContent = document.getElementById('shareUrl').innerText;

    window.copyText(textContent);
    message.success('复制成功!');
  }
  
  render() {
    const { needStr, data, type, title } = this.props;
    const { courseName, coverUrl = DEFAULT_COVER, scheduleVideoUrl } = data;
    const { shareUrl ,imgData,showImg,time} = this.state;

    // 判断是否是默认图, 默认图不需要在URL后面增加字符串
    const isDefaultCover = coverUrl === DEFAULT_COVER;
    
    let coverImgSrc = coverUrl;
    if(type === 'videoClass'){
      if((!coverUrl || isDefaultCover) && title !== '图文课' && title != '线下课'){
        coverImgSrc = `${scheduleVideoUrl}?x-oss-process=video/snapshot,t_0,m_fast&anystring=anystring`
      }
    }else{
      data.courseMediaVOS.map((item,index)=>{
        if( item.contentType === "COVER"){
          coverImgSrc = item.mediaUrl;
        }    
      })
    }

    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">{storeName}</span>
          </div>

          <div className="course-name-title">{type === 'videoClass' ? `${courseName}开课啦`: `邀请你观看直播：`}</div>
          {
            type === "liveClass" && 
            <div class="live-couse-name">{courseName}</div>
          }
          {
           showImg ?  <img
              crossOrigin='*'
              src={coverImgSrc+`?=${time}`}
              className="course-cover"
            />:  <img
              src={coverImgSrc+`?=${time}`}
              className="course-cover"
            />
          }
          <div className="qrcode-wrap">
            <div className="qrcode-wrap__left">
              <div className="text">长按识别二维码进入观看</div>
              <img className="finger" src="https://image.xiaomaiketang.com/xm/thpkWDwJsC.png"/>
            </div>
            <div className="qrcode-wrap__right" id="qrcodeWrap">
            </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={this.handleDownloadPoster}>下载海报</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;
