var t, t_ticket;
var g_orderno;
var captcha_frame;
var is_quick_btn = true;
var current_login_data = {};
var login_data_saved = {};

function detectDevice() {
    var userAgent = navigator.userAgent || navigator.vendor || window.opera;
    var width = window.innerWidth;
    if (/iPad|Android 3.0|Xoom|Sch-I800|Playbook|Tablet/i.test(userAgent) || (width >= 768 && width < 1024)) {
        return 'tablet';
    } else if (/Mobile|Android|iP(hone|od)|IEMobile|BlackBerry/i.test(userAgent) || width < 768) {
        return 'mobile';
    } else {
        return 'desktop';
    }
}

function updateDeviceTip() {
    var device = detectDevice();
    var tipElement = document.getElementById('deviceTip');
    if (tipElement) {
        if (device === 'tablet') {
            tipElement.innerHTML = '<i class="fas fa-exclamation-circle mr-1"></i>检测到平板设备，请选择手机QQ';
        } else if (device === 'mobile') {
            tipElement.innerHTML = '<i class="fas fa-exclamation-circle mr-1"></i>检测到手机设备，请选择平板QQ';
        } else {
            tipElement.textContent = '';
        }
    }
}

function handleAjaxError(xhr, status, error) {
    if (status === 'timeout') return '请求超时，请检查网络连接或稍后重试';
    if (status === 'error') return '网络错误，请检查网络连接';
    if (xhr.status === 0) return '无法连接到服务器，请检查网络连接';
    if (xhr.status >= 500) return '服务器错误，请稍后重试';
    if (xhr.status === 404) return '请求的接口不存在';
    return '请求失败';
}

function handleResponse(data, successCallback) {
    if(data.code == -100){
        showModal('提示', data.msg, [
            { text: '前往找回', class: 'px-4 py-2 bg-indigo-500 hover:bg-indigo-600 text-white rounded-lg text-sm transition-colors', onClick: function() { window.location.href='./'; } },
            { text: '取消', onClick: closeModal }
        ]);
        return false;
    }else if(data.code == -200){
        showModal('提示', data.msg, [
            { text: '前去购买', class: 'px-4 py-2 bg-indigo-500 hover:bg-indigo-600 text-white rounded-lg text-sm transition-colors', onClick: function() { window.location.href='./shop.php?qq='+$("input[name='qq']").val()+'&version='+encodeURIComponent(getBiz()); } },
            { text: '取消', onClick: closeModal }
        ]);
        return false;
    }else if(data.code == 1){
        if(successCallback) successCallback(data);
        return true;
    }else if(data.code == 20){
        handleSliderVerification(data);
        return false;
    }else if(data.code == 10){
        handleSmsVerification(data);
        return false;
    }else if(data.code == 114514){
        handleIdentityVerification(data);
        return false;
    }else{
        showToast(data.msg, 'error');
        return false;
    }
}

function showToast(msg, type = 'info') {
    var toastWrap = document.getElementById('toastWrap');
    var toast = document.createElement('div');
    var bgColor = type === 'success' ? 'bg-green-500' : type === 'error' ? 'bg-red-500' : 'bg-indigo-500';
    toast.className = bgColor + ' text-white px-4 py-3 rounded-lg shadow-lg flex items-center gap-2 transform transition-all duration-300 translate-y-0 opacity-100';
    toast.innerHTML = '<i class="fas fa-info-circle"></i><span>' + msg + '</span>';
    toastWrap.appendChild(toast);
    setTimeout(function() {
        toast.classList.add('translate-y-2', 'opacity-0');
        setTimeout(function() { toast.remove(); }, 300);
    }, 3000);
}

function showLoading() { document.getElementById('loadingOverlay').classList.remove('hidden'); }
function hideLoading() { document.getElementById('loadingOverlay').classList.add('hidden'); }

function getBiz() {
    var v = ($('#biz').val() || (window.ADD_PAGE_PARAMS && window.ADD_PAGE_PARAMS.biz) || 'cloud');
    return v === 'dg' ? 'dg' : 'cloud';
}

function showModal(title, content, buttons = []) {
    document.getElementById('modalTitle').textContent = title;
    document.getElementById('modalBody').innerHTML = content;
    var footer = document.getElementById('modalFooter');
    footer.innerHTML = '';
    if (buttons.length > 0) {
        footer.classList.remove('hidden');
        buttons.forEach(function(btn) {
            var button = document.createElement('button');
            button.className = btn.class || 'px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-600 rounded-lg text-sm transition-colors';
            var cd = parseInt(btn.countdownSeconds, 10);
            if (cd > 0) {
                button.disabled = true;
                button.classList.add('opacity-50', 'cursor-not-allowed');
                var baseText = btn.text || '我知道了';
                var left = cd;
                var applyLabel = function(n) {
                    button.textContent = n > 0 ? baseText + '（' + n + '）' : baseText;
                };
                applyLabel(left);
                var tid = setInterval(function() {
                    if (!button.isConnected) { clearInterval(tid); return; }
                    left--;
                    if (left <= 0) {
                        clearInterval(tid);
                        button.disabled = false;
                        button.classList.remove('opacity-50', 'cursor-not-allowed');
                        applyLabel(0);
                    } else {
                        applyLabel(left);
                    }
                }, 1000);
            } else {
                button.textContent = btn.text;
                if(btn.disabled){ button.disabled = true; button.classList.add('opacity-50', 'cursor-not-allowed'); }
            }
            button.onclick = btn.onClick;
            footer.appendChild(button);
        });
        footer.classList.add('flex', 'justify-end', 'gap-2');
    } else {
        footer.classList.add('hidden');
        footer.classList.remove('flex', 'justify-end', 'gap-2');
    }
    document.getElementById('appModal').classList.remove('hidden');
}

