<?php
/**
 * QQ空间秒赞后台管理 - QQ列表
 */
$title = 'QQ列表（秒赞）';
include __DIR__ . '/head.php';

// 检查是否安装
$tables = $DB->getColumn("SHOW TABLES LIKE '" . DBQZ . "qzone_qq'", 0);
if (!$tables) {
    include __DIR__ . '/foot.php';
    exit;
}
?>

<div class="p-4 md:p-6">
    <!-- QQ列表 -->
    <div class="bg-white rounded-lg shadow">
        <div class="p-4 md:p-6 border-b border-gray-200">
            <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-3">
                <h2 class="text-base md:text-lg font-semibold text-gray-800">QQ列表</h2>
                <div class="flex flex-wrap items-center gap-2">
                    <form onsubmit="loadQQList(1);return false;" class="flex items-center gap-2 w-full md:w-auto">
                        <input type="text" class="flex-1 min-w-[100px] px-2.5 py-1.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm" id="search_qq" placeholder="输入QQ号">
                        <select class="min-w-[80px] px-2.5 py-1.5 border border-gray-300 rounded-lg text-sm" id="filter_status">
                            <option value="">全部</option>
                            <option value="0">在线</option>
                            <option value="1">离线</option>
                            <option value="2">过期</option>
                        </select>
                        <button type="submit" class="px-2.5 py-1.5 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition text-sm">
                            <i class="fas fa-search"></i>
                        </button>
                    </form>
                    <div class="flex flex-wrap gap-2 w-full sm:w-auto">
                        <button type="button" class="flex-1 sm:flex-none px-2.5 py-1.5 bg-purple-600 hover:bg-purple-700 text-white font-medium rounded-lg transition text-sm whitespace-nowrap" onclick="syncCloudTime()">
                            <i class="fas fa-cloud-download-alt mr-1"></i>同步云端时长
                        </button>
                        <button type="button" class="flex-1 sm:flex-none px-2.5 py-1.5 bg-yellow-600 hover:bg-yellow-700 text-white font-medium rounded-lg transition text-sm whitespace-nowrap" onclick="batchEditTime()">
                            <i class="fas fa-clock mr-1"></i>批量增减时长
                        </button>
                        <button type="button" class="flex-1 sm:flex-none px-2.5 py-1.5 bg-red-600 hover:bg-red-700 text-white font-medium rounded-lg transition text-sm whitespace-nowrap" onclick="batchDeleteQQ()">
                            <i class="fas fa-trash mr-1"></i>批量删除
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <div class="p-3 md:p-6">
            <div class="overflow-x-auto">
                <table class="w-full min-w-[800px]">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase whitespace-nowrap">选择</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase whitespace-nowrap">QQ</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase whitespace-nowrap">所属ZID</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase whitespace-nowrap">账号状态</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase whitespace-nowrap">VIP到期</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase whitespace-nowrap">操作</th>
                        </tr>
                    </thead>
                    <tbody id="qq_list" class="divide-y divide-gray-200">
                        <tr><td colspan="6" class="px-4 py-8 text-center text-gray-400">加载中...</td></tr>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- 分页和数量显示 -->
        <div class="px-4 py-3 border-t border-gray-200 flex flex-col sm:flex-row sm:items-center justify-between gap-3 text-sm">
            <div class="text-gray-500">
                共 <span id="qq_total_count">0</span> 条记录
            </div>
            <div class="flex items-center gap-2">
                <select class="px-2.5 py-1 border border-gray-300 rounded text-xs" id="qq_pagesize" onchange="loadQQList(1)">
                    <option value="30">30</option>
                    <option value="50">50</option>
                    <option value="100">100</option>
                    <option value="200">200</option>
                </select>
                <button onclick="qqPrevPage()" id="qq_prev_btn" disabled
                        class="px-2.5 py-1 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded text-xs transition-colors">
                    <i class="fas fa-chevron-left"></i>
                </button>
                <span class="text-gray-500">第 <span id="qq_current_page">1</span> / <span id="qq_total_pages">1</span> 页</span>
                <button onclick="qqNextPage()" id="qq_next_btn" disabled
                        class="px-2.5 py-1 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded text-xs transition-colors">
                    <i class="fas fa-chevron-right"></i>
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 增减时长弹窗（Tailwind） -->
<div id="edit_time_modal" class="fixed inset-0 bg-black/50 hidden items-center justify-center z-50">
    <div class="bg-white rounded-2xl w-full max-w-md mx-4 shadow-2xl overflow-hidden">
        <div class="p-4 border-b flex justify-between items-center">
            <h3 class="font-bold text-gray-800">增减VIP时长</h3>
            <button type="button" onclick="hideEditTimeModal()" class="text-gray-400 hover:text-gray-600 text-xl leading-none">&times;</button>
        </div>
        <div class="p-4 space-y-3">
            <input type="hidden" id="edit_qq_id">
            <input type="hidden" id="edit_qq_zid">
            <div>
                <label class="block text-xs font-medium text-gray-700 mb-1">QQ号</label>
                <input type="text" id="edit_qq_display" class="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm bg-gray-50" readonly>
            </div>
            <div>
                <label class="block text-xs font-medium text-gray-700 mb-1">当前VIP到期</label>
                <input type="text" id="edit_vip_time" class="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm bg-gray-50" readonly>
            </div>
            <div>
                <label class="block text-xs font-medium text-gray-700 mb-1">增减时长</label>
                <div class="flex flex-col sm:flex-row gap-2">
                    <select class="px-3 py-2 border border-gray-200 rounded-lg text-sm w-full sm:w-28" id="edit_renew_type">
                        <option value="0">增加</option>
                        <option value="1">减少</option>
                    </select>
                    <input type="number" class="flex-1 px-3 py-2 border border-gray-200 rounded-lg text-sm" id="edit_time_num" placeholder="请输入数值" value="30">
                    <select class="px-3 py-2 border border-gray-200 rounded-lg text-sm w-full sm:w-20" id="edit_time_type">
                        <option value="0">月</option>
                        <option value="1" selected>天</option>
                        <option value="3">年</option>
                    </select>
                </div>
            </div>
        </div>
        <div class="p-4 border-t flex gap-2 justify-end">
            <button type="button" class="px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg text-sm font-medium" onclick="hideEditTimeModal()">取消</button>
            <button type="button" id="btn_confirm_edit_time" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm font-medium" onclick="confirmEditTime(this)">确定</button>
        </div>
    </div>
