var timeList = new Array();
var pagesize = 20;
var currentPage = 1;
var qqBiz = (window.QQ_BIZ || 'cloud') === 'dg' ? 'dg' : 'cloud';

function openModal(title, body, footer) {
    $('#modalTitle').html(title);
    $('#modalBody').html(body);
    if (footer) {
        $('#modalFooter').html(footer).removeClass('hidden');
    } else {
        $('#modalFooter').html('').addClass('hidden');
    }
    $('#appModal').removeClass('hidden');
}

function closeModal() {
    $('#appModal').addClass('hidden');
}

function showToast(msg, type, duration) {
    duration = duration || 2500;
    type = type || 'default';
    var bgClass = 'bg-gray-800';
    if (type === 'success') bgClass = 'bg-green-500';
    if (type === 'error') bgClass = 'bg-red-500';
    if (type === 'warning') bgClass = 'bg-orange-500';

    var id = 'toast_' + Date.now();
    var el = '<div id="' + id + '" class="px-5 py-2.5 ' + bgClass + ' text-white text-sm rounded-xl shadow-lg animate-fade-in">' + msg + '</div>';
    $('#toastWrap').append(el);
    setTimeout(function(){ $('#' + id).fadeOut(300, function(){ $(this).remove(); }); }, duration);
}

function showLoading() { $('#loadingOverlay').removeClass('hidden'); }
function hideLoading() { $('#loadingOverlay').addClass('hidden'); }

$(document).ready(function(){
    loadList(1);
    $('#initialLoading').hide();
});

function loadList(page, query) {
    currentPage = page;
    query = query || '';
    var url = 'ajax.php?act=qqlist&page=' + page + '&pagesize=' + pagesize + '&biz=' + encodeURIComponent(qqBiz) + '&' + query;
    showLoading();
    $.ajax({
        type: 'GET',
        url: url,
        dataType: 'json',
        success: function(data) {
            hideLoading();
            showlist(data);
            renderPagination(data.total || 0, data.page || 1, data.end || 1);
        },
        error: function() {
            hideLoading();
            showToast('加载失败，请重试', 'error');
        }
    });
}

function searchOrder() {
    var kw = $('input[name="kw"]').val();
    var type = $('select[name="type"]').val();
    var cid = $('select[name="cid"]').val();
    var query = 'kw=' + encodeURIComponent(kw) + '&type=' + type + '&cid=' + cid;
    loadList(1, query);
    return false;
}