function closeModal() { document.getElementById('appModal').classList.add('hidden'); }

function runWifiEnvironmentHint() {
    try {
        var cfg = window.ADD_PAGE_PARAMS || {};
        var mode = String(cfg.loginWifiHint != null ? cfg.loginWifiHint : '1');
        if (mode === '0') return;
        var countdownSeconds = 0;
        if (mode === '5') countdownSeconds = 5;
        else if (mode === '15') countdownSeconds = 15;
        var dev = detectDevice();
        if (dev !== 'mobile' && dev !== 'tablet') return;
        var c = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
        if (!c || typeof c.type !== 'string' || c.type !== 'wifi') return;
        var btn = { text: '我知道了', class: 'px-4 py-2 bg-indigo-500 hover:bg-indigo-600 text-white rounded-lg text-sm transition-colors', onClick: closeModal };
        if (countdownSeconds > 0) btn.countdownSeconds = countdownSeconds;
        showModal('网络提示',
            '<p class="text-left text-gray-700 text-sm leading-relaxed">检测到当前处于 <span class="font-semibold text-amber-700">Wi-Fi</span> 环境，可能会出现登录不上或扫码异常等情况。</p>' +
            '<p class="text-left text-gray-700 text-sm leading-relaxed mt-3">建议暂时 <span class="font-semibold">关闭 Wi-Fi</span>，改用 <span class="font-semibold">手机流量（移动数据）</span> 后再尝试登录。</p>',
            [btn]
        );
    } catch (e) {}
}

function initAddPageUi() {
    updateDeviceTip();
    runWifiEnvironmentHint();
}
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initAddPageUi);
} else {
    initAddPageUi();
}

function loading_pwd(){
    var qq = $("input[name='qq']").val();
    if(!qq || qq.length < 4){ showToast('请输入正确的QQ号', 'error'); return; }
    showLoading();
    $.ajax({
        type : 'POST', url : 'ajax_bot.php?act=loading_pwd', data : {qq:qq, biz:getBiz()}, dataType : 'json',
        success : function(data) {
            hideLoading();
            if(data.code == 1){ $("input[name='pwd']").val(data.pwd); showToast(data.msg, 'success'); }
            else{ showToast(data.msg, 'error'); }
        },
        error:function(xhr, status, error){ hideLoading(); showToast(handleAjaxError(xhr, status, error), 'error'); }
    });
}

function subbot(type){
    var cidVal = $('#cid').val();
    var $api = $('select[name="apiid"]');
    var apiidVal = $api.val();
    if(!apiidVal){
        if(cidVal === '' || cidVal === null || typeof cidVal === 'undefined'){
            showToast('请先选择分类', 'error');
        }else{
            showToast('请选择节点', 'error');
        }
        return false;
    }
    var qq = $("input[name='qq']").val();
    if(qq.length < 4 || qq.length > 10){ showToast('请输入正确的QQ号', 'error'); return false; }
    var typeName = $('select[name="apiid"]').find("option:selected").attr("type_name");
    if(type == 'pwd' && (typeName == 'myqq' || typeName == 'myqqa' || typeName == 'dr')){ showToast('该节点仅支持扫码登录', 'error'); return false; }
    if(type=='pwd' && $("input[name='pwd']").val() == ''){ showToast('密码不能为空', 'error'); return false; }
    var apipwd = $('select[name="apiid"]').find("option:selected").attr("apipwd");
    var is_pwd = $('select[name="apiid"]').find("option:selected").attr("is_pwd");
    // apipwd 为空=收费节点，为'0'=免费节点，有值=需要密码的免费节点
    if(apipwd && apipwd != '0' && apipwd != '' && $("input[name='apipwd']").val() == ''){ showToast('接口密码不能为空', 'error'); return false; }
    login_data_saved = { qq: qq, pwd: $("input[name='pwd']").val(), apiid: $('select[name="apiid"]').val(), cid: $("#cid").val(), protocol: $('select[name="protocol"]').val() };
    if(type == 'pwd'){ sessionStorage.setItem('save_pwd_' + qq, $("input[name='pwd']").val()); }
    showLoading();
    $.ajax({
        type : 'POST', url : 'ajax_bot.php?act=bot&type='+type, data : $('#form').serialize(), dataType : 'json',
        success : function(data) {
            hideLoading();
            if(!handleResponse(data, function(responseData){
                if(type == 'qr'){
                    $("#showQr").removeClass('hidden');
                    var qrData = responseData.base64 || responseData.qrcode;
                    $("#content").html('<img width="200px" height="200px" id="codeimg" qrurl="" src="data:image/png;base64,'+qrData+'"/>');
                    window.t = setInterval(function(){ get_qr_zt(responseData.qrid); }, 2500);
                }else if(type == 'pwd'){
                    showToast(responseData.msg || '登录成功', 'success');
                    setTimeout(function(){ window.location.href='./'; }, 2000);
                }
            })){ return false; }
        },
        error:function(xhr, status, error){ hideLoading(); showToast(handleAjaxError(xhr, status, error), 'error'); }
    });
}

