var pagesize = 30;
var page = 1;
var totalCount = 0;
var totalPages = 1;
var timeList = new Array();
var currentDelTimeId;
var currentDelTimeCids;
var qqBiz = 'cloud';

function searchOrder() {
    get_list(1);
}

function refreshTable() {
    pagesize = $('select[name="pageSize"]').val();
    get_list(1);
}

function openModal() {
    $('#batch_modal').modal('show');
}

function to_all_time(){
    $('#batch_modal').modal('hide');
    $('#to_all_time_modal').modal('show');
}

function confirm_to_all_time(){
    $('#to_all_time_modal').modal('hide');
    // 显示加载状态
    var loadingHtml = '<div class="loading-overlay" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.8); z-index: 9999; display: flex; justify-content: center; align-items: center;"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">加载中...</span></div></div>';
    $('body').append(loadingHtml);
    
    $.ajax({
        type : 'GET',
        url : 'ajax.php?act=to_all_time',
        data : {biz: qqBiz},
        dataType : 'json',
        success : function(data) {
            // 隐藏加载状态
            $('.loading-overlay').remove();
            showNotification(data.msg);
            if(data.code == 1){
                location.reload();
            }
        },
        error:function(data){
            // 隐藏加载状态
            $('.loading-overlay').remove();
            showNotification('服务器错误');
        }
    });
}

function all_del_qq(){
    $('#batch_modal').modal('hide');
    $('#all_del_qq_modal').modal('show');
}

function confirm_all_del_qq(){
    $('#all_del_qq_modal').modal('hide');
    var type = $('#del_type').val();
    // 显示加载状态
    var loadingHtml = '<div class="loading-overlay" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.8); z-index: 9999; display: flex; justify-content: center; align-items: center;"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">加载中...</span></div></div>';
    $('body').append(loadingHtml);
    
    $.ajax({
        type : 'POST',
        url : 'ajax.php?act=all_del_qq',
        data : {type:type, biz: qqBiz},
        dataType : 'json',
        success : function(data) {
            // 隐藏加载状态
            $('.loading-overlay').remove();
            showNotification(data.msg);
            if(data.code == 1){
                $('#endtime_modal').modal('hide');
                get_list(1);
            }
        },
        error:function(data){
            // 隐藏加载状态
            $('.loading-overlay').remove();
            showNotification('服务器错误');
        }
    });
}

function all_edit_time(){
    var renew_type = $('#renew_type1').val();
    var num = $('#num1').val();
    var cid = $('#cid1').val();
    var type = $('#type1').val();
    var remark = $('#remark').val();
    // 显示加载状态
    var loadingHtml = '<div class="loading-overlay" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.8); z-index: 9999; display: flex; justify-content: center; align-items: center;"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">加载中...</span></div></div>';
    $('body').append(loadingHtml);
    
    $.ajax({
        type : 'POST',
        url : 'ajax.php?act=all_edit_time',
        data : {cid:cid,renew_type:renew_type,num:num,type:type,remark:remark,biz: qqBiz},
        dataType : 'json',
        success : function(data) {
            // 隐藏加载状态
            $('.loading-overlay').remove();
            // 无论成功还是失败都关闭批量操作弹窗
            $('#batch_modal').modal('hide');
            showNotification(data.msg);
            if(data.code == 1){
                location.reload();
            }
        },
        error:function(data){
            // 隐藏加载状态
            $('.loading-overlay').remove();
            // 错误时也关闭批量操作弹窗
            $('#batch_modal').modal('hide');
            showNotification('服务器错误');
        }
    });
}

function add_qq_time(){
    var cid = $('#cid_add_qq_time').val();
    var qq = $('#add_qq_time').val();
    // 显示加载状态
    var loadingHtml = '<div class="loading-overlay" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.8); z-index: 9999; display: flex; justify-content: center; align-items: center;"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">加载中...</span></div></div>';
    $('body').append(loadingHtml);
    
    $.ajax({
        type : 'POST',
        url : 'ajax.php?act=add_qq_time',
        data : {cid:cid,qq:qq,type:$('#add_qq_time_type').val(),num:$('#add_qq_time_num').val(),userzid:$('#userzid').val(),biz: qqBiz},
        dataType : 'json',
        success : function(data) {
            // 隐藏加载状态
            $('.loading-overlay').remove();
            if(data.code == 1){
                $('#batch_modal').modal('hide');
                showNotification(data.msg);
                location.reload();
            }else{
                showNotification(data.msg);
            }
        },
        error:function(data){
            // 隐藏加载状态
            $('.loading-overlay').remove();
            showNotification('服务器错误');
        }
    });
}