function showlist(data) {
    var is_time_shift = data.is_time_shift;
    var html = '';

    if (!Array.isArray(data.data) || data.data.length === 0) {
        html = '<div class="col-span-full">'+
            '<div class="bg-white rounded-2xl shadow-lg p-12 text-center">'+
                '<div class="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4">'+
                    '<i class="fas fa-robot text-gray-400 text-2xl"></i>'+
                '</div>'+
                '<p class="text-gray-500 mb-2">暂无数据</p>'+
                '<a href="./add.php?biz=' + encodeURIComponent(qqBiz) + '" class="text-indigo-600 text-sm hover:underline">前往添加QQ</a>'+
            '</div>'+
        '</div>';
    } else {
        $.each(data.data, function(i, v) {
            var citybz = v.citybz || '默认通道';
            var isOnline = v.login_zt == 1;
            // apipwd ''=收费节点 | '0'=免费 | 有值=接口密码节点(免费)
            var isFree = v.apipwd === '0' || v.apipwd === 0 || (v.apipwd && v.apipwd !== '');
            var remainHtml = calcRemainDays(v.id, v.isend, v.endtime, v.endtime_arr, isFree);
            var noSecond = isQqListExpiredForSecondLogin(isFree, v.endtime);
            var moreTimeBtn = '';
            var avatarHtml = '<img src="//q2.qlogo.cn/headimg_dl?dst_uin=' + v.qq + '&spec=100" class="w-14 h-14 rounded-full border-2 border-indigo-100 object-cover shadow-sm">';
            var statusBadge = isOnline ?
                '<span class="px-2.5 py-1 inline-flex items-center text-xs font-medium rounded-full bg-gradient-to-r from-green-400 to-green-500 text-white shadow-sm"><span class="w-1.5 h-1.5 bg-white rounded-full mr-1.5 animate-pulse"></span>在线</span>' :
                '<span class="px-2.5 py-1 inline-flex items-center text-xs font-medium rounded-full bg-gradient-to-r from-gray-400 to-gray-500 text-white shadow-sm"><span class="w-1.5 h-1.5 bg-white rounded-full mr-1.5"></span>离线</span>';

            var btns = '';
            if (qqBiz === 'dg' && isOnline) {
                btns += '<a href="./bugua.php?qq=' + v.qq + '&id=' + (v.cityid || 0) + '" class="flex-1 flex flex-col items-center justify-center py-2 hover:bg-indigo-50 rounded-lg transition-colors group">'+
                    '<i class="fas fa-cog text-indigo-500 text-sm mb-0.5 group-hover:scale-110 transition-transform"></i>'+
                    '<span class="text-xs text-gray-600 group-hover:text-indigo-600">代挂配置</span>'+
                '</a>';
            }
            if (isOnline) {
                btns += '<button onclick="login(' + v.id + ',1)" class="flex-1 flex flex-col items-center justify-center py-2 hover:bg-red-50 rounded-lg transition-colors group">'+ 
                    '<i class="fas fa-power-off text-red-500 text-sm mb-0.5 group-hover:scale-110 transition-transform"></i>'+ 
                    '<span class="text-xs text-gray-600 group-hover:text-red-600">下线</span>'+ 
                '</button>';
                var nodeTypeOn = v.cid2 ? v.cid2.toLowerCase().trim() : '';
                if (!noSecond && parseInt(v.isend, 10) === 1 && !['myqq', 'myqqa', 'dr'].includes(nodeTypeOn)) {
                    btns += '<button onclick="login(' + v.id + ',0)" class="flex-1 flex flex-col items-center justify-center py-2 hover:bg-indigo-50 rounded-lg transition-colors group">'+ 
                        '<i class="fas fa-key text-indigo-500 text-sm mb-0.5 group-hover:scale-110 transition-transform"></i>'+ 
                        '<span class="text-xs text-gray-600 group-hover:text-indigo-600">二次</span>'+ 
                    '</button>';
                }
            } else {
                btns += '<a href="./add.php?biz=' + encodeURIComponent(qqBiz) + '&qq=' + v.qq + '&apiid=' + v.cityid + '&protocol=' + v.protocol + '" class="flex-1 flex flex-col items-center justify-center py-2 hover:bg-orange-50 rounded-lg transition-colors group">'+ 
                    '<i class="fas fa-redo text-orange-500 text-sm mb-0.5 group-hover:scale-110 transition-transform"></i>'+ 
                    '<span class="text-xs text-gray-600 group-hover:text-orange-600">重登</span>'+ 
                '</a>';
                // 二次登录仅支持dulu、xlz，my/dr不支持
                var nodeType = v.cid2 ? v.cid2.toLowerCase().trim() : '';
                if (!noSecond && !['myqq', 'myqqa', 'dr'].includes(nodeType)) {
                    btns += '<button onclick="login(' + v.id + ',0)" class="flex-1 flex flex-col items-center justify-center py-2 hover:bg-indigo-50 rounded-lg transition-colors group">'+ 
                        '<i class="fas fa-key text-indigo-500 text-sm mb-0.5 group-hover:scale-110 transition-transform"></i>'+ 
                        '<span class="text-xs text-gray-600 group-hover:text-indigo-600">二次</span>'+ 
                    '</button>';
                }
            }

            btns += '<button onclick="get_endtime(' + v.id + ')" class="flex-1 flex flex-col items-center justify-center py-2 hover:bg-blue-50 rounded-lg transition-colors group">'+
                '<i class="fas fa-clock text-blue-500 text-sm mb-0.5 group-hover:scale-110 transition-transform"></i>'+
                '<span class="text-xs text-gray-600 group-hover:text-blue-600">时长</span>'+
            '</button>';
            btns += '<a href="./shop.php?qq=' + v.qq + '&version=' + encodeURIComponent(qqBiz) + '" class="flex-1 flex flex-col items-center justify-center py-2 hover:bg-green-50 rounded-lg transition-colors group">'+
                '<i class="fas fa-sync-alt text-green-500 text-sm mb-0.5 group-hover:scale-110 transition-transform"></i>'+
                '<span class="text-xs text-gray-600 group-hover:text-green-600">续费</span>'+
            '</a>';
            html += '<div class="relative bg-white rounded-2xl border border-indigo-100 shadow-sm overflow-hidden hover:shadow-lg hover:-translate-y-0.5 transition-all">'+
                '<div class="px-3 py-2 bg-gradient-to-r from-indigo-50 to-white border-b border-indigo-100 flex items-center justify-between min-h-[72px]">'+
                    '<div class="flex items-center gap-3">'+
                        '<div class="flex-shrink-0">' + avatarHtml + '</div>'+
                        '<div>'+
                            '<div class="font-semibold text-gray-900 text-base">'+ v.qq + '</div>'+
                            '<div class="mt-1">' + statusBadge + '</div>'+
                        '</div>'+
                    '</div>'+
                    '<button onclick="show_extend(\'' + v.qq + '\',' + v.id + ',\'' + v.p_name + '\',\'' + is_time_shift + '\',\'' + v.dropline + '\',\'' + v.online + '\',\'' + (v.cityid || 0) + '\')" '+
                    'class="w-10 h-10 flex items-center justify-center rounded-full bg-white border border-indigo-100 hover:bg-indigo-50 transition-all">'+
                        '<i class="fas fa-cog text-blue-600 text-xl"></i>'+
                    '</button>'+
                '</div>'+
                '<div class="flex min-h-[70px]">'+
                    '<div class="w-2/3 border-t border-gray-100">'+
                        '<div class="px-3 py-2 text-xs text-gray-500 border-b border-gray-100">'+
                            '<i class="fas fa-tag mr-1"></i>分类: <span class="text-gray-700">' + (v.login_class_name || '未分类') + '</span>'+
                        '</div>'+
                        '<div class="px-3 py-2 text-xs text-gray-500">'+
                            '<i class="fas fa-server mr-1"></i>节点: <span class="text-gray-700">' + citybz + '</span>'+
                        '</div>'+
                    '</div>'+
                    '<div class="flex-1 border-t border-l border-gray-100 flex flex-col items-center justify-center text-xs text-gray-700 bg-gray-50/60">'+
                        '<div class="text-[11px] text-gray-400 mb-0.5">剩余时长</div>' +
                        remainHtml + moreTimeBtn +
                    '</div>'+
                '</div>'+
                '<div class="border-t border-gray-100 flex justify-around py-1.5 px-2 bg-white">'+
                    btns +
                '</div>'+
            '</div>';
        });
    }
    $('#listTable').html(html);
}

