import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { generateQRcode } from 'amos-core';
import { Button } from 'amos-framework';
import { toUtf8 } from './../../../../component/table/tool'

class PointQRCode extends Component {
  constructor(props) {
    super(props);
    this.state = {
      pointQRInfo: {}
    };
  }

  componentWillMount = () => {
    let { pointQRInfo } = this.props;
    this.setState(pointQRInfo);
  }

  generateQrTags = (value, cdata) => {
    return `
      <div style="height: 150px; text-align: center; padding: 3px 5px; display: table; width: 100%; margin-top: 20px;">
        <div style="display: table-cell; vertical-align: middle;">
          <p style="font-size: 35px; text-align: center; margin: 0; padding:0;">${value}</p>
          <img src="${cdata}""/>
        </div>
      </div>
    `;
  };

  print(value, cdata) {
    let newWindow = window.open('打印二维码', '_blank');
    newWindow.document.write(this.generateQrTags(value, cdata));
    newWindow.document.close();
    setTimeout(() => {
      newWindow.print();
      newWindow.close();
    }, 100);
  }

  saveAs() {

  }

  downloadIamge(src, name) {
    let image = new Image();
    // 解决跨域 Canvas 污染问题
    image.setAttribute('crossOrigin', 'anonymous');
    image.onload = () => {
      let canvas = document.createElement('canvas');
      canvas.width = image.width;
      canvas.height = image.height;

      let context = canvas.getContext('2d');
      context.drawImage(image, 0, 0, image.width, image.height);
      let url = canvas.toDataURL('image/png');

      // 生成一个a元素
      let a = document.createElement('a');
      // 创建一个单击事件
      let event = new MouseEvent('click');

      // 将a的download属性设置为我们想要下载的图片名称，若name不存在则使用‘下载图片名称’作为默认名称
      a.download = name || '下载图片名称';
      // 将生成的URL设置为a.href属性
      a.href = url;

      // 触发a的单击事件
      a.dispatchEvent(event);
    };

    image.src = src;
  }

  render() {
    let { pointQRInfo } = this.props;
    const options = {
      value: toUtf8(pointQRInfo.code),
      size: 250,
      fgColor: '#000000',
      bgColor: '#ffffff',
      level: 'H'
    };
    return (
      <div className="point-qr-print">
        <div className="point-info-qr">
          <div className="point-info-number">{pointQRInfo.code}</div>
          <img src={generateQRcode(options)} alt="" />
          <div className="point-info-name">{pointQRInfo.name}</div>
        </div>
        <div className="point-qr-print-button">
          <Button onClick={(e) => this.print(pointQRInfo.name, generateQRcode(options))}>打印</Button>
          <Button onClick={(e) => this.downloadIamge(generateQRcode(options), pointQRInfo.name)}>另存</Button>
        </div>
      </div>
    );
  }
}

PointQRCode.propTypes = {
  pointId: PropTypes.number,
  pointQRInfo: PropTypes.any
};

export default PointQRCode;
