<?php
$title='轮播图管理';
include __DIR__ . '/head.php';
$active='carousel';
?>
<div class="p-4 md:p-6">
        <!-- 页面标题 -->
        <div class="flex justify-between items-center mb-6">
            <h1 class="text-2xl font-bold text-gray-800">轮播图管理</h1>
            <button onclick="openAddModal()" 
                    class="px-4 py-2 bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-700 hover:to-purple-700 text-white rounded-xl font-medium transition-all shadow-sm hover:shadow-md">
                <i class="fas fa-plus mr-2"></i>添加轮播图
            </button>
        </div>
        
        <!-- 轮播图列表 -->
        <div class="bg-white rounded-2xl shadow-xl overflow-hidden">
            <div class="px-4 md:px-6 py-4 border-b border-gray-100">
                <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
                    <h3 class="font-semibold text-gray-800">轮播图列表</h3>
                    <div class="flex items-center gap-2 w-full md:w-auto">
                        <input type="text" id="searchInput" placeholder="搜索标题" 
                               class="w-full md:w-48 px-3 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition-all">
                        <button onclick="searchCarousel()" 
                                class="px-3 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg transition-colors whitespace-nowrap">
                            <i class="fas fa-search"></i>
                        </button>
                    </div>
                </div>
            </div>
            
            <div class="overflow-x-auto">
                <table class="w-full min-w-[1100px]">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider w-16">ID</th>
                            <th class="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider w-24">标题</th>
                            <th class="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider min-w-[150px]">图片</th>
                            <th class="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">链接</th>
                            <th class="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider w-16">类型</th>
                            <th class="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider w-24">排序</th>
                            <th class="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider w-16">状态</th>
                            <th class="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider w-32">添加时间</th>
                            <th class="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider w-24">操作</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-100" id="carouselList">
                        <!-- 轮播图数据将通过JavaScript动态加载 -->
                    </tbody>
                </table>
            </div>
            
            <!-- 分页控件 -->
            <div class="px-6 py-4 border-t border-gray-100 flex items-center justify-between">
                <div class="text-sm text-gray-500">
                    共 <span id="totalCount">0</span> 条记录
                </div>
                <div class="flex items-center gap-2">
                    <button onclick="prevPage()" id="prevPage" disabled 
                            class="px-3 py-1.5 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg text-sm transition-colors">
                        <i class="fas fa-chevron-left"></i>
                    </button>
                    <span class="text-sm text-gray-500">第 <span id="currentPage">1</span> / <span id="totalPages">1</span> 页</span>
                    <button onclick="nextPage()" id="nextPage" disabled 
                            class="px-3 py-1.5 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg text-sm transition-colors">
                        <i class="fas fa-chevron-right"></i>
                    </button>
                </div>
            </div>
        </div>
    