function get_qr_zt(qrid){
    $.ajax({
        type : 'POST', url : 'ajax_bot.php?act=get_qr_zt', data : {qrid:qrid, biz:getBiz()}, dataType : 'json',
        success : function(data) {
            if(data.code == 1){
                clearInterval(t);
                $('#qrloginmsg').html(data.msg);
                showToast(data.msg, 'success');
                setTimeout(function(){ window.location.href='./'; }, 2000);
            }else if(data.code == -1){
                clearInterval(t);
                $('#qrloginmsg').html(data.msg);
            }else if(data.code == 114514){
                clearInterval(t);
                $('#qrloginmsg').html(data.msg);
                handleIdentityVerification(data);
            }else{
                $('#qrloginmsg').html(data.msg);
            }
        },
        error:function(xhr, status, error){ clearInterval(t); showToast(handleAjaxError(xhr, status, error), 'error'); }
    });
}

function handleSliderVerification(data){
    var jumpurl = 'cap_frame_sdk.php?qq='+data.qq+'&sid='+data.sid+'&aid='+data.aid+'&uin='+data.qq+'&captcha='+encodeURIComponent(data.hkurl);
    if(data.hktype == 3){ jumpurl = data.hkurl; }
    var iframeHeight = Math.min(400, window.innerHeight * 0.7) + 'px';
    var content = '<iframe src="' + jumpurl + '" width="100%" height="' + iframeHeight + '" frameborder="0"></iframe>';
    showModal('滑块验证码', content);
    captcha_frame = true;
    if(data.hktype == 3 || data.hktype == 5){
        window.t_ticket = setInterval(function() { setTimeout(check_ticket(data.qq), 0) }, 3000);
    }
}

function handleSmsVerification(data){
    $("#showPwd").removeClass('hidden');
    $('#showPwdTitle').text('手机验证码');
    $('#content_pwd').empty();
    var qq = data.qq;
    window.current_sms_data = data;
    var skipSend = !!(data.skip_send_sms);
    var statusHtml = skipSend
        ? '<button type="button" onclick="submit_code(\''+qq+'\')" class="w-full py-2.5 bg-indigo-500 hover:bg-indigo-600 text-white rounded-lg text-sm font-medium transition-colors">提交验证码</button>'
        : '<div class="flex items-center justify-center gap-2 text-indigo-500"><i class="fas fa-spinner fa-spin"></i><span>发送中...</span></div>';
    var html = '<div class="p-5"><div class="mb-4"><label class="block text-sm font-medium text-gray-700 mb-1.5">验证码</label><input type="text" class="w-full px-3 py-2.5 bg-gray-50 border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 text-sm text-center tracking-widest" id="phonecode" placeholder="请输入6位验证码" maxlength="6" autocomplete="one-time-code"></div><div id="smsStatus">'+statusHtml+'</div></div>';
    $('#content_pwd').html(html);
    if(skipSend) return;
    $.ajax({
        type : 'POST', url : 'ajax_bot.php?act=send_phone_code', data : {qq:qq, biz:getBiz()}, dataType : 'json',
        success : function(ret) {
            if(ret.code == 1){
                showToast(ret.msg, 'success');
                $('#smsStatus').html('<button type="button" onclick="submit_code(\''+qq+'\')" class="w-full py-2.5 bg-indigo-500 hover:bg-indigo-600 text-white rounded-lg text-sm font-medium transition-colors">提交验证码</button>');
            }else{
                $('#smsStatus').html('<p class="text-red-500 text-sm mb-2 text-center">'+ret.msg+'</p><button type="button" onclick="resendSms()" class="w-full py-2.5 bg-green-500 hover:bg-green-600 text-white rounded-lg text-sm font-medium transition-colors">重新发送</button>');
            }
        },
        error:function(xhr, status, error){
            $('#smsStatus').html('<p class="text-red-500 text-sm mb-2 text-center">'+handleAjaxError(xhr, status, error)+'</p><button type="button" onclick="resendSms()" class="w-full py-2.5 bg-green-500 hover:bg-green-600 text-white rounded-lg text-sm font-medium transition-colors">重新发送</button>');
        }
    });
}

function resendSms(){ if(window.current_sms_data){ handleSmsVerification(window.current_sms_data); } }

function handleIdentityVerification(data){
    if(data.sid && data.aid){
        var jumpurl = 'cap_frame_sdk.php?qq='+data.qq+'&type=verify&sid='+data.sid+'&aid='+data.aid+'&uin='+data.qq;
        if(data.hkurl && data.hkurl !== ''){ jumpurl += '&captcha='+encodeURIComponent(data.hkurl); }
        var iframeHeight = Math.min(400, window.innerHeight * 0.7) + 'px';
        var content = '<iframe src="' + jumpurl + '" width="100%" height="' + iframeHeight + '" frameborder="0"></iframe>';
        showModal('身份验证', content);
        captcha_frame = true;
    }else{
        showModal('提示', '需要进行身份验证，但参数不完整，请重新登录', [{ text: '确定', onClick: function() { window.location.reload(); } }]);
    }
}

