<?php
$title = '代挂操作';
include __DIR__ . '/head.php';

if((($conf['dg_open'] ?? '0') != '1')) {
    echo '<div class="p-4 text-center text-gray-500">代挂系统未开启</div>';
    include __DIR__ . '/foot.php';
    exit;
}

$qq = isset($_GET['qq']) ? preg_replace('/\D/', '', (string)$_GET['qq']) : '';
if(!preg_match('/^[0-9]{4,10}$/', $qq)) {
    echo '<div class="p-4 text-center text-gray-500">参数错误</div>';
    include __DIR__ . '/foot.php';
    exit;
}

$qqrow = $DB->getRow("SELECT qq,cityid,login_zt,endtime_arr FROM pre_dg_qq WHERE qq='{$qq}' AND zid='{$userrow['zid']}' LIMIT 1");
if(!$qqrow) {
    echo '<div class="p-4 text-center text-gray-500">该代挂QQ不在您名下</div>';
    include __DIR__ . '/foot.php';
    exit;
}

$endArr = json_decode($qqrow['endtime_arr'] ?? '', true);
if(!is_array($endArr)) $endArr = [];
$hasValid = false;
$maxEndTs = 0;
foreach($endArr as $t){
    $ts = $t ? strtotime($t) : 0;
    if($ts > $maxEndTs) $maxEndTs = $ts;
    if($ts > time()) $hasValid = true;
}
$maxEnd = $maxEndTs > 0 ? date('Y-m-d H:i:s', $maxEndTs) : '-';

$loginOk = (intval($qqrow['login_zt']) === 1 && intval($qqrow['cityid']) > 0);
$nodeId = intval($qqrow['cityid'] ?? 0);
$nodeName = '';
$nodeHasApi = false;
if($nodeId > 0){
    $node = $DB->getRow("SELECT citybz,query_api FROM pre_loginconfig WHERE id='{$nodeId}' AND biz='dg' AND status='1' LIMIT 1");
    if($node){
        $nodeName = $node['citybz'] ?? '';
        $nodeHasApi = !empty($node['query_api']);
    }
}
?>

<script>
window.DG_OPS_PARAMS = <?php echo json_encode([
    'qq' => $qqrow['qq'],
    'hasValid' => $hasValid ? 1 : 0,
    'maxEnd' => $maxEnd,
    'nodeId' => $nodeId,
    'nodeName' => $nodeName,
    'loginOk' => $loginOk ? 1 : 0,
    'nodeHasApi' => $nodeHasApi ? 1 : 0,
], JSON_UNESCAPED_UNICODE); ?>;
</script>