</div>

<!-- 批量增减时长弹窗（Tailwind） -->
<div id="batch_edit_time_modal" class="fixed inset-0 bg-black/50 hidden items-center justify-center z-50">
    <div class="bg-white rounded-2xl w-full max-w-md mx-4 shadow-2xl overflow-hidden">
        <div class="p-4 border-b flex justify-between items-center">
            <h3 class="font-bold text-gray-800">批量增减VIP时长</h3>
            <button type="button" onclick="hideBatchEditTimeModal()" class="text-gray-400 hover:text-gray-600 text-xl leading-none">&times;</button>
        </div>
        <div class="p-4 space-y-3">
            <div>
                <label class="block text-xs font-medium text-gray-700 mb-1">已选择数量</label>
                <input type="text" id="batch_selected_count" class="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm bg-gray-50" readonly value="0">
            </div>
            <div>
                <label class="block text-xs font-medium text-gray-700 mb-1">增减时长</label>
                <div class="flex flex-col sm:flex-row gap-2">
                    <select class="px-3 py-2 border border-gray-200 rounded-lg text-sm w-full sm:w-28" id="batch_renew_type">
                        <option value="0">增加</option>
                        <option value="1">减少</option>
                    </select>
                    <input type="number" class="flex-1 px-3 py-2 border border-gray-200 rounded-lg text-sm" id="batch_time_num" placeholder="请输入数值" value="30">
                    <select class="px-3 py-2 border border-gray-200 rounded-lg text-sm w-full sm:w-20" id="batch_time_type">
                        <option value="0">月</option>
                        <option value="1" selected>天</option>
                        <option value="3">年</option>
                    </select>
                </div>
            </div>
        </div>
        <div class="p-4 border-t flex gap-2 justify-end">
            <button type="button" class="px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg text-sm font-medium" onclick="hideBatchEditTimeModal()">取消</button>
            <button type="button" id="btn_confirm_batch_edit_time" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm font-medium" onclick="confirmBatchEditTime(this)">确定</button>
        </div>
    </div>
</div>

<!-- 通用确认弹窗（Tailwind） -->
<div id="confirm_modal" class="fixed inset-0 bg-black/50 hidden items-center justify-center z-50">
    <div class="bg-white rounded-2xl w-full max-w-sm mx-4 shadow-2xl overflow-hidden">
        <div class="p-4 border-b flex justify-between items-center">
            <h3 class="font-bold text-gray-800" id="confirm_title">请确认</h3>
            <button type="button" onclick="hideConfirmModal()" class="text-gray-400 hover:text-gray-600 text-xl leading-none">&times;</button>
        </div>
        <div class="p-4 text-sm text-gray-700" id="confirm_message"></div>
        <div class="p-4 border-t flex gap-2 justify-end">
            <button type="button" class="px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg text-sm font-medium" onclick="hideConfirmModal()">取消</button>
            <button type="button" id="btn_confirm_ok" class="px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg text-sm font-medium" onclick="confirmOk(this)">确定</button>
        </div>
    </div>