function submit_code(qq){
    var keycode = $('#phonecode').val();
    var $btn = $('#smsStatus button');
    var originalText = $btn.text();
    $btn.prop('disabled', true).text('提交中...').addClass('opacity-50 cursor-not-allowed');
    showLoading();
    $.ajax({
        type : 'POST', url : 'ajax_bot.php?act=submit_phone_code', data : {qq:qq,code:keycode, biz:getBiz()}, dataType : 'json',
        success : function(data) {
            hideLoading();
            $btn.prop('disabled', false).text(originalText).removeClass('opacity-50 cursor-not-allowed');
            if(!handleResponse(data, function(responseData){
                showModal('提示', responseData.msg, [{ text: '确定', class: 'px-4 py-2 bg-indigo-500 hover:bg-indigo-600 text-white rounded-lg text-sm transition-colors', onClick: function() { window.location.href='./'; } }]);
            })){ return false; }
        },
        error:function(xhr, status, error){
            hideLoading();
            $btn.prop('disabled', false).text(originalText).removeClass('opacity-50 cursor-not-allowed');
            showToast(handleAjaxError(xhr, status, error), 'error');
        }
    });
}

function closeQrModal(){ $("#showQr").addClass('hidden'); clearInterval(t); }
function closePwdModal(){ $("#showPwd").addClass('hidden'); $('#showPwdTitle').text('密码登录'); clearInterval(t); clearInterval(t_ticket); }

window.getticket = function(d){
    closeModal();
    showLoading();
    $.ajax({
        type : 'POST', url : 'ajax_bot.php?act=submit_ticket', data : {qq:d.qq,randstr:d.randstr,ticket:d.ticket, biz:getBiz()}, dataType : 'json',
        success : function(data) {
            hideLoading();
            if(!handleResponse(data, function(responseData){
                showModal('提示', responseData.msg, [{ text: '确定', class: 'px-4 py-2 bg-indigo-500 hover:bg-indigo-600 text-white rounded-lg text-sm transition-colors', onClick: function() { window.location.href='./'; } }]);
            })){ return false; }
        },
        error:function(xhr, status, error){ hideLoading(); showToast(handleAjaxError(xhr, status, error), 'error'); }
    });
}

window.submit_verify_1 = function(d){
    closeModal();
    showLoading();
    $.ajax({
        type : 'POST', url : 'ajax_bot.php?act=submit_verify_1', data : {qq:d.qq,randstr:d.randstr,ticket:d.ticket, biz:getBiz()}, dataType : 'json',
        success : function(data) {
            hideLoading();
            if(!handleResponse(data, function(responseData){
                if(responseData.phoneNum && responseData.phoneNum !== ''){
                    showVerify2Input(responseData);
                }else{
                    showModal('提示', responseData.msg || '验证成功', [{ text: '确定', class: 'px-4 py-2 bg-indigo-500 hover:bg-indigo-600 text-white rounded-lg text-sm transition-colors', onClick: function() { window.location.reload(); } }]);
                }
            })){ return false; }
        },
        error:function(xhr, status, error){ hideLoading(); showToast(handleAjaxError(xhr, status, error), 'error'); }
    });
}

function showVerify2Input(data){
    var areaCode = data.areaCode || '+86';
    var qq = data.qq;
    var phoneNum = data.phoneNum || '';
    var prefix = phoneNum.substring(0, 3);
    var suffix = phoneNum.substring(phoneNum.length - 2);
    $("#showPwd").removeClass('hidden');
    $('#content_pwd').empty();
    var html = '<div class="p-5"><div class="bg-gray-50 p-4 rounded-lg mb-4"><p class="text-center text-gray-600">请补全您的手机号</p></div><div class="mb-4"><div class="flex items-center justify-center gap-1"><span class="text-xl font-bold text-gray-800">'+prefix+'</span><div class="flex gap-1">';
    for(var i=0; i<6; i++){
        html += '<input type="text" class="verify2-digit w-8 py-2 border border-gray-200 rounded text-lg text-center" maxlength="1" data-index="'+i+'" inputmode="numeric" pattern="[0-9]*">';
    }
    html += '</div><span class="text-xl font-bold text-gray-800">'+suffix+'</span></div></div><div class="text-center"><button type="button" onclick="submitVerify2(\''+qq+'\', \''+prefix+'\', \''+suffix+'\')" class="px-6 py-2 bg-indigo-500 hover:bg-indigo-600 text-white rounded-lg text-sm font-medium">确认</button></div></div>';
    $('#content_pwd').html(html);
    $('.verify2-digit').on('input', function() {
        var index = parseInt($(this).data('index'));
        var value = $(this).val();
        if(!/^\d*$/.test(value)) { $(this).val(''); return; }
        if(value.length === 1 && index < 5) { $('.verify2-digit[data-index="' + (index + 1) + '"]').focus(); }
    });
    $('.verify2-digit').on('keydown', function(e) {
        var index = parseInt($(this).data('index'));
        if(e.keyCode === 8 && $(this).val() === '' && index > 0) { $('.verify2-digit[data-index="' + (index - 1) + '"]').focus(); }
    });
    $('.verify2-digit[data-index="0"]').focus();
}