function showNotification(message) {
    $('#notification_message').text(message);
    $('#notification_modal').modal('show');
}

function confirm_batch_del() {
    $('#batch_del_confirm_modal').modal('hide');
    batch_delqq();
}

function batch_delqq(){
    var ids = [];
    $('input[name="checkbox[]"]:checked').each(function() {
        ids.push($(this).val());
    });
    
    if(ids.length == 0) {
        showNotification('请选择要删除的QQ');
        return;
    }
    
    // 显示加载状态
    var loadingHtml = '<div class="loading-overlay" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255,255,255,0.8); z-index: 9999; display: flex; justify-content: center; align-items: center;"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">加载中...</span></div></div>';
    $('body').append(loadingHtml);
    
    $.ajax({
        type : 'POST',
        url : 'ajax.php?act=batch_delqq',
        data : {ids: ids, biz: qqBiz},
        dataType : 'json',
        success : function(data) {
            // 隐藏加载状态
            $('.loading-overlay').remove();
            
            var content = '';
            if(data.code == 1){
                content = '<div class="text-green-600 mb-2"><i class="fas fa-check-circle mr-2"></i>删除完成</div>' +
                          '<div class="text-sm text-gray-600">成功删除 ' + data.success_count + ' 个QQ，失败 ' + data.fail_count + ' 个</div>';
            }else{
                content = '<div class="text-red-600 mb-2"><i class="fas fa-times-circle mr-2"></i>删除失败</div>' +
                          '<div class="text-sm text-gray-600">' + (data.msg || '未知错误') + '</div>';
            }
            $('#batch_del_result_content').html(content);
            $('#batch_del_result_modal').modal('show');
            if(data.code == 1){
                get_list(1);
            }
        },
        error:function(data){
            // 隐藏加载状态
            $('.loading-overlay').remove();
            var content = '<div class="text-red-600 mb-2"><i class="fas fa-times-circle mr-2"></i>服务器错误</div>' +
                          '<div class="text-sm text-gray-600">' + (data.msg || '未知错误') + '</div>';
            $('#batch_del_result_content').html(content);
            $('#batch_del_result_modal').modal('show');
        }
    });
}

