import React, { useState } from 'react';
import { Button, message, Popover } from 'antd';
import { CommonAPI } from '@/api';

const QrcodePopover: React.FC<{
  children?: React.ReactNode;
  text?: string;
  path?: string;
}> = ({ children, text, path }) => {
  QrcodePopover.defaultProps = {
    path: 'pages/welcome/index',
  };
  // 登录二维码的地址
  const [qrCodeData, setQrCodeData] = useState<string>();
  // 获取登录二维码
  const getQrcodeLogin = async () => {
    // 获取二维码
    const res = await CommonAPI.getAppletQRCode({
      page: path || 'pages/welcome/index',
      scene: 'type=share',
    });
    if (res && res.code === '200') {
      if (!res.result) {
        message.warning('获取登录二维码失败');
        return;
      }
      // 设置当前登录的二维码
      setQrCodeData(`data:image/png;base64,${res.result}`);
    }
  };
  // 开启回调
  const handleOpenChange = async (e: boolean) => {
    if (e) {
      // 如果获取成功就不再获取
      if (qrCodeData) return;
      // 如果开启，就获取二维码
      await getQrcodeLogin();
    }
  };
  const content = (
    <div className="flex-center" style={{ flexDirection: 'column' }}>
      <div style={{ width: '12.5rem', height: '12.5rem' }}>
        {qrCodeData && (
          <img
            className="animate__animated animate__faster animate__fadeIn"
            style={{ width: '12.5rem', height: '12.5rem' }}
            src={qrCodeData}
            alt="云享飞小程序"
          />
        )}
      </div>
      <div style={{ marginTop: '1rem' }}>请前往小程序进行继续操作</div>
    </div>
  );
  return (
    <Popover
      content={content}
      trigger="focus"
      placement="bottomRight"
      onOpenChange={handleOpenChange}
    >
      {children && children}
      {text && (
        <Button type="link" style={{ color: '#3366cc', padding: 0, margin: 0 }}>
          {text}
        </Button>
      )}
    </Popover>
  );
};

export default QrcodePopover;