<!-- 添加/编辑轮播图模态框 -->
<div id="carouselModal" class="fixed inset-0 z-50 hidden">
    <div class="fixed inset-0 bg-black/50 transition-opacity" onclick="closeCarouselModal()"></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-2xl 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">
                <h3 id="modalTitle" class="text-lg font-semibold text-gray-800">添加轮播图</h3>
                <button onclick="closeCarouselModal()" class="w-8 h-8 flex items-center justify-center rounded-full hover:bg-gray-100 text-gray-400 hover:text-gray-600 transition-colors">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="px-5 py-4 overflow-y-auto">
                <form id="carouselForm">
                    <input type="hidden" id="carouselId">
                    
                    <div class="space-y-4">
                        <div class="space-y-2">
                            <label class="block text-sm font-medium text-gray-700">标题</label>
                            <input type="text" id="carouselTitle" required 
                                   class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-colors">
                        </div>
                        
                        <div class="space-y-2">
                            <label class="block text-sm font-medium text-gray-700">类型</label>
                            <div class="flex gap-4">
                                <label class="flex items-center gap-2 cursor-pointer">
                                    <input type="radio" name="carouselType" value="1" checked 
                                           class="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300">
                                    <span class="text-sm text-gray-700">上传图片</span>
                                </label>
                                <label class="flex items-center gap-2 cursor-pointer">
                                    <input type="radio" name="carouselType" value="0" 
                                           class="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300">
                                    <span class="text-sm text-gray-700">外链图片</span>
                                </label>
                            </div>
                        </div>
                        
                        <div class="space-y-2 hidden" id="imageUrlContainer">
                            <label class="block text-sm font-medium text-gray-700">图片地址</label>
                            <input type="url" id="carouselImage" required 
                                   class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-colors">
                            <p class="text-xs text-gray-500">建议上传 16:9 比例的图片</p>
                        </div>
                        
                        <div class="space-y-2 hidden" id="imageUploadContainer">
                            <label class="block text-sm font-medium text-gray-700">上传图片</label>
                            <input type="file" id="carouselFile" accept="image/*" 
                                   class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-colors">
                            <p class="text-xs text-gray-500">支持 JPG、PNG、GIF 格式，建议尺寸 1920x1080 (16:9)</p>
                        </div>
                        
                        <div class="space-y-2">
                            <label class="block text-sm font-medium text-gray-700">跳转链接</label>
                            <input type="url" id="carouselLink" 
                                   class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-colors">
                        </div>
                        
                        <div class="space-y-2">
                            <label class="block text-sm font-medium text-gray-700">排序</label>
                            <input type="number" id="carouselSort" value="50" min="0" max="999" 
                                   class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-colors">
                        </div>
                        
                        <div class="space-y-2">
                            <label class="block text-sm font-medium text-gray-700">状态</label>
                            <div class="flex gap-4">
                                <label class="flex items-center gap-2 cursor-pointer">
                                    <input type="radio" name="carouselStatus" value="1" checked 
                                           class="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300">
                                    <span class="text-sm text-gray-700">启用</span>
                                </label>
                                <label class="flex items-center gap-2 cursor-pointer">
                                    <input type="radio" name="carouselStatus" value="0" 
                                           class="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300">
                                    <span class="text-sm text-gray-700">禁用</span>
                                </label>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
            <div class="px-5 py-3 border-t border-gray-100 flex justify-end gap-2">
                <button onclick="closeCarouselModal()" 
                        class="px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg font-medium transition-colors">
                    取消
                </button>
                <button onclick="saveCarousel()" 
                        class="px-4 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg font-medium transition-colors">
                    保存
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Toast 提示 -->
<div id="toastWrap" class="fixed top-6 right-6 z-50 flex flex-col items-end gap-2"></div>

<!-- Loading 遮罩 -->
<div id="loadingOverlay" class="fixed inset-0 z-50 hidden bg-white/30 flex items-center justify-center">
    <div class="w-10 h-10 border-4 border-indigo-200 border-t-indigo-600 rounded-full animate-spin"></div>
</div>

<script>
var currentPage = 1;
var totalPages = 1;
var pageSize = 10;

// 类型和状态文本映射
var typeText = {
    0: '<span class="px-2 py-1 bg-blue-100 text-blue-700 rounded-full text-xs">外链</span>',
    1: '<span class="px-2 py-1 bg-green-100 text-green-700 rounded-full text-xs">上传</span>'
};

var statusText = {
    1: '<span class="px-2 py-1 bg-green-100 text-green-700 rounded-full text-xs">启用</span>',
    0: '<span class="px-2 py-1 bg-red-100 text-red-700 rounded-full text-xs">禁用</span>'
};

$(document).ready(function() {
    loadCarouselList();
    
    // 类型切换事件
    $('input[name="carouselType"]').change(function() {
        var type = $(this).val();
        if (type == 0) {
            $('#imageUrlContainer').removeClass('hidden');
            $('#imageUploadContainer').addClass('hidden');
            $('#carouselImage').prop('required', true);
            $('#carouselFile').prop('required', false);
        } else {
            $('#imageUrlContainer').addClass('hidden');
            $('#imageUploadContainer').removeClass('hidden');
            $('#carouselImage').prop('required', false);
            $('#carouselFile').prop('required', true);
        }
    });
    
    // 页面加载时初始化显示状态
    $(document).ready(function() {
        $('input[name="carouselType"]:checked').trigger('change');
    });
});