function getStatusBadge(id, login_zt, qq, apiid, protocol) {
    var isOnline = login_zt == 1;
    var badge = isOnline ?
        '<span class="px-2 py-0.5 inline-flex text-xs font-semibold rounded-full bg-green-100 text-green-800"><i class="fas fa-check-circle mr-1"></i>在线 (' + qq + ')</span>' :
        '<span class="px-2 py-0.5 inline-flex text-xs font-semibold rounded-full bg-yellow-100 text-yellow-800"><i class="fas fa-exclamation-circle mr-1"></i>离线 (' + qq + ')</span>';

    var actionBtn = '';
    if (isOnline) {
        actionBtn = '<div class="w-full mt-1 flex justify-center">'+ 
            '<button class="px-2 py-0.5 text-xs bg-red-500 hover:bg-red-600 text-white rounded-full transition-colors leading-tight" onclick="login(' + id + ',1)"><i class="fas fa-sign-out-alt mr-1"></i>下线</button>'+ 
            '</div>';
    } else {
        actionBtn = '<div class="w-full mt-1 flex justify-center gap-1">'+ 
            '<a href="./add.php?qq=' + qq + '&apiid=' + apiid + '&protocol=' + protocol + '" class="px-1.5 py-0.5 text-xs bg-orange-500 hover:bg-orange-600 text-white rounded-full transition-colors leading-tight" style="font-size:10px;"><i class="fas fa-redo mr-0.5"></i>重新登录</a>';
        // 二次登录仅支持dulu、xlz，my/dr不支持
        // 注意：此处无法直接获取节点类型，仅在主要列表渲染中进行控制
        // 如果需要在弹窗中也控制，需要修改后端返回更多数据
        actionBtn += '<button class="px-1.5 py-0.5 text-xs bg-indigo-500 hover:bg-indigo-600 text-white rounded-full transition-colors leading-tight" onclick="login(' + id + ',0)" style="font-size:10px;"><i class="fas fa-key mr-0.5"></i>二次登录</button>'+ 
            '</div>';
    }
    return badge + actionBtn;
}

