import html2canvas from 'html2canvas'
import QRCode from 'qrcode'
import { ScreenShot } from './typing'

/**
 * @description 屏幕截图
 * @param el 需要截图的dom节点
 * @returns img img 的标签
 */
export const screenShot: ScreenShot = async (el) => {
  const _el = typeof el === 'string' ? document.getElementById(el) : el

  return new Promise((resolve) => {
    html2canvas(_el!, {
      useCORS: true
    }).then(canvas => {
      const img = document.createElement('img')
      img.src = canvas.toDataURL('image/png')
      img.style.width = '100vw'
      resolve(img)
    })
  })
}

export const createQrcode = (text: string): Promise<string> => {
  return new Promise((resolve) => {
    QRCode.toDataURL(text, { errorCorrectionLevel: 'H' }, function (err, url) {
      if (err) {
        throw new Error(err.message)
      } else {
        resolve(url)
      }
    })
  })
}