</div>

<script>
var qqPage = 1, qqPages = 1;

function loadQQList(page) {
    qqPage = page || 1;
    var qq = document.getElementById('search_qq').value;
    var status = document.getElementById('filter_status').value;
    var pagesize = document.getElementById('qq_pagesize').value;

    $.post('ajax_qzone.php?act=get_qq_list', {page: qqPage, qq: qq, status: status, pagesize: pagesize}, function(res) {
        if (res.code === 1) {
            var html = '';
            if (res.data.length === 0) {
                html = '<tr><td colspan="6" class="px-4 py-8 text-center text-gray-400">暂无数据</td></tr>';
            } else {
                res.data.forEach(function(item) {
                    var statusClass = item.login_status == 0 ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800';
                    var statusText = item.login_status == 0 ? '在线' : '离线';
                    var isVip = new Date(item.vip_time) > new Date();
                    
                    // VIP到期时间显示，可点击编辑
                    var vipTimeClass = isVip ? 'text-yellow-600 cursor-pointer hover:underline' : 'text-gray-400 cursor-pointer hover:underline';
                    var vipTimeText = isVip ? item.vip_time : '未开通';
                    
                    // 计算剩余天数
                    var remainText = '';
                    if (isVip) {
                        var now = new Date();
                        var vipDate = new Date(item.vip_time);
                        var diff = vipDate - now;
                        var days = Math.floor(diff / (1000 * 60 * 60 * 24));
                        if (days > 0) {
                            remainText = '<span class="text-xs text-gray-500">(剩余' + days + '天)</span>';
                        }
                    }

                    html += '<tr class="hover:bg-gray-50">' +
                        '<td class="px-4 py-3"><input type="checkbox" class="qq-checkbox" data-id="' + item.id + '" data-qq="' + item.qq + '" data-zid="' + item.user_id + '"></td>' +
                        '<td class="px-4 py-3">' +
                            '<div class="flex items-center">' +
                                '<img src="https://q1.qlogo.cn/g?b=qq&nk=' + item.qq + '&s=100" class="w-8 h-8 rounded-full mr-3" onerror="this.src=\'https://q1.qlogo.cn/g?b=qq&nk=0&s=100\'">' +
                                '<div>' +
                                    '<div class="font-medium text-gray-800">' + item.qq + '</div>' +
                                    '<div class="text-xs text-gray-500">' + escHtml(item.nickname || '') + '</div>' +
                                '</div>' +
                            '</div>' +
                        '</td>' +
                        '<td class="px-4 py-3 text-gray-600">' + item.user_id + '</td>' +
                        '<td class="px-4 py-3"><span class="px-2 py-1 text-xs rounded-full ' + statusClass + '">' + statusText + '</span></td>' +
                        '<td class="px-4 py-3 text-sm">' +
                            '<span class="' + vipTimeClass + '" onclick="openEditTime(' + item.id + ', \'' + item.qq + '\', \'' + item.vip_time + '\', ' + item.user_id + ')">' + vipTimeText + '</span> ' + remainText +
                        '</td>' +
                        '<td class="px-4 py-3 whitespace-nowrap">' +
                            '<div class="flex items-center gap-1.5">' +
                                '<a href="./sso.php?zid=' + item.user_id + '" target="_blank" class="px-2.5 py-1.5 text-xs bg-emerald-600 hover:bg-emerald-700 text-white font-medium rounded-lg transition shadow-sm whitespace-nowrap"><i class="fas fa-sign-in-alt mr-1"></i>登入</a>' +
                                '<button onclick="openEditTime(' + item.id + ', \'' + item.qq + '\', \'' + item.vip_time + '\', ' + item.user_id + ')" class="px-2.5 py-1.5 text-xs bg-amber-500 hover:bg-amber-600 text-white font-medium rounded-lg transition shadow-sm whitespace-nowrap"><i class="fas fa-clock mr-1"></i>时长</button>' +
                                '<button onclick="deleteQQ(' + item.id + ')" class="px-2.5 py-1.5 text-xs bg-red-600 hover:bg-red-700 text-white font-medium rounded-lg transition shadow-sm whitespace-nowrap"><i class="fas fa-trash"></i></button>' +
                            '</div>' +
                        '</td></tr>';
                });
            }
            document.getElementById('qq_list').innerHTML = html;

            qqPages = res.pages || 1;
            document.getElementById('qq_total_count').textContent = res.total || 0;
            document.getElementById('qq_current_page').textContent = qqPage;
            document.getElementById('qq_total_pages').textContent = qqPages;

            document.getElementById('qq_prev_btn').disabled = qqPage <= 1;
            document.getElementById('qq_next_btn').disabled = qqPage >= qqPages;
        }
    }, 'json');
}