function loadCarouselList() {
    showLoading();
    $.ajax({
        type: 'POST',
        url: 'ajax.php?act=get_carousel',
        data: {
            page: currentPage,
            pagesize: pageSize,
            keyword: $('#searchInput').val()
        },
        dataType: 'json',
        success: function(data) {
            hideLoading();
            if (data.code == 1) {
                renderCarouselList(data.data || []);
                $('#totalCount').text(data.total || 0);
                totalPages = Math.ceil((data.total || 0) / pageSize) || 1;
                $('#currentPage').text(currentPage);
                $('#totalPages').text(totalPages);
                
                // 更新分页按钮状态
                $('#prevPage').prop('disabled', currentPage == 1);
                $('#nextPage').prop('disabled', currentPage == totalPages);
            } else {
                renderCarouselList([]);
                showToast('加载失败', 'error');
            }
        },
        error: function() {
            hideLoading();
            showToast('服务器错误', 'error');
            renderCarouselList([]);
        }
    });
}

function renderCarouselList(data) {
    var list = $('#carouselList');
    list.empty();
    
    if (data.length === 0) {
        list.html('<tr><td colspan="9" class="px-6 py-12 text-center text-gray-500"><i class="fas fa-images text-3xl mb-2"></i><p>暂无轮播图数据</p></td></tr>');
        return;
    }
    
    $.each(data, function(i, item) {
        var row = '<tr class="hover:bg-gray-50 transition-colors">'
                + '<td class="px-4 py-3 whitespace-nowrap text-sm text-gray-900 text-center">' + item.id + '</td>'
                + '<td class="px-4 py-3 whitespace-nowrap text-sm font-medium text-gray-900 text-center">' + item.title + '</td>'
                + '<td class="px-4 py-3 text-center">'
                + '<img src="' + item.image + '" class="w-32 h-16 object-cover rounded-lg border border-gray-200 mx-auto">'
                + '</td>'
                + '<td class="px-4 py-3 text-sm text-gray-500 text-center">'
                + (item.link ? '<a href="' + item.link + '" target="_blank" class="text-indigo-600 hover:text-indigo-800">' + item.link + '</a>' : '-')
                + '</td>'
                + '<td class="px-4 py-3 whitespace-nowrap text-center">' + typeText[item.type] + '</td>'
                + '<td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500 text-center">' + item.sort + '</td>'
                + '<td class="px-4 py-3 whitespace-nowrap text-center">' + statusText[item.status] + '</td>'
                + '<td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500 text-center">' + item.addtime + '</td>'
                + '<td class="px-4 py-3 whitespace-nowrap text-sm font-medium text-center">'
                + '<div class="flex gap-2 justify-center">'
                + '<button onclick="editCarousel(' + item.id + ')" class="text-indigo-600 hover:text-indigo-900 transition-colors">'
                + '<i class="fas fa-edit"></i>'
                + '</button>'
                + '<button onclick="deleteCarousel(' + item.id + ')" class="text-red-600 hover:text-red-900 transition-colors">'
                + '<i class="fas fa-trash"></i>'
                + '</button>'
                + '</div>'
                + '</td>'
                + '</tr>';

        list.append(row);
    });
}

function openAddModal() {
    $('#modalTitle').text('添加轮播图');
    $('#carouselForm')[0].reset();
    $('#carouselId').val('');
    $('input[name="carouselType"]').val(['0']).trigger('change');
    $('#carouselModal').removeClass('hidden');
    $('body').css('overflow', 'hidden');
}

function editCarousel(id) {
    showLoading();
    $.ajax({
        type: 'POST',
        url: 'ajax.php?act=get_carousel_detail',
        data: {id: id},
        dataType: 'json',
        success: function(data) {
            hideLoading();
            if (data.code == 1) {
                var item = data.data;
                $('#modalTitle').text('编辑轮播图');
                $('#carouselId').val(item.id);
                $('#carouselTitle').val(item.title);
                $('#carouselLink').val(item.link);
                $('#carouselSort').val(item.sort);
                $('input[name="carouselStatus"]').val([item.status]);
                
                // 先设置类型并触发change事件，再设置图片地址
                $('input[name="carouselType"][value="' + String(item.type) + '"]').prop('checked', true).trigger('change');
                $('#carouselImage').val(item.image);
                
                $('#carouselModal').removeClass('hidden');
                $('body').css('overflow', 'hidden');
            } else {
                showToast('获取轮播图详情失败', 'error');
            }
        },
        error: function() {
            hideLoading();
            showToast('服务器错误', 'error');
        }
    });
}

