<?php
$title='接口数据';
include __DIR__ . '/head.php';

$is=$DB->getColumn("select count(*) from information_schema.columns where table_name = 'pre_loginconfig' and column_name = 'cid'");
if($is==0){
	$DB->exec("ALTER TABLE `pre_loginconfig` ADD COLUMN `cid` varchar(255) DEFAULT NULL COMMENT '协议分类' AFTER `id`");
	$DB->exec("ALTER TABLE `pre_loginconfig` ADD COLUMN `cids` int(11) NOT NULL DEFAULT 0 COMMENT '分类id' AFTER `cid`");
}
?>

<div class="p-4 md:p-6">
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
        <div class="p-4 md:p-6 border-b border-gray-200">
            <h2 class="text-base md:text-lg font-semibold text-gray-800">接口数据</h2>
        </div>
        <div class="p-4 md:p-6">
            <div class="mb-4 flex gap-2">
                <button type="button" class="px-4 py-2 bg-indigo-600 hover:bg-indigo-700 text-white font-medium rounded-lg transition text-sm" onclick="delAllOffline()">
                    <i class="fas fa-layer-group mr-2"></i>删除所有节点离线
                </button>
            </div>

            <div class="mb-6">
                <div class="grid grid-cols-1 md:grid-cols-4 gap-4 items-center">
                    <label class="text-xs md:text-sm font-medium text-gray-700">选择接口</label>
                    <div class="md:col-span-3">
                        <select class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm" id="apiid">
                            <option value="0">请选择接口</option>
                            <?php
                            $rs = $DB->query("SELECT * FROM pre_loginconfig");
                            while($res = $rs->fetch()){
                                echo '<option value="'.$res['id'].'">'.$res['citybz'].'</option>';
                            }
                            ?>
                        </select>
                    </div>
                </div>
            </div>

            <div class="mb-4 p-4 bg-red-50 border border-red-200 rounded-lg">
                <p class="text-sm text-red-600">
                    <i class="fas fa-exclamation-triangle mr-2"></i>
                    注意：部分框架删除QQ时，框架会崩、卡死、假死、闪退，会报数组下标报错等问题，这是框架自身的问题
                </p>
            </div>

            <div class="mb-4 flex gap-2">
                <button type="button" class="px-4 py-2 bg-red-600 hover:bg-red-700 text-white font-medium rounded-lg transition text-sm" onclick="delqq()">
                    <i class="fas fa-trash mr-2"></i>选择删除
                </button>
                <button type="button" class="px-4 py-2 bg-orange-600 hover:bg-orange-700 text-white font-medium rounded-lg transition text-sm" onclick="delOffline()">
                    <i class="fas fa-user-slash mr-2"></i>删除离线
                </button>
            </div>

            <div class="overflow-x-auto">
                <table class="w-full min-w-[600px] divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">选择</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">QQ</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">昵称</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                        </tr>
                    </thead>
                    <tbody id="table-body" class="bg-white divide-y divide-gray-200">
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- 删除所有节点离线-确认弹窗 -->
<div class="modal fade" id="del_all_offline_confirm_modal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered mx-auto" style="max-width: 360px;">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">删除所有离线</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-3">
                <p class="text-sm text-gray-700 mb-0" style="white-space: pre-line; word-break: break-word;">确定要删除所有节点下的离线QQ吗？
将并发请求各节点，请勿重复点击。</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="px-3 py-1.5 border border-gray-300 rounded-lg text-sm" data-bs-dismiss="modal">取消</button>
                <button type="button" class="px-3 py-1.5 bg-indigo-600 hover:bg-indigo-700 text-white font-medium rounded-lg transition text-sm" id="del_all_offline_confirm_btn">确定</button>
            </div>
        </div>
    </div>
</div>

<!-- 删除结果弹窗 -->
<div class="modal fade" id="del_result_modal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered mx-auto" style="max-width: 400px;">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">删除结果</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-3">
                <div id="del_result_content"></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="px-3 py-1.5 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition text-sm" data-bs-dismiss="modal">确定</button>
            </div>
        </div>
    </div>
</div>

<?php include 'foot.php'; ?>