function submitVerify2(qq, prefix, suffix){
    var middle = '';
    $('.verify2-digit').each(function() { middle += $(this).val(); });
    if(!middle || middle.length < 6){ showToast('请输入完整的6位手机号', 'error'); return; }
    var phoneNum = prefix + middle + suffix;
    var areaCode = '+86';
    var $btn = $('#content_pwd button');
    var originalText = $btn.text();
    $btn.prop('disabled', true).text('提交中...').addClass('opacity-50 cursor-not-allowed');
    showLoading();
    $.ajax({
        type : 'POST', url : 'ajax_bot.php?act=submit_verify_2', data : {qq:qq, areaCode:areaCode, phoneNum:phoneNum, mobile:phoneNum, biz:getBiz()}, dataType : 'json',
        success : function(data) {
            hideLoading();
            $btn.prop('disabled', false).text(originalText).removeClass('opacity-50 cursor-not-allowed');
            if(data.code == 1){
                if(data.sms && data.sendTo){ showSmsInstruction(qq, data.sms, data.sendTo); }
                else{ showToast(data.msg || '验证成功', 'success'); window.location.reload(); }
            }else{ showToast(data.msg, 'error'); }
        },
        error:function(xhr, status, error){
            hideLoading();
            $btn.prop('disabled', false).text(originalText).removeClass('opacity-50 cursor-not-allowed');
            showToast(handleAjaxError(xhr, status, error), 'error');
        }
    });
}

function showSmsInstruction(qq, sms, sendTo){
    $("#showPwd").removeClass('hidden');
    $('#content_pwd').empty();
    var smsUrl = buildSmsUrl(sendTo, sms);
    var html = '<div class="p-5"><h3 class="text-center text-gray-800 font-semibold mb-4">发送短信</h3><div class="bg-gray-50 p-4 rounded-lg mb-4"><p class="text-center text-gray-600">请使用手机发送短信到：</p><p class="text-center text-gray-800 text-xl font-bold mt-2">'+sendTo+'</p></div><div class="bg-green-50 p-4 rounded-lg mb-4"><p class="text-center text-green-700 font-medium">短信内容：'+sms+'</p></div><div class="flex gap-3 justify-center"><a href="'+smsUrl+'" class="px-5 py-2 bg-indigo-500 hover:bg-indigo-600 text-white rounded-lg text-sm font-medium">快捷发送</a><button type="button" onclick="confirmSmsSend(\''+qq+'\')" class="px-5 py-2 bg-green-500 hover:bg-green-600 text-white rounded-lg text-sm font-medium">短信已发送</button></div></div>';
    $('#content_pwd').html(html);
}

function buildSmsUrl(sendTo, sms){
    var ua = navigator.userAgent || '';
    var encoded = encodeURIComponent(sms || '');
    var isIOS = /iPhone|iPad|iPod/i.test(ua);
    var isInApp = !!window.plus || /Html5Plus|; wv\)|\bwv\b|WebView/i.test(ua);

    // Web2App / APP内打开：不显式拼 body=，避免被二次补全
    if (isInApp) return 'sms:' + sendTo + '?' + encoded;
    if (isIOS) return 'sms:' + sendTo + '&body=' + encoded;
    return 'sms:' + sendTo + '?body=' + encoded;
}

function confirmSmsSend(qq){
    var $btn = $('#content_pwd button');
    var originalText = $btn.text();
    $btn.prop('disabled', true).text('确认中...').addClass('opacity-50 cursor-not-allowed');
    showLoading();
    $.ajax({
        type : 'POST', url : 'ajax_bot.php?act=success_sms', data : {qq:qq, biz:getBiz()}, dataType : 'json',
        success : function(data) {
            hideLoading();
            $btn.prop('disabled', false).text(originalText).removeClass('opacity-50 cursor-not-allowed');
            if(data.code == 1){ loginAfterVerify(qq); }
            else{ showToast(data.msg, 'error'); }
        },
        error:function(xhr, status, error){
            hideLoading();
            $btn.prop('disabled', false).text(originalText).removeClass('opacity-50 cursor-not-allowed');
            showToast(handleAjaxError(xhr, status, error), 'error');
        }
    });
}

function loginAfterVerify(qq){
    showLoading();
    $.ajax({
        type : 'POST', url : 'ajax_bot.php?act=login_qq', data : {qq:qq, pwd:'', biz:getBiz()}, dataType : 'json',
        success : function(data) {
            hideLoading();
            if(!handleResponse(data, function(responseData){
                showModal('提示', responseData.msg || '登录成功', [{ text: '确定', class: 'px-4 py-2 bg-indigo-500 hover:bg-indigo-600 text-white rounded-lg text-sm transition-colors', onClick: function() { window.location.href='./'; } }]);
            })){ return false; }
        },
        error:function(xhr, status, error){ hideLoading(); showToast(handleAjaxError(xhr, status, error), 'error'); }
    });
}

function check_ticket(qq){
    $.ajax({
        type : 'POST', url : 'ajax_bot.php?act=check_ticket', data : {qq:qq, biz:getBiz()}, dataType : 'json',
        success : function(data) {
            if(data.code == 1){
                clearInterval(t);
                clearInterval(t_ticket);
                showModal('提示', data.msg);
                window.location.href='./';
            }else if(data.code == 2){
                clearInterval(t);
                clearInterval(t_ticket);
                closeModal();
                $('#content_pwd').empty();
                var html = '<div class="p-5 text-center">'+data.msg+'<br><input type="text" id="phonecode" class="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm mt-3" placeholder="请输入验证码"><br><button type="button" onclick="submit_code(\''+qq+'\')" class="mt-3 px-6 py-2 bg-indigo-500 hover:bg-indigo-600 text-white rounded-lg text-sm font-medium">提交</button></div>';
                $('#content_pwd').html(html);
            }else if(data.code == -1){
                clearInterval(t);
                clearInterval(t_ticket);
                closeModal();
                $('#content_pwd').html('<div class="p-5 text-center text-red-500">登录失败<br>'+data.msg+'</div>');
            }
        },
        error:function(xhr, status, error){ showToast(handleAjaxError(xhr, status, error), 'error'); }
    });
}

