$(document).ready(function(){
	getqrpic();
});
var interval1,interval2;
function getRecoverBiz(){
	if(typeof window !== 'undefined' && window.RECOVER_BIZ === 'dg'){
		return 'dg';
	}
	if(typeof window !== 'undefined' && window.QQ_BIZ === 'dg'){
		return 'dg';
	}
	if(typeof currentVersion !== 'undefined' && currentVersion === 'dg'){
		return 'dg';
	}
	return 'cloud';
}
function setCookie(name,value){
	var exp = new Date();
	exp.setTime(exp.getTime() + 30*1000);
	document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}
function getCookie(name){
	var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
	if(arr=document.cookie.match(reg))
		return unescape(arr[2]);
	else
		return null;
}
function delCookie(name){
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval=getCookie(name);
    if(cval!=null){
      document.cookie= name + "="+cval+";expires="+exp.toGMTString();
    }
}
function getqrpic(force){
	force = force || false;
	cleartime();
	var qrsig = getCookie('qrsig');
	var qrimg = getCookie('qrimg');
	var login_sig = getCookie('login_sig');
	if(qrsig!=null && qrimg!=null && force==false){
		$('#qrimg').attr('qrsig',qrsig);
		$('#qrimg').attr('login_sig',login_sig);
		$('#qrimg').html('<img id="qrcodeimg" onclick="getqrpic(true)" src="data:image/png;base64,'+qrimg+'" title="点击刷新">');
		interval1=setInterval(loginload,1000);
		interval2=setInterval(qrlogin,3000);
	}else{
		var getvcurl='ajax.php?act=get_web_qrcode&r='+Math.random(1);
		$.get(getvcurl, function(d) {
			if(d.saveOK ==0){
				setCookie('qrsig',d.qrsig);
				setCookie('qrimg',d.data);
				setCookie('login_sig', d.login_sig || '');
				$('#qrimg').attr('qrsig',d.qrsig);
				$('#qrimg').attr('login_sig',d.login_sig || '');
				$('#qrimg').html('<img id="qrcodeimg" onclick="getqrpic(true)" src="data:image/png;base64,'+d.data+'" title="点击刷新">');
				interval1=setInterval(loginload,1000);
				interval2=setInterval(qrlogin,3000);
			}else{
				alert(d.msg);
			}
		}, 'json');
	}
}
function qrlogin(){
	if ($('#login').attr("data-lock") === "true") return;
	var qrsig=$('#qrimg').attr('qrsig');
	var login_sig=$('#qrimg').attr('login_sig') || '';
	var url = 'ajax.php?act=get_web_qrlogin&qrsig='+decodeURIComponent(qrsig)+'&login_sig='+encodeURIComponent(login_sig)+'&biz='+encodeURIComponent(getRecoverBiz())+'&r='+Math.random(1);
	$.get(url, function(d) {
		if(d.saveOK ==0 || d.code == 1){
			$('#loginmsg').html('QQ已成功登录！');
			$('#login').attr("data-lock", "true");
			cleartime();
			showToast('成功找回QQ', 'success');
			setTimeout(function(){
				window.location.href='./';
			}, 2000);
		}else if(d.saveOK ==1){
			getqrpic(true);
			$('#loginmsg').html('请重新扫描二维码');
		}else if(d.saveOK ==2){
			$('#loginmsg').html('使用QQ手机版扫描二维码');
		}else if(d.saveOK ==3){
			$('#loginmsg').html('扫描成功，请在手机上确认授权登录');
		}else if(d.saveOK ==4){
			cleartime();
			$('#loginmsg').html('QQ验证失败，请解除登录异常后重试！');
		}else if(d.code == -1){
			cleartime();
			$('#loginmsg').html(d.msg);
		}else{
			cleartime();
			$('#loginmsg').html(d.msg);
		}
	}, 'json');
}
function loginload(){
	if ($('#login').attr("data-lock") === "true") return;
	var load=document.getElementById('loginload').innerHTML;
	var len=load.length;
	if(len>2){
		load='.';
	}else{
		load+='.';
	}
	document.getElementById('loginload').innerHTML=load;
}
function cleartime(){
	clearInterval(interval1);
	clearInterval(interval2);
	if (window.mloginTimer) {
		clearInterval(window.mloginTimer);
		window.mloginTimer = null;
	}
	delCookie('qrsig');
	delCookie('qrimg');
	delCookie('login_sig');
}
	function mloginurlnew(){
    // 获取qrsig
    var qrsig = $('#qrimg').attr('qrsig');

    // 确保有qrsig
    if (!qrsig) {
        getqrpic(true);
        return;
    }

    var ua = window.navigator.userAgent.toLowerCase();
    var is_ios = ua.indexOf('iphone') > -1 || ua.indexOf('ipad') > -1;
    var schemacallback = '';

    if(is_ios){
        schemacallback = 'mqqwpa://';
    }else if(ua.indexOf('ucbrowser') > -1){
        schemacallback = 'ucweb://';
    }else if(ua.indexOf('meizu') > -1){
        schemacallback = 'mzbrowser://';
    }else if(ua.indexOf('liebaofast') > -1){
        schemacallback = 'lb://';
    }else if(ua.indexOf('baidubrowser') > -1){
        schemacallback = 'bdbrowser://';
    }else if(ua.indexOf('baiduboxapp') > -1){
        schemacallback = 'bdapp://';
    }else if(ua.indexOf('mqqbrowser') > -1){
        schemacallback = 'mqqbrowser://';
    }else if(ua.indexOf('qihoobrowser') > -1){
        schemacallback = 'qihoobrowser://';
    }else if(ua.indexOf('chrome') > -1){
        schemacallback = 'googlechrome://';
    }else if(ua.indexOf('sogoumobilebrowser') > -1){
        schemacallback = 'SogouMSE://';
    }else if(ua.indexOf('xiaomi') > -1){
        schemacallback = 'miuibrowser://';
    }else{
        schemacallback = 'googlechrome://';
    }

    // 跳转到QQ登录
    if(is_ios){
        window.location.href = 'wtloginmqq3://ptlogin/qlogin?qrcode=' + encodeURIComponent(qrsig) + '&schemacallback=' + encodeURIComponent(schemacallback);
    }else{
        window.location.href = 'wtloginmqq://ptlogin/qlogin?qrcode=' + encodeURIComponent(qrsig) + '&schemacallback=' + encodeURIComponent(schemacallback);
    }

    // 清除之前的定时器
    if (window.mloginTimer) {
        clearInterval(window.mloginTimer);
    }

    // 启动持续的登录状态检查（轮询方式检测登录状态）
    window.mloginTimer = setInterval(function() {
        checkLoginStatus();
    }, 2000);

    // 增强页面可见性API监听，当页面重新获得焦点时立即检查登录状态
    document.addEventListener('visibilitychange', function visibilityChangeHandler() {
        if (!document.hidden) {
            console.log('页面重新获得焦点，立即检查登录状态');
            checkLoginStatus();
        }
    });

    // 窗口获得焦点时检查
    window.addEventListener('focus', function focusHandler() {
        console.log('窗口获得焦点，检查登录状态');
        checkLoginStatus();
    });
}

