import React, { useRef } from 'react'
import { Popover, Button } from 'antd';
import { QrcodeOutlined } from '@ant-design/icons';
import QRCode from '@/components/QRCode'

const style = {
  display: 'flex',
  alignItem: 'center'
}

export default (props) => {
  const { text, title } = props

  const qrcodeRef = useRef()
  const download = () => {
    if (qrcodeRef.current) {
      qrcodeRef.current.getCanvas().then((canvas) => {
        const imageData = canvas.toDataURL('image/png', .8);
        const link = document.createElement('a');
        link.download = `${title}.png`
        link.href = imageData
        link.click()
      });
    }
  }

  const content = (
    <QRCode ref={qrcodeRef} border content={text} title={title} />
  )

  return (
    <div style={style}>
      {/* 这个 div 主要用于下载 */}
      <div style={{ zIndex: -1, position: 'fixed', top: '-500vh' }}>{content}</div>
      <Popover content={content} placement="right">
        <QrcodeOutlined style={{ fontSize: '32px' }} />
      </Popover>
      <Button style={{ marginLeft: '16px' }} onClick={download} type='link'>下载</Button>
    </div>
  )
}