<div class="space-y-4">
    <div class="bg-white rounded-2xl border border-indigo-100 shadow-sm p-4 md:p-5">
        <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
            <div class="flex items-center gap-3 min-w-0">
                <img src="//q2.qlogo.cn/headimg_dl?dst_uin=<?php echo htmlspecialchars($qqrow['qq']); ?>&spec=100" class="w-14 h-14 rounded-full border-2 border-indigo-100 object-cover shadow-sm">
                <div class="min-w-0">
                    <div class="text-lg font-bold text-gray-900 truncate"><?php echo htmlspecialchars($qqrow['qq']); ?></div>
                    <div class="mt-1 flex flex-wrap items-center gap-2">
                        <span class="px-2.5 py-1 inline-flex items-center text-xs font-medium rounded-full <?php echo $loginOk ? 'bg-emerald-50 text-emerald-700 border border-emerald-100' : 'bg-gray-100 text-gray-500 border border-gray-200'; ?>">
                            <?php echo $loginOk ? '在线' : '离线'; ?>
                        </span>
                        <span class="px-2.5 py-1 inline-flex items-center text-xs font-medium rounded-full <?php echo $nodeId > 0 ? 'bg-indigo-50 text-indigo-700 border border-indigo-100' : 'bg-gray-100 text-gray-500 border border-gray-200'; ?>">
                            <?php echo $nodeId > 0 ? ('节点：' . htmlspecialchars($nodeName ?: (string)$nodeId)) : '节点：未登录'; ?>
                        </span>
                        <span class="px-2.5 py-1 inline-flex items-center text-xs font-medium rounded-full <?php echo $hasValid ? 'bg-emerald-50 text-emerald-700 border border-emerald-100' : 'bg-rose-50 text-rose-700 border border-rose-100'; ?>">
                            到期：<?php echo htmlspecialchars($maxEnd); ?>
                        </span>
                    </div>
                </div>
            </div>
            <div class="flex gap-2">
                <a href="./qqlist.php?biz=dg" class="px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg text-sm font-medium transition-colors inline-flex items-center gap-2">
                    <i class="fas fa-arrow-left text-xs"></i>
                    返回列表
                </a>
            </div>
        </div>
    </div>

    <div class="bg-white rounded-2xl border border-indigo-100 shadow-sm p-4 md:p-5">
        <div class="flex items-center justify-between gap-3">
            <div class="min-w-0">
                <div class="text-base font-semibold text-gray-800 inline-flex items-center gap-2">
                    <i class="fas fa-sliders-h text-indigo-500"></i>
                    代挂配置
                </div>
            </div>
        </div>

        <div id="dg_state_loading" class="mt-4 rounded-xl border border-gray-100 bg-gray-50 p-4 flex items-center gap-3">
            <div class="w-5 h-5 border-2 border-indigo-200 border-t-indigo-600 rounded-full animate-spin"></div>
            <div class="text-sm text-gray-600">正在加载数据...</div>
        </div>

        <div id="dg_state_error" class="hidden mt-4 rounded-xl border border-rose-100 bg-rose-50 p-4">
            <div class="text-sm font-semibold text-rose-700 inline-flex items-center gap-2">
                <i class="fas fa-circle-xmark"></i>
                加载失败
            </div>
            <div id="dg_state_error_msg" class="text-xs text-rose-600 mt-1"></div>
            <div class="mt-3">
                <button type="button" class="px-4 py-2 bg-gray-800 hover:bg-gray-900 text-white rounded-lg text-sm font-medium transition-colors inline-flex items-center gap-2" onclick="dgQuery()">
                    <i class="fas fa-rotate-right text-xs"></i>
                    重新尝试
                </button>
            </div>
        </div>

        <div id="dg_state_expired" class="hidden mt-4 rounded-xl border border-amber-100 bg-amber-50 p-4">
            <div class="text-sm font-semibold text-amber-700 inline-flex items-center gap-2">
                <i class="fas fa-triangle-exclamation"></i>
                账号已到期
            </div>
            <div class="text-xs text-amber-600 mt-1">续费后才能进行查询/补挂/开关操作</div>
            <div class="mt-3">
                <a id="dg_renew_link" href="#" class="px-4 py-2 bg-amber-600 hover:bg-amber-700 text-white rounded-lg text-sm font-medium transition-colors inline-flex items-center gap-2">
                    <i class="fas fa-cart-shopping text-xs"></i>
                    前往续费
                </a>
            </div>
        </div>

        <div id="dg_state_login" class="hidden mt-4 rounded-xl border border-indigo-100 bg-indigo-50 p-4">
            <div class="text-sm font-semibold text-indigo-700 inline-flex items-center gap-2">
                <i class="fas fa-right-to-bracket"></i>
                需要登录
            </div>
            <div class="text-xs text-indigo-600 mt-1">请先在代挂版登录该QQ，登录后才能执行查询/补挂/开关</div>
            <div class="mt-3">
                <a id="dg_login_link" href="#" class="px-4 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg text-sm font-medium transition-colors inline-flex items-center gap-2">
                    <i class="fas fa-user-check text-xs"></i>
                    去登录
                </a>
            </div>
        </div>

        <div id="dg_state_noapi" class="hidden mt-4 rounded-xl border border-rose-100 bg-rose-50 p-4">
            <div class="text-sm font-semibold text-rose-700 inline-flex items-center gap-2">
                <i class="fas fa-ban"></i>
                节点不支持代挂操作
            </div>
            <div class="text-xs text-rose-600 mt-1">该QQ绑定的登录节点未开通代挂操作能力，请到后台节点管理检查</div>
        </div>

        <div id="dg_content" class="hidden mt-4 space-y-4">
            <div class="grid grid-cols-2 lg:grid-cols-4 gap-3">
                <div class="rounded-2xl border border-gray-100 bg-gray-50 p-4 flex items-center justify-between gap-3">
                    <div>
                        <div class="text-xs text-gray-400 mb-1">基础成长</div>
                        <div class="text-lg font-bold text-gray-900" id="dg_stat_jcjs">-</div>
                    </div>
                    <div class="w-9 h-9 rounded-xl bg-indigo-50 text-indigo-600 flex items-center justify-center border border-indigo-100">
                        <i class="fas fa-seedling leading-none"></i>
                    </div>
                </div>
                <div class="rounded-2xl border border-gray-100 bg-gray-50 p-4 flex items-center justify-between gap-3">
                    <div>
                        <div class="text-xs text-gray-400 mb-1">付费加倍</div>
                        <div class="text-lg font-bold text-gray-900" id="dg_stat_ffjs">-</div>
                    </div>
                    <div class="w-9 h-9 rounded-xl bg-amber-50 text-amber-600 flex items-center justify-center border border-amber-100">
                        <i class="fas fa-coins leading-none"></i>
                    </div>
                </div>
                <div class="rounded-2xl border border-gray-100 bg-gray-50 p-4 flex items-center justify-between gap-3">
                    <div>
                        <div class="text-xs text-gray-400 mb-1">额外活跃</div>
                        <div class="text-lg font-bold text-gray-900" id="dg_stat_ewjs">-</div>
                    </div>
                    <div class="w-9 h-9 rounded-xl bg-emerald-50 text-emerald-600 flex items-center justify-center border border-emerald-100">
                        <i class="fas fa-fire leading-none"></i>
                    </div>
                </div>
                <div class="rounded-2xl border border-gray-100 bg-gray-50 p-4 flex items-center justify-between gap-3">
                    <div>
                        <div class="text-xs text-gray-400 mb-1">今日加速</div>
                        <div class="text-lg font-bold text-gray-900" id="dg_stat_jrjs">-</div>
                    </div>
                    <div class="w-9 h-9 rounded-xl bg-sky-50 text-sky-600 flex items-center justify-center border border-sky-100">
                        <i class="fas fa-bolt leading-none"></i>
                    </div>
                </div>
            </div>

            <div class="rounded-2xl border border-gray-100 overflow-hidden">
                <div class="px-4 py-3 bg-gray-50 border-b border-gray-100 text-sm font-semibold text-gray-800 flex items-center gap-2">
                    <i class="fas fa-signal text-indigo-500"></i>
                    在线状态
                </div>
                <div class="divide-y divide-gray-100">
                    <div class="px-4 py-3 flex items-center justify-between">
                        <div class="text-sm text-gray-700 flex items-center gap-2"><i class="fas fa-desktop text-gray-400 leading-none"></i>电脑在线</div>
                        <div class="flex items-center gap-3">
                            <label class="relative inline-flex items-center cursor-pointer select-none">
                                <input type="checkbox" id="dg_pc_switch" class="sr-only peer">
                                <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-indigo-200 rounded-full peer peer-checked:bg-indigo-600 after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border after:border-gray-300 after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:after:translate-x-full"></div>
                            </label>
                            <div class="w-20 flex items-center justify-center">
                                <button type="button" id="dg_pc_bugua_btn" class="px-3 py-1.5 text-xs rounded-lg bg-amber-600 hover:bg-amber-700 text-white font-medium transition-colors">补挂</button>
                                <span id="dg_pc_done" class="hidden inline-flex h-7 min-w-[72px] items-center justify-center text-xs rounded-full bg-emerald-50 text-emerald-700 border border-emerald-100">已完成</span>
                            </div>
                        </div>
                    </div>
                    <div class="px-4 py-3 flex items-center justify-between">
                        <div class="text-sm text-gray-700 flex items-center gap-2"><i class="fas fa-mobile-screen-button text-gray-400 leading-none"></i>手机在线</div>
                        <div class="flex items-center gap-3">
                            <div class="w-11 h-6 opacity-0 pointer-events-none"></div>
                            <div class="w-20 flex items-center justify-center">
                                <span id="dg_status_sjzx" class="inline-flex h-7 min-w-[72px] items-center justify-center text-xs rounded-full bg-gray-100 text-gray-500 border border-gray-200">未知</span>
                            </div>
                        </div>
                    </div>
                    <div class="px-4 py-3 flex items-center justify-between">
                        <div class="text-sm text-gray-700 flex items-center gap-2"><i class="fas fa-shield-heart text-gray-400 leading-none"></i>连续登录</div>
                        <div class="flex items-center gap-3">
                            <div class="w-11 h-6 opacity-0 pointer-events-none"></div>
                            <div class="w-20 flex items-center justify-center">
                                <span id="dg_status_lxdl" class="inline-flex h-7 min-w-[72px] items-center justify-center text-xs rounded-full bg-gray-100 text-gray-500 border border-gray-200">未知</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="rounded-2xl border border-gray-100 overflow-hidden">
                <div class="px-4 py-3 bg-gray-50 border-b border-gray-100 flex items-center justify-between">
                    <div class="text-sm font-semibold text-gray-800 inline-flex items-center gap-2">
                        <i class="fas fa-list-check text-indigo-500"></i>
                        项目列表
                    </div>
                    <div class="flex items-center gap-2">
                        <button type="button" class="px-3 py-1.5 bg-amber-600 hover:bg-amber-700 text-white rounded-lg text-xs font-medium transition-colors inline-flex items-center gap-2" onclick="dgConfirmBatchBugua()">
                            <i class="fas fa-wand-magic-sparkles text-[10px]"></i>
                            一键补挂
                        </button>
                        <button type="button" class="px-3 py-1.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg text-xs font-medium transition-colors inline-flex items-center gap-2" onclick="dgQuery()">
                            <i class="fas fa-rotate-right text-[10px]"></i>
                            刷新
                        </button>
                    </div>
                </div>
                <div id="dg_projects" class="divide-y divide-gray-100"></div>
            </div>
        </div>
    </div>
