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',
  justifyContent: 'center',
  flexDirection: 'column',
}

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 = (
    <div style={style}>
      <QRCode ref={qrcodeRef} border content={text} title={title} />
      <div style={{ textAlign: 'center' }}>
        <Button  onClick={download} type='primary'>下载</Button>
      </div>
    </div>
  )

  return (
    <Popover content={content} placement="right">
      <QrcodeOutlined style={{ fontSize: '32px' }} />
    </Popover>
  )
}