function parseQqListEndDate(dateStr) {
    if (!dateStr) return null;
    var formats = [
        /^(\d{4})-(\d{2})-(\d{2})$/,
        /^(\d{4})\/(\d{2})-(\d{2})$/,
        /^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/,
        /^(\d{4})\/(\d{2})\/(\d{2}) (\d{2}):(\d{2}):(\d{2})$/
    ];
    for (var fi = 0; fi < formats.length; fi++) {
        var match = dateStr.match(formats[fi]);
        if (match) {
            var year = parseInt(match[1], 10);
            var month = parseInt(match[2], 10) - 1;
            var day = parseInt(match[3], 10);
            var hours = match[4] ? parseInt(match[4], 10) : 0;
            var minutes = match[5] ? parseInt(match[5], 10) : 0;
            var seconds = match[6] ? parseInt(match[6], 10) : 0;
            var date = new Date(year, month, day, hours, minutes, seconds);
            if (date.getFullYear() === year && date.getMonth() === month && date.getDate() === day) {
                return date;
            }
        }
    }
    var date = new Date(dateStr);
    return isNaN(date.getTime()) ? null : date;
}

/** 与列表「已过期」展示一致：过期则不允许二次登录（仍可下线） */
function isQqListExpiredForSecondLogin(isFree, endtime) {
    if (isFree) return false;
    var endDate = parseQqListEndDate(endtime);
    if (!endDate) return false;
    return endDate.getTime() <= new Date().getTime();
}

function calcRemainDays(id, isend, endtime, endtime_arr, isFree) {
    timeList[id] = endtime_arr;

    if (isFree) {
        return '<span class="text-green-600">当前节点免费</span>';
    }

    var endDate = parseQqListEndDate(endtime);
    if (!endDate) {
        return '<span class="text-red-500">时间格式异常</span>';
    }

    var nowFull = new Date();
    if (endDate.getTime() <= nowFull.getTime()) {
        return '<span class="text-red-500 font-medium">已过期</span>';
    }

    var now = new Date(); now.setHours(0,0,0,0);
    var targetDate = new Date(endDate); targetDate.setHours(0,0,0,0);

    var diff = _getDateDiff(now, targetDate);
    var displayText = '', colorClass = 'text-indigo-600';

    if (diff.years < 0 || (diff.years === 0 && diff.months < 0) || (diff.years === 0 && diff.months === 0 && diff.days < 0)) {
        displayText = '已过期'; colorClass = 'text-red-500';
    } else if (diff.years === 0 && diff.months === 0 && diff.days === 0) {
        displayText = '今天到期'; colorClass = 'text-orange-500';
    } else {
        var totalMonths = diff.years * 12 + diff.months;
        if (totalMonths > 50) { displayText = '永久'; colorClass = 'text-green-600'; }
        else {
            var parts = [];
            if (diff.years > 0) parts.push(diff.years + '年');
            if (diff.months > 0) parts.push(diff.months + '月');
            if (diff.days > 0) parts.push(diff.days + '天');
            displayText = parts.join('');
        }
    }
    return '<span class="' + colorClass + ' font-medium">' + displayText + '</span>';
}

function _getDateDiff(nowDate, targetDate) {
    var years = targetDate.getFullYear() - nowDate.getFullYear();
    var months = targetDate.getMonth() - nowDate.getMonth();
    var days = targetDate.getDate() - nowDate.getDate();
    if (days < 0) { days += new Date(targetDate.getFullYear(), targetDate.getMonth(), 0).getDate(); months--; }
    if (months < 0) { months += 12; years--; }
    return { years: years, months: months, days: days };
}