</div>

<div id="appModal" class="fixed inset-0 z-50 hidden">
    <div class="fixed inset-0 bg-black/50 backdrop-blur-sm transition-opacity" onclick="closeModal()"></div>
    <div class="fixed inset-0 flex items-center justify-center p-4">
        <div class="bg-white rounded-2xl shadow-2xl w-full max-w-md max-h-[85vh] flex flex-col relative transform transition-all">
            <div class="flex items-center justify-between px-5 py-4 border-b border-gray-100 bg-gray-50/50 rounded-t-2xl">
                <h3 id="modalTitle" class="text-lg font-semibold text-gray-800"></h3>
                <button onclick="closeModal()" class="w-8 h-8 flex items-center justify-center rounded-full hover:bg-gray-200 text-gray-400 hover:text-gray-600 transition-colors">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div id="modalBody" class="px-5 py-4 overflow-y-auto"></div>
            <div id="modalFooter" class="px-5 py-3 border-t border-gray-100 hidden"></div>
        </div>
    </div>
</div>

<script>
function openModal(title, content, footerCallback) {
    document.getElementById('modalTitle').textContent = title;
    document.getElementById('modalBody').innerHTML = content;
    const modalFooter = document.getElementById('modalFooter');
    if (footerCallback) {
        modalFooter.innerHTML = footerCallback();
        modalFooter.classList.remove('hidden');
    } else {
        modalFooter.classList.add('hidden');
    }
    document.getElementById('appModal').classList.remove('hidden');
    document.body.style.overflow = 'hidden';
}

