<?php
include("../includes/common.php");
$title='系统概览';
include './head.php';
if($islogin==1){}else exit("<script language='javascript'>window.location.href='./login.php';</script>");

// 获取当前后台目录名
$current_admin_dir = basename(dirname($_SERVER['SCRIPT_NAME']));
// 读取当前版本号
$current_version = @file_get_contents(ROOT.$current_admin_dir.'/version') ?: '1.0.0';

// 检查数据库版本
include 'version.config.php';
$stmt = $DB->query("SELECT v FROM pre_config WHERE k='db_version'");
$db_version = $stmt->fetch(PDO::FETCH_COLUMN) ?: '1.0';
$db_need_update = version_compare($db_version, $current_db_version, '<');

// 检查数据表
$stmt = $DB->query("SHOW TABLES LIKE 'pre_sync_config'");
$table_exists = $stmt->fetch();
$db_need_update = $db_need_update || !$table_exists;
?>
<style>
/* 基础卡片样式 */
.status-card {
    padding: 20px;
    margin-bottom: 20px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

/* 推广信息卡片 */
#promotion-card {
    max-width: 100%;
    margin: 0;
    padding: 15px;
}

/* 轮播图样式 */
#promotion-carousel {
    width: 100%;
    margin: 0 auto 15px;
    background: #f8f9fa;
    border-radius: 6px;
    box-shadow: 0 1px 6px rgba(0,0,0,0.08);
}

#promotion-carousel .carousel-inner {
    position: relative;
    width: 100%;
    height: 0;
    padding-bottom: 44.44%;
}

#promotion-carousel .item {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: none;
    transform: translateX(0);
    transition: transform 0.6s ease-in-out;
}

#promotion-carousel .item.active,
#promotion-carousel .item.next,
#promotion-carousel .item.prev {
    display: block;
}

#promotion-carousel .item.next {
    transform: translateX(100%);
}

#promotion-carousel .item.prev {
    transform: translateX(-100%);
}

#promotion-carousel .item.next.left,
#promotion-carousel .item.prev.right {
    transform: translateX(0);
}

#promotion-carousel .item.active.left {
    transform: translateX(-100%);
}

#promotion-carousel .item.active.right {
    transform: translateX(100%);
}

#promotion-carousel .item img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    object-position: center;
}

/* 轮播图指示器 */
#promotion-carousel .carousel-indicators {
    position: absolute;
    bottom: 20px;
    left: 50%;
    transform: translateX(-50%);
    margin: 0;
    padding: 6px 30px;
    background: rgba(0,0,0,0.3);
    border-radius: 20px;
    text-align: center;
    z-index: 10;
    display: inline-flex;
    gap: 8px;
}

#promotion-carousel .carousel-indicators li {
    display: block;
    width: 6px;
    height: 6px;
    margin: 0;
    background: rgba(255,255,255,0.5);
    border: none;
    border-radius: 50%;
    cursor: pointer;
    transition: all 0.3s ease;
}

#promotion-carousel .carousel-indicators li.active {
    background: #fff;
    transform: scale(1.5);
}

/* 轮播图控制器 */
#promotion-carousel .carousel-control {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    width: 40px;
    height: 40px;
    line-height: 40px;
    background: rgba(0,0,0,0.3);
    border-radius: 50%;
    color: #fff;
    text-align: center;
    text-decoration: none;
    opacity: 0;
    transition: all 0.3s ease;
    z-index: 10;
    padding: 0;
}

#promotion-carousel .carousel-control.left {
    left: 20px;
}

#promotion-carousel .carousel-control.right {
    right: 20px;
}

#promotion-carousel:hover .carousel-control {
    opacity: 0.8;
}

#promotion-carousel .carousel-control:hover {
    background: rgba(0,0,0,0.6);
    opacity: 1;
}

#promotion-carousel .carousel-control .glyphicon {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    font-size: 16px;
    width: 16px;
    height: 16px;
    margin: 0;
    padding: 0;
    display: flex;
    align-items: center;
    justify-content: center;
}

#promotion-carousel .carousel-control.left .glyphicon {
    margin-left: -1px;
}

#promotion-carousel .carousel-control.right .glyphicon {
    margin-left: 1px;
}

/* 响应式适配 */
@media (max-width: 768px) {
    .status-card {
        padding: 15px;
        margin-bottom: 15px;
    }
    
    #promotion-card {
        padding: 10px;
    }
    
    #promotion-carousel {
        margin-bottom: 10px;
    }
    
    #promotion-carousel .carousel-inner {
        padding-bottom: 44.44%;
    }
    
    .promotion-list {
        margin-top: 10px;
    }
    
    .promotion-item {
        margin-bottom: 8px;
    }
    
    .promotion-item a {
        padding: 10px 12px;
    }
}

