import React, { Component } from 'react';
import './posterPop.less';
import { _asyncThrottle, _throttle, waitTime } from '../../utils/utils';
import skinStore from '../../store/newSkin';
import { observer } from 'mobx-react';
import modalStore from '../../store/modal';
import { sensorMdExpouse } from '../../utils/sensorMd';
import html2canvas from 'html2canvas';
import Toast from '../toast';

@observer
class LongImgPop extends Component {
  constructor(props) {
    super(props);
    this.state = {
      posterImg: '',
    }
  }

  async componentDidMount() {
    await waitTime(300)
    // 开始截图
    const shareContent = document.querySelector("#posetBox"); // 需要截图的包裹的（原生的）DOM 对象
    const width = shareContent.offsetWidth; // 获取dom 宽度
    const height = shareContent.offsetHeight; // 获取dom 高度
    const canvas = document.createElement("canvas"); // 创建一个canvas节点
    const scale = 2; // 定义任意放大倍数 支持小数
    const scaleW = width * scale;
    const scaleH = height * scale;
    canvas.width = scaleW; // 定义canvas 宽度 * 缩放
    canvas.height = scaleH; // 定义canvas高度 *缩放
    canvas.style.width = scaleW + "px";
    canvas.style.height = scaleH + "px";
    canvas.getContext("2d").scale(scale, scale); // 获取context,设置scale
    html2canvas(shareContent, {
      backgroundColor: "transparent",
      allowTaint: true,
      scale: 1, // 添加的scale 参数
      canvas: canvas, // 自定义 canvas
      logging: true, // 日志开关，便于查看html2canvas的内部执行流程
      width: scaleW, // dom 原始宽度
      height: scaleH,
      useCORS: true, // 【重要】开启跨域配置
    }).then(canvas => {
      const base64 = canvas.toDataURL("image/png")
      this.setState({
        posterImg: base64
      }, () => {
        Toast('请长按保存图片分享给好友吧～')
      })
    })
  }

  // 返回
  backHandle = _asyncThrottle(() => {
    modalStore.closePop();
  })

  render() {
    const { close } = skinStore.common;
    const { bg, code_img_test } = skinStore.posterPop;
    return (
      <div className="posterPop">
        <div className="poster_box" id="posetBox">
          <img className="bg" src={bg} alt="" />
          <img className="code_img" src={code_img_test} alt="" />
        </div>
        {
          this.state.posterImg && <img className="poster_img" src={this.state.posterImg}></img>
        }
        <div className="tip">长按保存海报分享</div>
        <div className="close" onClick={this.backHandle} style={{ 'backgroundImage': `url(${close})` }}></div>
      </div>
    );
  }
}

export default LongImgPop;
