<!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">
        <!-- Breadcrumb -->
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a th:href="@{/}">首页</a></li>
                <li class="breadcrumb-item"><a th:href="@{/orders}">订单管理</a></li>
                <li class="breadcrumb-item active">创建订单</li>
            </ol>
        </nav>
        
        <!-- Order Form -->
        <div class="row">
            <div class="col-lg-8">
                <form th:action="@{/orders/create}" method="post" th:object="${order}" id="orderForm">
                    <!-- Order Basic Info -->
                    <div class="card mb-4">
                        <div class="card-header">
                            <h5 class="mb-0">
                                <i class="fas fa-info-circle me-2"></i>订单基本信息
                            </h5>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="orderType" class="form-label">
                                        <i class="fas fa-tag me-2"></i>订单类型
                                    </label>
                                    <select class="form-select" id="orderType" th:field="*{orderType}" required>
                                        <option th:each="type : ${orderTypes}" 
                                                th:value="${type.name()}" 
                                                th:text="${type.displayName}">商品订单</option>
                                    </select>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label for="currency" class="form-label">
                                        <i class="fas fa-coins me-2"></i>货币
                                    </label>
                                    <select class="form-select" id="currency" th:field="*{currency}">
                                        <option value="CNY">人民币 (CNY)</option>
                                        <option value="USD">美元 (USD)</option>
                                        <option value="EUR">欧元 (EUR)</option>
                                    </select>
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                <label for="description" class="form-label">
                                    <i class="fas fa-file-text me-2"></i>订单描述
                                </label>
                                <textarea class="form-control" id="description" th:field="*{description}" 
                                          rows="3" placeholder="请输入订单描述..."></textarea>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Order Items -->
                    <div class="card mb-4">
                        <div class="card-header">
                            <div class="row align-items-center">
                                <div class="col">
                                    <h5 class="mb-0">
                                        <i class="fas fa-shopping-basket me-2"></i>订单商品
                                    </h5>
                                </div>
                                <div class="col-auto">
                                    <button type="button" class="btn btn-sm btn-outline-primary" id="addItemBtn">
                                        <i class="fas fa-plus me-1"></i>添加商品
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div class="card-body">
                            <div id="orderItems">
                                <div class="order-item border rounded p-3 mb-3" data-index="0">
                                    <div class="row">
                                        <div class="col-md-4 mb-3">
                                            <label class="form-label">商品名称 *</label>
                                            <input type="text" class="form-control item-name" name="orderItems[0].productName" 
                                                   placeholder="请输入商品名称" required>
                                        </div>
                                        <div class="col-md-3 mb-3">
                                            <label class="form-label">SKU</label>
                                            <input type="text" class="form-control item-sku" name="orderItems[0].productSku" 
                                                   placeholder="商品SKU">
                                        </div>
                                        <div class="col-md-2 mb-3">
                                            <label class="form-label">单价 *</label>
                                            <input type="number" class="form-control item-price" name="orderItems[0].unitPrice" 
                                                   step="0.01" min="0" placeholder="0.00" required>
                                        </div>
                                        <div class="col-md-2 mb-3">
                                            <label class="form-label">数量 *</label>
                                            <input type="number" class="form-control item-quantity" name="orderItems[0].quantity" 
                                                   min="1" value="1" required>
                                        </div>
                                        <div class="col-md-1 mb-3">
                                            <label class="form-label">&nbsp;</label>
                                            <button type="button" class="btn btn-outline-danger d-block remove-item" 
                                                    style="display: none;">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-md-8 mb-3">
                                            <label class="form-label">商品描述</label>
                                            <textarea class="form-control item-description" name="orderItems[0].productDescription" 
                                                      rows="2" placeholder="请输入商品描述..."></textarea>
                                        </div>
                                        <div class="col-md-4 mb-3">
                                            <label class="form-label">小计</label>
                                            <div class="input-group">
                                                <span class="input-group-text currency-symbol">CNY</span>
                                                <input type="text" class="form-control item-subtotal" readonly>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Order Total -->
                            <div class="row mt-3">
                                <div class="col-md-8"></div>
                                <div class="col-md-4">
                                    <div class="card bg-light">
                                        <div class="card-body">
                                            <div class="d-flex justify-content-between align-items-center">
                                                <span class="fw-bold">订单总计：</span>
                                                <span class="fs-5 text-primary">
                                                    <span class="currency-symbol">CNY</span>
                                                    <span id="totalAmount">0.00</span>
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Contact Information -->
                    <div class="card mb-4">
                        <div class="card-header">
                            <h5 class="mb-0">
                                <i class="fas fa-user me-2"></i>联系信息
                            </h5>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="contactEmail" class="form-label">
                                        <i class="fas fa-envelope me-2"></i>联系邮箱
                                    </label>
                                    <input type="email" class="form-control" id="contactEmail" th:field="*{contactEmail}" 
                                           placeholder="请输入联系邮箱">
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label for="contactPhone" class="form-label">
                                        <i class="fas fa-phone me-2"></i>联系电话
                                    </label>
                                    <input type="tel" class="form-control" id="contactPhone" th:field="*{contactPhone}" 
                                           placeholder="请输入联系电话">
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Address Information -->
                    <div class="card mb-4">
                        <div class="card-header">
                            <h5 class="mb-0">
                                <i class="fas fa-map-marker-alt me-2"></i>地址信息
                            </h5>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="shippingAddress" class="form-label">
                                        <i class="fas fa-truck me-2"></i>收货地址
                                    </label>
                                    <textarea class="form-control" id="shippingAddress" th:field="*{shippingAddress}" 
                                              rows="3" placeholder="请输入收货地址..."></textarea>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label for="billingAddress" class="form-label">
                                        <i class="fas fa-file-invoice me-2"></i>账单地址
                                    </label>
                                    <textarea class="form-control" id="billingAddress" th:field="*{billingAddress}" 
                                              rows="3" placeholder="请输入账单地址..."></textarea>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Form Actions -->
                    <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                        <a th:href="@{/orders}" class="btn btn-secondary me-md-2">
                            <i class="fas fa-times me-2"></i>取消
                        </a>
                        <button type="submit" class="btn btn-primary" id="submitBtn">
                            <span class="loading">
                                <i class="fas fa-spinner fa-spin me-2"></i>创建中...
                            </span>
                            <span class="submit-text">
                                <i class="fas fa-save me-2"></i>创建订单
                            </span>
                        </button>
                    </div>
                </form>
            </div>
            
            <!-- Sidebar -->
            <div class="col-lg-4">
                <!-- Order Summary -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0">
                            <i class="fas fa-calculator me-2"></i>订单摘要
                        </h5>
                    </div>
                    <div class="card-body">
                        <div id="orderSummary">
                            <div class="text-muted text-center py-3">
                                <i class="fas fa-shopping-basket fa-2x mb-2"></i>
                                <p>请添加商品到订单</p>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Help -->
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">
                            <i class="fas fa-question-circle me-2"></i>帮助信息
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="small">
                            <h6>订单类型说明：</h6>
                            <ul class="list-unstyled">
                                <li><span class="badge bg-primary me-2">商品订单</span>实体商品订单</li>
                                <li><span class="badge bg-info me-2">服务订单</span>服务类订单</li>
                                <li><span class="badge bg-success me-2">订阅订单</span>订阅服务订单</li>
                                <li><span class="badge bg-warning me-2">数字商品</span>数字产品订单</li>
                                <li><span class="badge bg-secondary me-2">实体商品</span>实体产品订单</li>
                            </ul>
                            
                            <h6 class="mt-3">注意事项：</h6>
                            <ul class="list-unstyled">
                                <li>• 订单创建后状态为"待支付"</li>
                                <li>• 支持支付宝和PayPal支付</li>
                                <li>• 订单超时未支付将自动取消</li>
                                <li>• 请确保联系信息准确无误</li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <style>
        .order-item {
            background-color: #f8f9fa;
            transition: all 0.3s ease;
        }
        
        .order-item:hover {
            background-color: #e9ecef;
        }
        
        .loading {
            display: none;
        }
        
        .loading.show {
            display: inline-block;
        }
        
        .card-header {
            background-color: #f8f9fa;
            border-bottom: 1px solid #dee2e6;
        }
        
        .form-label {
            font-weight: 600;
            color: #495057;
        }
        
        .item-subtotal {
            background-color: #f8f9fa;
        }
    </style>
    
    <script>
        let itemIndex = 0;
        
        // Add new order item
        document.getElementById('addItemBtn').addEventListener('click', function() {
            itemIndex++;
            const template = document.querySelector('.order-item').cloneNode(true);
            
            // Update indices
            template.setAttribute('data-index', itemIndex);
            template.querySelectorAll('input, textarea').forEach(function(input) {
                const name = input.getAttribute('name');
                if (name) {
                    input.setAttribute('name', name.replace('[0]', '[' + itemIndex + ']'));
                }
            });
            
            // Clear values
            template.querySelectorAll('input, textarea').forEach(function(input) {
                if (input.type !== 'number' || input.classList.contains('item-quantity')) {
                    input.value = '';
                }
                if (input.classList.contains('item-quantity')) {
                    input.value = '1';
                }
            });
            
            // Show remove button
            template.querySelector('.remove-item').style.display = 'block';
            
            // Add event listeners
            addItemEventListeners(template);
            
            document.getElementById('orderItems').appendChild(template);
            updateOrderSummary();
        });
        
        // Remove order item
        document.addEventListener('click', function(e) {
            if (e.target.closest('.remove-item')) {
                const item = e.target.closest('.order-item');
                item.remove();
                updateOrderSummary();
            }
        });
        
        // Add event listeners to order item
        function addItemEventListeners(item) {
            const priceInput = item.querySelector('.item-price');
            const quantityInput = item.querySelector('.item-quantity');
            const subtotalInput = item.querySelector('.item-subtotal');
            
            function updateSubtotal() {
                const price = parseFloat(priceInput.value) || 0;
                const quantity = parseInt(quantityInput.value) || 0;
                const subtotal = price * quantity;
                subtotalInput.value = subtotal.toFixed(2);
                updateOrderSummary();
            }
            
            priceInput.addEventListener('input', updateSubtotal);
            quantityInput.addEventListener('input', updateSubtotal);
        }
        
        // Add event listeners to existing items
        document.querySelectorAll('.order-item').forEach(addItemEventListeners);
        
        // Update order summary
        function updateOrderSummary() {
            const items = document.querySelectorAll('.order-item');
            const summary = document.getElementById('orderSummary');
            let total = 0;
            let itemCount = 0;
            
            items.forEach(function(item) {
                const price = parseFloat(item.querySelector('.item-price').value) || 0;
                const quantity = parseInt(item.querySelector('.item-quantity').value) || 0;
                const subtotal = price * quantity;
                
                if (price > 0 && quantity > 0) {
                    total += subtotal;
                    itemCount++;
                }
            });
            
            document.getElementById('totalAmount').textContent = total.toFixed(2);
            
            if (itemCount > 0) {
                let summaryHtml = '<div class="mb-3">';
                items.forEach(function(item, index) {
                    const name = item.querySelector('.item-name').value;
                    const price = parseFloat(item.querySelector('.item-price').value) || 0;
                    const quantity = parseInt(item.querySelector('.item-quantity').value) || 0;
                    const subtotal = price * quantity;
                    
                    if (name && price > 0 && quantity > 0) {
                        summaryHtml += `
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <div>
                                    <div class="fw-bold">${name}</div>
                                    <small class="text-muted">${price.toFixed(2)} × ${quantity}</small>
                                </div>
                                <span class="fw-bold">${subtotal.toFixed(2)}</span>
                            </div>
                        `;
                    }
                });
                summaryHtml += '</div>';
                summaryHtml += `
                    <hr>
                    <div class="d-flex justify-content-between align-items-center">
                        <span class="fw-bold">总计：</span>
                        <span class="fs-5 text-primary">${total.toFixed(2)}</span>
                    </div>
                `;
                summary.innerHTML = summaryHtml;
            } else {
                summary.innerHTML = `
                    <div class="text-muted text-center py-3">
                        <i class="fas fa-shopping-basket fa-2x mb-2"></i>
                        <p>请添加商品到订单</p>
                    </div>
                `;
            }
        }
        
        // Currency change
        document.getElementById('currency').addEventListener('change', function() {
            const currency = this.value;
            document.querySelectorAll('.currency-symbol').forEach(function(symbol) {
                symbol.textContent = currency;
            });
        });
        
        // Form submission
        document.getElementById('orderForm').addEventListener('submit', function(e) {
            const submitBtn = document.getElementById('submitBtn');
            const loading = submitBtn.querySelector('.loading');
            const submitText = submitBtn.querySelector('.submit-text');
            
            // Show loading state
            loading.classList.add('show');
            submitText.style.display = 'none';
            submitBtn.disabled = true;
            
            // Validate form
            const items = document.querySelectorAll('.order-item');
            let hasValidItem = false;
            
            items.forEach(function(item) {
                const name = item.querySelector('.item-name').value.trim();
                const price = parseFloat(item.querySelector('.item-price').value) || 0;
                const quantity = parseInt(item.querySelector('.item-quantity').value) || 0;
                
                if (name && price > 0 && quantity > 0) {
                    hasValidItem = true;
                }
            });
            
            if (!hasValidItem) {
                e.preventDefault();
                alert('请至少添加一个有效商品');
                loading.classList.remove('show');
                submitText.style.display = 'inline-block';
                submitBtn.disabled = false;
                return false;
            }
        });
        
        // Auto-save draft
        const formData = {};
        const form = document.getElementById('orderForm');
        
        form.addEventListener('input', function(e) {
            if (e.target.name && e.target.name.includes('orderItems')) {
                return; // Skip order items for now
            }
            
            formData[e.target.name] = e.target.value;
            localStorage.setItem('orderFormDraft', JSON.stringify(formData));
        });
        
        // Restore draft on page load
        const savedDraft = localStorage.getItem('orderFormDraft');
        if (savedDraft) {
            try {
                const draft = JSON.parse(savedDraft);
                Object.keys(draft).forEach(function(key) {
                    const field = form.querySelector(`[name="${key}"]`);
                    if (field && draft[key]) {
                        field.value = draft[key];
                    }
                });
            } catch (e) {
                console.error('Failed to restore form draft:', e);
            }
        }
        
        // Clear draft on successful submission
        form.addEventListener('submit', function() {
            localStorage.removeItem('orderFormDraft');
        });
        
        // Initial update
        updateOrderSummary();
    </script>
</body>
</html>