/* 加载状态样式 */
.promotion-content {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    color: #666;
    display: flex;
    align-items: center;
    gap: 5px;
}

.promotion-content .fa-spinner {
    font-size: 16px;
}

/* 文字资源列表样式 */
.promotion-list {
    margin: 15px auto 0;
    padding: 0;
}

.promotion-item {
    padding: 0;
    margin-bottom: 10px;
    background: #fff;
    border-radius: 6px;
    transition: all 0.25s ease;
    border: 1px solid rgba(0,0,0,0.06);
    position: relative;
}

.promotion-item:hover {
    transform: translateX(5px);
    box-shadow: 0 3px 12px rgba(0,0,0,0.12);
    border-color: rgba(26,188,156,0.3);
}

/* 移除绿色光效果 */
.promotion-item:after {
    display: none;
}

.promotion-item a {
    display: block;
    padding: 12px 15px;
    color: #444;
    text-decoration: none;
    font-size: 13px;
    line-height: 1.4;
    position: relative;
}

.promotion-item a:hover {
    color: #1abc9c;
}

.promotion-item .glyphicon {
    float: left;
    margin: 3px 12px 0 0;
    color: #1abc9c;
    font-size: 14px;
}

.promotion-item .content-text {
    display: block;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

/* 响应式适配 */
@media (max-width: 768px) {
    .promotion-list {
        padding: 0 10px;
    }
    
    .promotion-item {
        margin-bottom: 10px;
    }
    
    .promotion-item a {
        padding: 12px;
    }
}

/* 留言板样式 */
.message-list {
    max-height: 400px;
    overflow-y: auto;
    margin-bottom: 15px;
}

.message-item {
    padding: 15px;
    border-bottom: 1px solid #eee;
    transition: all 0.3s ease;
}

.message-item:hover {
    background: #f8f9fa;
}

.message-item:last-child {
    border-bottom: none;
}

.message-header {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
}

.message-avatar {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    margin-right: 10px;
    border: 1px solid #eee;
    padding: 2px;
    background: #fff;
}

.message-info {
    flex: 1;
}

.message-domain {
    font-size: 14px;
    color: #333;
    margin-bottom: 3px;
    font-weight: 500;
}

.message-time {
    font-size: 12px;
    color: #999;
}

.message-content {
    color: #666;
    line-height: 1.6;
    margin-left: 42px;
    font-size: 13px;
    word-break: break-all;
}

.message-form {
    border-top: 1px solid #eee;
    padding-top: 15px;
    margin-top: 15px;
}

.message-form textarea {
    resize: vertical;
    min-height: 80px;
}

.message-pagination {
    text-align: center;
    margin: 15px 0 5px;
}

.message-pagination .pagination {
    margin: 0;
}

.message-pagination .page-info {
    display: inline-block;
    padding: 6px 12px;
    color: #666;
    font-size: 12px;
    background: #f8f9fa;
    border-radius: 4px;
    margin: 0 10px;
}

@media (max-width: 767px) {
    .message-list {
        max-height: 300px;
    }
    .message-item {
        padding: 12px;
    }
    .message-content {
        margin-left: 32px;
    }
    .message-avatar {
        width: 24px;
        height: 24px;
        margin-right: 8px;
    }
    .message-pagination .page-info {
        display: block;
        margin: 10px 0;
    }
    .mobile-order-1 {
        order: 1;
    }
    .mobile-order-2 {
        order: 2;
    }
    .mobile-order-3 {
        order: 3;
    }
}

/* 更新日志样式 */
.changelog-list {
    max-height: 500px;
    overflow-y: auto;
    padding-right: 5px;
}

.changelog-current {
    margin-bottom: 20px;
    padding-bottom: 20px;
    border-bottom: 1px solid #eee;
}

.version-tag {
    margin-bottom: 10px;
}

.version-tag .label {
    margin-right: 8px;
}

.version-tag .version {
    font-size: 16px;
    font-weight: 500;
    color: #333;
}

.version-content {
    color: #666;
    line-height: 1.6;
    font-size: 13px;
    white-space: pre-wrap;
    word-break: break-all;
}

.changelog-history .version-item {
    margin-bottom: 15px;
    padding-bottom: 15px;
    border-bottom: 1px solid #eee;
}

.changelog-history .version-item:last-child {
    margin-bottom: 0;
    padding-bottom: 0;
    border-bottom: none;
}

.changelog-history .version-header {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
}

.changelog-history .version-number {
    font-size: 14px;
    font-weight: 500;
    color: #333;
    margin-right: 10px;
}

.changelog-history .version-date {
    font-size: 12px;
    color: #999;
}

.changelog-history .version-desc {
    color: #666;
    line-height: 1.6;
    font-size: 13px;
    white-space: pre-wrap;
    word-break: break-all;
}

@media (max-width: 767px) {
    .changelog-list {
        max-height: 400px;
    }
}
</style>

<div class="col-xs-12 col-sm-12 col-lg-12">
    <div class="row d-flex flex-column flex-sm-row">
        <!-- 左侧内容 -->
        <div class="col-xs-12 col-sm-8 col-lg-8 mobile-order-2">
            <!-- 推广信息 -->
            <div class="block">
                <div class="block-title"><h3 class="panel-title">推广信息</h3></div>
                <div class="status-card" id="promotion-card">
                    <!-- 图片资源轮播 -->
                    <div id="promotion-carousel" class="carousel slide" data-ride="carousel" style="display:none;">
                        <ol class="carousel-indicators" id="promotion-indicators"></ol>
                        <div class="carousel-inner" id="promotion-content"></div>
                        <a class="left carousel-control" href="#promotion-carousel" data-slide="prev">
                            <span class="glyphicon glyphicon-chevron-left"></span>
                        </a>
                        <a class="right carousel-control" href="#promotion-carousel" data-slide="next">
                            <span class="glyphicon glyphicon-chevron-right"></span>
                        </a>
                    </div>
                    <!-- 文字资源列表 -->
                    <div class="promotion-list" id="promotion-list"></div>
                </div>
            </div>

            <!-- 授权和版本信息行 -->
            <div class="row">
                <!-- 授权信息 -->
                <div class="col-xs-12 col-sm-6 col-lg-6">
                    <div class="block">
                        <div class="block-title"><h3 class="panel-title">授权信息</h3></div>
                        <div class="status-card" id="auth-card">
                            <div class="form-group">
                                <label>授权域名:</label>
                                <span id="auth-domain"></span>
                            </div>
                            <div class="form-group">
                                <label>授权状态:</label>
                                <span id="auth-status">检查中...</span>
                            </div>
                            <div class="form-group">
                                <label>授权类型:</label>
                                <span id="auth-type">检查中...</span>
                            </div>
                            <div class="form-group">
                                <label>到期时间:</label>
                                <span id="auth-expire">检查中...</span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 版本信息 -->
                <div class="col-xs-12 col-sm-6 col-lg-6">
                    <div class="block">
                        <div class="block-title"><h3 class="panel-title">版本信息</h3></div>
                        <div class="status-card" id="version-card">
                            <div class="form-group">
                                <label>当前版本:</label>
                                <span id="current-version"><?php echo htmlspecialchars($current_version);?></span>
                            </div>
                            <div class="form-group">
                                <label>最新版本:</label>
                                <span id="latest-version">检查中...</span>
                            </div>
                            <div class="form-group">
                                <label>数据库版本:</label>
                                <span><?php echo htmlspecialchars($db_version);?></span>
                                <?php if($db_need_update):?>
                                <span class="label label-warning">需要更新到 <?php echo $current_db_version;?></span>
                                <a href="./cx-update.php?update=1" class="btn btn-xs btn-warning">点击更新数据库</a>
                                <?php else:?>
                                <span class="label label-success">已是最新</span>
                                <?php endif;?>
                            </div>
                            <div id="update-info" class="update-info" style="display:none">
                                <div class="form-group">
                                    <label>更新说明:</label>
                                    <div id="update-description"></div>
                                </div>
                                <div class="form-group">
                                    <label>文件大小:</label>
                                    <span id="update-size"></span>
                                </div>
                                <div class="form-group">
                                    <label>发布时间:</label>
                                    <span id="update-time"></span>
                                </div>
                                <div id="update-progress" style="display:none">
                                    <div class="progress-text">更新进度：<span id="progress-status">准备开始</span></div>
                                    <div class="progress progress-striped active">
                                        <div id="progress-bar" class="progress-bar progress-bar-success" role="progressbar" style="width: 0%">
                                            <span id="progress-text">0%</span>
                                        </div>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <button id="update-button" class="btn btn-success btn-sm" onclick="startUpdate()">开始更新</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 右侧留言板 -->
        <div class="col-xs-12 col-sm-4 col-lg-4 right-cards mobile-order-1">
            <div class="block">
                <div class="block-title">
                    <h3 class="panel-title">留言板&提出建议或留下BUG反馈，共同变好</h3>
                </div>
                <div class="status-card" id="message-card">
                    <div id="message-list" class="message-list"></div>
                    <div class="message-pagination">
                        <ul class="pagination pagination-sm" id="message-pagination"></ul>
                        <div id="message-total" class="page-info"></div>
                    </div>
                    <div class="message-form">
                        <div class="form-group">
                            <textarea class="form-control" id="message-content" placeholder="请输入留言内容..." rows="3"></textarea>
                        </div>
                        <div class="form-group">
                            <button class="btn btn-primary btn-sm" id="submit-message-btn" onclick="submitMessage()">
                                <i class="fa fa-send"></i> 提交留言
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 更新日志 -->
            <div class="block">
                <div class="block-title">
                    <h3 class="panel-title">更新日志</h3>
                </div>
                <div class="status-card" id="changelog-card">
                    <div class="changelog-list">
                        <div class="changelog-current">
                            <div class="version-tag">
                                <span class="label label-success">当前版本</span>
                                <span class="version" id="changelog-current-version"><?php echo htmlspecialchars($current_version);?></span>
                            </div>
                            <div class="version-content" id="changelog-current-content">
                                <div class="text-center text-muted">
                                    <i class="fa fa-spinner fa-spin"></i> 加载中...
                                </div>
                            </div>
                        </div>
                        <div class="changelog-history" id="changelog-history">
                            <div class="text-center text-muted">
                                <i class="fa fa-spinner fa-spin"></i> 加载历史版本...
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
var updateInfo = null;

function checkAuth() {
    var domain = window.location.hostname;
    
    // 先从localStorage中获取缓存
    var cachedData = localStorage.getItem('auth_cache');
    var now = new Date().getTime();
    
    if (cachedData) {
        try {
            cachedData = JSON.parse(cachedData);
            // 检查缓存是否在10分钟内
            if (now - cachedData.timestamp < 600000) { // 10分钟 = 600000毫秒
                // 使用缓存数据
                updateAuthUI(cachedData.data);
                return;
            }
        } catch(e) {
            console.error('缓存数据解析错误:', e);
        }
    }
    
    // 如果没有缓存或缓存已过期，则发送请求
    $.ajax({
        type: 'POST',
        url: 'cx-ajax.php?act=checkAuth',
        data: {domain: domain},
        dataType: 'json',
        success: function(data) {
            if(data.code == 200) {
                // 更新UI
                updateAuthUI(data);
                
                // 保存到缓存
                localStorage.setItem('auth_cache', JSON.stringify({
                    timestamp: now,
                    data: data
                }));
            } else {
                $('#auth-status').html('<span class="label label-danger">未授权</span>');
                $('#auth-type').html('');
                $('#auth-expire').text('');
                alert(data.message);
            }
        },
        error: function() {
            alert('请求失败');
        }
    });
}

// 更新授权UI的辅助函数
function updateAuthUI(data) {
    if(data.code == 200) {
        $('#auth-domain').text(data.data.domain);
        $('#auth-status').html('<span class="label label-success">已授权</span>');
        $('#auth-type').html(data.data.is_trial == 1 ? 
            '<span class="label label-warning">试用版</span>' : 
            '<span class="label label-success">正式版</span>');
        $('#auth-expire').text(data.data.expire_date);
    }
}

function formatFileSize(bytes) {
    if(bytes < 1024) return bytes + ' B';
    else if(bytes < 1048576) return (bytes/1024).toFixed(2) + ' KB';
    else return (bytes/1048576).toFixed(2) + ' MB';
}

function checkUpdate() {
    var version = $('#current-version').text();
    $.ajax({
        type: 'GET',
        url: 'cx-ajax.php?act=checkUpdate&version=' + version,
        dataType: 'json',
        success: function(data) {
            if(data.status === 'update_available') {
                updateInfo = data;
                $('#latest-version').text(data.version);
                $('#latest-version').append(' <span class="label label-warning">发现新版本</span>');
                $('#update-description').html(data.description).css('white-space', 'pre-wrap');
                $('#update-size').text(formatFileSize(data.file_size));
                $('#update-time').text(data.release_time);
                $('#update-button').prop('disabled', false);
                $('#update-progress').hide();
                $('#update-info').show();
                
                // 使用Bootstrap模态框显示更新提示
                var modalHtml = '<div class="modal fade" id="updateModal" tabindex="-1" role="dialog">' +
                    '<div class="modal-dialog" role="document">' +
                    '<div class="modal-content">' +
                    '<div class="modal-header">' +
                    '<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>' +
                    '<h4 class="modal-title">发现新版本</h4>' +
                    '</div>' +
                    '<div class="modal-body">' +
                    '<h4>新版本：v' + data.version + '</h4>' +
                    '<p><b>更新时间：</b>' + data.release_time + '</p>' +
                    '<p><b>更新大小：</b>' + formatFileSize(data.file_size) + '</p>' +
                    '<p><b>更新内容：</b></p>' +
                    '<div class="well well-sm" style="white-space: pre-wrap;">' + data.description + '</div>' +
                    (data.has_more_updates ? '<div class="alert alert-warning" style="margin-top:10px;"><i class="fa fa-exclamation-circle"></i> 提示：完成此版本更新后还有新的版本可更新，建议逐个版本依次更新。</div>' : '') +
                    '</div>' +
                    '<div class="modal-footer">' +
                    '<button type="button" class="btn btn-default" data-dismiss="modal">稍后再说</button>' +
                    '<button type="button" class="btn btn-success" onclick="startUpdate()">立即更新</button>' +
                    '</div>' +
                    '</div>' +
                    '</div>' +
                    '</div>';

                // 移除可能存在的旧模态框
                $('#updateModal').remove();
                // 添加新模态框到body
                $('body').append(modalHtml);
                // 显示模态框
                $('#updateModal').modal('show');
                
                // 如果还有更多更新可用，显示提示
                if(data.has_more_updates) {
                    $('#update-description').append('<br><span class="text-warning">注意：完成此版本更新后还有新的更新可用</span>');
                }
            } else if(data.status === 'up_to_date') {
                updateInfo = null;
                $('#latest-version').text(data.version);
                $('#latest-version').append(' <span class="label label-success">已是最新</span>');
                $('#update-info').hide();
            } else if(data.status === 'no_updates') {
                updateInfo = null;
                $('#latest-version').text('未知');
                $('#latest-version').append(' <span class="label label-default">无更新记录</span>');
                $('#update-info').hide();
            } else {
                updateInfo = null;
                alert('检查更新失败');
                $('#update-info').hide();
            }
        },
        error: function() {
            alert('请求失败');
        }
    });
}

function updateProgress(status, percent) {
    $('#progress-status').text(status);
    $('#progress-bar').css('width', percent + '%');
    $('#progress-text').text(percent + '%');
}

function startUpdate() {
    if(!updateInfo) {
        alert('没有可用的更新信息');
        return;
    }
    
    var adminDir = prompt('请输入后台目录名称:', 'admin');
    if(adminDir === null) return; // 用户点击取消
    if(adminDir.trim() === '') {
        alert('目录名称不能为空');
        return;
    }
    
    if(!confirm('确定要更新到最新版本吗？更新前请注意备份重要数据。')) {
        return;
    }
    
    $('#update-button').prop('disabled', true);
    $('#update-progress').show();
    updateProgress('正在下载更新包...', 0);
    
    $.ajax({
        type: 'POST',
        url: 'cx-ajax.php?act=startUpdate',
        data: {
            version: updateInfo.version,
            download_url: updateInfo.download_url,
            file_name: updateInfo.file_name,
            admin_dir: adminDir.trim()
        },
        dataType: 'json',
        success: function(data) {
            if(data.code == 0) {
                checkUpdateProgress();
            } else {
                alert('开始更新失败：' + data.msg);
                $('#update-button').prop('disabled', false);
            }
        },
        error: function() {
            alert('请求失败');
            $('#update-button').prop('disabled', false);
        }
    });
}

function checkUpdateProgress() {
    $.ajax({
        url: 'cx-ajax.php?act=getUpdateProgress',
        dataType: 'json',
        success: function(data) {
            if(data.code == 0) {
                updateProgress(data.status, data.percent);
                if(data.finished) {
                    if(data.success) {
                        alert('更新成功！系统将自动刷新。');
                        location.reload();
                    } else {
                        alert('更新失败：' + data.msg);
                        $('#update-button').prop('disabled', false);
                    }
                } else {
                    setTimeout(checkUpdateProgress, 1000);
                }
            } else {
                alert('获取更新进度失败');
                $('#update-button').prop('disabled', false);
            }
        },
        error: function() {
            alert('请求失败');
            $('#update-button').prop('disabled', false);
        }
    });
}

function debugAuth() {
    $.ajax({
        url: 'cx-ajax.php?act=debug&type=auth',
        dataType: 'json',
        success: function(data) {
            var debugInfo = JSON.stringify(data, null, 2);
            var win = window.open('', '_blank');
            win.document.write('<pre>' + debugInfo + '</pre>');
        }
    });
}

function debugUpdate() {
    $.ajax({
        url: 'cx-ajax.php?act=debug&type=update',
        dataType: 'json',
        success: function(data) {
            var debugInfo = JSON.stringify(data, null, 2);
            var win = window.open('', '_blank');
            win.document.write('<pre>' + debugInfo + '</pre>');
        }
    });
}

function debugAd() {
    $.ajax({
        url: 'cx-ajax.php?act=debug&type=ad',
        dataType: 'json',
        success: function(data) {
            var debugInfo = JSON.stringify(data, null, 2);
            var win = window.open('', '_blank');
            win.document.write('<pre>' + debugInfo + '</pre>');
        }
    });
}

function debugChangelog() {
    $.ajax({
        url: 'cx-ajax.php?act=debug&type=changelog',
        dataType: 'json',
        success: function(data) {
            var debugInfo = JSON.stringify(data, null, 2);
            var win = window.open('', '_blank');
            win.document.write('<pre>' + debugInfo + '</pre>');
        }
    });
}

// 加载资源
function loadResources() {
    // 显示加载状态
    $('#promotion-content').html('<div class="item active"><div class="promotion-content"><i class="fa fa-spinner fa-spin"></i> 加载中...</div></div>');
    $('#promotion-carousel').show();
    $('.carousel-control, .carousel-indicators').hide();
    
    $.ajax({
        type: 'GET',
        url: 'cx-ajax.php?act=getAd',
        dataType: 'json',
        success: function(response) {
            console.log('资源数据:', response);
            
            if(response.code === 200 && response.data && response.data.length > 0) {
                var imageContent = '';
                var imageIndicators = '';
                var textContent = '';
                var imageCount = 0;
                var textCount = 0;
                
                response.data.forEach(function(item, index) {
                    if(item.res_type === 'image') {
                        // 图片资源
                        imageIndicators += '<li data-target="#promotion-carousel" data-slide-to="' + imageCount + '"' + 
                            (imageCount === 0 ? ' class="active"' : '') + '></li>';
                        imageContent += '<div class="item' + (imageCount === 0 ? ' active' : '') + '">' +
                            '<a href="' + item.res_url + '" data-id="' + item.id + '" onclick="handleResourceClick(' + item.id + ', event)">' +
                            '<img src="' + item.res_content + '" alt="推广内容">' +
                            '</a></div>';
                        imageCount++;
                    } else if(item.res_type === 'text') {
                        // 文字资源
                        var style = '';
                        if(item.style) {
                            if(item.style.color) style += 'color:' + item.style.color + ';';
                            if(item.style.text_style) {
                                style += 'font-size:' + item.style.text_style.font_size + ';';
                                style += 'font-weight:' + item.style.text_style.font_weight + ';';
                                style += 'text-decoration:' + item.style.text_style.text_decoration + ';';
                            }
                        }
                        textContent += '<div class="promotion-item">' +
                            '<a href="' + item.res_url + '" data-id="' + item.id + '" style="' + style + '" onclick="handleResourceClick(' + item.id + ', event)">' +
                            '<span class="glyphicon glyphicon-link"></span>' +
                            '<span class="content-text">' + item.res_content + '</span>' +
                            '</a></div>';
                        textCount++;
                    }
                });
                
                // 更新界面
                if(imageCount > 0) {
                    $('#promotion-carousel').show();
                    $('#promotion-indicators').html(imageIndicators);
                    $('#promotion-content').html(imageContent);
                    if(imageCount > 1) {
                        $('.carousel-control, .carousel-indicators').show();
                        $('#promotion-carousel').carousel({
                            interval: 5000
                        });
                    }
                } else {
                    $('#promotion-carousel').hide();
                }
                
                if(textCount > 0) {
                    $('#promotion-list').html(textContent).show();
                } else {
                    $('#promotion-list').hide();
                }
            } else {
                showEmptyResource();
            }
        },
        error: function() {
            showEmptyResource();
        }
    });
}

// 显示空资源状态
function showEmptyResource() {
    $('#promotion-carousel').hide();
    $('#promotion-list').html('<div class="alert alert-info">暂无推广内容</div>');
}

// 处理资源点击
function handleResourceClick(id, event) {
    event.preventDefault();
    event.stopPropagation();
    var link = $(event.currentTarget).attr('href');
    
    $.ajax({
        type: 'GET',
        url: 'cx-ajax.php?act=recordClick&id=' + id,
        dataType: 'json',
        success: function(response) {
            if(response.code === 200) {
                window.open(link, '_blank');
            } else {
                console.log('点击记录失败:', response.message);
                window.open(link, '_blank');
            }
        },
        error: function(xhr, status, error) {
            console.log('请求失败:', error);
            window.open(link, '_blank');
        }
    });
}

// 加载留言列表
function loadMessages(page = 1) {
    $('#message-list').html('<div class="text-center" style="padding: 20px;"><i class="fa fa-spinner fa-spin"></i> 加载中...</div>');
    $('#message-pagination').empty();
    $('#message-total').empty();
    
    $.ajax({
        type: 'GET',
        url: 'cx-ajax.php?act=getMessages&page=' + page,
        dataType: 'json',
        success: function(response) {
            if(response.code === 200 && response.data && response.data.messages && response.data.messages.length > 0) {
                var html = '';
                response.data.messages.forEach(function(message) {
                    var defaultAvatar = 'data:image/svg+xml,' + encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><text y=".9em" font-size="90">🌐</text></svg>');
                    html += '<div class="message-item">' +
                        '<div class="message-header">' +
                        '<img src="' + (message.favicon_url || defaultAvatar) + '" class="message-avatar" ' +
                        'onerror="this.onerror=null;this.src=\'' + defaultAvatar + '\'">' +
                        '<div class="message-info">' +
                        '<div class="message-domain">' + htmlEncode(message.domain) + '</div>' +
                        '<div class="message-time">' + message.created_at + '</div>' +
                        '</div>' +
                        '</div>' +
                        '<div class="message-content">' + htmlEncode(message.content) + '</div>' +
                        '</div>';
                });
                $('#message-list').html(html);
                
                // 更新分页
                var pagination = response.data.pagination;
                if(pagination.total_pages > 1) {
                    var paginationHtml = '';
                    // 上一页
                    paginationHtml += '<li class="' + (page <= 1 ? 'disabled' : '') + '">' +
                        '<a href="javascript:' + (page <= 1 ? 'void(0)' : 'loadMessages(' + (page-1) + ')') + '">' +
                        '<i class="fa fa-angle-left"></i></a></li>';
                    
                    // 页码
                    var startPage = Math.max(1, page - 2);
                    var endPage = Math.min(pagination.total_pages, page + 2);
                    
                    if(startPage > 1) {
                        paginationHtml += '<li><a href="javascript:loadMessages(1)">1</a></li>';
                        if(startPage > 2) paginationHtml += '<li class="disabled"><span>...</span></li>';
                    }
                    
                    for(var i = startPage; i <= endPage; i++) {
                        paginationHtml += '<li class="' + (i == page ? 'active' : '') + '">' +
                            '<a href="javascript:loadMessages(' + i + ')">' + i + '</a></li>';
                    }
                    
                    if(endPage < pagination.total_pages) {
                        if(endPage < pagination.total_pages - 1) paginationHtml += '<li class="disabled"><span>...</span></li>';
                        paginationHtml += '<li><a href="javascript:loadMessages(' + pagination.total_pages + ')">' + 
                            pagination.total_pages + '</a></li>';
                    }
                    
                    // 下一页
                    paginationHtml += '<li class="' + (page >= pagination.total_pages ? 'disabled' : '') + '">' +
                        '<a href="javascript:' + (page >= pagination.total_pages ? 'void(0)' : 'loadMessages(' + (page+1) + ')') + '">' +
                        '<i class="fa fa-angle-right"></i></a></li>';
                    
                    $('#message-pagination').html(paginationHtml);
                }
                
                // 显示总数
                $('#message-total').html('共 ' + pagination.total + ' 条留言');
            } else {
                $('#message-list').html('<div class="alert alert-info">暂无留言</div>');
            }
        },
        error: function() {
            $('#message-list').html('<div class="alert alert-danger">加载留言失败</div>');
        }
    });
}

// HTML编码函数
function htmlEncode(str) {
    if(!str) return '';
    return str.replace(/[<>&"']/g, function(match) {
        switch(match) {
            case '<': return '&lt;';
            case '>': return '&gt;';
            case '&': return '&amp;';
            case '"': return '&quot;';
            case "'": return '&#39;';
        }
    });
}

// 提交留言
function submitMessage() {
    var content = $('#message-content').val().trim();
    
    if(!content) {
        alert('请输入留言内容');
        return;
    }
    
    var $btn = $('#submit-message-btn').prop('disabled', true)
        .html('<i class="fa fa-spinner fa-spin"></i> 提交中...');
    
    $.ajax({
        type: 'POST',
        url: 'cx-ajax.php?act=submitMessage',
        data: {
            content: content
        },
        dataType: 'json',
        success: function(response) {
            if(response.code === 200) {
                $('#message-content').val('');
                loadMessages(1);
            } else {
                alert('留言提交失败：' + response.message);
            }
        },
        error: function() {
            alert('提交请求失败');
        },
        complete: function() {
            $btn.prop('disabled', false)
                .html('<i class="fa fa-send"></i> 提交留言');
        }
    });
}

// 加载更新日志
function loadChangelog(page = 1) {
    var version = $('#current-version').text();
    
    // 显示加载状态
    $('#changelog-current-content').html('<div class="text-center text-muted"><i class="fa fa-spinner fa-spin"></i> 加载中...</div>');
    $('#changelog-history').html('<div class="text-center text-muted"><i class="fa fa-spinner fa-spin"></i> 加载历史版本...</div>');
    
    $.ajax({
        type: 'GET',
        url: 'cx-ajax.php?act=getChangelog&version=' + version + '&page=' + page + '&limit=10',
        dataType: 'json',
        success: function(response) {
            if(response.code === 200 && response.data) {
                // 显示当前版本更新说明
                if(response.data.current) {
                    var currentLog = response.data.current;
                    $('#changelog-current-content').html(
                        '<div class="version-date">' + currentLog.release_time + '</div>' +
                        '<div class="version-desc">' + htmlEncode(currentLog.description).replace(/\n/g, '<br>') + '</div>'
                    );
                } else {
                    $('#changelog-current-content').html('<div class="text-muted">暂无更新说明</div>');
                }

                // 显示历史版本更新说明
                if(response.data.history && response.data.history.length > 0) {
                    var html = '';
                    response.data.history.forEach(function(log) {
                        // 跳过当前版本
                        if(log.version === version) return;
                        
                        // 检查版本号格式
                        var versionDisplay = log.version;
                        if(!/^\d+\.\d+\.\d+$/.test(versionDisplay)) {
                            versionDisplay = '1.0.0'; // 默认版本号
                        }
                        
                        html += '<div class="version-item">' +
                            '<div class="version-header">' +
                            '<span class="version-number">v' + versionDisplay + '</span>' +
                            '<span class="version-date">' + log.release_time + '</span>' +
                            '</div>' +
                            '<div class="version-desc">' + htmlEncode(log.description).replace(/\n/g, '<br>') + '</div>' +
                            '</div>';
                    });
                    
                    // 添加分页控件
                    if(response.data.pagination && response.data.pagination.total_pages > 1) {
                        html += '<div class="text-center mt-3">';
                        html += '<ul class="pagination pagination-sm">';
                        
                        // 上一页
                        if(page > 1) {
                            html += '<li><a href="javascript:loadChangelog(' + (page-1) + ')"><i class="fa fa-angle-left"></i></a></li>';
                        } else {
                            html += '<li class="disabled"><span><i class="fa fa-angle-left"></i></span></li>';
                        }
                        
                        // 页码
                        var startPage = Math.max(1, page - 2);
                        var endPage = Math.min(response.data.pagination.total_pages, page + 2);
                        
                        if(startPage > 1) {
                            html += '<li><a href="javascript:loadChangelog(1)">1</a></li>';
                            if(startPage > 2) html += '<li class="disabled"><span>...</span></li>';
                        }
                        
                        for(var i = startPage; i <= endPage; i++) {
                            if(i === page) {
                                html += '<li class="active"><span>' + i + '</span></li>';
                            } else {
                                html += '<li><a href="javascript:loadChangelog(' + i + ')">' + i + '</a></li>';
                            }
                        }
                        
                        if(endPage < response.data.pagination.total_pages) {
                            if(endPage < response.data.pagination.total_pages - 1) html += '<li class="disabled"><span>...</span></li>';
                            html += '<li><a href="javascript:loadChangelog(' + response.data.pagination.total_pages + ')">' + 
                                response.data.pagination.total_pages + '</a></li>';
                        }
                        
                        // 下一页
                        if(page < response.data.pagination.total_pages) {
                            html += '<li><a href="javascript:loadChangelog(' + (page+1) + ')"><i class="fa fa-angle-right"></i></a></li>';
                        } else {
                            html += '<li class="disabled"><span><i class="fa fa-angle-right"></i></span></li>';
                        }
                        
                        html += '</ul>';
                        html += '<div class="text-muted">共 ' + response.data.pagination.total + ' 条记录</div>';
                        html += '</div>';
                    }
                    
                    if(html) {
                        $('#changelog-history').html(html);
                    } else {
                        $('#changelog-history').html('<div class="text-muted">暂无历史版本记录</div>');
                    }
                } else {
                    $('#changelog-history').html('<div class="text-muted">暂无历史版本记录</div>');
                }
            } else {
                var errorMsg = response.message || '获取更新说明失败';
                $('#changelog-current-content').html(
                    '<div class="text-danger"><i class="fa fa-exclamation-circle"></i> ' + htmlEncode(errorMsg) + '</div>'
                );
                $('#changelog-history').html(
                    '<div class="text-danger"><i class="fa fa-exclamation-circle"></i> ' + htmlEncode(errorMsg) + '</div>'
                );
            }
        },
        error: function(xhr, status, error) {
            var errorMsg = '加载失败: ' + (error || '未知错误');
            $('#changelog-current-content, #changelog-history').html(
                '<div class="text-danger"><i class="fa fa-exclamation-circle"></i> ' + htmlEncode(errorMsg) + '</div>'
            );
        }
    });
}

$(document).ready(function(){
    checkAuth();
    checkUpdate();
    loadResources();
    loadMessages();
    loadChangelog();
    
    // 鼠标悬停时暂停轮播
    $('#promotion-carousel').hover(
        function() { $(this).carousel('pause'); },
        function() { $(this).carousel('cycle'); }
    );
});
</script>
</div></div>
<?php include './foot.php';?>
