{% extends "admin/change_list.html" %}
{% block content_title %}{% endblock %}
{% block object-tools %}
{% endblock %}
{% block body_main %}

<style>
    /* 自定义增强样式 */
    .progress-bar {
        transition: width 0.5s ease-in-out;
    }
    
    .version-card {
        border-left: 3px solid;
        background: linear-gradient(90deg, rgba(13,202,240,0.06) 0%, rgba(25,135,84,0.04) 100%);
    }
    
    .version-divider {
        border-right: 2px dashed rgba(0,0,0,0.12);
    }
    
    @media (max-width: 768px) {
        .version-divider {
            border-right: none;
            border-bottom: 2px dashed rgba(0,0,0,0.12);
            margin-bottom: 1.5rem;
            padding-bottom: 1rem;
        }
    }
    </style>
    
    <div class="card version-card border-0 shadow-lg overflow-hidden">
        <div class="card-body p-4">
            <div class="row g-4 align-items-stretch">
                <!-- 当前版本 -->
                <div class="col-lg-6 pe-lg-4 version-divider">
                    <div class="d-flex align-items-start h-100">
                        <div class="flex-shrink-0">
                            <i class="bi bi-pc-display-horizontal fs-1 text-info opacity-75"></i>
                        </div>
                        <div class="flex-grow-1 ms-3">
                            <h3 class="h5 fw-semibold mb-3">
                                <span class="badge bg-info bg-opacity-10 text-info fs-6">当前系统版本</span>
                            </h3>
                            <div class="d-flex flex-column">
                                <span class="display-6 fw-bold text-dark mb-1">{{ current_version }}</span>
                                <small class="text-muted opacity-75">
                                    <i class="bi bi-clock-history me-1"></i>
                                    最后检测：{{ last_check_time }}
                                </small>
                            </div>
                        </div>
                    </div>
                </div>
    
                <!-- 最新版本 -->
                <div class="col-lg-6 ps-lg-4">
                    <div class="d-flex align-items-start h-100">
                        <div class="flex-shrink-0">
                            <i class="bi bi-stars fs-1 text-success opacity-75"></i>
                        </div>
                        <div class="flex-grow-1 ms-3">
                            <h3 class="h5 fw-semibold mb-3">
                                <span class="badge bg-success bg-opacity-10 text-success fs-6">最新可用版本</span>
                            </h3>
                            <div class="d-flex flex-column h-100">
                                <div class="d-flex align-items-center gap-2 mb-3">
                                    <span class="display-6 fw-bold text-dark">{{ latest_version }}</span>
                                    {% if can_upgrade %}
                                    <button type="button" 
                                            class="btn btn-success btn-md rounded-pill py-2 hover-scale"
                                            id="startUpgrade"
                                            data-version="{{ latest_version }}">
                                        <i class="bi bi-rocket-takeoff me-2"></i>
                                        立即升级
                                    </button>
                                    {% elif update_notice == '版本检测失败' %}
                                    <span class="badge bg-danger bg-opacity-20 text-danger fs-6">检测失败</span>
                                    {% else %}
                                    <span class="badge bg-secondary bg-opacity-20 text-dark fs-6">已是最新版本</span>
                                    {% endif %}
                                </div>
                                <div class="mt-auto">
                                    <small class="text-muted opacity-75 d-block">
                                        <i class="bi bi-info-circle me-1"></i>
                                        {{ update_notice }}{% if latest_version_data and can_upgrade %} <a href="#" id="show_version_mes" class="text-decoration-underline ms-2">查看详情</a>{% endif %}
                                    </small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- 模态框主体 -->