function qqPrevPage() {
    if (qqPage > 1) loadQQList(qqPage - 1);
}

function qqNextPage() {
    if (qqPage < qqPages) loadQQList(qqPage + 1);
}

// 打开增减时长弹窗
function openEditTime(id, qq, vipTime, zid) {
    document.getElementById('edit_qq_id').value = id;
    document.getElementById('edit_qq_zid').value = zid;
    document.getElementById('edit_qq_display').value = qq;
    document.getElementById('edit_vip_time').value = vipTime || '未开通';
    document.getElementById('edit_time_num').value = 30;
    document.getElementById('edit_renew_type').value = '0';
    document.getElementById('edit_time_type').value = '1';
    showEditTimeModal();
}

// 确认增减时长
function confirmEditTime(btn) {
    // 防止重复点击
    if (btn.disabled) return;
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i>处理中...';
    
    var id = document.getElementById('edit_qq_id').value;
    var renewType = document.getElementById('edit_renew_type').value;
    var timeNum = parseInt(document.getElementById('edit_time_num').value) || 0;
    var timeType = document.getElementById('edit_time_type').value;
    
    // 计算天数
    var days = 0;
    if (timeType == 0) {
        days = timeNum * 30; // 月
    } else if (timeType == 1) {
        days = timeNum; // 天
    } else if (timeType == 3) {
        days = timeNum * 365; // 年
    }
    
    if (renewType == 1) {
        days = -days; // 减少时长
    }
    
    $.post('ajax_qzone.php?act=set_vip', {qid: id, days: days}, function(res) {
        btn.disabled = false;
        btn.innerHTML = '确定';
        if (res.code === 1) {
            showToast('操作成功', 'success');
            hideEditTimeModal();
            loadQQList(qqPage);
        } else {
            showToast(res.msg, 'error');
        }
    }, 'json').fail(function() {
        btn.disabled = false;
        btn.innerHTML = '确定';
        showToast('网络错误，请重试', 'error');
    });
}

// 获取选中的QQ
function getSelectedQQs() {
    var selected = [];
    document.querySelectorAll('.qq-checkbox:checked').forEach(function(cb) {
        selected.push({
            id: cb.dataset.id,
            qq: cb.dataset.qq,
            zid: cb.dataset.zid
        });
    });
    return selected;
}

// 批量增减时长
function batchEditTime() {
    var selected = getSelectedQQs();
    if (selected.length === 0) {
        showToast('请先选择要操作的QQ', 'warning');
        return;
    }
    document.getElementById('batch_selected_count').value = selected.length + ' 个';
    document.getElementById('batch_time_num').value = 30;
    document.getElementById('batch_renew_type').value = '0';
    document.getElementById('batch_time_type').value = '1';
    showBatchEditTimeModal();
}

// 确认批量增减时长
function confirmBatchEditTime(btn) {
    // 防止重复点击
    if (btn.disabled) return;
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i>处理中...';
    
    var selected = getSelectedQQs();
    var renewType = document.getElementById('batch_renew_type').value;
    var timeNum = parseInt(document.getElementById('batch_time_num').value) || 0;
    var timeType = document.getElementById('batch_time_type').value;
    
    // 计算天数
    var days = 0;
    if (timeType == 0) {
        days = timeNum * 30; // 月
    } else if (timeType == 1) {
        days = timeNum; // 天
    } else if (timeType == 3) {
        days = timeNum * 365; // 年
    }
    
    if (renewType == 1) {
        days = -days; // 减少时长
    }
    
    var ids = selected.map(function(item) { return item.id; });
    $.post('ajax_qzone.php?act=batch_set_vip', {ids: ids.join(','), days: days}, function(res) {
        btn.disabled = false;
        btn.innerHTML = '确定';
        if (res.code === 1) {
            showToast('批量操作成功', 'success');
            hideBatchEditTimeModal();
            loadQQList(qqPage);
        } else {
            showToast(res.msg, 'error');
        }
    }, 'json').fail(function() {
        btn.disabled = false;
        btn.innerHTML = '确定';
        showToast('网络错误，请重试', 'error');
    });
}

