import React, { useState, useRef, useEffect } from 'react';
import Service from "@/common/js/service";
import User from '@/common/js/user';
import qrcode from "@/libs/qrcode/qrcode.js";
import { PATH } from '@/domains/basic-domain/constants';
import { corpType } from '@/domains/brand/constants'
import './WechatLogin.less';
import { brandName, BRAND, brandIcon, brandLogo } from '@/domains/brand/constants'
declare var location: any;
declare var window: any;


export default function WechatLogin(props: any) {
  const freshTime = 60;
  const init: any = null;
  const [status, setStatus] = useState(0);
  const [ticket, setTicket] = useState('');
  const [leftTime, setLeftTime] = useState(freshTime);
  const QRCode = useRef(init);
  const timer = useRef(init);
  const leftTimeRef = useRef(init);

  useEffect(() => {
    leftTimeRef.current = leftTime;
  }, [leftTime]);

  useEffect(() => {
    clearInterval(timer.current as any);
    if (status === 0) {
      Service.Hades('anon/hades/getTicket', {}).then((res: any) => {
        setTicket(res.result);
        const redirect = `${PATH}?ticket=${res.result}&appTermEnum=XIAOMAI_CLOUD_CLASS_PC_WEB_ADMIN&env=${process.env.DEPLOY_ENV || 'dev'}&corpType=${corpType}`;
        const qrcodeWrapDom: any = document.querySelector('#qrcode');
        let qrnode = new qrcode({
          text: redirect,
          correctLevel: 2,
          size: 180,
          image: brandIcon,
          imageSize: 50,
        });
        qrcodeWrapDom.innerHTML = '';
        qrcodeWrapDom && qrcodeWrapDom.appendChild(qrnode);
        // QRCode.current.innerHTML = ''
        // QRCode.current.prepend(qrnode);
        setLeftTime(freshTime);
        timer.current = setInterval(() => {
          if (leftTimeRef.current == 0) {
            clearInterval(timer.current);
            setStatus(1);
            return;
          }

          setLeftTime(leftTimeRef.current - 1);
        }, 1000);
      });
    }
    return () => {
      clearInterval(timer.current);
    };
  }, [status]);

  useEffect(() => {
    if (leftTime == 60 || !ticket) {
      return;
    }

    Service.Hades('anon/hades/getTicketState', {
      ticket,
    }).then((res: any) => {
      if (res.result === 'AUTH_SUCCESS') {
        Service.Hades('anon/hades/getTicketWXWorkLogin', {
          ticket,
        }).then((_res: any) => {
          User.setUserId(_res.result.loginInfo.userId);
          User.setToken(_res.result.loginInfo.xmToken);
          User.setEnterpriseId(_res.result.enterpriseId);
          User.setIdentifier(_res.result.identifier);
          window.currentStoreUserInfo = {}
          window.currentStoreUserInfo.userId = _res.result.loginInfo.userId;
          window.currentStoreUserInfo.token = _res.result.loginInfo.xmToken;
          window.currentStoreUserInfo.enterpriseId = _res.result.enterpriseId;
          window.RCHistory.push({
            pathname: `/switch-route`,
          });
        });
      }
    });
  }, [leftTime]);

  return (
    <div className='wechatLoginBox'>
      <div className='rwm'>
        <div id='qrcode'></div>

        {status === 1 && (
          <div className='error'>
            <div>
              二维码已过期
              <p
                className='ope'
                onClick={() => {
                  setStatus(0);
                }}>
                刷新
              </p>
            </div>
          </div>
        )}
        {status === 2 && (
          <div className='error'>
            <div>
              所在企业还未注册学院
              <p
                className='ope'
                onClick={() => {
                  setStatus(0);
                }}>
                我知道了
              </p>
            </div>
          </div>
        )}
        {status === 3 && (
          <div className='error'>
            <div>
              你还不是学院员工，请联系企业管理员
              <p
                className='ope'
                onClick={() => {
                  setStatus(0);
                }}>
                我知道了
              </p>
            </div>
          </div>
        )}
      </div>
      <p className='text'>请使用企业微信扫码登录</p>
    </div>
  );
}