function closeModal() {
    document.getElementById('appModal').classList.add('hidden');
    document.body.style.overflow = '';
}

var dgProjectMap = [
    { id: 1, name: '领福利券', key: 'lflq', icon: 'fa-ticket' },
    { id: 2, name: '添加好友', key: 'tjhy', icon: 'fa-user-plus' },
    { id: 3, name: '点赞说说', key: 'dzss', icon: 'fa-thumbs-up' },
    { id: 4, name: '发布说说', key: 'fbss', icon: 'fa-comment' },
    { id: 5, name: '日签打卡', key: 'rqdk', icon: 'fa-calendar-check' },
    { id: 6, name: '音乐听歌', key: 'yltg', icon: 'fa-music' },
    { id: 7, name: '金币兑换', key: 'jbdh', icon: 'fa-exchange' },
    { id: 8, name: '盲盒签到', key: 'mhqd', icon: 'fa-gift' },
    { id: 9, name: '魔法画室', key: 'mfhs', icon: 'fa-paintbrush' },
    { id: 10, name: '经典农场', key: 'jdnc', icon: 'fa-leaf' },
    { id: 11, name: '浏览动态', key: 'lldt', icon: 'fa-eye' },
    { id: 12, name: '福利金豆', key: 'fljd', icon: 'fa-diamond' },
    { id: 13, name: '阅读小说', key: 'ydxs', icon: 'fa-book' },
    { id: 14, name: '波点音乐', key: 'gnyl', icon: 'fa-dot-circle' },
    { id: 16, name: '体验游戏', key: 'tyyx', icon: 'fa-gamepad' }
];
var dgLastDataObj = null;

