import React, { useState, useRef, useEffect } from 'react';
import qrcode from '@/core/qrcode/qrcode.js'
import Service from "@/common/js/service";
import User from '@/common/js/user';
import './WechatLogin.less'
const Logo = require("@/common/images/logo.png")
declare var location: 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 = `${location.origin + location.pathname.replace('index.html', '') + 'h5.html'}?ticket=${res.result}&appTermEnum=XIAOMAI_CLOUD_CLASS_PC_WEB_ADMIN&env=${process.env.DEPLOY_ENV || 'prod'}`
                // console.log(redirect)
                // const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=ww409ccf9c6e31f19e&redirect_uri=${encodeURIComponent(redirect)}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
                // console.log(url)
                let qrnode = new qrcode({
                    text: redirect,
                    correctLevel: 2,
                    size: 160,
                    image: Logo,
                    imageSize: 50
                });
                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);
                    window.RCHistory.push({
                        pathname: `/switch-route`,
                    })
                })
            }

        })

    }, [leftTime])

    return <div className='wechatLoginBox'>
        <div className="rwm">
            <div id="qrcode" ref={(dom) => {
                QRCode.current = dom
            }}></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>
}