function mloginurlnew(){
    var qrurl = $('#codeimg').attr('qrurl');
    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://'; }
    if(is_ios){
        alert('跳转到QQ登录后请手动返回当前浏览器');
        is_quick_btn=false;
        setTimeout(function(){is_quick_btn=true},1000);
        window.location.href = 'wtloginmqq3://ptlogin/qlogin?qrcode=' + encodeURIComponent(qrurl) + '&schemacallback=' + encodeURIComponent(schemacallback);
    }else{
        is_quick_btn=false;
        setTimeout(function(){is_quick_btn=true},1000);
        window.location.href = 'wtloginmqq://ptlogin/qlogin?qrcode=' + encodeURIComponent(qrurl) + '&schemacallback=' + encodeURIComponent(schemacallback);
    }
}

$(document).ready(function(){
    var apilist, protocol, apidata, login_config;
    get_list();
    $('select[name="apiid"]').change(function(){
        $_GET.protocol = $('select[name="protocol"]').val();
        get_point();
    });
    $('#cid').change(function(){
        $_GET.qq = $('input[name="qq"]').val();
        $_GET.pwd = $('input[name="pwd"]').val();
        $_GET.protocol = $('select[name="protocol"]').val();
        delete $_GET.apiid;
        show_api();
    });
    $('select[name="protocol"]').change(function(){ check_protocol_pwd(); });
});

function get_list(){
    showLoading();
    var params = { act: 'getapi', biz: getBiz() };
    if($_GET['qq']){ params.qq = $_GET['qq']; }
    $.ajax({
        type : 'GET', url : 'ajax.php', data: params, dataType : 'json',
        success : function(data) {
            hideLoading();
            apilist = data;
            protocol = data.protocol;
            apidata = data.data;
            login_config = data.login_config;
            var show_apiclass = login_config.show_apiclass || 0;
            if(show_apiclass == 1){
                $('#cid-container').hide();
            }else{
                $('#cid-container').show();
            }
            var showSelectTip = !(login_config && String(login_config.login_select_open) === '0');
            if(showSelectTip && show_apiclass == 0){
                $('#cid').append('<option value="">请选择分类</option>');
            }
            $.each(data.class, function(k,v){
                $('#cid').append('<option value="'+v.id+'" free="'+v.free+'"'+('selected' in v ?'selected':'')+'>'+v.name+'</option>');
            });
            if(show_apiclass == 1){
                show_api();
            }else if(!$_GET['apiid'] || $_GET['apiid'] == '0'){
                if(showSelectTip){
                    $('#cid').val('');
                }else if($('#cid option').length > 0){
                    $('#cid').val($('#cid option:first').val());
                }
            }
            if(login_config.login_tip != ''){ $('#login_tip').html(login_config.login_tip+'<br/>'); }
            if(login_config.open_qq_quick == 1){ $('#open_qq_quick').show(); }
            show_api();
        },
        error:function(xhr, status, error){ hideLoading(); showToast(handleAjaxError(xhr, status, error), 'error'); }
    });
}