function dgShowLoading() {
    $('#dg_state_loading').removeClass('hidden');
    $('#dg_state_error').addClass('hidden');
    $('#dg_content').addClass('hidden');
}

function dgShowError(msg) {
    $('#dg_state_loading').addClass('hidden');
    $('#dg_state_error').removeClass('hidden');
    $('#dg_content').addClass('hidden');
    $('#dg_state_error_msg').text(msg || '加载失败');
}

function dgShowExpired() {
    $('#dg_state_loading').addClass('hidden');
    $('#dg_state_error').addClass('hidden');
    $('#dg_state_expired').removeClass('hidden');
    $('#dg_content').addClass('hidden');
}

function dgHideExpired() {
    $('#dg_state_expired').addClass('hidden');
}

function dgShowContent() {
    $('#dg_state_loading').addClass('hidden');
    $('#dg_state_error').addClass('hidden');
    $('#dg_content').removeClass('hidden');
}

function dgNormalizeData(v) {
    if (v === null || typeof v === 'undefined') return { obj: null, raw: '' };
    if (typeof v === 'string') {
        var s = v;
        try {
            var parsed = JSON.parse(s);
            return { obj: parsed, raw: JSON.stringify(parsed) };
        } catch (e) {
            return { obj: null, raw: s };
        }
    }
    try {
        return { obj: v, raw: JSON.stringify(v) };
    } catch (e2) {
        return { obj: null, raw: String(v) };
    }
}

function dgSetBadge($el, ok) {
    $el.removeClass('bg-gray-100 text-gray-500 bg-emerald-50 text-emerald-700 bg-rose-50 text-rose-700 border border-gray-200 border-emerald-100 border-rose-100');
    if (ok === true) {
        $el.addClass('inline-flex h-7 min-w-[72px] items-center justify-center bg-emerald-50 text-emerald-700 border border-emerald-100').text('已完成');
    } else if (ok === false) {
        $el.addClass('inline-flex h-7 min-w-[72px] items-center justify-center bg-rose-50 text-rose-700 border border-rose-100').text('未完成');
    } else {
        $el.addClass('inline-flex h-7 min-w-[72px] items-center justify-center bg-gray-100 text-gray-500 border border-gray-200').text('未知');
    }
}


function dgParseBoolTri(v) {
    if (v === true || v === 'true' || v === 1 || v === '1') return true;
    if (v === false || v === 'false' || v === 0 || v === '0') return false;
    return null;
}


