<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org" th:replace="~{layout :: layout(~{::title}, ~{::content})}">
<head>
    <title>订单管理 - 管理员</title>
</head>
<body>
    <div th:fragment="content">
        <!-- Page Actions -->
        <div th:fragment="page-actions">
            <div class="btn-group" role="group">
                <button type="button" class="btn btn-outline-primary dropdown-toggle" data-bs-toggle="dropdown">
                    <i class="fas fa-filter me-2"></i>筛选
                </button>
                <ul class="dropdown-menu">
                    <li><a class="dropdown-item" th:href="@{/orders/admin}">全部订单</a></li>
                    <li><a class="dropdown-item" th:href="@{/orders/admin(status=PENDING)}">待支付</a></li>
                    <li><a class="dropdown-item" th:href="@{/orders/admin(status=PAID)}">已支付</a></li>
                    <li><a class="dropdown-item" th:href="@{/orders/admin(status=SHIPPED)}">已发货</a></li>
                    <li><a class="dropdown-item" th:href="@{/orders/admin(status=COMPLETED)}">已完成</a></li>
                    <li><a class="dropdown-item" th:href="@{/orders/admin(status=CANCELLED)}">已取消</a></li>
                </ul>
            </div>
            <button type="button" class="btn btn-outline-success" onclick="exportOrders()">
                <i class="fas fa-download me-2"></i>导出
            </button>
        </div>
        
        <!-- Orders Statistics -->
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="card bg-primary text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h6 class="mb-1">总订单数</h6>
                                <h3 class="mb-0" th:text="${totalElements}">0</h3>
                            </div>
                            <i class="fas fa-shopping-cart fa-2x opacity-75"></i>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-warning text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h6 class="mb-1">待支付</h6>
                                <h3 class="mb-0" th:text="${pendingCount ?: 0}">0</h3>
                            </div>
                            <i class="fas fa-clock fa-2x opacity-75"></i>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-success text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h6 class="mb-1">已完成</h6>
                                <h3 class="mb-0" th:text="${completedCount ?: 0}">0</h3>
                            </div>
                            <i class="fas fa-check-circle fa-2x opacity-75"></i>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-info text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h6 class="mb-1">今日订单</h6>
                                <h3 class="mb-0" th:text="${todayCount ?: 0}">0</h3>
                            </div>
                            <i class="fas fa-calendar-day fa-2x opacity-75"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Orders Table -->
        <div class="card">
            <div class="card-header">
                <div class="row align-items-center">
                    <div class="col">
                        <h5 class="mb-0">
                            <i class="fas fa-list me-2"></i>订单管理
                        </h5>
                    </div>
                    <div class="col-auto">
                        <div class="row g-2">
                            <div class="col">
                                <select class="form-select form-select-sm" id="statusFilter">
                                    <option value="">全部状态</option>
                                    <option th:each="status : ${orderStatuses}" 
                                            th:value="${status.name()}" 
                                            th:text="${status.displayName}"
                                            th:selected="${status == param.status}"></option>
                                </select>
                            </div>
                            <div class="col">
                                <div class="input-group input-group-sm" style="max-width: 200px;">
                                    <input type="text" class="form-control" placeholder="搜索订单号..." id="searchInput">
                                    <button class="btn btn-outline-secondary" type="button">
                                        <i class="fas fa-search"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover mb-0" id="ordersTable">
                        <thead>
                            <tr>
                                <th width="120">订单号</th>
                                <th width="100">用户</th>
                                <th width="100">金额</th>
                                <th width="100">状态</th>
                                <th width="100">类型</th>
                                <th width="120">创建时间</th>
                                <th width="200">操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr th:each="order : ${orders.content}" class="order-row">
                                <td>
                                    <a th:href="@{|/orders/${order.id}|}" class="text-decoration-none">
                                        <span th:text="${order.orderNumber}">ORD123456789</span>
                                    </a>
                                </td>
                                <td>
                                    <div class="d-flex align-items-center">
                                        <div class="avatar-circle me-2">
                                            <i class="fas fa-user"></i>
                                        </div>
                                        <div>
                                            <div class="fw-bold" th:text="${order.user.username}">用户名</div>
                                            <small class="text-muted" th:text="${order.user.email}">邮箱</small>
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    <span th:text="${order.currency}">CNY</span>
                                    <span th:text="${order.totalAmount}">0.00</span>
                                </td>
                                <td>
                                    <span th:if="${order.status.name() == 'PENDING'}" class="badge bg-warning" th:text="${order.status.displayName}">待支付</span>
                                    <span th:if="${order.status.name() == 'CONFIRMED'}" class="badge bg-info" th:text="${order.status.displayName}">已确认</span>
                                    <span th:if="${order.status.name() == 'PAID'}" class="badge bg-primary" th:text="${order.status.displayName}">已支付</span>
                                    <span th:if="${order.status.name() == 'PROCESSING'}" class="badge bg-secondary" th:text="${order.status.displayName}">处理中</span>
                                    <span th:if="${order.status.name() == 'SHIPPED'}" class="badge bg-success" th:text="${order.status.displayName}">已发货</span>
                                    <span th:if="${order.status.name() == 'DELIVERED'}" class="badge bg-success" th:text="${order.status.displayName}">已送达</span>
                                    <span th:if="${order.status.name() == 'COMPLETED'}" class="badge bg-success" th:text="${order.status.displayName}">已完成</span>
                                    <span th:if="${order.status.name() == 'CANCELLED'}" class="badge bg-danger" th:text="${order.status.displayName}">已取消</span>
                                    <span th:if="${order.status.name() == 'REFUNDED'}" class="badge bg-secondary" th:text="${order.status.displayName}">已退款</span>
                                </td>
                                <td>
                                    <span th:text="${order.orderType.displayName}">商品订单</span>
                                </td>
                                <td>
                                    <small th:text="${#temporals.format(order.createdAt, 'yyyy-MM-dd HH:mm')}">2024-01-01 10:00</small>
                                </td>
                                <td>
                                    <div class="btn-group" role="group">
                                        <a th:href="@{|/orders/${order.id}|}" class="btn btn-sm btn-outline-primary">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                        <div class="btn-group" role="group">
                                            <button type="button" class="btn btn-sm btn-outline-secondary dropdown-toggle" data-bs-toggle="dropdown">
                                                <i class="fas fa-cog"></i>
                                            </button>
                                            <ul class="dropdown-menu">
                                                <li th:if="${order.canShip()}" class="dropdown-item" style="cursor: pointer;" 
                                                    th:onclick="'shipOrder(' + ${order.id} + ')'">
                                                    <i class="fas fa-truck me-2"></i>发货
                                                </li>
                                                <li th:if="${order.canComplete()}" class="dropdown-item" style="cursor: pointer;" 
                                                    th:onclick="'completeOrder(' + ${order.id} + ')'">
                                                    <i class="fas fa-check me-2"></i>完成订单
                                                </li>
                                                <li th:if="${order.canCancel()}" class="dropdown-item" style="cursor: pointer;" 
                                                    th:onclick="'cancelOrder(' + ${order.id} + ')'">
                                                    <i class="fas fa-times me-2"></i>取消订单
                                                </li>
                                                <li><hr class="dropdown-divider"></li>
                                                <li class="dropdown-item" style="cursor: pointer;" 
                                                    th:onclick="'updateStatus(' + ${order.id} + ')'">
                                                    <i class="fas fa-edit me-2"></i>更新状态
                                                </li>
                                            </ul>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
            
            <div class="card-footer">
                <div class="row align-items-center">
                    <div class="col">
                        <small class="text-muted">
                            共 <span th:text="${totalElements}">0</span> 个订单，
                            第 <span th:text="${currentPage + 1}">1</span> 页，
                            共 <span th:text="${totalPages}">1</span> 页
                        </small>
                    </div>
                    <div class="col-auto">
                        <nav aria-label="订单分页">
                            <ul class="pagination pagination-sm mb-0">
                                <li class="page-item" th:classappend="${currentPage == 0} ? 'disabled' : ''">
                                    <a class="page-link" th:href="@{/orders/admin(page=${currentPage - 1}, size=${orders.size}, sortBy=${sortBy}, sortDir=${sortDir}, status=${param.status})}">上一页</a>
                                </li>
                                <li class="page-item" th:each="i : ${#numbers.sequence(0, totalPages - 1)}" 
                                    th:classappend="${i == currentPage} ? 'active' : ''">
                                    <a class="page-link" th:href="@{/orders/admin(page=${i}, size=${orders.size}, sortBy=${sortBy}, sortDir=${sortDir}, status=${param.status})}" 
                                       th:text="${i + 1}">1</a>
                                </li>
                                <li class="page-item" th:classappend="${currentPage == totalPages - 1} ? 'disabled' : ''">
                                    <a class="page-link" th:href="@{/orders/admin(page=${currentPage + 1}, size=${orders.size}, sortBy=${sortBy}, sortDir=${sortDir}, status=${param.status})}">下一页</a>
                                </li>
                            </ul>
                        </nav>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Update Status Modal -->
        <div class="modal fade" id="updateStatusModal" tabindex="-1">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">
                            <i class="fas fa-edit me-2"></i>更新订单状态
                        </h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <form id="updateStatusForm">
                        <div class="modal-body">
                            <div class="mb-3">
                                <label for="newStatus" class="form-label">新状态</label>
                                <select class="form-select" id="newStatus" required>
                                    <option th:each="status : ${orderStatuses}" 
                                            th:value="${status.name()}" 
                                            th:text="${status.displayName}">状态</option>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label for="statusNotes" class="form-label">备注（可选）</label>
                                <textarea class="form-control" id="statusNotes" rows="3" 
                                          placeholder="请输入状态更新备注..."></textarea>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                            <button type="submit" class="btn btn-primary">确认更新</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        
        <!-- Cancel Order Modal -->
        <div class="modal fade" id="cancelOrderModal" tabindex="-1">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">
                            <i class="fas fa-exclamation-triangle me-2"></i>取消订单
                        </h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <form id="cancelOrderForm">
                        <div class="modal-body">
                            <p>确定要取消此订单吗？此操作不可撤销。</p>
                            <div class="mb-3">
                                <label for="cancelReason" class="form-label">取消原因（可选）</label>
                                <textarea class="form-control" id="cancelReason" rows="3" 
                                          placeholder="请输入取消原因..."></textarea>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                            <button type="submit" class="btn btn-danger">确认取消</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        
        <!-- Ship Order Modal -->
        <div class="modal fade" id="shipOrderModal" tabindex="-1">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">
                            <i class="fas fa-truck me-2"></i>订单发货
                        </h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <form id="shipOrderForm">
                        <div class="modal-body">
                            <div class="mb-3">
                                <label for="trackingNumber" class="form-label">物流单号（可选）</label>
                                <input type="text" class="form-control" id="trackingNumber" 
                                       placeholder="请输入物流单号...">
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                            <button type="submit" class="btn btn-info">确认发货</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    
    <style>
        .avatar-circle {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 0.875rem;
        }
        
        .order-row:hover {
            background-color: #f8f9fa;
        }
        
        .btn-group .btn {
            margin-right: 0.25rem;
        }
        
        .btn-group .btn:last-child {
            margin-right: 0;
        }
        
        .table th {
            border-top: none;
            font-weight: 600;
            color: #495057;
        }
        
        .card-header {
            background-color: #f8f9fa;
            border-bottom: 1px solid #dee2e6;
        }
        
        .card-footer {
            background-color: #f8f9fa;
            border-top: 1px solid #dee2e6;
        }
        
        .badge {
            font-size: 0.75rem;
        }
    </style>
    
    <script>
        let currentOrderId = null;
        
        // Status filter
        document.getElementById('statusFilter').addEventListener('change', function() {
            const status = this.value;
            const url = new URL(window.location);
            if (status) {
                url.searchParams.set('status', status);
            } else {
                url.searchParams.delete('status');
            }
            url.searchParams.set('page', '0'); // Reset to first page
            window.location.href = url.toString();
        });
        
        // Search functionality
        document.getElementById('searchInput').addEventListener('input', function() {
            const searchTerm = this.value.toLowerCase();
            const rows = document.querySelectorAll('.order-row');
            
            rows.forEach(function(row) {
                const orderNumber = row.cells[0].textContent.toLowerCase();
                const username = row.cells[1].textContent.toLowerCase();
                
                if (orderNumber.includes(searchTerm) || username.includes(searchTerm)) {
                    row.style.display = '';
                } else {
                    row.style.display = 'none';
                }
            });
        });
        
        // Update status
        function updateStatus(orderId) {
            currentOrderId = orderId;
            const modal = new bootstrap.Modal(document.getElementById('updateStatusModal'));
            modal.show();
        }
        
        // Cancel order
        function cancelOrder(orderId) {
            currentOrderId = orderId;
            const modal = new bootstrap.Modal(document.getElementById('cancelOrderModal'));
            modal.show();
        }
        
        // Ship order
        function shipOrder(orderId) {
            currentOrderId = orderId;
            const modal = new bootstrap.Modal(document.getElementById('shipOrderModal'));
            modal.show();
        }
        
        // Complete order
        function completeOrder(orderId) {
            if (confirm('确定要完成此订单吗？')) {
                fetch(`/orders/${orderId}/complete`, {
                    method: 'POST'
                })
                .then(response => {
                    if (response.ok) {
                        location.reload();
                    } else {
                        alert('完成订单失败');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('完成订单失败');
                });
            }
        }
        
        // Export orders
        function exportOrders() {
            const url = new URL(window.location);
            url.pathname = '/orders/export';
            window.open(url.toString(), '_blank');
        }
        
        // Update status form submission
        document.getElementById('updateStatusForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            if (!currentOrderId) return;
            
            const status = document.getElementById('newStatus').value;
            const notes = document.getElementById('statusNotes').value;
            
            const formData = new FormData();
            formData.append('status', status);
            if (notes) {
                formData.append('notes', notes);
            }
            
            fetch(`/orders/${currentOrderId}/status`, {
                method: 'POST',
                body: formData
            })
            .then(response => {
                if (response.ok) {
                    location.reload();
                } else {
                    alert('更新状态失败');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('更新状态失败');
            });
        });
        
        // Cancel order form submission
        document.getElementById('cancelOrderForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            if (!currentOrderId) return;
            
            const reason = document.getElementById('cancelReason').value;
            const formData = new FormData();
            if (reason) {
                formData.append('reason', reason);
            }
            
            fetch(`/orders/${currentOrderId}/cancel`, {
                method: 'POST',
                body: formData
            })
            .then(response => {
                if (response.ok) {
                    location.reload();
                } else {
                    alert('取消订单失败');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('取消订单失败');
            });
        });
        
        // Ship order form submission
        document.getElementById('shipOrderForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            if (!currentOrderId) return;
            
            const trackingNumber = document.getElementById('trackingNumber').value;
            const formData = new FormData();
            if (trackingNumber) {
                formData.append('trackingNumber', trackingNumber);
            }
            
            fetch(`/orders/${currentOrderId}/ship`, {
                method: 'POST',
                body: formData
            })
            .then(response => {
                if (response.ok) {
                    location.reload();
                } else {
                    alert('发货失败');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('发货失败');
            });
        });
        
        // Auto-refresh every 30 seconds
        setInterval(function() {
            // Only refresh if no modal is open and no form is being edited
            if (!document.querySelector('.modal.show') && !document.querySelector('form:focus')) {
                location.reload();
            }
        }, 30000);
    </script>
</body>
</html>





































