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;
@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;
    // 分享信息
    this.shareInfo = {
      ...this.lifeCommonService.generateShareCode(),
      customerId: this.lifeCustomerInfo.customerId,
      productId: this.materialItemId,
      url: `${environment.ORIGINNAME}/life/${this.materialItemId}?shareCode=${this.lifeCommonService.generateShareCode().shareCode}`
    };
    // 发送请求保存分享码
    this.shareCallBack();
  }

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

  canvasPic() {
    this.canvas.nativeElement.width = document.querySelector('#bannerPlaceHolder').clientWidth;
    this.canvas.nativeElement.height = document.querySelector('#bannerPlaceHolder').clientHeight;
    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();
    // 画圆形头像
    const avatarurlWidth = 50;    // 绘制的头像宽度
    const avatarurlHeigth = 50;  // 绘制的头像高度
    const avatarurlX = 10;  // 绘制的头像在画布上的位置
    const avatarurlY = this.canvas.nativeElement.height - 130 + 47;  // 绘制的头像在画布上的位置
    const avatarImg = new Image();
    avatarImg.src = 'https://mdev.zuihuibi.cn/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.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: 100,
        height: 100,
        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 = () => {
        // 绘制图像  就是绘制二维码到我们自己写的canvas中去
        ctx.drawImage(shareQr, this.canvas.nativeElement.width - 120, this.canvas.nativeElement.height - 130 + 10, 100, 100);
        document.querySelector('#bannerImg').setAttribute('src', canvas.toDataURL('image/png', 1));
        this.canvas.nativeElement.style.display = 'none';
      };
      // 绘制字体
      ctx.font = 'bold 14px 微软雅黑';
      ctx.fillStyle = '#081a71';
      ctx.fillText('长按了解详情', this.canvas.nativeElement.width - 115, this.canvas.nativeElement.height - 5);
      ctx.font = 'bold 15px 微软雅黑';
      ctx.fillText(`银盾保险经纪 ${this.lifeCustomerInfo['practitionerBasicInfo']['name']}`, 75, this.canvas.nativeElement.height - 130 + 65);
      ctx.fillText(`手机号：${this.lifeCustomerInfo.mobileNo}`, 75, this.canvas.nativeElement.height - 25);
      // ctx.fillText('微信号：123456', 70, this.canvas.nativeElement.height - 40);
    };
  }

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

      }
    });
  }

}