<script>
    $(document).ready(function(){
        $('#apiid').change(function(){ get_frame_qq(); });
        $('#del_all_offline_confirm_btn').on('click', function(){ doDelAllOffline(); });
        // 关闭「删除所有离线」确认弹窗时强制收起「删除结果」弹窗，避免闪过
        $('#del_all_offline_confirm_modal').on('hidden.bs.modal', function(){
            $('#del_result_modal').modal('hide');
        });
    });

    function get_frame_qq() {
        var apiid = $('#apiid').val();
        if(apiid == 0)return false;
        showLoading();
        $.ajax({
            type : 'POST',
            url : 'ajax.php?act=get_frame_qq',
            data : {apiid:apiid},
            dataType : 'json',
            success : function(data) {
                hideLoading();
                var rows = data.rows || [];
                fillTable(rows);
            },
            error:function(data){
                hideLoading();
                showToast('服务器错误', 'error');
                return false;
            }
        });
    }

    function fillTable(data) {
        var tbody = $('#table-body');
        tbody.empty();
        
        if (data.length === 0) {
            var emptyRow = '<tr><td colspan="4" class="px-4 py-4 text-center text-gray-500">暂无数据</td></tr>';
            tbody.append(emptyRow);
            return;
        }
        
        $.each(data, function(index, row) {
            var statusHtml = row.zt == '登录成功' ? 
                '<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">登录成功</span>' : 
                '<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">未登录</span>';
            
            var nick = (row.nick || '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
            var rowHtml = '<tr>' +
                '<td class="px-4 py-3">' +
                    '<input type="checkbox" class="form-checkbox h-4 w-4 text-blue-600 rounded" data-qq="' + row.qq + '">' +
                '</td>' +
                '<td class="px-4 py-3 text-sm text-gray-900">' + row.qq + '</td>' +
                '<td class="px-4 py-3 text-sm text-gray-600">' + nick + '</td>' +
                '<td class="px-4 py-3">' + statusHtml + '</td>' +
            '</tr>';
            
            tbody.append(rowHtml);
        });
    }

    function delOffline(){
        var checkboxes = $('#table-body input[type="checkbox"]');
        var qq = [];
        var offlineCount = 0;
        
        checkboxes.each(function() {
            var row = $(this).closest('tr');
            var statusText = row.find('td:last').text().trim();
            if(statusText === '未登录'){
                qq.push($(this).data('qq'));
                offlineCount++;
            }
        });
        
        if(offlineCount == 0){
            showToast('没有离线的QQ', 'error');return false;
        }
        
        showLoading();
        $.ajax({
            type : 'POST',
            url : 'ajax.php?act=batch_del_frame_qq',
            data : {apiid:$('#apiid').val(),qq:JSON.stringify(qq)},
            dataType : 'json',
            success : function(data) {
                hideLoading();
                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>';
                }
                $('#del_result_content').html(content);
                $('#del_result_modal').modal('show');
                if(data.code == 1){
                    get_frame_qq();
                }
            },
            error:function(xhr, status, error){
                hideLoading();
                console.log('删除失败:', xhr.responseText);
                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">' + (xhr.responseText || error) + '</div>';
                $('#del_result_content').html(content);
                $('#del_result_modal').modal('show');
                return false;
            }
        });
    }

    function delAllOffline(){
        $('#del_result_modal').modal('hide');
        $('#del_all_offline_confirm_modal').modal('show');
    }
    function doDelAllOffline(){
        $('#del_all_offline_confirm_modal').modal('hide');
        showLoading();
        $.ajax({
            type : 'POST',
            url : 'ajax.php?act=batch_del_all_offline',
            data : {},
            dataType : 'json',
            success : function(data) {
                hideLoading();
                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 mb-2">成功 ' + data.success_count + ' 个，失败 ' + data.fail_count + ' 个</div>';
                    if(data.node_results && data.node_results.length){
                        content += '<div class="text-xs text-gray-500 border-t pt-2 mt-2 max-h-32 overflow-y-auto">';
                        $.each(data.node_results, function(i, r){
                            if(r.success > 0 || r.fail > 0)
                                content += '<div>' + (r.name || ('节点' + (i+1))) + '：成功 ' + (r.success||0) + '，失败 ' + (r.fail||0) + '</div>';
                        });
                        content += '</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>';
                }
                $('#del_result_content').html(content);
                $('#del_result_modal').modal('show');
                if(data.code == 1 && $('#apiid').val() != '0'){
                    get_frame_qq();
                }
            },
            error:function(xhr, status, error){
                hideLoading();
                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">' + (xhr.responseText || error) + '</div>';
                $('#del_result_content').html(content);
                $('#del_result_modal').modal('show');
            }
        });
    }

    function delqq(){
        var checkboxes = $('#table-body input[type="checkbox"]:checked');
        var qq = [];
        
        checkboxes.each(function() {
            qq.push($(this).data('qq'));
        });
        
        if(qq.length<1){
            showToast('请勾选后再删除', 'error');return false;
        }
        
        showLoading();
        $.ajax({
            type : 'POST',
            url : 'ajax.php?act=batch_del_frame_qq',
            data : {apiid:$('#apiid').val(),qq:JSON.stringify(qq)},
            dataType : 'json',
            success : function(data) {
                hideLoading();
                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>';
                }
                $('#del_result_content').html(content);
                $('#del_result_modal').modal('show');
                if(data.code == 1){
                    get_frame_qq();
                }
            },
            error:function(xhr, status, error){
                hideLoading();
                console.log('删除失败:', xhr.responseText);
                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">' + (xhr.responseText || error) + '</div>';
                $('#del_result_content').html(content);
                $('#del_result_modal').modal('show');
                return false;
            }
        });
    }
</script>
