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';
import {Buffer} from 'buffer';

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>;
  // 区分险种 1.产险-健康险
  productType: number;
  materialItemId: string;
  lifeCustomerInfo: any;
  shareInfo: any;
  // 自定义内容部分高度
  contentHeight: number = 90;
  // 二维码宽度
  qrcodeWidth: number = 70;
  qrcodeBgWidth: number = 80;
  qrcodePadding = 5;
  rightWidth = 5;
  bottomHeight = 5;

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

  ngOnInit() {
    this.materialItemId = this.activateRoute.snapshot.paramMap.get('itemId');
    if (this.materialItemId.substr(0, 2) === 'ph') {
      this.productType = 1;
    }
    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}`
    };
    if (this.productType === 1) {
      this.shareInfo.productId = null;
      this.shareInfo.planId = this.materialItemId .substr(2);
      this.shareInfo.url = `${environment.ORIGINNAME}/hProductDetail/${this.materialItemId .substr(2)}?shareCode=${shareCodeUuid}&type=9`;
    }
    // 发送请求保存分享码
    this.shareCallBack();
  }

  async canvasPic() {
    const qrcodeUrl = await this.qrcode() + '';
    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 img = new Image();
    // 画圆形头像
    const avatarurlWidth = 50 * ratio;    // 绘制的头像宽度
    const avatarurlHeigth = 50 * ratio;  // 绘制的头像高度
    const avatarurlX = 10 * ratio;  // 绘制的头像在画布上的位置
    const avatarurlY = this.canvas.nativeElement.height - (this.contentHeight + 50) / 2 * ratio;  // 绘制的头像在画布上的位置
    const avatarImg = new Image();
    avatarImg.setAttribute('crossOrigin', 'anonymous');
    if (this.lifeCustomerInfo.practitionerBasicInfo.headImagePath) {
      avatarImg.src = this.lifeCustomerInfo.practitionerBasicInfo.headImagePath;
    } else {
      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 - this.contentHeight * ratio, this.canvas.nativeElement.width * ratio, this.contentHeight * 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();
      // 这里的image只能在onload里面绘制 在外面就会被覆盖了 因为优先加载完毕就会优先绘制 然后就被之后绘制的海报背景遮挡了
      const shareQr = new Image();
      // 设置base64编码格式值
      shareQr.src = qrcodeUrl;
      shareQr.onload = () => {
        const qrcodeBgX = document.body.clientWidth - (this.rightWidth + this.qrcodeBgWidth);
        const qrcodeBgY = document.body.clientHeight - (this.bottomHeight + this.qrcodeBgWidth);
        const qrcodeX = qrcodeBgX + this.qrcodePadding;
        const qrcodeY = qrcodeBgY + this.qrcodePadding;
        ctx.fillStyle = '#fff';
        ctx.fillRect(qrcodeBgX, qrcodeBgY, this.qrcodeBgWidth, this.qrcodeBgWidth);
        ctx.save();
        // // 绘制图像  就是绘制二维码到我们自己写的canvas中去
        ctx.drawImage(shareQr, qrcodeX, qrcodeY, this.qrcodeWidth, this.qrcodeWidth);
        document.querySelector('#bannerImg').setAttribute('src', canvas.toDataURL('image/png', 1));
        this.canvas.nativeElement.style.display = 'none';
      };
      // 绘制字体
      ctx.fillStyle = '#000';
      ctx.font = `${12 * ratio}px 微软雅黑`;
      ctx.fillText(`${this.lifeCustomerInfo.practitionerBasicInfo.name}`, 75 * ratio, avatarurlY + 15 * ratio); // Y指的是文字底部的位置
      ctx.fillText(`银盾保险经纪`, 75 * ratio, avatarurlY + 30 * ratio); // Y指的是文字底部的位置
      ctx.fillText(`${this.lifeCustomerInfo.mobileNo}`, 75 * ratio, avatarurlY + 45 * 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 {

      }
    });
  }

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

  qrcode() {
    return new Promise((resolve, reject) => {
      const qr = document.querySelector('#qrcode');
      // 对二维码进行初始化
      const qrCode = new QRCode(qr, {
        // 二维码内容
        text: `${this.shareInfo.url}`,
        // 二维码宽度
        width: 100,
        // 二维码高度
        height: 100,
        // 二维码前景色
        colorDark: '#000',
        // 二维码背景色
        colorLight: '#fff',
        /*!
         容错级别，可设置为：
         QRCode.CorrectLevel.L
         QRCode.CorrectLevel.M
         QRCode.CorrectLevel.Q
         QRCode.CorrectLevel.H
         */
        correctLevel: QRCode.CorrectLevel.H,
        // 二维码中心图片
        iconSrc: `./assets/images/icons/yd.jpg`,
        // 二维码中心图片边框弧度
        iconRadius: 6,
        // 二维码中心图片边框宽度
        iconBorderWidth: 5,
        // 二维码中心图片边框颜色
        iconBorderColor: '#fff',
      });
      // 我们的qrcode生成二维码之后也会有一个canvas对象我们获取到这个元素
      // 这里的image只能在onload里面绘制 在外面就会被覆盖了 因为优先加载完毕就会优先绘制 然后就被之后绘制的海报背景遮挡了
      setTimeout(() => {
        const newCanvas = document.querySelector('#qrcode canvas') as HTMLCanvasElement;
        const qrcodeUrl = newCanvas.toDataURL('image/png', 1);
        resolve(qrcodeUrl);
      }, 100)
    });
  }
}
