import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {environment} from '../../../environments/environment';
import {LifeCommonService} from '../../common/life-common.service';
import {MyService} from '../my.service';
declare var QRCode: any;
import * as uuid from 'uuid';
@Component({
  selector: 'ydlife-mk-material-detail',
  templateUrl: './mk-material-detail.component.html',
  styleUrls: ['./mk-material-detail.component.scss']
})
export class MkMaterialDetailComponent implements OnInit {
  @ViewChild('canvas') canvas: ElementRef<any>;
  materialItemId: string;
  lifeCustomerInfo: any;
  shareInfo: any;

  constructor(private activateRoute: ActivatedRoute,
              private lifeCommonService: LifeCommonService,
              private myService: MyService) {
  }

  ngOnInit() {
    this.materialItemId = this.activateRoute.snapshot.paramMap.get('itemId');
    this.lifeCustomerInfo = localStorage.getItem('lifeCustomerInfo') ? JSON.parse(localStorage.getItem('lifeCustomerInfo')) : null;
    // 分享信息
    const shareCodeUuid = uuid.v4();
    this.shareInfo = {
      ...this.lifeCommonService.generateShareCode(),
      shareCode: shareCodeUuid,
      customerId: this.lifeCustomerInfo.customerId,
      productId: this.materialItemId,
      url: `${environment.ORIGINNAME}/life/${this.materialItemId}?shareCode=${shareCodeUuid}`
    };
    // 发送请求保存分享码
    this.shareCallBack();
  }

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

  canvasPic() {
    const canvas = this.canvas.nativeElement as HTMLCanvasElement;
    const ctx = canvas.getContext('2d');
    const ratio = this.getPixelRatio(ctx);
    const W = document.body.clientWidth;
    const H = document.body.clientHeight;
    canvas.width = W * ratio;
    canvas.height = H * ratio;
    canvas.style.width = W + 'px';
    canvas.style.height = H + 'px';
    const qr = document.querySelector('#qrcode');
    const img = new Image();
    // 画圆形头像
    const avatarurlWidth = 50 * ratio;    // 绘制的头像宽度
    const avatarurlHeigth = 50 * ratio;  // 绘制的头像高度
    const avatarurlX = 10 * ratio;  // 绘制的头像在画布上的位置
    const avatarurlY = this.canvas.nativeElement.height - 80 * ratio;  // 绘制的头像在画布上的位置
    const avatarImg = new Image();
    avatarImg.src = `${environment.ORIGINNAME}/assets/img/meng.png`;
    // // 这里的第一张图片就是可以是你们的海报 这里注意绘制的顺序 我们要手动控制
    img.src = `${environment.ORIGINNAME}/ydLife/assets/images/mk-material/${this.materialItemId}.jpg`;
    img.onload = () => {
      ctx.drawImage(img, 0, 0, this.canvas.nativeElement.width, this.canvas.nativeElement.height);
      ctx.save();
      ctx.fillStyle = '#f5e7cd';
      ctx.fillRect(0, this.canvas.nativeElement.height - 125 * ratio, this.canvas.nativeElement.width * ratio, 125 * ratio);
      ctx.beginPath(); // 开始绘制
      // 先画个圆  前两个参数确定了圆心 （x,y） 坐标  第三个参数是圆的半径  四参数是绘图方向  默认是false，即顺时针
      ctx.arc(avatarurlWidth / 2 + avatarurlX, avatarurlHeigth / 2 + avatarurlY, avatarurlWidth / 2, 0, Math.PI * 2, false);
      ctx.clip(); // 画好了圆 剪切  原始画布中剪切任意形状和尺寸。一旦剪切了某个区域，则所有之后的绘图都会被限制在被剪切的区域内 这也是我们要save上下文的原因
      ctx.drawImage(avatarImg, avatarurlX, avatarurlY, avatarurlWidth, avatarurlHeigth); // 推进去图片，必须是https图片
      ctx.restore(); // 恢复之前保存的绘图上下文 恢复之前保存的绘图上下午即状态 还可以继续绘制
      ctx.save();
      // 对二维码进行初始化
      const qrCode = new QRCode(qr, {
        width: 60,
        height: 60,
        colorDark: '#000000',
        colorLight: '#ffffff',
      });
      // 为二维码设置内容
      qrCode.makeCode(this.shareInfo.url);
      // 我们的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 = () => {
        ctx.save();
        ctx.fillStyle = '#fff';
        ctx.fillRect(document.body.clientWidth - 116, document.body.clientHeight - 116, 111, 111);
        ctx.save();
        // 绘制图像  就是绘制二维码到我们自己写的canvas中去
        ctx.drawImage(shareQr, document.body.clientWidth - 110, document.body.clientHeight - 110, 100, 100);
        document.querySelector('#bannerImg').setAttribute('src', canvas.toDataURL('image/png', 1));
        this.canvas.nativeElement.style.display = 'none';
      };
      // 绘制字体
      ctx.fillStyle = '#000';
      ctx.font = `bold ${15 * ratio}px 微软雅黑`;
      ctx.fillText(`银盾保险经纪 ${this.lifeCustomerInfo.practitionerBasicInfo.name}`, 75 * ratio, this.canvas.nativeElement.height - 65 * ratio);
      ctx.fillText(`手机号：${this.lifeCustomerInfo.mobileNo}`, 75 * ratio, this.canvas.nativeElement.height - 25 * ratio);
      ctx.scale(ratio, ratio);
    };
  }

  getPixelRatio(context) {
    const backingStore = context.backingStorePixelRatio ||
      context.webkitBackingStorePixelRatio ||
      context.mozBackingStorePixelRatio ||
      context.msBackingStorePixelRatio ||
      context.oBackingStorePixelRatio ||
      context.backingStorePixelRatio || 1;
    return (window.devicePixelRatio || 1) / backingStore;
  }

  shareCallBack() {
    this.myService.shareCallBack(this.shareInfo).subscribe(res => {
      if (res['success']) {
        setTimeout(() => {
          this.canvasPic();
        }, 500);
      } else {

      }
    });
  }

}