function dgProjectWczt(dataObj, pd) {
    if (!pd || typeof pd !== 'object') return null;
    if (Object.prototype.hasOwnProperty.call(pd, 'wczt')) {
        return dgParseBoolTri(pd.wczt);
    }
    return null;
}

function dgConfirmBugua(projectId, projectName){
    openModal('确认补挂', '<div class="text-sm text-gray-600">确定补挂【' + escHtml(projectName) + '】吗？</div>', function(){
        return '<div class="flex gap-2">'+
            '<button onclick="closeModal()" class="flex-1 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg font-medium transition-colors">取消</button>'+
            '<button onclick="dgDoBugua(' + projectId + ')" class="flex-1 py-2 bg-amber-600 hover:bg-amber-700 text-white rounded-lg font-medium transition-colors">确定</button>'+
        '</div>';
    });
}

function dgDoBugua(projectId){
    closeModal();
    dgAction('bugua', projectId, null, null, function(ok){
        if(ok) dgQuery();
    });
}

function dgGetPendingProjectIds(){
    if(!dgLastDataObj) return [];
    var ids = [];
    dgProjectMap.forEach(function(p){
        var pd = (dgLastDataObj && dgLastDataObj[p.key]) ? dgLastDataObj[p.key] : null;
        if(!pd || typeof pd !== 'object') return;
        if(dgProjectWczt(dgLastDataObj, pd) === true) return;
        ids.push(p.id);
    });
    return ids;
}

function dgConfirmBatchBugua(){
    var ids = dgGetPendingProjectIds();
    if(!ids || ids.length === 0){
        showToast('暂无未完成任务', 2000, 'warning');
        return;
    }
    openModal('一键补挂', '<div class="text-sm text-gray-600">确定补挂未完成任务（共 ' + ids.length + ' 个）吗？</div>', function(){
        return '<div class="flex gap-2">'+
            '<button onclick="closeModal()" class="flex-1 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg font-medium transition-colors">取消</button>'+
            '<button onclick="dgDoBatchBugua()" class="flex-1 py-2 bg-amber-600 hover:bg-amber-700 text-white rounded-lg font-medium transition-colors">确定</button>'+
        '</div>';
    });
}

function dgDoBatchBugua(){
    var ids = dgGetPendingProjectIds();
    if(!ids || ids.length === 0){
        closeModal();
        showToast('暂无未完成任务', 2000, 'warning');
        return;
    }
    closeModal();
    dgAction('batch_bugua', 0, ids.join(','), null, function(ok){
        if(ok) dgQuery();
    });
}

