import React, { Component } from 'react'
import QRCode from "qrcode"
import './poster.scss'
import { getParam, http } from "@/utils"
import { Toast } from "antd-mobile"

function showToast(text) {
  Toast.info(text, 2, null, false)
}

class Poster extends Component {

  state = {
    redirectUrl: '',
    backgroundUrl: '',
    avatar: '',
    username: '',
    poster: this.props.poster,
  }

  componentDidMount() {
    const {poster} = this.props
    if (!poster) {
      http.get(`${API["base-api"]}/assistance/active_haibao_info/${getParam('assis_word')}`)
        .then(res => {
          const {data, errno, msg} = res.data
          if (errno === 200) {

            this.setState({
              avatar: data.head_img,
              username: data.user_name,
              redirectUrl: data.m_redirect_code,
              backgroundUrl: data.background_img_url
            }, () => {
              this.generatePoster()
            })

          } else {
            showToast(msg)
          }
        })
    }

  }


  generatePoster = async () => {
    let canvas = document.createElement('canvas'),
      scale = window.devicePixelRatio || 1,
      ctx = canvas.getContext('2d'),
      posterWidth = window.innerWidth * 0.72,
      canvasWidth = posterWidth * scale

    const {backgroundUrl, avatar, username, redirectUrl} = this.state


    const bg = await this.getImage(backgroundUrl)
    canvas.style.width = posterWidth + 'px'
    canvas.style.height = posterWidth * bg.height / bg.width + 'px'
    canvas.width = canvasWidth
    canvas.height = canvasWidth * bg.height / bg.width

    console.log(canvas.width)
    // ctx.scale(scale, scale)
    ctx.drawImage(bg, 0, 0, canvas.width, canvas.height)
    // ctx.drawImage(bg, 0, 0, Math.round(+canvas.style.width.slice(0, -2)), Math.round(+canvas.style.height.slice(0, -2)))


    let r = 16 * scale
    const avatarImage = await this.getImage(avatar)
    const ax = 20 * scale
    const ay = 15 / 2 * scale
    ctx.save()
    ctx.beginPath()
    ctx.arc(r + ax, r + ay, r, 0, Math.PI * 2)
    ctx.clip()
    ctx.drawImage(avatarImage, ax, ay, 2 * r, 2 * r)
    ctx.restore()


    ctx.font = `${12 * scale}px serif`
    ctx.fillStyle = '#fff'
    ctx.fillText(username, 2 * r + ax + (7 * scale), 22 * scale)

    let qrcode = await this.getQRCodeCanvas(redirectUrl, scale, posterWidth)
    ctx.drawImage(qrcode, 192 * scale, 405 * scale, posterWidth * (100 / (window.innerWidth * 0.72)), posterWidth * (100 / (window.innerWidth * 0.72)))
    // 540 384 810
    // 894 636 1342
    // ctx.drawImage(qrcode, 220, 450, 60, 60)
    // document.body.appendChild(canvas)


    this.setState({
      poster: canvas.toDataURL()
    }, () => {
      const {savePoster} = this.props
      savePoster && savePoster(this.state.poster)
    })
  }


  getImage = url => {
    return new Promise(resolve => {
      const img = new Image()
      img.setAttribute('crossOrigin', 'anonymous')
      img.onload = function () {
        resolve(this)
      }
      img.src = url
    })
  }

  getQRCodeCanvas = (text, scale, posterWidth) => {
    const canvas = document.createElement('canvas')
    let codeWidth = 100 * scale, codeHeight = 100 * scale,
      codeSize = posterWidth * (100 / (window.innerWidth * 0.72))

    canvas.style.width = `${codeSize}px`
    canvas.style.height = `${codeSize}px`
    canvas.width = codeWidth
    canvas.height = codeHeight

    return QRCode.toCanvas(canvas, text)
  }

  render() {
    const {poster} = this.state
    return (
      <div id='poster'>
        <div className="placard-desc">
          长按下方海报，分享给好友～
        </div>
        <div className="total-container">
          <div className="placard-img-container" id='imgWrapper'>
            <img src={poster} alt='分享海报'/>
          </div>
        </div>
      </div>
    )
  }
}

export default Poster
