/*
 * @Description  :
 * @Version      : 1.0
 * @Author       : Shiming
 * @Date         : 2021-12-03 11:10:14
 * @LastEditors  : Shiming
 * @LastEditTime : 2022-03-01 14:19:47
 * @FilePath     : \\tms-obc-web\\src\\app\\routes\\supply-management\\components\\qrcode-page\\qrcode-page.component.ts
 * Copyright (C) 2022 huzhenhong. All rights reserved.
 */

import { Component, OnInit, ViewChild } from '@angular/core';
import { QRComponent } from '@delon/abc/qr';
import { SFSchema, SFUISchema } from '@delon/form';
import { NzModalRef } from 'ng-zorro-antd/modal';
import html2canvas from 'html2canvas';

@Component({
  selector: 'app-supply-management-qrcode-page',
  templateUrl: './qrcode-page.component.html'
})
export class SupplyManagementQrcodePageComponent implements OnInit {
  @ViewChild('qr') qr!: QRComponent;
  record: any = {};
  i: any;
  schema: SFSchema = {};
  qrCodeValue = '';
  ui: SFUISchema = {
    '*': {
      spanLabelFixed: 100,
      grid: { span: 12 },
    },
    $no: {
      widget: 'text'
    },
    $href: {
      widget: 'string',
    },
    $description: {
      widget: 'textarea',
      grid: { span: 24 },
    },
  };

  constructor(
    private modal: NzModalRef,
  ) { }

  ngOnInit(): void {
    this.qrCodeValue = `rid:${this.i?.id}`;
  }


  /**
   * 下载二维码
   * @param downloadName 文件名
   * @param contents 内容
   */
  downLoadQrcode(downloadName: any, contents: any): void {
    let aLink = document.createElement('a');
    const content = contents;
    let blob = this.base64ToBlob(content); //new Blob([content]);
    let evt = document.createEvent("HTMLEvents");
    evt.initEvent("click", true, true);//initEvent 不加后两个参数在IE下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
    aLink.download = downloadName;
    aLink.href = URL.createObjectURL(blob);
    // aLink.dispatchEvent(evt);
    aLink.click();


  }

  //base64转blob
  base64ToBlob(code: any) {
    let parts = code.split(';base64,');
    let contentType = parts[0].split(':')[1];
    let raw = window.atob(parts[1]);
    let rawLength = raw.length;
    let uInt8Array = new Uint8Array(rawLength);
    for (let i = 0; i < rawLength; ++i) {
      uInt8Array[i] = raw.charCodeAt(i);
    }
    return new Blob([uInt8Array], { type: contentType });
  }

  close(): void {
    this.modal.destroy();
  }

  /**
   * 把页面装成canvas
   */
  toCanvasPhoto() {
    let aLink = document.createElement('a');
    html2canvas(document.getElementById('qr_page')!, { height: 340 }).then((canvas:any) => {
      let url = canvas.toDataURL("image/jpeg");
      this.downLoadQrcode('二维码', url);

    })
  }


}