function dgRenderProjects(dataObj) {
    var container = $('#dg_projects');
    container.empty();
    dgProjectMap.forEach(function(p) {
        var pd = (dataObj && dataObj[p.key]) ? dataObj[p.key] : null;
        var kgzt = pd && typeof pd === 'object' ? pd.kgzt : null;
        var enabled = (kgzt === true || kgzt === 'true' || kgzt === 1 || kgzt === '1');
        var completedState = dgProjectWczt(dataObj, pd);

        var row = $('<div class="px-4 py-3 flex items-center gap-3 hover:bg-gray-50 transition-colors"></div>');
        var left = $('<div class="min-w-0 flex-1 flex items-center gap-3"></div>');
        left.append('<div class="w-10 h-10 rounded-xl border border-gray-100 bg-white flex items-center justify-center text-gray-500"><i class="fas '+escHtml(p.icon || 'fa-cube')+'"></i></div>');
        var leftText = $('<div class="min-w-0"></div>');
        leftText.append('<div class="text-sm font-semibold text-gray-900 truncate">'+escHtml(p.name)+'</div>');
        leftText.append('<div class="text-xs text-gray-400 mt-0.5">项目ID：'+p.id+'</div>');
        left.append(leftText);
        row.append(left);

        var swWrap = $('<div class="flex items-center gap-3"></div>');
        var sw = $('<label class="relative inline-flex items-center cursor-pointer select-none"></label>');
        var input = $('<input type="checkbox" class="sr-only peer">');
        if (enabled) input.prop('checked', true);
        var track = $('<div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-indigo-200 rounded-full peer peer-checked:bg-indigo-600 after:content-[\'\'] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border after:border-gray-300 after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:after:translate-x-full"></div>');
        sw.append(input).append(track);
        swWrap.append(sw);

        var action = $('<div class="w-20 flex items-center justify-center"></div>');
        if (completedState === true) {
            action.append('<span class="inline-flex px-2.5 py-1 text-xs rounded-full bg-emerald-50 text-emerald-700 border border-emerald-100">已完成</span>');
        } else if (completedState === false) {
            action.append('<button type="button" class="px-3 py-1.5 text-xs rounded-lg bg-amber-600 hover:bg-amber-700 text-white font-medium transition-colors">补挂</button>');
        } else {
            action.append('<span class="inline-flex px-2.5 py-1 text-xs rounded-full bg-gray-100 text-gray-500 border border-gray-200">未知</span>');
        }
        swWrap.append(action);
        row.append(swWrap);

        input.on('change', function() {
            var checked = $(this).is(':checked');
            dgAction(checked ? 'open' : 'close', p.id, null, null, function(ok) {
                if (ok) {
                    dgQuery();
                } else {
                    input.prop('checked', !checked);
                }
            });
        });
        action.find('button').on('click', function() {
            dgConfirmBugua(p.id, p.name);
        });
        container.append(row);
    });
}

function dgRenderStats(dataObj) {
    var round1 = function(v){
        var n = parseFloat(v);
        if(!isFinite(n)) return null;
        return Math.round((n + Number.EPSILON) * 10) / 10;
    };
    $('#dg_stat_jcjs').text((dataObj && typeof dataObj.jcjs !== 'undefined') ? String(dataObj.jcjs) + ' 天' : '-');
    $('#dg_stat_ffjs').text((dataObj && typeof dataObj.ffjs !== 'undefined') ? String(dataObj.ffjs) + ' 倍' : '-');
    $('#dg_stat_ewjs').text((dataObj && typeof dataObj.ewjs !== 'undefined') ? String(dataObj.ewjs) + ' 天' : '-');
    var jr = (dataObj && typeof dataObj.jrjs !== 'undefined') ? round1(dataObj.jrjs) : null;
    $('#dg_stat_jrjs').text(jr === null ? '-' : jr.toFixed(1) + ' 天');
}

function dgRenderOnline(dataObj) {
    var dn = dataObj && dataObj.dnzx ? dataObj.dnzx.wczt : null;
    var sj = dataObj && dataObj.sjzx ? dataObj.sjzx.wczt : null;
    var lx = dataObj && dataObj.lxdl ? dataObj.lxdl.wczt : null;
    dgSetBadge($('#dg_status_sjzx'), sj === true ? true : (sj === false ? false : null));
    dgSetBadge($('#dg_status_lxdl'), lx === true ? true : (lx === false ? false : null));
    var dnKg = dataObj && dataObj.dnzx ? dataObj.dnzx.kgzt : null;
    var pcEnabled = (dnKg === true || dnKg === 'true');
    $('#dg_pc_switch').prop('checked', !!pcEnabled);
    var dnDone = (dn === true);
    var $pcBuguaBtn = $('#dg_pc_bugua_btn');
    var $pcDone = $('#dg_pc_done');
    if(dnDone){
        $pcBuguaBtn.addClass('hidden');
        $pcDone.removeClass('hidden');
    }else{
        $pcDone.addClass('hidden');
        $pcBuguaBtn.removeClass('hidden');
    }
}

function dgLoadNodes(onDone){
    if(onDone) onDone(false);
}

