import React, { Component } from "react"
import QRCode from "qrcode"
import "./poster.scss"
import { getParam, http } from "src/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"),
      ctx = canvas.getContext("2d"),
      posterWidth = 270,
      canvasWidth = 540

    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

    ctx.drawImage(bg, 0, 0, canvas.width, canvas.height)

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

    ctx.font = `24px serif`
    ctx.fillStyle = "#fff"
    ctx.fillText(username, 2 * r + ax + 10, ay + r - 5)

    let qrcode = await this.getQRCodeCanvas(redirectUrl, posterWidth)
    ctx.drawImage(qrcode, 380, 796, 140, 140)

    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, posterWidth) => {
    const canvas = document.createElement("canvas")
    let codeWidth = 100,
      codeHeight = 100,
      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