<div class="modal fade" id="versionModal" tabindex="-1" aria-labelledby="versionModalLabel">
    <div class="modal-dialog  modal-dialog-centered modal-dialog-scrollable">
        <div class="modal-content">
            <!-- 头部 -->
            <div class="modal-header bg-primary-subtle text-white">
                <h3 class="modal-title fs-5" id="versionModalLabel">
                    {{ latest_version_data.version}}
                    {% if latest_version_data.release_date %}
                    <small class="fs-6 ps-2">{{ latest_version_data.release_date }}</small>
                    {% endif %}
                </h3>
                <button type="button" class="btn-close btn-close-white" id="autoCloseBtn" data-bs-dismiss="modal"></button>
            </div>

            <!-- 正文内容 -->
            <div class="modal-body">
                {% if latest_version_data.changes %}
                <div class="small">
                    <!-- 新增功能 -->
                    {% if latest_version_data.changes.added %}
                    <section class=" py-2 border-bottom">
                        <h4 class="col-12 text-success mb-2"><i class="bi bi-plus-circle"></i> 新增功能</h4>
                        <ul class="ms-3 text-success">
                            {% for item in latest_version_data.changes.added %}
                            <li class="">{{ item }}</li>
                            {% endfor %}
                            </ul>
                    </section>
                    {% endif %}

                    <!-- 问题修复 -->
                    {% if latest_version_data.changes.fixed %}
                    <section class=" py-2 border-bottom">
                        <h4 class="col-12 text-secondary mb-2"><i class="bi bi-bug"></i> 问题修复</h4>
                        <ul class="ms-3 text-secondary">
                        {% for item in latest_version_data.changes.fixed %}
                        <li class="">{{ item }}</li>
                        {% endfor %}
                        </ul>
                    </section>
                    {% endif %}

                    <!-- 优化改进 -->
                    {% if latest_version_data.changes.changed %}
                    <section class=" py-2 border-bottom">
                        <h4 class="col-12 text-primary mb-2"><i class="bi bi-lightning-charge"></i> 功能优化</h4>
                        <ul class="ms-3 text-primary">
                            {% for item in latest_version_data.changes.changed %}
                            <li class="">{{ item }}</li>
                            {% endfor %}
                        </ul>
                    </section>
                    {% endif %}
                    <!-- 移除功能 -->
                    {% if latest_version_data.changes.deprecated %}
                    <section class=" py-2 border-bottom">
                        <h4 class="col-12 text-danger mb-2"><i class="bi bi-trash3"></i> 移除功能</h4>
                        <ul class="ms-3 text-danger">
                            {% for item in latest_version_data.changes.deprecated %}
                            <li class="">{{ item }}</li>
                            {% endfor %}
                        </ul>
                    </section>
                    {% endif %}
                    <!-- 数据库升级提示-->
                    {% if latest_version_data.database_upgrade %}
                    <div class="alert alert-warning">
                        <p>本次升级需要进行数据库升级</p>
                        <p>建立数据升级文件</p>
                        <pre><code>python manage.py makemigrations</code></pre> 
                        <p>执行数据库升级</p>
                        <pre><code>python manage.py migrate</code></pre> 
                    </div>
                    {% endif %}
                </div>
                {% else %}
                <div class="alert alert-warning">暂无详细更新说明</div>
                {% endif %}
            </div>

            <!-- 底部元信息 -->
            {% if latest_version_data.metadata %}
            <div class="modal-footer bg-light">
                {% if latest_version_data.metadata.compatibility %}
                    <span class="text-muted">版本支持: </span>
                    {% for k,v in latest_version_data.metadata.compatibility.items %}
                    <span class="badge bg-dark">{{k}}:{{ v }}+</span>
                    {% endfor %}
                {% endif %}
            </div>
            {% endif %}
        </div>
    </div> 
</div>  
 
<div class="card bg-warning-subtle my-md-5 my-3">
    <div class="card-header"><p>数据库升级方法</p></div>
    <div class="card-body">
        
        <p>建立数据升级文件</p>
        <pre><code>python manage.py makemigrations</code></pre> 
        <p>执行数据库升级</p>
        <pre><code>python manage.py migrate</code></pre> 
    </div>
</div>

    <script>
        const $ = django.jQuery
        $(document).ready(function() {
            // 类选择器绑定事件（适用于多个元素）
            $('#show_version_mes').on('click', function(e) {
                const myModal = new bootstrap.Modal('#versionModal', {
                    keyboard: false
                  })
                myModal.show()
                
            });
        });
        
      </script>