function dgAction(op, projectId, projectIds, raw, cb){
    var qq = (window.DG_OPS_PARAMS && window.DG_OPS_PARAMS.qq) || '';
    var nodeId = (window.DG_OPS_PARAMS && window.DG_OPS_PARAMS.nodeId) ? window.DG_OPS_PARAMS.nodeId : 0;
    showLoading();
    $.ajax({
        type: 'POST',
        url: 'ajax.php?act=dg_action',
        dataType: 'json',
        data: {biz: 'dg', op: op, qq: qq, nodeId: nodeId, projectId: projectId || 0, projectIds: projectIds || '', projectKey: raw || ''},
        success: function(res){
            hideLoading();
            if(!res){
                showToast('返回为空', 2500, 'error');
                if(cb) cb(false);
                return;
            }
            if(res.code == 1){
                if(op !== 'query'){
                    showToast(res.msg || '操作成功', 2500, 'success');
                }
                if(cb) cb(true, res);
            }else{
                showToast(res.msg || '失败', 2500, 'error');
                if(cb) cb(false, res);
            }
        },
        error: function(){
            hideLoading();
            showToast('请求失败', 2500, 'error');
            if(cb) cb(false);
        }
    });
}

function dgQuery(){
    dgHideExpired();
    $('#dg_state_login').addClass('hidden');
    $('#dg_state_noapi').addClass('hidden');
    if(!(window.DG_OPS_PARAMS && window.DG_OPS_PARAMS.hasValid == 1)){
        dgShowExpired();
        return;
    }
    if(!(window.DG_OPS_PARAMS && window.DG_OPS_PARAMS.loginOk == 1)){
        $('#dg_state_loading').addClass('hidden');
        $('#dg_state_error').addClass('hidden');
        $('#dg_content').addClass('hidden');
        $('#dg_state_login').removeClass('hidden');
        return;
    }
    if(!(window.DG_OPS_PARAMS && window.DG_OPS_PARAMS.nodeHasApi == 1)){
        $('#dg_state_loading').addClass('hidden');
        $('#dg_state_error').addClass('hidden');
        $('#dg_content').addClass('hidden');
        $('#dg_state_noapi').removeClass('hidden');
        return;
    }
    dgShowLoading();
    dgAction('query', 0, '', null, function(ok, res){
        if(!ok){
            dgLastDataObj = null;
            dgShowError((res && res.msg) ? res.msg : '查询失败');
            return;
        }
        try {
            var normalized = dgNormalizeData(res && typeof res.data !== 'undefined' ? res.data : null);
            var obj = normalized.obj;
            dgLastDataObj = obj && typeof obj === 'object' ? obj : null;
            dgRenderStats(obj);
            dgRenderOnline(obj);
            dgRenderProjects(obj);
            dgShowContent();
        } catch (err) {
            if (window.console && console.error) console.error(err);
            dgShowError('数据渲染失败，请刷新页面重试');
        }
    });
}

$(document).ready(function(){
    var qq = (window.DG_OPS_PARAMS && window.DG_OPS_PARAMS.qq) || '';
    $('#dg_renew_link').attr('href', './shop.php?qq=' + encodeURIComponent(qq) + '&version=dg');
    $('#dg_login_link').attr('href', './add.php?biz=dg&qq=' + encodeURIComponent(qq));
    $('#dg_pc_switch').on('change', function(){
        var checked = $(this).is(':checked');
        dgAction(checked ? 'open' : 'close', 15, '', 'dnzx', function(ok){
            if(ok) dgQuery();
            else $('#dg_pc_switch').prop('checked', !checked);
        });
    });
    $('#dg_pc_bugua_btn').on('click', function(){
        openModal('确认补挂', '<div class="text-sm text-gray-600">确定补挂【电脑在线】吗？</div>', function(){
            return '<div class="flex gap-2">'+
                '<button onclick="closeModal()" class="flex-1 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg font-medium transition-colors">取消</button>'+
                '<button onclick="closeModal();dgAction(\'bugua\',15,\'\',\'dnzx\',function(ok){if(ok) dgQuery();});" class="flex-1 py-2 bg-amber-600 hover:bg-amber-700 text-white rounded-lg font-medium transition-colors">确定</button>'+
            '</div>';
        });
    });
    dgQuery();
});
</script>

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