function closeCarouselModal() {
    $('#carouselModal').addClass('hidden');
    $('body').css('overflow', '');
}

function saveCarousel() {
    var formData = new FormData();
    formData.append('id', $('#carouselId').val());
    formData.append('title', $('#carouselTitle').val());
    formData.append('link', $('#carouselLink').val());
    formData.append('sort', $('#carouselSort').val());
    formData.append('status', $('input[name="carouselStatus"]:checked').val());
    formData.append('type', $('input[name="carouselType"]:checked').val());
    
    var type = $('input[name="carouselType"]:checked').val();
    if (type == 0) {
        formData.append('image', $('#carouselImage').val());
    } else {
        var file = $('#carouselFile')[0].files[0];
        if (file) {
            formData.append('file', file);
        }
    }
    
    showLoading();
    $.ajax({
        type: 'POST',
        url: 'ajax.php?act=save_carousel',
        data: formData,
        processData: false,
        contentType: false,
        dataType: 'json',
        success: function(data) {
            hideLoading();
            if (data.code == 1) {
                showToast('保存成功', 'success');
                closeCarouselModal();
                loadCarouselList();
            } else {
                showToast(data.msg || '保存失败', 'error');
            }
        },
        error: function() {
            hideLoading();
            showToast('服务器错误', 'error');
        }
    });
}

function deleteCarousel(id) {
    if (confirm('确定要删除这个轮播图吗？')) {
        showLoading();
        $.ajax({
            type: 'POST',
            url: 'ajax.php?act=delete_carousel',
            data: {id: id},
            dataType: 'json',
            success: function(data) {
                hideLoading();
                if (data.code == 1) {
                    showToast('删除成功', 'success');
                    loadCarouselList();
                } else {
                    showToast(data.msg || '删除失败', 'error');
                }
            },
            error: function() {
                hideLoading();
                showToast('服务器错误', 'error');
            }
        });
    }
}

function searchCarousel() {
    currentPage = 1;
    loadCarouselList();
}

function prevPage() {
    if (currentPage > 1) {
        currentPage--;
        loadCarouselList();
    }
}

function nextPage() {
    if (currentPage < totalPages) {
        currentPage++;
        loadCarouselList();
    }
}

// Toast 提示函数
function showToast(message, type = 'info', duration = 2000) {
    const toastWrap = $('#toastWrap');
    const toast = $('<div>').addClass('px-4 py-2 rounded-lg shadow-lg flex items-center gap-2 transform transition-all duration-300 ease-in-out opacity-0 translate-x-4');
    
    let bgClass = 'bg-gray-800';
    if (type === 'success') bgClass = 'bg-green-600';
    if (type === 'error') bgClass = 'bg-red-600';
    if (type === 'warning') bgClass = 'bg-yellow-600';
    
    toast.addClass(bgClass).addClass('text-white');
    toast.html(`<i class="fas fa-${type === 'success' ? 'check' : type === 'error' ? 'exclamation' : type === 'warning' ? 'exclamation-triangle' : 'info'}"></i><span>${message}</span>`);
    
    toastWrap.append(toast);
    
    // 触发动画
    setTimeout(() => {
        toast.removeClass('opacity-0 translate-x-4');
    }, 10);
    
    // 自动移除
    setTimeout(() => {
        toast.addClass('opacity-0 translate-x-4');
        setTimeout(() => {
            toast.remove();
        }, 300);
    }, duration);
}

// Loading 遮罩函数
function showLoading() {
    $('#loadingOverlay').removeClass('hidden');
}

function hideLoading() {
    $('#loadingOverlay').addClass('hidden');
}
</script>
</div>

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