import {Component, ElementRef, OnInit, TemplateRef, ViewChild} from '@angular/core';
declare var QRCode: any;
@Component({
  selector: 'ydlife-mk-material',
  templateUrl: './mk-material.component.html',
  styleUrls: ['./mk-material.component.scss']
})
export class MkMaterialComponent implements OnInit {
  @ViewChild('canvas') canvas: ElementRef<any>;
  public hide: boolean = true;

  constructor() {
  }

  ngOnInit() {
    this.canvas.nativeElement.width = window.screen.width;
    this.canvas.nativeElement.height = window.screen.height;
    const canvas = this.canvas.nativeElement as HTMLCanvasElement;
    canvas.width = canvas.width * 1;
    canvas.height = canvas.height * 1;
    const qr = document.querySelector('#qrcode');
    const ctx = canvas.getContext('2d');
    const img = new Image();
    // // 这里的第一张图片就是可以是你们的海报 这里注意绘制的顺序 我们要手动控制
    img.src = 'https://mdev.zuihuibi.cn/ydLife/assets/images/mk-material/life.jpg';
    img.onload = () => {
      ctx.drawImage(img, 0, 0, this.canvas.nativeElement.width, this.canvas.nativeElement.height);
      // 对二维码进行初始化
      const qrCode = new QRCode(qr, {
        width: 100,
        height: 100,
        colorDark: '#000000',
        colorLight: '#ffffff',
      });
      // 为二维码设置内容
      qrCode.makeCode('http://mdev.zuihuibi.cn');
      // 我们的qrcode生成二维码之后也会有一个canvas对象我们获取到这个元素
      const newCanvas = qr.firstChild as HTMLCanvasElement;
      const base64 = newCanvas.toDataURL('image/png', 1);
      // 这里的image只能在onload里面绘制 在外面就会被覆盖了 因为优先加载完毕就会优先绘制 然后就被之后绘制的海报背景遮挡了
      const shareQr = new Image();
      // 设置base64编码格式值
      shareQr.src = base64;
      shareQr.onload = () => {
        // 绘制图像  就是绘制二维码到我们自己写的canvas中去
        ctx.drawImage(shareQr, this.canvas.nativeElement.width - 120, this.canvas.nativeElement.height - 150, 100, 100);
        document.querySelector('#bannerImg').setAttribute('src', canvas.toDataURL('image/png', 1));
      };
      // 绘制字体
      ctx.font = '14px 微软雅黑';
      ctx.fillStyle = '#081a71';
      ctx.fillText('长按了解详情', this.canvas.nativeElement.width - 115, this.canvas.nativeElement.height - 30);
    };
  }

  download(canvas) {
    const a = document.createElement('a');
    // 设置地址
    a.href = canvas.toDataURL('image/png', 1);
    // 设置下载名称
    a.download = '银盾保险在线';
    // 触发点击事件
    a.click();
  }

}