function show_api(){
    var cid = $('#cid').val();
    var show_apiclass = (login_config && login_config.show_apiclass) || 0;
    
    // 如果是隐藏分类模式，直接合并所有节点
    if(show_apiclass == 1){
        $('select[name="apiid"]').html('');
        var all_nodes = [];
        $.each(apidata, function(k, nodes){
            if(!nodes) return true;
            $.each(nodes, function(n, node){
                var exists = all_nodes.some(function(exists_node){ return exists_node.id == node.id; });
                if(!exists) all_nodes.push(node);
            });
        });
        if(all_nodes.length > 0){
            $.each(all_nodes, function(i, v){
                var canUse = (v.can_use == 1) ? ' can_use="1"' : '';
                $('select[name="apiid"]').append('<option value="'+ v.id +'" type_name="'+ v.type +'" apipwd="'+ v.apipwd +'" apimsg="'+ encodeURIComponent(v.msg) +'" apimsg_type="'+ v.msg_type +'" api_error_check="'+ v.api_error_check +'"'+canUse+'>' + v.citybz +_name(v.show_online_census,v.online_census)+'</option>');
            });
            if($_GET['apiid'] && $_GET['apiid'] != 0 && $('select[name="apiid"] option[value="'+$_GET['apiid']+'"]').length > 0){
                $('select[name="apiid"]').val($_GET['apiid']);
            }
            if($_GET['qq']){ $('input[name="qq"]').val($_GET['qq']); }
            if($_GET['pwd']){ $('input[name="pwd"]').val($_GET['pwd']); }
            $('#qr').show();
            updateLoginButtons();
            $('select[name="apiid"]').off('change').on('change', function(){ get_point(); updateLoginButtons(); });
            get_point();
        }else{
            $('select[name="apiid"]').html('<option value="">暂无节点</option>');
            if($_GET['qq']){ $('input[name="qq"]').val($_GET['qq']); }
            if($_GET['pwd']){ $('input[name="pwd"]').val($_GET['pwd']); }
            $('#qr, #pwd').hide();
        }
        return;
    }

    // 仅在当前未选择分类且 URL 中带 apiid 时，根据 apiid 反推一次分类
    if((cid === '' || cid === null) && $_GET['apiid'] && $_GET['apiid'] != 0){
        var foundApiid = false;
        $.each(apidata, function(k,value){
            if(!apidata[k] || apidata[k].length === 0) return true;
            $.each(apidata[k], function(n,v){
                if(v.id == $_GET['apiid']){ $('#cid').val(k); cid = k; foundApiid = true; return false; }
            });
            if(foundApiid) return false;
        });
        if(!foundApiid){
            $('#cid').val('');
            cid = '';
            showToast('指定节点不存在，请选择', 'info');
        }
    }
    if(cid === '' || cid === null){
        var showSelectTip = !(login_config && String(login_config.login_select_open) === '0');
        if(showSelectTip && show_apiclass == 0){
            $('select[name="apiid"]').html('<option value="">请选择节点</option>');
        }else{
            $('select[name="apiid"]').html('');
        }
        $('#free').html('');
        $('#qr, #pwd').hide();
        if($_GET['qq']){ $("input[name='qq']").val($_GET['qq']); }
        if($_GET['pwd']){ $("input[name='pwd']").val($_GET['pwd']); }
        return;
    }
    var free = $('#cid').find("option:selected").attr("free");
    if(free && free != '0' && parseInt(free) > 0){
        $('#free').html('分类节点：<font color="blue">'+$('#cid option:selected').text()+'</font>,可免费体验 '+free+' 天(一号一次)');
    }else{ $('#free').html(''); }
    var needFallback = !apidata[cid] || apidata[cid].length === 0;
    var hasApipwdNode = apidata[cid] && apidata[cid].some(function(v){ return v.apipwd && v.apipwd != '0' && v.apipwd != ''; });
    if(!needFallback && $_GET['qq']){
        var curHasCanUse = false;
        for(var i = 0; i < apidata[cid].length; i++){ if(apidata[cid][i].can_use == 1){ curHasCanUse = true; break; } }
        if(!curHasCanUse && !hasApipwdNode) needFallback = true;
    }
    // 分类设置了免费体验时长(free>0)或有接口密码节点时不提示购买，照常显示节点
    var hasFreeTrial = free && free != '0' && parseInt(free) > 0;
    if(needFallback && (hasFreeTrial || hasApipwdNode)){ needFallback = false; }
    if(needFallback){
        var categoryHasNodes = apidata[cid] && apidata[cid].length > 0;
        if(categoryHasNodes && $_GET['qq']){
            showModal('提示', '当前分类未购买请更换分类或购买', [{ text: '前去购买', class: 'px-4 py-2 bg-indigo-500 hover:bg-indigo-600 text-white rounded-lg text-sm transition-colors', onClick: function(){ window.location.href='./shop.php?qq='+$_GET['qq']+'&version='+encodeURIComponent(getBiz()); } }, { text: '取消', onClick: closeModal }]);
        }else{
            showToast('当前分类下没有登录节点<br>请换一个分类', 'error');
        }
        $('select[name="apiid"]').html('<option value="">暂无节点</option>');
        $('#qr, #pwd').hide();
        return;
    }
    $('select[name="apiid"]').html('');
    var showSelectTip = !(login_config && String(login_config.login_select_open) === '0');
    if(showSelectTip){
        $('select[name="apiid"]').append('<option value="">请选择节点</option>');
    }
    $.each(apidata[cid], function(i,v){
        var canUse = (v.can_use == 1) ? ' can_use="1"' : '';
        $('select[name="apiid"]').append('<option value="'+ v.id +'" type_name="'+ v.type +'" apipwd="'+ v.apipwd +'" apimsg="'+ encodeURIComponent(v.msg) +'" apimsg_type="'+ v.msg_type +'" api_error_check="'+ v.api_error_check +'"'+canUse+'>' + v.citybz +_name(v.show_online_census,v.online_census)+'</option>');
    });
    $('#qr').show();
    updateLoginButtons();
    $('select[name="apiid"]').off('change').on('change', function(){ get_point(); updateLoginButtons(); });
    if($_GET['apiid'] && $_GET['apiid'] != 0 && $('select[name="apiid"] option[value="'+$_GET['apiid']+'"]').length > 0){
        var opt = $('select[name="apiid"] option[value="'+$_GET['apiid']+'"]');
        if(!$_GET['qq'] || opt.attr('can_use') == '1'){
            $('select[name="apiid"]').val($_GET['apiid']);
        }else{
            showToast('指定节点无权限，请选择其他节点', 'info');
        }
    }else if(showSelectTip){
        $('select[name="apiid"]').val('');
    }
    if($_GET['qq']){ $('input[name="qq"]').val($_GET['qq']); }
    if($_GET['pwd']){ $('input[name="pwd"]').val($_GET['pwd']); }
    get_point();
}

