import React, { useContext, useEffect, useState } from 'react';
import { Modal, Image } from 'antd';
import api from '~/api';
import { UserContext } from '~/lib/userProvider';
import errImg from '~/assets/errImg';

type Props = {
  open: boolean;
  onCancel: () => void;
};

export default function LoginModal(props: Props) {
  const [qrCode, setQrCode] = useState('');
  const [randomLoginCode, setRandomLoginCode] = useState('');
  const { userInfo, setUserInfo } = useContext(UserContext);
  const [timeHandle, setTimeHandle] = useState<NodeJS.Timer | null>(null);
  useEffect(() => {
    /* if (props.open) {
      new window.WxLogin({
        self_redirect: true,
        id: "login_container",
        appid: "wx18b7883acd204278",
        scope: "snsapi_login",
        redirect_uri: encodeURIComponent("https://iuav.mmcuav.cn/"),
        state: "",
        style: "",
        href: "",
      });
    } */
    if (!props.open) {
      setQrCode('');
      return;
    }

    setRandomLoginCode(String(Date.now()));
  }, [props.open]);

  useEffect(() => {
    if (randomLoginCode) {
      //获取登录码
      api
        .getAppletQRCode({
          randomLoginCode,
        })
        .then((res) => {
          if (res.code == '200') {
            setQrCode('data:image/png;base64,' + res.result || '');
          } else {
            window.messageApi.error('获取登录二维码失败');
          }
        });
    }

    if (randomLoginCode && !userInfo) {
      if (timeHandle) {
        clearTimeout(timeHandle);
      }
      const handle = setInterval(() => {
        api
          .getLoginInfo({
            randomLoginCode: randomLoginCode,
          })
          .then((res) => {
            if (res.code === '200') {
              clearInterval(handle);
              setTimeHandle(null);

              window.localStorage.setItem('token', res.result.token);
              api.userInfo().then((res) => {
                setUserInfo(res.result);
                window.messageApi.success('登录成功');
                props.onCancel();
                window.location.reload();
              });
            }
          });
      }, 1000);
      setTimeHandle(handle);
    }
  }, [randomLoginCode]);

  useEffect(() => {
    if (!props.open && timeHandle) {
      clearTimeout(timeHandle);
    }
  }, [timeHandle, props.open]);

  return (
    <>
      <Modal open={props.open} onCancel={props.onCancel} width={400} footer={null}>
        <div
          style={{
            fontSize: 20,
            fontFamily: 'MicrosoftYaHeiUI-Bold, MicrosoftYaHeiUI',
            fontWeight: 'bold',
            color: '#000',
            marginTop: 17,
            marginBottom: 48,
            textAlign: 'center',
          }}
        >
          欢迎来到云享飞
        </div>
        <div id='login_container' style={{ margin: 'auto', display: 'table' }}>
          <Image src={qrCode} width={150} height={150} fallback={errImg}></Image>
        </div>
        <div
          style={{
            // marginTop: -120,
            marginBottom: 52,
            fontSize: 14,
            fontFamily: 'MicrosoftYaHei',
            color: '#3E454D',
            textAlign: 'center',
          }}
        >
          打开微信扫一扫
        </div>
      </Modal>
    </>
  );
}