function _calcRemainText(timeStr) {
    var endDate = new Date(timeStr.replace(/-/g, '/'));
    if (isNaN(endDate.getTime())) return '时间格式异常';
    var nowFull = new Date();
    if (endDate.getTime() <= nowFull.getTime()) return '已过期';
    var now = new Date(); now.setHours(0, 0, 0, 0);
    var endMid = new Date(endDate); endMid.setHours(0, 0, 0, 0);
    var diff = _getDateDiff(now, endMid);
    if (diff.years < 0 || (diff.years === 0 && diff.months < 0) || (diff.years === 0 && diff.months === 0 && diff.days < 0)) return '已过期';
    if (diff.years === 0 && diff.months === 0 && diff.days === 0) return '今天到期';
    var tm = diff.years * 12 + diff.months;
    if (tm > 50) return '永久';
    var p = [];
    if (diff.years > 0) p.push(diff.years + '年');
    if (diff.months > 0) p.push(diff.months + '月');
    if (diff.days > 0) p.push(diff.days + '天');
    return p.join('');
}

function get_endtime(id) {
    var list = timeList[id];
    if (!list || !list.length) { showToast('无时长数据', 'warning'); return; }

    list.sort(function(a, b) {
        return (b.current || 0) - (a.current || 0);
    });

    var html = '<div class="space-y-3">';
    $.each(list, function(i, v) {
        var isFreeNode = v.free_node == 1;
        var isExpired = v.isend == 1 && !isFreeNode;
        var remainText = isFreeNode ? '免费' : (isExpired ? '已过期' : _calcRemainText(v.time));
        var expiredTag = isExpired ? '<span class="ml-2 px-1.5 py-0.5 text-xs bg-red-100 text-red-600 rounded-full">过期</span>' : '';
        var currentTag = v.current == 1 ? '<span class="ml-2 px-1.5 py-0.5 text-xs bg-green-100 text-green-600 rounded-full">' + (isFreeNode ? '当前免费节点' : '当前') + '</span>' : '';
        var delBtn = isExpired ? '<button class="px-2 py-1 text-xs bg-red-500 hover:bg-red-600 text-white rounded-lg transition-colors" onclick="del_time(' + id + ',' + v.id + ')">删除</button>' : '';
        html += '<div class="flex items-center justify-between p-3 bg-gray-50 border border-gray-100 rounded-xl">'+
            '<div>'+
                '<div class="text-sm font-medium text-gray-800">' + (v.name || '未知') + expiredTag + currentTag + '</div>'+
                '<div class="text-xs text-gray-500 mt-1">到期: ' + (v.time || '-') + '</div>'+
                '<div class="text-xs mt-0.5">剩余: <span class="' + (isFreeNode ? 'text-green-600' : (isExpired ? 'text-red-500' : 'text-indigo-600')) + ' font-medium">' + remainText + '</span></div>'+
            '</div>'+
            '<div>' + delBtn + '</div>'+
        '</div>';
    });
    html += '</div>';
    openModal('时长详情', html);
}

function renderPagination(total, page, totalPages) {
    var html = '';
    if (totalPages <= 1) { $('#pagination').html(''); return; }
    html += '<li><a class="px-3 py-2 rounded-lg border border-gray-300 text-gray-600 hover:bg-gray-50 transition-colors' + (page == 1 ? ' opacity-50 pointer-events-none' : '') + '" href="javascript:loadList(' + (page - 1) + ')">上一页</a></li>';
    for (var i = 1; i <= totalPages; i++) {
        if (i == 1 || i == totalPages || (i >= page - 2 && i <= page + 2)) {
            html += '<li><a class="px-3 py-2 rounded-lg ' + (i == page ? 'bg-indigo-500 text-white' : 'border border-gray-300 text-gray-600 hover:bg-gray-50') + ' transition-colors" href="javascript:loadList(' + i + ')">' + i + '</a></li>';
        } else if (i == page - 3 || i == page + 3) {
            html += '<li><span class="px-3 py-2 text-gray-400">...</span></li>';
        }
    }
    html += '<li><a class="px-3 py-2 rounded-lg border border-gray-300 text-gray-600 hover:bg-gray-50 transition-colors' + (page == totalPages ? ' opacity-50 pointer-events-none' : '') + '" href="javascript:loadList(' + (page + 1) + ')">下一页</a></li>';
    $('#pagination').html(html);
}