function get_list(pageNum, query) {
    page = pageNum || 1;
    query = query || '';
    var kw = $('input[name="kw"]').val();
    var type = $('select[name="type"]').val();
    
    // 显示加载状态
    var loadingHtml = '<div class="loading-overlay" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.8); z-index: 9999; display: flex; justify-content: center; align-items: center;"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">加载中...</span></div></div>';
    $('body').append(loadingHtml);
    
    $.ajax({
        type: 'POST',
        url: 'ajax.php?act=get_qqlist',
        data: {
            kw: kw,
            type: type,
            pagesize: pagesize,
            page: page,
            biz: qqBiz
        },
        dataType: 'json',
        success: function(data) {
            // 隐藏加载状态
            $('.loading-overlay').remove();
            
            if (data && Array.isArray(data.data) && data.data.length) {
                var html = '';
                $.each(data.data, function(index, row) {
                    timeList[row.id] = row.endtime_arr;
                    var statusClass = row.login_zt == 1 ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700';
                    var statusText = row.login_zt == 1 ? '在线' : '离线';
                    var interfaceName = row.cname || row.citybz || '未绑定接口';
                    var endtimeClass = row.endtime > new Date().toISOString().slice(0, 19).replace('T', ' ') ? 'text-blue-600 hover:underline' : 'text-red-600 hover:underline';
                    var endtimeHtml = '<span class="' + endtimeClass + '" onclick="get_endtime(' + row.id + ')">' + row.endtime + '</span>';
                    if (row.endtime_arr && row.endtime_arr.length > 1) {
                        endtimeHtml += ' <span class="px-1 py-0.5 text-xs bg-gray-200 text-gray-700 rounded cursor-pointer" onclick="get_endtime(' + row.id + ')"><i class="fa fa-chevron-down"></i></span>';
                    }
                    
                    html += '<tr class="hover:bg-gray-50">';
                    html += '<td class="px-4 py-3 text-sm text-gray-500 whitespace-nowrap"><input type="checkbox" name="checkbox[]" value="' + row.id + '" class="rounded border-gray-300"></td>';
                    html += '<td class="px-4 py-3 text-sm font-medium text-gray-800 whitespace-nowrap">' + row.qq + '</td>';
                    html += '<td class="px-4 py-3 text-sm whitespace-nowrap"><span class="text-blue-600 hover:underline cursor-pointer" onclick="setzid(' + row.id + ')">' + row.zid + '</span></td>';
                    html += '<td class="px-4 py-3 whitespace-nowrap"><span class="px-2 py-1 text-xs ' + statusClass + ' rounded">' + statusText + '</span></td>';
                    html += '<td class="px-4 py-3 text-sm text-gray-600 whitespace-nowrap">' + row.cityid + '</td>';
                    html += '<td class="px-4 py-3 whitespace-nowrap"><span class="text-blue-600 hover:underline cursor-pointer" onclick="setapiid(' + row.id + ',\'' + interfaceName + '\')">' + interfaceName + '</span></td>';
                    html += '<td class="px-4 py-3 text-sm whitespace-nowrap">' + endtimeHtml + '</td>';
                    html += '<td class="px-4 py-3 whitespace-nowrap">';
                    html += '<div class="flex items-center gap-1.5 whitespace-nowrap">';
                    html += '<a href="./sso.php?zid=' + row.zid + '" target="_blank" class="px-2 py-0.5 text-xs bg-green-600 text-white rounded hover:bg-green-700 whitespace-nowrap">登入</a>';
                    html += '<button onclick="deleteQQ(' + row.id + ')" class="px-2 py-0.5 text-xs bg-red-600 text-white rounded hover:bg-red-700 whitespace-nowrap">删除</button>';
                    html += '</div>';
                    html += '</td>';
                    html += '</tr>';
                });
                $('#qq-list').html(html);
                
                // 更新分页信息
                totalCount = data.total || 0;
                totalPages = Math.ceil(totalCount / pagesize) || 1;
                $('#totalCount').text(totalCount);
                $('#currentPage').text(page);
                $('#totalPages').text(totalPages);
                
                // 更新分页按钮状态
                $('#prevPage').prop('disabled', page == 1);
                $('#nextPage').prop('disabled', page == totalPages);
            } else {
                $('#qq-list').html('<tr><td colspan="8" class="px-6 py-12 text-center text-gray-500"><i class="fas fa-robot text-3xl mb-2"></i><p>暂无QQ数据</p></td></tr>');
                $('#totalCount').text('0');
                $('#currentPage').text('1');
                $('#totalPages').text('1');
                $('#prevPage').prop('disabled', true);
                $('#nextPage').prop('disabled', true);
            }
        },
        error: function() {
            // 隐藏加载状态
            $('.loading-overlay').remove();
            showNotification('服务器错误');
            $('#qq-list').html('<tr><td colspan="8" class="px-6 py-12 text-center text-gray-500"><i class="fas fa-exclamation-triangle text-3xl mb-2"></i><p>加载失败</p></td></tr>');
            $('#totalCount').text('0');
            $('#currentPage').text('1');
            $('#totalPages').text('1');
            $('#prevPage').prop('disabled', true);
            $('#nextPage').prop('disabled', true);
        }
    });
}

function prevPage() {
    if (page > 1) {
        get_list(page - 1);
    }
}

function nextPage() {
    if (page < totalPages) {
        get_list(page + 1);
    }
}

var currentRenewId;

function renewQQ(id) {
    currentRenewId = id;
    $('#renew_qq_modal').modal('show');
}

function confirm_renew_qq() {
    var text = $('#renew_time').val();
    if(!text) return;
    $('#renew_qq_modal').modal('hide');
    // 显示加载状态
    var loadingHtml = '<div class="loading-overlay" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.8); z-index: 9999; display: flex; justify-content: center; align-items: center;"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">加载中...</span></div></div>';
    $('body').append(loadingHtml);
    
    $.ajax({
        type: 'POST',
        url: 'ajax.php?act=renew_qq',
        data: {id: currentRenewId, time: text, biz: qqBiz},
        dataType: 'json',
        success: function(data) {
            // 隐藏加载状态
            $('.loading-overlay').remove();
            showNotification(data.msg);
            if(data.code == 1) {
                get_list(page);
            }
        }
    });
}

var currentDeleteId;

function deleteQQ(id) {
    currentDeleteId = id;
    $('#delete_qq_modal').modal('show');
}

