import React, { useEffect, useRef, useState } from 'react'
import Taro from '@tarojs/taro'
import { Canvas, View } from '@tarojs/components'
import { getConfig } from './config'
import posterSDKFactory from './sdk'

export default (props) => {
  const { dataSource, onStart, onEnd, onError } = props

  const [sdk, setSDK] = useState()
  const processing = useRef(false)

  const config = useRef()
  config.current = getConfig()

  useEffect(() => {
    Taro.nextTick(() => {
      posterSDKFactory('#canvas-poster').then((res) => {
        res.initCanvas({
          ...config.current,
        })
        setSDK(res)
      })
    })
  }, [])

  useEffect(() => {
    const { poster, miniCode, name, avatar, desc = '长按识别在线看房',  } = dataSource || {}
    if (sdk && poster && !processing.current) {
      onStart()
      processing.current = true
      const conf = config.current
      
      sdk.onError((err) => {
        if (onError) {
          onError(err)
        } else {
          console.error(err)
        }
      })

      // 名称
      sdk.darwText(name, conf.name)
      // 小程序码
      sdk.darwText(desc, conf.desc)

      let cnt = 0
      // 封面
      sdk.getImage(poster).then((posterImg) => {
        sdk.drawImage(posterImg, conf.poster)
        cnt += 1
      }).catch(() => cnt += 1)
      // 头像
      sdk.getImage(avatar).then((avatarImg) => {
        sdk.drawImage(avatarImg, conf.avatar)
        cnt += 1
      }).catch(() => cnt += 1)
      // 小程序码
      sdk.getImage(miniCode).then((miniCodeImg) => {
        sdk.drawImage(miniCodeImg, conf.miniCode)
        cnt += 1
      }).catch(() => cnt += 1)

      const ticker = setInterval(() => {
        if (cnt >= 3) {
          // 图片全部处理完
          const image = sdk.toDataURL()
          onEnd(image, sdk)
          clearInterval(ticker)
        }
      }, 200);

    }
  }, [sdk, dataSource, onStart, onEnd, onError])

  return <View style={{width: 0, height: 0}}><Canvas type='2d' id='canvas-poster' /></View>
}
