import html2canvas from 'html2canvas'
import { transferFile } from '../TransferFile'

function dpr() {
  if (window.devicePixelRatio && window.devicePixelRatio > 1) {
    return window.devicePixelRatio
  }
  return 1
}

export async function downloadQrCode(selector: string, downloadName: string = '邀请码') {
  // 获取节点
  const dom = document.getElementById(selector) as HTMLDivElement
  // 获取节点高度
  const {width, height} = dom?.getBoundingClientRect()
  // 获取像素比
  const scaleBy = dpr()
  // 创建canvas
  const canvas = document.createElement('canvas')
  canvas.width = width * scaleBy
  canvas.height = height * scaleBy
  // canvas.style.width = `${width}px`
  // canvas.style.height = `${height}px`
  // const context = canvas.getContext('2d')
  // context?.scale(1, 1)
  return await html2canvas(dom, {canvas}).then(async () => {
    const dataUrl = canvas.toDataURL('image/png')
    const file = transferFile(dataUrl, 'file')
    const imgUrl = URL.createObjectURL(file)
    const a =document.createElement('a')
    const event = new MouseEvent('click')
    a.target = "_self"
    a.download = downloadName
    a.href = dataUrl
    a.dispatchEvent(event)
  })
}
