// @ts-nocheck

import React, { useEffect, useState,useRef } from 'react';
import styles from './styles.less';
import { loginService } from '@/service';

import classnames from 'classnames';
import { Screen_svg } from '@/data';

export const sleep = (t) => new Promise((r) => setTimeout(r, t));

const QRCode = (props: any) => {
  const {
    onRegisterClick,
    onResetPwdClick,
    isShowQRCode,
    setIsShowQRCode,
    onSuccess,
    ...restProps
  } = props;

  const [qRInfo, setQRInfo] = useState(null);
  const isExeCallback = useRef(null)

  useEffect(() => {
    (async () => {
      if (isShowQRCode) {
        isExeCallback.current = true
        const qrCache = JSON.parse(localStorage?.getItem('qrCache') || '{}')
        let qrRes = qrCache
        if(!qrRes?.data){
          qrRes = await loginService.getQRCode();
          localStorage.setItem('qrCache',JSON.stringify(qrRes))
        }
        
        setQRInfo({
          ...qrRes?.data,
          image: 'data:image/png;base64,' + qrRes?.data?.image,
          error: !qrRes?.data?.image,
        });
        handleCheckLogin(qrRes?.data?.scene);
      }else{
        isExeCallback.current = false
      }
    })();
     
    return () => isExeCallback.current = false
  }, [isShowQRCode]);
  

  const handleCheckLogin = async (scene: string) => {
    const qrLoginRes = await loginService.handleQRCodeLogin({
      scene,
    });

    if (qrLoginRes?.data?.token) {
      localStorage.removeItem('qrCache')
      if (onSuccess) {
        onSuccess(qrLoginRes?.data?.token);
      }
      return;
    }

    await sleep(2000);

    if(isExeCallback?.current){
      handleCheckLogin(scene);
    }
  };

  return (
    <div className={styles.wrapper}>
      <div className={styles.header}>
        <span>微信二维码登录</span>
        <Screen_svg onClick={() => setIsShowQRCode(false)} />
      </div>
      <div className={styles.scan_box}>
        {qRInfo?.image ? (
          <img className={styles.image} src={qRInfo?.image} />
        ) : (
          <div className={styles.image} />
        )}
        <div className={styles.tip}>请使用微信扫描二维码登录“AMiner”</div>
        <div className={styles.tool}>
          <a onClick={onResetPwdClick}>忘记密码？</a>|{' '}
          <a onClick={onRegisterClick}>注册</a>
        </div>
      </div>
    </div>
  );
};

export default QRCode;