// 检查登录状态
function checkLoginStatus() {
    var qrsig = $('#qrimg').attr('qrsig');
    if (!qrsig) {
        // 如果没有qrsig，重新获取二维码
        getqrpic(true);
        return;
    }

    var login_sig = $('#qrimg').attr('login_sig') || '';
    var url = 'ajax.php?act=get_web_qrlogin&qrsig=' + decodeURIComponent(qrsig) + '&login_sig=' + encodeURIComponent(login_sig) + '&biz=' + encodeURIComponent(getRecoverBiz()) + '&r=' + Math.random(1);
    $.get(url, function(d) {
        if(d.saveOK == 0 || d.code == 1){
            $('#loginmsg').html('QQ已成功登录！');
            $('#login').attr("data-lock", "true");

            // 清除所有定时器
            cleartime();
            if (window.mloginTimer) {
                clearInterval(window.mloginTimer);
                window.mloginTimer = null;
            }

            layer.alert('成功找回', {
                icon: 1,
                closeBtn: false
            }, function(){
                window.location.href = './';
            });
        }else if(d.saveOK == 2 || d.saveOK == 3){
            // 等待中，继续轮询
        }else{
            // 其他情况，停止轮询
            if (window.mloginTimer) {
                clearInterval(window.mloginTimer);
                window.mloginTimer = null;
            }
            cleartime();
            $('#loginmsg').html('登录失败，请重试');
        }
    }, 'json').fail(function() {
        // 请求失败，继续轮询
    });
}
