import React, {useState, useRef, useEffect, useCallback} from 'react'
import { useModel } from 'umi'
import { Button, Spin } from 'antd';
import QRCode from 'qrcodejs2'
import styles from './style.less';

export default (props) => {
  const { initialState } = useModel('@@initialState');
  const [isLoading, setLoading] = useState(false);
  const qrcodeRef = useRef()
  const linkRef = useRef()

  const downloadQrcode = useCallback(() => {
    if (linkRef.current) {
      linkRef.current.click();
    }
  }, [])


  useEffect(() => {
    // 初始化二维码
    const qrcode = new QRCode(qrcodeRef.current, {
      width: 200,
      height: 200, // 高度
      text: initialState.report_url
    })

    const canvas = qrcodeRef.current.querySelector('canvas')

    // 创建下载链接
    const aElement = document.createElement('a');
    linkRef.current = aElement;
    linkRef.current.download = 'qrcode.png'

    // 构造链接地址
    setLoading(true);
    linkRef.current.href = canvas.toDataURL('image/jpg')
    setLoading(false);
  }, [])

  return isLoading ?
    <Spin
      size="small"
      style={{
        marginLeft: 8,
        marginRight: 8,
      }}
    />
  : (
      <div className={styles.qrcodebox}>
        <p>疫情监测结果表入口</p>
        <div ref={qrcodeRef} />
        <p><Button onClick={downloadQrcode}>下载</Button></p>
      </div>
    )
}