function get_point(){
    var type = $('select[name="apiid"]').find("option:selected").attr("type_name");
    var apimsg = $('select[name="apiid"]').find("option:selected").attr("apimsg");
    var apimsg_type = $('select[name="apiid"]').find("option:selected").attr("apimsg_type");
    var apipwd = $('select[name="apiid"]').find("option:selected").attr("apipwd");
    var apiid = $('select[name="apiid"]').val();
    var apiErrorCheck = $('select[name="apiid"]').find("option:selected").attr("api_error_check");
    var errorTip = login_config.api_error_tip || '本节点可能存在异常，请选择其他节点';
    var isNodeLink = apiid && String(apiid).indexOf('link_') === 0;
    if(apiid && !isNodeLink && apiErrorCheck == '1') {
        showLoading();
        $.ajax({
            type : 'POST', url : 'ajax.php?act=check_api', data : {id: apiid}, dataType : 'json',
            success : function(data) {
                hideLoading();
                if(!(data.retcode == 200 || data.code == 0 || data.msg == 'ok' || (data.bot && data.bot.list))){
                    showModal('节点异常', errorTip, [{ text: '确定', onClick: closeModal }]);
                }
            },
            error : function() { hideLoading(); showModal('节点异常', errorTip, [{ text: '确定', onClick: closeModal }]); }
        });
    }
    if(apimsg != 'null' && apimsg != '' && apimsg.trim() != ''){
        if(apimsg_type == '0'){
            $('#apimsg .prose').html(decodeURIComponent(apimsg));
            $('#apimsg').removeClass('hidden');
        }else if(apimsg_type == '1' || apimsg_type == '5' || apimsg_type == '10'){
            $('#apimsg').addClass('hidden');
            var i = Number(apimsg_type);
            var content = decodeURIComponent(apimsg);
            var buttons = [];
            if(i == 1){ buttons.push({ text: '确定', onClick: closeModal }); }
            else if(i == 5 || i == 10){ buttons.push({ text: '关闭 ('+i+'秒)', disabled: true, onClick: closeModal }); }
            showModal(i==1?'信息':'信息 '+i+' 秒后可关闭', content, buttons);
            if(i==5 || i==10){
                var modalTitle = document.getElementById('modalTitle');
                var footerButtons = document.getElementById('modalFooter').querySelectorAll('button');
                var interval = setInterval(function() {
                    modalTitle.textContent = '信息 '+i+' 秒后可关闭';
                    if(footerButtons.length > 0){ footerButtons[0].textContent = '关闭 ('+i+'秒)'; }
                    i--;
                    if(i === 0){
                        clearInterval(interval);
                        modalTitle.textContent = '信息';
                        if(footerButtons.length > 0){
                            footerButtons[0].textContent = '关闭';
                            footerButtons[0].disabled = false;
                            footerButtons[0].classList.remove('opacity-50', 'cursor-not-allowed');
                        }
                    }
                }, 1000);
            }
        }else{
            $('#apimsg .prose').html(decodeURIComponent(apimsg));
            $('#apimsg').removeClass('hidden');
        }
    }else{
        $('#apimsg .prose').html('');
        $('#apimsg').addClass('hidden');
    }
    $('select[name="protocol"]').html('');
    if(type in protocol){
        $.each(protocol[type], function(i,v){
            $('select[name="protocol"]').append('<option value="'+ v.type +'" is_pwd="'+ v.is_pwd +'">' + v.name + '</option>');
        });
    }else{
        $('select[name="protocol"]').append('<option value="0">电脑端</option>');
    }
    if(apipwd && apipwd != '0' && apipwd != ''){ $('#_apipwd').show(); }
    else{ $('#_apipwd').hide(); }
    if($_GET['protocol']){
        if($_GET['protocol'] == 'null'){ $('select[name="protocol"] option:eq(0)').prop('selected', true); }
        else{
            if($('select[name="protocol"] option[value="'+$_GET['protocol']+'"]').length > 0){ $('select[name="protocol"]').val($_GET['protocol']); }
            else{ $('select[name="protocol"] option:eq(0)').prop('selected', true); }
        }
        $_GET['protocol'] = '';
    }
    updateLoginButtons();
}

function _name(zt,count){
    if(zt == 1 && count != 0){ return ' _在线:'+count; }
    return '';
}

var $_GET = (function(){
    if(window.ADD_PAGE_PARAMS){
        var p = window.ADD_PAGE_PARAMS;
        return { qq: p.qq||'', apiid: p.apiid||'', protocol: p.protocol||'', biz: p.biz||'' };
    }
    var url = window.document.location.href.toString();
    var u = url.split("?");
    if(typeof(u[1]) == "string"){
        u = u[1].split("&");
        var get = {};
        for(var i in u){
            var j = u[i].split("=");
            get[decodeURIComponent(j[0])] = decodeURIComponent(j[1]||'');
        }
        return get;
    }
    return {};
})();

function updateLoginButtons(){
    var typeName = $('select[name="apiid"]').find("option:selected").attr("type_name");
    var apipwd = $('select[name="apiid"]').find("option:selected").attr("apipwd");
    if(typeName == 'myqq' || typeName == 'myqqa' || typeName == 'dr'){
        $('#pwd').hide();
        $('#_pwd').hide();
        $('#qr').show();
        if(apipwd && apipwd != '0' && apipwd != ''){ $('#_apipwd').show(); }
        else{ $('#_apipwd').hide(); }
    }else{
        check_protocol_pwd();
        if(apipwd && apipwd != '0' && apipwd != ''){ $('#_apipwd').show(); }
        else{ $('#_apipwd').hide(); }
    }
}

function check_protocol_pwd(){
    var is_pwd = $('select[name="protocol"]').find("option:selected").attr("is_pwd");
    if(is_pwd === undefined || is_pwd === null || is_pwd === ''){ is_pwd = '1'; }
    if(is_pwd == '1'){ $('#_pwd').show(); $('#pwd').show(); $('#qr').show(); }
    else if(is_pwd == '2'){ $('#_pwd').show(); $('#pwd').show(); $('#qr').hide(); }
    else{ $('#_pwd').hide(); $('#pwd').hide(); $('#qr').show(); }
}