function set_qq_config(id, zt, type) {
    type = type || 'dropline';
    showLoading();
    $.ajax({
        type: 'POST', url: 'ajax.php?act=set_qq_config',
        data: {id:id, zt:zt, type:type, biz: qqBiz}, dataType: 'json',
        success: function(data) {
            hideLoading();
            if (data.code == 1) {
                showToast(data.msg, 'success');
                closeModal();
                loadList(currentPage);
            } else {
                showToast(data.msg, 'error');
            }
        },
        error: function() { hideLoading(); showToast('服务器错误', 'error'); }
    });
}

function login(id, zt) {
    showLoading();
    $.ajax({
        type: 'POST', url: 'ajax.php?act=login',
        data: {id:id, zt:zt, biz: qqBiz}, dataType: 'json',
        success: function(data) {
            hideLoading();
            if (data.code == 1) {
                showToast(data.msg, 'success');
                loadList(currentPage);
            } else {
                showToast(data.msg, 'error');
            }
        },
        error: function() { hideLoading(); showToast('服务器错误', 'error'); }
    });
}

function del(id) {
    closeModal();
    var body = '<div class="text-center mb-4">'+
        '<div class="w-14 h-14 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-3"><i class="fas fa-exclamation-triangle text-red-500 text-2xl"></i></div>'+
        '<p class="text-red-600 font-bold mb-1">！！警告！！</p>'+
        '<p class="text-sm text-gray-600">确认删除后，账号授权将彻底抹除且无法恢复，须重新购买。</p>'+
    '</div>'+
    '<input type="text" id="delConfirmInput" class="w-full px-4 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 outline-none" placeholder="请输入 确认删除">';
    var footer = '<div class="flex gap-2 justify-end">'+
        '<button onclick="closeModal()" class="px-4 py-2 text-sm text-gray-600 bg-gray-100 hover:bg-gray-200 rounded-lg transition-colors">取消</button>'+
        '<button onclick="doDelete(' + id + ')" class="px-4 py-2 text-sm text-white bg-red-500 hover:bg-red-600 rounded-lg transition-colors">确认删除</button>'+
    '</div>';
    openModal('删除确认', body, footer);
}

function doDelete(id) {
    var text = $('#delConfirmInput').val();
    if (text !== '确认删除') { showToast('请输入 确认删除', 'warning'); return; }
    closeModal(); showLoading();
    $.post('ajax.php?act=del_qq', {id:id, biz: qqBiz}, function(d) {
        hideLoading();
        if (d.code == 1) {
            showToast(d.msg, 'success');
            loadList(currentPage);
        } else {
            showToast(d.msg, 'error');
        }
    }, 'json').fail(function(){ hideLoading(); showToast('服务器错误', 'error'); });
}

function del_time(id, cids) {
    showLoading();
    $.ajax({
        type: 'POST', url: 'ajax.php?act=del_time',
        data: {id:id, cids:cids, biz: qqBiz}, dataType: 'json',
        success: function(data) {
            hideLoading();
            if (data.code == 1) {
                showToast(data.msg, 'success');
                closeModal();
                loadList(currentPage);
            } else {
                showToast(data.msg, 'error');
            }
        },
        error: function() { hideLoading(); showToast('服务器错误', 'error'); }
    });
}

function shift(id) {
    closeModal();
    var body = '<div class="text-center mb-4">'+
        '<p class="text-sm text-red-500 mb-2">把到期时长转移到其他的账号</p>'+
    '</div>'+
    '<input type="text" id="shiftQQInput" class="w-full px-4 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 outline-none" placeholder="输入自己平台内的QQ号">';
    var footer = '<div class="flex gap-2 justify-end">'+
        '<button onclick="closeModal()" class="px-4 py-2 text-sm text-gray-600 bg-gray-100 hover:bg-gray-200 rounded-lg transition-colors">取消</button>'+
        '<button onclick="doShift(' + id + ')" class="px-4 py-2 text-sm text-white bg-indigo-500 hover:bg-indigo-600 rounded-lg transition-colors">确认转移</button>'+
    '</div>';
    openModal('时长转移', body, footer);
}

function doShift(id) {
    var qq = $('#shiftQQInput').val();
    if (!qq) { showToast('请输入QQ号', 'warning'); return; }
    closeModal(); showLoading();
    $.post('ajax.php?act=qq_time_shift', {id:id, qq:qq, biz: qqBiz}, function(d) {
        hideLoading();
        if (d.code == 1) {
            showToast(d.msg, 'success');
            loadList(currentPage);
        } else {
            showToast(d.msg, 'error');
        }
    }, 'json').fail(function(){ hideLoading(); showToast('服务器错误', 'error'); });
}