function deleteQQ(id) {
    showConfirmModal('删除QQ', '确定要删除该QQ账号吗？', function(done) {
        $.post('ajax_qzone.php?act=delete_qq', {id: id}, function(res) {
            done();
            if (res.code === 1) {
                showToast('删除成功', 'success');
                loadQQList(qqPage);
            } else {
                showToast(res.msg, 'error');
            }
        }, 'json').fail(function() {
            done();
            showToast('网络错误，请重试', 'error');
        });
    });
}

function batchDeleteQQ() {
    var selected = getSelectedQQs();
    if (selected.length === 0) {
        showToast('请先选择要删除的QQ', 'warning');
        return;
    }
    var ids = selected.map(function(item) { return item.id; });
    showConfirmModal('批量删除', '确定要删除选中的 ' + selected.length + ' 个QQ吗？', function(done) {
        $.post('ajax_qzone.php?act=batch_delete_qq', {ids: ids.join(',')}, function(res) {
            done();
            if (res.code === 1) {
                showToast('批量删除成功', 'success');
                loadQQList(qqPage);
            } else {
                showToast(res.msg, 'error');
            }
        }, 'json').fail(function() {
            done();
            showToast('网络错误，请重试', 'error');
        });
    });
}

function syncCloudTime() {
    showConfirmModal('同步云端时长', '确定要从云端同步QQ到秒赞吗？<br>只会同步云端存在的QQ，秒赞已有QQ不会重复添加', function(done) {
        $.post('ajax_qzone.php?act=sync_cloud_time', {}, function(res) {
            done();
            if (res.code === 1) {
                showToast('同步成功：新增 ' + res.added + ' 个QQ', 'success');
                loadQQList(1);
            } else if (res.code === 0) {
                showToast(res.msg, 'warning');
            } else {
                showToast(res.msg || '同步失败', 'error');
            }
        }, 'json').fail(function() {
            done();
            showToast('网络错误，请重试', 'error');
        });
    });
}

// ================== Tailwind 弹窗控制 ==================
function showEditTimeModal() {
    var m = document.getElementById('edit_time_modal');
    m.classList.remove('hidden');
    m.classList.add('flex');
}
function hideEditTimeModal() {
    var m = document.getElementById('edit_time_modal');
    m.classList.add('hidden');
    m.classList.remove('flex');
    var btn = document.getElementById('btn_confirm_edit_time');
    if (btn) { btn.disabled = false; btn.innerHTML = '确定'; }
}
function showBatchEditTimeModal() {
    var m = document.getElementById('batch_edit_time_modal');
    m.classList.remove('hidden');
    m.classList.add('flex');
}
function hideBatchEditTimeModal() {
    var m = document.getElementById('batch_edit_time_modal');
    m.classList.add('hidden');
    m.classList.remove('flex');
    var btn = document.getElementById('btn_confirm_batch_edit_time');
    if (btn) { btn.disabled = false; btn.innerHTML = '确定'; }
}

var confirmCallback = null;
function showConfirmModal(title, message, onConfirm) {
    confirmCallback = typeof onConfirm === 'function' ? onConfirm : null;
    document.getElementById('confirm_title').innerText = title || '请确认';
    document.getElementById('confirm_message').innerHTML = message || '';
    var btn = document.getElementById('btn_confirm_ok');
    btn.disabled = false;
    btn.innerHTML = '确定';
    var m = document.getElementById('confirm_modal');
    m.classList.remove('hidden');
    m.classList.add('flex');
}
function hideConfirmModal() {
    var m = document.getElementById('confirm_modal');
    m.classList.add('hidden');
    m.classList.remove('flex');
    confirmCallback = null;
}
function confirmOk(btn) {
    if (!confirmCallback) { hideConfirmModal(); return; }
    if (btn.disabled) return;
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i>处理中...';
    // 提供 done() 给回调，结束 loading 并关闭弹窗
    confirmCallback(function done() {
        hideConfirmModal();
    });
}

// HTML转义
function escHtml(str) {
    if (!str) return '';
    return str.replace(/&/g, '&amp;')
              .replace(/</g, '&lt;')
              .replace(/>/g, '&gt;')
              .replace(/"/g, '&quot;')
              .replace(/'/g, '&#039;');
}

// 初始化加载
loadQQList(1);
</script>

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