<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>版本总览</title>
    <link rel="stylesheet" href="{{ asset('CmsProUi/component/pear/css/pear.css') }}">
    <link rel="stylesheet" href="{{ asset('CmsProUi/font-awesome/4.7.0/css/font-awesome.min.css') }}">
    <link rel="stylesheet" href="{{ asset('Admin/css/admin.css') }}">
    <link rel="stylesheet" href="{{ asset('Admin/css/variables.css') }}">
    <link rel="stylesheet" href="{{ asset('Admin/css/reset.css') }}">
    <style>
        .markdown-body { font-size:14px; line-height:1.8; color:#333; }
        .markdown-body h1 { font-size:20px; border-bottom:1px solid #eee; padding-bottom:8px; margin:16px 0 8px; }
        .markdown-body h2 { font-size:18px; border-bottom:1px solid #eee; padding-bottom:6px; margin:14px 0 6px; }
        .markdown-body h3 { font-size:16px; margin:12px 0 6px; }
        .markdown-body ul { padding-left:20px; margin:6px 0; }
        .markdown-body li { margin:3px 0; }
        .markdown-body hr { border:none; border-top:1px solid #eee; margin:12px 0; }
        .markdown-body code { background:#f5f5f5; padding:2px 6px; border-radius:3px; font-size:13px; }
        .markdown-body strong { font-weight:bold; }
        .markdown-body p { margin:6px 0; }
    </style>
</head>
<body>
<div class="pear-container">
    <div class="layui-card">
        <div class="layui-card-header">当前版本</div>
        <div class="layui-card-body">
            <div class="layui-row layui-col-space20">
                <div class="layui-col-md3">
                    <div style="text-align:center;padding:20px;background:#f8f8f8;border-radius:8px;">
                        <div style="font-size:36px;font-weight:bold;color:#1e9fff;">v{{ $currentVersion['version'] ?? '5.0.1' }}</div>
                        <div style="margin-top:8px;color:#999;">Build {{ $currentVersion['build'] ?? '' }}</div>
                    </div>
                </div>
                <div class="layui-col-md3">
                    <div style="padding:20px;">
                        <div style="color:#999;margin-bottom:8px;">安装时间</div>
                        <div>{{ $currentVersion['install_time'] ?? '-' }}</div>
                    </div>
                </div>
                <div class="layui-col-md6">
                    <div style="padding:20px;">
                        <div style="color:#999;margin-bottom:8px;">更新日志</div>
                        <div class="markdown-body" id="currentChangelog">{!! $currentVersion['changelog'] ?? '-' !!}</div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="layui-card" id="updateCard" style="display:none;margin-top:15px;">
        <div class="layui-card-header" style="color:#ff9800;">
            <i class="fa fa-bell"></i> 新版本可用
        </div>
        <div class="layui-card-body">
            <div id="updateInfo"></div>
            <div style="margin-top:15px;">
                <button class="layui-btn" id="btnUpgrade"><i class="fa fa-cloud-download"></i> 立即升级</button>
                <button class="layui-btn layui-btn-primary" id="btnSkip"><i class="fa fa-close"></i> 跳过此版本</button>
                <button class="layui-btn layui-btn-normal" id="btnCheck"><i class="fa fa-refresh"></i> 检查更新</button>
            </div>
        </div>
    </div>

    <div class="layui-card" id="noUpdateCard" style="display:none;margin-top:15px;">
        <div class="layui-card-body" style="text-align:center;padding:30px;color:#5fb878;">
            <i class="fa fa-check-circle" style="font-size:48px;"></i>
            <div style="margin-top:10px;font-size:16px;">当前已是最新版本</div>
        </div>
    </div>

    <div class="layui-card" id="upgradeProgressCard" style="display:none;margin-top:15px;">
        <div class="layui-card-header">升级进度</div>
        <div class="layui-card-body">
            <div id="progressInfo"></div>
            <div class="layui-progress" style="margin-top:15px;">
                <div class="layui-progress-bar" id="progressBar" lay-percent="0%"></div>
            </div>
            <div id="progressDetail" style="margin-top:10px;color:#999;"></div>
        </div>
    </div>
</div>

<script src="{{ asset('CmsProUi/component/layui/layui.js') }}"></script>
<script src="{{ asset('CmsProUi/component/pear/pear.js') }}"></script>
<script src="{{ asset('CmsProUi/component/marked/marked.min.js') }}"></script>
<script>
layui.use(['jquery', 'layer', 'element'], function(){
    var $ = layui.jquery,
        layer = layui.layer,
        element = layui.element;

    $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': '{{ csrf_token() }}' } });

    var currentEl = document.getElementById('currentChangelog');
    if (currentEl && currentEl.textContent.trim() && currentEl.textContent.trim() !== '-') {
        var mdText = currentEl.textContent.trim().replace(/^\d+\.\d+\.\d+:\s*/, '');
        currentEl.innerHTML = marked.parse(mdText);
    }

    var latestVersion = '';
    var latestBuild = '';

    var statusMap = {
        'idle': '空闲',
        'pending': '等待中',
        'running': '升级中',
        'success': '升级成功',
        'failed': '升级失败',
        'rolling_back': '回滚中',
        'rolled_back': '已回滚',
        'rollback_failed': '回滚失败'
    };

    function translateStatus(status) {
        return statusMap[status] || status;
    }

    function renderMarkdown(text) {
        if (!text) return '';
        var mdText = text.replace(/^\d+\.\d+\.\d+:\s*/, '');
        return marked.parse(mdText);
    }

    function buildUpdateInfoHtml(res) {
        var html = '<div style="margin-bottom:10px;">';
        html += '<strong>最新版本：</strong>v' + res.data.latest_version + ' Build ' + res.data.latest_build;
        html += '</div>';
        html += '<div style="margin-bottom:10px;"><strong>升级路径：</strong>';
        html += res.data.current_version + ' → ' + res.data.upgrade_path.map(function(step) { return step.to; }).join(' → ');
        html += '</div>';
        if (res.data.changelog) {
            html += '<div style="margin-bottom:10px;"><strong>更新日志：</strong><div class="markdown-body" style="margin-top:8px;">' + renderMarkdown(res.data.changelog) + '</div></div>';
        }
        return html;
    }

    function checkUpdate() {
        $.get('/admin/versionmgr/api/check', function(res) {
            if (res.code === 0 && res.data.has_update) {
                latestVersion = res.data.latest_version;
                latestBuild = res.data.latest_build;
                $('#updateInfo').html(buildUpdateInfoHtml(res));
                $('#updateCard').show();
                $('#noUpdateCard').hide();
            } else if (res.code === 0) {
                $('#noUpdateCard').show();
                $('#updateCard').hide();
            }
        });
    }

    checkUpdate();

    $('#btnCheck').on('click', function() {
        var idx = layer.load();
        $.get('/admin/versionmgr/api/check', function(res) {
            layer.close(idx);
            if (res.code === 0 && res.data.has_update) {
                latestVersion = res.data.latest_version;
                latestBuild = res.data.latest_build;
                $('#updateInfo').html(buildUpdateInfoHtml(res));
                $('#updateCard').show();
                $('#noUpdateCard').hide();
                layer.msg('发现新版本', {icon: 1});
            } else if (res.code === 0) {
                $('#noUpdateCard').show();
                $('#updateCard').hide();
                layer.msg('当前已是最新版本', {icon: 1});
            } else {
                layer.msg(res.message, {icon: 2});
            }
        });
    });

    $('#btnSkip').on('click', function() {
        if (!latestVersion) return;
        layer.confirm('确定跳过 v' + latestVersion + ' 的更新提醒？', {icon:3}, function(idx) {
            layer.close(idx);
            $.post('/admin/versionmgr/api/skip', {version: latestVersion, build: latestBuild}, function(res) {
                if (res.code === 0) {
                    layer.msg('已跳过此版本', {icon: 1});
                    $('#updateCard').hide();
                    $('#noUpdateCard').show();
                } else {
                    layer.msg(res.message, {icon: 2});
                }
            });
        });
    });

    // 进度轮询句柄与幂等保护，避免重复启动
    var pollTimer = null;
    var pollRunning = false;

    function stopPolling() {
        if (pollTimer) {
            clearInterval(pollTimer);
            pollTimer = null;
        }
        pollRunning = false;
    }

    function startPolling() {
        if (pollRunning) return;
        pollRunning = true;

        var maxPolls = 200; // 最多轮询200次（约10分钟），防止无限轮询
        var pollCount = 0;
        pollTimer = setInterval(function() {
            pollCount++;
            if (pollCount > maxPolls) {
                stopPolling();
                layer.msg('升级状态查询超时，请刷新页面查看', {icon: 2});
                return;
            }
            $.get('/admin/versionmgr/api/upgrade/status', function(res) {
                if (res.code !== 0) return;
                var data = res.data;
                var percent = data.progress || 0;
                element.progress('', percent + '%');

                var detail = '状态：' + translateStatus(data.status);
                if (data.completed_steps && data.completed_steps.length > 0) {
                    detail += '<br>已完成：v' + data.completed_steps.join(', v');
                }
                if (data.remaining_steps && data.remaining_steps.length > 0) {
                    detail += '<br>待完成：v' + data.remaining_steps.join(', v');
                }
                if (data.error_message) {
                    detail += '<br><span style="color:red;">错误：' + data.error_message + '</span>';
                }
                $('#progressDetail').html(detail);

                var terminalStates = ['success', 'failed', 'rolled_back', 'rollback_failed'];
                if (data.status === 'success') {
                    stopPolling();
                    layer.msg('升级成功！', {icon: 1, time: 1500}, function() {
                        location.reload();
                    });
                    setTimeout(function() { location.reload(); }, 2000);
                } else if (terminalStates.indexOf(data.status) !== -1) {
                    stopPolling();
                    layer.msg('升级失败：' + (data.error_message || '未知错误'), {icon: 2});
                }
            }).fail(function() {
                // 单次查询失败不中断轮询，保持进度可见
            });
        }, 3000);
    }

    $('#btnUpgrade').on('click', function() {
        if (!latestVersion) return;
        layer.confirm('确定升级到 v' + latestVersion + '？升级过程中系统将暂时不可用。', {icon:3}, function(idx) {
            layer.close(idx);

            // 立即显示进度卡片并重置进度，启动轮询
            $('#progressInfo').html('正在升级到 v' + latestVersion + ' ...');
            $('#progressDetail').html('状态：等待开始');
            element.progress('', '0%');
            $('#upgradeProgressCard').show();
            // 滚动到进度卡片，让用户看到进度
            try { $('#upgradeProgressCard')[0].scrollIntoView({behavior:'smooth', block:'center'}); } catch(e) {}
            startPolling();

            // 升级接口同步执行所有步骤，会阻塞较长时间，最终返回终态
            $.post('/admin/versionmgr/api/upgrade', {target_version: latestVersion}, function(res) {
                // 同步接口返回时升级已结束，轮询通常已捕获终态；这里兜底处理
                if (res.code === 0 && res.data.status === 'success') {
                    stopPolling();
                    layer.msg('升级成功！', {icon: 1, time: 1500}, function() {
                        location.reload();
                    });
                    setTimeout(function() { location.reload(); }, 2000);
                } else if (res.code === 0 && res.data.status === 'failed') {
                    stopPolling();
                    layer.alert('升级失败：' + (res.data.error_message || '请查看日志'), {icon: 2, title: '升级失败'});
                } else if (res.code === 0) {
                    // 异步任务场景（当前实现为同步，理论不会进入）
                    layer.msg(res.message || '升级任务已启动', {icon: 1});
                } else {
                    stopPolling();
                    layer.msg(res.message, {icon: 2});
                }
            }).fail(function() {
                // 网络异常时不停轮询，让轮询继续探查后端真实状态
                layer.msg('升级请求网络异常，正在继续查询进度...', {icon: 2});
            });
        });
    });
});
</script>
</body>
</html>
