import html2canvas from 'html2canvas'
import { transferFile } from '../TransferFile'
import { getImgUrl } from '../GetImgUrl'
import { isIOSMobile } from '../Common'

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

export async function downloadQrCode(selector: string, downloadName: string = '邀请码', entId?: 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, allowTaint: true}).then(async () => {
    const dataUrl = canvas.toDataURL('image/png')
    // console.log(dataUrl, 'qw')
    // const urlObj = await getImgUrl(dataUrl, entId as string)
    // const img = urlObj.url
    // const file = transferFile(dataUrl, 'file')
    // const imgUrl = URL.createObjectURL(file)
    // return urlObj
    // console.log(urlObj, 'urlO')
    if (isIOSMobile()) {
      console.log('ios')
      return dataUrl
    }
    const a =document.createElement('a')
    const event = new MouseEvent('click')
    a.target = "_self"
    a.download = downloadName
    a.href = dataUrl
    a.dispatchEvent(event)
  }).catch(err => {
    console.log(err, 'html2canvas err')
  })
}