<!-- 进度模态框 -->
<div class="modal fade" id="upgradeModal">
    <div class="modal-dialog modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header bg-dark text-white">
                <h5 class="modal-title">
                    <i class="bi bi-gear"></i> 固件升级中...
                </h5>
            </div>
            <div class="modal-body">
                <div class="progress mb-3">
                    <div class="progress-bar" role="progressbar" 
                         style="width:0%" id="upgradeProgress"></div>
                </div>
                <div class="log-container border p-2 text-muted small">
                    <div id="upgradeLogs"></div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    (function($) {
        
    const upgradeModule = {
        pollInterval: null,
        modal: null,

        // 初始化模块
        init: function() {
            this.modal = new bootstrap.Modal('#upgradeModal')
            $('#startUpgrade').click(() => this.startUpgrade())
        },

        // 启动升级主流程
        startUpgrade: async function() {
            this.showProgressModal();
            
            try {
                const response = await $.ajax({
                    url: '/upgrade/start/',
                    method: 'POST',
                    headers: {'X-CSRFToken': '{{ csrf_token }}'},
                    data: JSON.stringify({
                        version: $('#startUpgrade').data('version')
                    }),
                    contentType: 'application/json'
                });
                
                this.startPolling();
            } catch (error) {
                this.updateStatus('failed', `启动失败: ${error.statusText}`);
            }
        },

        // 展示进度窗口
        showProgressModal: function() {
            $('#upgradeModal .modal-title').html(`
                <i class="bi bi-gear fa-spin"></i> 升级进行中...
            `);
            $('#upgradeProgress').css('width', '0%').removeClass('bg-success bg-danger');
            $('#upgradeLogs').empty();
            this.modal.show();
        },

        // 启动轮询查询
        startPolling: function() {
            let retryCount = 0;
            const maxRetries = 3;
            const baseDelay = 1500;
            
            const executePoll = () => {
                clearTimeout(this.pollTimer); // 关键修复：每次开始前清理旧定时器
                
                $.getJSON(`/upgrade/progress/`)
                    .done(data => {
                        retryCount = 0;
                        this.handleProgress(data);
                        
                        // 保持原有递归逻辑
                        if(!['success', 'failed'].includes(data.status)) {
                            this.pollTimer = setTimeout(executePoll, baseDelay);
                        }
                    })
                    .fail((xhr, status, error) => {
                        if (++retryCount > maxRetries) {
                            this.handlePollingError('服务器连接失败，已达最大重试次数');
                            return;
                        }
                        
                        // 指数退避策略（保持原有公式）
                        const delay = Math.min(baseDelay * Math.pow(2, retryCount), 30000);
                        this.pollTimer = setTimeout(executePoll, delay);
                        
                        // 在日志中显示重试信息（保持原有样式）
                        $('#upgradeLogs').append(`
                            <div class="text-warning">
                                ${new Date().toLocaleTimeString()} 连接中断，${delay/1000}秒后第${retryCount}次重试...
                            </div>
                        `).scrollTop($('#upgradeLogs').prop('scrollHeight'));
                    });
            };
            
            this.pollTimer = setTimeout(executePoll, 0); // 立即启动
        },
        
        handleProgress: function(data) {
            // 初始化（保持原有写法）
            if (!this.uniqueLogs) this.uniqueLogs = new Set();
            if (this.lastPercentage === undefined) this.lastPercentage = -1;
        
            // 进度条更新（增加样式重置）
            if (this.lastPercentage !== data.percentage) {
                $('#upgradeProgress')
                    .css('width', `${data.percentage}%`)
                    .removeClass('bg-success bg-danger'); // 进度变化时重置颜色
                this.lastPercentage = data.percentage;
            }
        
            // 日志处理（增加空格规范化）
            if (data.logs?.length > 0) {
                data.logs.forEach(log => {
                    const cleanLog = log.trim().replace(/\s+/g, ' '); // 关键修复：标准化日志格式
                    if (!this.uniqueLogs.has(cleanLog)) {
                        const logEntry = `<div class="log-item">${new Date().toLocaleTimeString()} ${cleanLog}</div>`;
                        $('#upgradeLogs').append(logEntry);
                        this.uniqueLogs.add(cleanLog); // 存储处理后的日志
                    }
                });
                $('#upgradeLogs').scrollTop($('#upgradeLogs').prop('scrollHeight'));
            }
        
            // 终态处理（修复定时器清除方式）
            if (['success', 'failed'].includes(data.status)) {
                clearTimeout(this.pollTimer); // 改用clearTimeout
                this.updateStatus(data.status, data.message);
                this.uniqueLogs.clear();
                this.lastPercentage = undefined;
            }
        },
        
        

        // 更新最终状态
        // 修改后的updateStatus方法
updateStatus: function(status, message) {
    const statusConfig = {
        success: {
            icon: 'bi-check-circle-fill',
            color: 'text-success',
            title: '升级完成'
        },
        failed: {
            icon: 'bi-exclamation-octagon-fill',
            color: 'text-danger',
            title: '升级失败'
        }
    };

    // 更新模态框标题
    $('#upgradeModal .modal-title').html(`
        <i class="bi ${statusConfig[status].icon} ${statusConfig[status].color}"></i>
        ${statusConfig[status].title}
    `);

    // 成功状态特殊处理
    if (status === 'success') {
        // 添加页面刷新倒计时提示
        $('#upgradeLogs').append(`
            <div class="alert alert-success mt-3">
                系统将在 <span id="refreshCountdown">5</span> 秒后自动刷新...
            </div>
        `);
        this.scrollLogsToBottom();

        // 启动倒计时
        let countdown = 5;
        const countdownInterval = setInterval(() => {
            $('#refreshCountdown').text(--countdown);
            if(countdown <= 0) clearInterval(countdownInterval);
        }, 1000);

        // 5秒后执行刷新
        setTimeout(() => {
            // 传递刷新标识
            window.location.search = '?upgrade_success=1';
        }, 5000);
    }

    // 失败状态保留原有样式
    if (status === 'failed') {
        $('#upgradeProgress').addClass('bg-danger');
    }

    // 添加最终状态消息
    if (message) {
        $('#upgradeLogs').append(`
            <div class="${statusConfig[status].color} fw-bold">
                [最终状态] ${message}
            </div>
        `);
        this.scrollLogsToBottom();
    }
},


        // 处理轮询错误（带中文参数）
        handlePollingError: function(message) {
            clearTimeout(this.pollTimer);
            this.updateStatus('failed', message || '与服务器的连接异常');
        },

        // 停止轮询方法
        stopPolling: function() {
            clearTimeout(this.pollTimer);
            this.pollTimer = null;
        },
        // 公共工具方法
    scrollLogsToBottom: function() {
        const logs = $('#upgradeLogs')[0];
        logs.scrollTop = logs.scrollHeight;
    },
    
    cleanup: function() {
        this.uniqueLogs.clear();
        this.lastPercentage = -1;
    },
    
    stopPolling: function() {
        clearTimeout(this.pollTimer);
        this.pollTimer = null;
    }
    };

    // 初始化升级模块
    upgradeModule.init();
})(django.jQuery)
</script>


{% endblock %}