function show_extend(qq, id, v, v2, v3, v4, cityid) {
    var items = '';
    items += '<div class="flex items-center justify-between p-3 bg-gray-50 rounded-xl">'+
        '<div class="text-sm text-gray-700">登录通道</div>'+
        '<div class="text-sm text-indigo-600 font-medium">' + v + '</div>'+
    '</div>';
    items += '<div class="flex items-center justify-between p-3 bg-gray-50 rounded-xl">'+
        '<div class="text-sm text-gray-700">删除账号 <span class="text-red-500 text-xs">谨慎操作</span></div>'+
        '<button class="px-3 py-1 text-xs text-white bg-red-500 hover:bg-red-600 rounded-lg transition-colors" onclick="del(' + id + ')">删除</button>'+
    '</div>';
    if (v2 == 1) {
        items += '<div class="flex items-center justify-between p-3 bg-gray-50 rounded-xl">'+
            '<div class="text-sm text-gray-700">时长转移</div>'+
            '<button class="px-3 py-1 text-xs text-white bg-green-500 hover:bg-green-600 rounded-lg transition-colors" onclick="shift(' + id + ')">转移</button>'+
        '</div>';
    }
    items += '<div class="flex items-center justify-between p-3 bg-gray-50 rounded-xl">'+
        '<div>'+
            '<div class="text-sm text-gray-700">掉线重登</div>'+
            '<div class="text-xs text-red-400">多个地方登录会挤线</div>'+
        '</div>'+
        (v3 == 1 ?
            '<button class="px-3 py-1 text-xs text-white bg-green-500 hover:bg-green-600 rounded-lg transition-colors" onclick="set_qq_config(' + id + ',' + v3 + ')">开启中</button>' :
            '<button class="px-3 py-1 text-xs text-white bg-gray-400 hover:bg-gray-500 rounded-lg transition-colors" onclick="set_qq_config(' + id + ',' + v3 + ')">已关闭</button>'
        ) +
    '</div>';
    items += '<div class="flex items-center justify-between p-3 bg-gray-50 rounded-xl">'+
        '<div>'+
            '<div class="text-sm text-gray-700">自动登录</div>'+
            '<div class="text-xs text-red-400">二次登录数据不失效时</div>'+
        '</div>'+
        (v4 == 0 ?
            '<button class="px-3 py-1 text-xs text-white bg-green-500 hover:bg-green-600 rounded-lg transition-colors" onclick="set_qq_config(' + id + ',' + v4 + ',\'online\')">开启中</button>' :
            '<button class="px-3 py-1 text-xs text-white bg-gray-400 hover:bg-gray-500 rounded-lg transition-colors" onclick="set_qq_config(' + id + ',' + v4 + ',\'online\')">已关闭</button>'
        ) +
    '</div>';

    openModal('账号: ' + qq, '<div class="space-y-3"><div class="text-xs text-gray-400">更多设置与安全操作</div>' + items + '</div>');
}


function recoverQQ() {
    window.RECOVER_BIZ = qqBiz;
    var body = '<div style="padding:10px;">'+
        '<div class="text-center font-bold" id="login">'+
            '<span id="loginmsg">请先使用QQ手机版扫描二维码</span>'+
            '<span id="loginload" style="padding-left:10px;color:#790909;">.</span>'+
        '</div>'+
        '<div class="flex justify-center my-3" id="qrimg"></div>'+
        '<div class="flex flex-col gap-2">'+
            '<button class="w-full px-4 py-2 bg-indigo-500 hover:bg-indigo-600 text-white rounded-lg text-sm transition-colors" onclick="getqrpic(true)">刷新二维码</button>'+
            '<button class="w-full px-4 py-2 bg-yellow-500 hover:bg-yellow-600 text-white rounded-lg text-sm transition-colors" onclick="mloginurlnew()">QQ快捷登录</button>'+
        '</div>'+
    '</div>';
    openModal('找回QQ', body);
    $.getScript('qqlogin/qrlogin.js');
}

function refreshList() {
    loadList(currentPage);
}