function confirm_delete_qq() {
    $('#delete_qq_modal').modal('hide');
    // 显示加载状态
    var loadingHtml = '<div class="loading-overlay" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.8); z-index: 9999; display: flex; justify-content: center; align-items: center;"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">加载中...</span></div></div>';
    $('body').append(loadingHtml);
    
    $.ajax({
        type: 'POST',
        url: 'ajax.php?act=delete_qq',
        data: {id: currentDeleteId, biz: qqBiz},
        dataType: 'json',
        success: function(data) {
            // 隐藏加载状态
            $('.loading-overlay').remove();
            showNotification(data.msg);
            if(data.code == 1) {
                get_list(page);
            }
        }
    });
}

function get_endtime(id) {
    var endtime_arr = timeList[id];
    if(!endtime_arr || endtime_arr.length == 0) return;
    
    var html = '';
        for(var i = 0; i < endtime_arr.length; i++) {
            var item = endtime_arr[i];
            html += '<div class="flex justify-between items-start gap-2 p-3 border-b min-w-0"><div class="min-w-0 flex-1" style="word-break:break-word;overflow-wrap:break-word;"><span class="font-medium">' + item.name + '</span><span class="mx-2">：</span><br><span>' + item.time + '</span>' + (item.isend == 1 ? '<span class="text-danger ms-2">（已过期）</span>' : '') + '</div><div class="flex items-center gap-1.5 flex-shrink-0"><button type="button" class="px-2 py-0.5 text-xs bg-blue-600 text-white rounded hover:bg-blue-700" onclick="edit_endtime(' + id + ',' + item.id + ')">增减</button><button type="button" class="px-2 py-0.5 text-xs bg-red-600 text-white rounded hover:bg-red-700" onclick="del_time(' + id + ',' + item.id + ')">删除</button></div></div>';
        }
    
    $('#endtime_modal .modal-body').html(html);
    $('#endtime_modal').modal('show');
}

function setzid(id) {
    var tmp = '<div class="mb-3"><label class="block text-sm font-medium mb-2">用户ZID</label><input type="number" class="w-full px-3 py-2 border border-gray-300 rounded-lg" id="zid" placeholder="请输入ZID"></div>';
    $('#setzid_modal .modal-body').html(tmp);
    $('#setzid_modal').data('id', id);
    $('#setzid_modal').modal('show');
}

function confirm_setzid() {
    var id = $('#setzid_modal').data('id');
    var zid = $('#zid').val();
    if(!zid) return;
    
    $('#setzid_modal').modal('hide');
    // 显示加载状态
    var loadingHtml = '<div class="loading-overlay" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.8); z-index: 9999; display: flex; justify-content: center; align-items: center;"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">加载中...</span></div></div>';
    $('body').append(loadingHtml);
    
    $.ajax({
        type : 'POST',
        url : 'ajax.php?act=setzid',
        data : {id:id,zid:zid,biz: qqBiz},
        dataType : 'json',
        success : function(data) {
            // 隐藏加载状态
            $('.loading-overlay').remove();
            showNotification(data.msg);
            if(data.code == 1){
                $('#endtime_modal').modal('hide');
                get_list(page);
            }
        },
        error:function(data){
            // 隐藏加载状态
            $('.loading-overlay').remove();
            showNotification('服务器错误');
        }
    });
}

function setapiid(id, cname) {
    // 显示加载状态
    var loadingHtml = '<div class="loading-overlay" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.8); z-index: 9999; display: flex; justify-content: center; align-items: center;"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">加载中...</span></div></div>';
    $('body').append(loadingHtml);
    
    $.ajax({
        type : 'POST',
        url : 'ajax.php?act=getapiid',
        data : {id:id, biz: qqBiz},
        dataType : 'json',
        success : function(data) {
            // 隐藏加载状态
            $('.loading-overlay').remove();
            let tmp = '<div style="padding:20px;">当前接口：<b><font color="red">'+cname+'</font></b><br><select class="w-full px-3 py-2 border border-gray-300 rounded-lg mt-2" id="apiid">';
            $.each(data, function(i,v){
                tmp += '<option value="'+v.id+'">'+(v.type2==1?'【独享】'+v.citybz:v.citybz)+'</option>';
            });
            tmp += '</select><font color="red" class="block mt-2">如果开启了【QQ与登录接口绑定】<br>此操作可给QQ号更换登录接口</font></div>';
            $('#setapiid_modal .modal-body').html(tmp);
            $('#setapiid_modal').data('id', id);
            $('#setapiid_modal').modal('show');
        },
        error:function(data){
            // 隐藏加载状态
            $('.loading-overlay').remove();
            showNotification('服务器错误');
        }
    });
}

