import html2canvas from 'html2canvas'
import QRCode from 'qrcode'
import { ScreenShot } from './typing'
import { getWXSignature } from '@/api/common'
import wx from 'weixin-js-sdk'

/**
 * @description 屏幕截图
 * @param el 需要截图的dom节点
 * @returns img img 的标签
 */
export const screenShot: ScreenShot = async (el) => {
  const _el = typeof el === 'string' ? document.getElementById(el) : el
  const scale = window.devicePixelRatio;
    // canvas.width = 1000 * scale;
    // canvas.height = 1000 * scale;
    // ctx.scale(scale, scale);
  return new Promise((resolve) => {
    html2canvas(_el!, {
      useCORS: true,
      scale,
    }).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> => {
  console.log('text:', text);
  
  return new Promise((resolve) => {
    QRCode.toDataURL(text, { errorCorrectionLevel: 'H' }, function (err, url) {
      if (err) {
        throw new Error(err.message)
      } else {
        resolve(url)
      }
    })
  })
}


/**
 * @description 注册wx-open-launch-app
 */

export async function registerWxopenButton() {
  return new Promise(async resolve => {
    const {data} = await getWXSignature();
    console.log('register: wxopenButto:', data);
    
 
      const {signature, appId, nonceStr, timestamp} = data;
      wx.config({
        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印
        appId, // 必填，公众号的唯一标识
        timestamp, // 必填，生成签名的时间戳
        nonceStr, // 必填，生成签名的随机串
        signature,// 必填，签名
        jsApiList: ['openLocation', 'getLocation'], // 必填，需要使用的JS接口列表
        openTagList: ['wx-open-launch-app'] // 可选，需要使用的开放标签列表，例如['wx-open-launch-app']
      });
      wx.error((res: any) => {
        console.log(res);
      });

      wx.ready(() => {
        resolve(true);
      });
   
  });
}
