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

const QrcodePopover: React.FC<{
  children?: React.ReactNode;
  text?: string;
  path?: string;
  scene?: string;
  placement?: PopoverProps['placement'];
}> = ({ children, text, path, scene, placement }) => {
  QrcodePopover.defaultProps = {
    path: 'pages/welcome/index',
    scene: 'type=share',
    placement: 'bottomRight',
  };
  // 登录二维码的地址
  const [qrCodeData, setQrCodeData] = useState<string>();
  // 获取登录二维码
  const getQrcodeLogin = async () => {
    // 获取二维码
    const res = await CommonAPI.getAppletQRCode({
      page: path || 'pages/welcome/index',
      scene: 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 flex-col">
      <div className="h-[12.5rem] w-[12.5rem]">
        {qrCodeData && (
          <img
            className="animate__animated animate__faster animate__fadeIn h-[12.5rem] w-[12.5rem]"
            src={qrCodeData}
            alt="云享飞小程序"
          />
        )}
      </div>
      <div className="mt-[1rem]">请前往小程序进行继续操作</div>
    </div>
  );
  return (
    <Popover
      content={content}
      trigger={'click'}
      placement={placement || 'bottomRight'}
      onOpenChange={handleOpenChange}
    >
      <div>
        {children && children}
        {text && (
          <Button type="link" className="m-0 p-0 text-[#3366cc]">
            {text}
          </Button>
        )}
      </div>
    </Popover>
  );
};

export default QrcodePopover;