function confirm_setapiid() {
    var id = $('#setapiid_modal').data('id');
    var apiid = $('#apiid').val();
    if(!apiid) return;
    
    $('#setapiid_modal').modal('hide');
    // 显示加载状态
    var loadingHtml = '<div class="loading-overlay" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.8); z-index: 9999; display: flex; justify-content: center; align-items: center;"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">加载中...</span></div></div>';
    $('body').append(loadingHtml);
    
    $.ajax({
        type : 'POST',
        url : 'ajax.php?act=setapiid',
        data : {id:id,apiid:apiid,biz: qqBiz},
        dataType : 'json',
        success : function(data) {
            // 隐藏加载状态
            $('.loading-overlay').remove();
            showNotification(data.msg);
            if(data.code == 1){
                $('#endtime_modal').modal('hide');
                get_list(page);
            }
        },
        error:function(data){
            // 隐藏加载状态
            $('.loading-overlay').remove();
            showNotification('服务器错误');
        }
    });
}

function edit_endtime(id, cids) {
    var tmp = '<div class="flex flex-wrap gap-2 mt-2"><select class="flex-1 min-w-[120px] px-3 py-2 border border-gray-300 rounded-lg" id="renew_type"><option value="0">续费</option><option value="1">扣除</option></select><input type="number" class="flex-1 min-w-[120px] px-3 py-2 border border-gray-300 rounded-lg" id="num" placeholder="请输入数值"><select class="flex-1 min-w-[80px] px-3 py-2 border border-gray-300 rounded-lg" id="type"><option value="0">月</option><option value="1">天</option></select></div>';
    $('#edit_endtime_modal .modal-body').html(tmp);
    $('#edit_endtime_modal').data('id', id);
    $('#edit_endtime_modal').data('cids', cids);
    $('#edit_endtime_modal').modal('show');
}

function confirm_edit_endtime() {
    var id = $('#edit_endtime_modal').data('id');
    var cids = $('#edit_endtime_modal').data('cids');
    var renew_type = $('#renew_type').val();
    var num = $('#num').val();
    var type = $('#type').val();
    if(!num) return;
    
    $('#edit_endtime_modal').modal('hide');
    // 显示加载状态
    var loadingHtml = '<div class="loading-overlay" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.8); z-index: 9999; display: flex; justify-content: center; align-items: center;"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">加载中...</span></div></div>';
    $('body').append(loadingHtml);
    
    $.ajax({
        type : 'POST',
        url : 'ajax.php?act=edit_endtime',
        data : {id:id,cids:cids,renew_type:renew_type,num:num,type:type,biz: qqBiz},
        dataType : 'json',
        success : function(data) {
            // 隐藏加载状态
            $('.loading-overlay').remove();
            showNotification(data.msg);
            if(data.code == 1){
                $('#endtime_modal').modal('hide');
                get_list(page);
            }
        },
        error:function(data){
            // 隐藏加载状态
            $('.loading-overlay').remove();
            showNotification('服务器错误');
        }
    });
}

function del_time(id, cids) {
    currentDelTimeId = id;
    currentDelTimeCids = cids;
    $('#del_time_modal').modal('show');
}

function confirm_del_time() {
    $('#del_time_modal').modal('hide');
    // 显示加载状态
    var loadingHtml = '<div class="loading-overlay" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.8); z-index: 9999; display: flex; justify-content: center; align-items: center;"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">加载中...</span></div></div>';
    $('body').append(loadingHtml);
    
    $.ajax({
        type : 'POST',
        url : 'ajax.php?act=del_time',
        data : {id: currentDelTimeId, cids: currentDelTimeCids, biz: qqBiz},
        dataType : 'json',
        success : function(data) {
            // 隐藏加载状态
            $('.loading-overlay').remove();
            showNotification(data.msg);
            if(data.code == 1){
                $('#endtime_modal').modal('hide');
                get_list(page);
            }
        },
        error:function(data){
            // 隐藏加载状态
            $('.loading-overlay').remove();
            showNotification('服务器错误');
        }
    });
}

$(document).ready(function() {
    $(document).on('show.bs.modal', '.modal', function() {
        var openModals = $('.modal.show').length;
        var zIndex = 1055 + (openModals * 20);
        $(this).css('z-index', zIndex);
        setTimeout(function() {
            $('.modal-backdrop').not('.modal-stack').last().css('z-index', zIndex - 10).addClass('modal-stack');
        }, 0);
    });
    qqBiz = ($('#biz').val() || 'cloud') === 'dg' ? 'dg' : 'cloud';
    get_list(1);
});
