<?php
require_once 'conn.php';
checkLogin();

$id = $_GET['id'] ?? '';
$page = $_GET['Page'] ?? '';
$keys = urlencode($_GET['Keys'] ?? '');

$hrefstr = "keys=$keys&Page=$page";

// 验证并获取订单数据
if (!empty($id) && is_numeric($id)) {
    // 获取订单基本信息
    $employee_id = $_SESSION['employee_id'];
    $sql = "SELECT o.*, c.cs_company, c.cs_code, cc.contact_name 
            FROM orders o 
            LEFT JOIN customer c ON o.customer_id = c.id 
            LEFT JOIN customer_contact cc ON o.contact_id = cc.id 
            WHERE o.id = $id AND o.employee_id = $employee_id";

    $result = mysqli_query($conn, $sql);

    if ($row = mysqli_fetch_assoc($result)) {
        $order = $row;
    } else {
        echo "<script>alert('订单不存在或您没有权限查看');history.back();</script>";
        exit;
    }

    // 获取订单项信息
    $sql = "SELECT oi.*, p.ProductName, pc.name as category_name, 
                   ps.id as product_spec_id, ps.spec_name, ps.spec_value,
                   oi.specification_id  /* 显式获取数据库中的specification_id */
            FROM order_items oi 
            LEFT JOIN products p ON oi.product_id = p.id 
            LEFT JOIN product_categories pc ON p.category_id = pc.id
            LEFT JOIN product_specifications ps ON oi.specification_id = ps.id
            WHERE oi.order_id = $id";

    $itemsResult = mysqli_query($conn, $sql);

    $orderItems = [];
    while ($itemRow = mysqli_fetch_assoc($itemsResult)) {
        // 调试输出
        error_log("订单项数据: " . print_r($itemRow, true));
        $orderItems[] = $itemRow;
    }
} else {
    echo "<script>alert('订单不存在!');history.back();</script>";
    exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>编辑订单</title>
    <link rel="stylesheet" href="css/common.css" type="text/css" />
    <link rel="stylesheet" href="css/alert.css" type="text/css" />
    <script src="js/jquery-1.7.2.min.js"></script>
    <script src="js/js.js"></script>
    <style>
        body {
            margin: 0;
            padding: 20px;
            background: #fff;
        }
        #man_zone {
            margin-left: 0;
        }
        .product-row {
            position: relative;
            padding: 12px 15px;
            padding-right: 40px; /* Add right padding to make room for delete button */
            margin-bottom: 8px;
            border-radius: 4px;
            display: flex;
            align-items: center;
            flex-wrap: wrap;
            gap: 8px;
            background-color: #f9f9f9;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        .delete-product {
            position: absolute;
            right: 10px;
            top: 50%;
            transform: translateY(-50%);
            color: #e74c3c;
            font-weight: bold;
            font-size: 18px;
            cursor: pointer;
            width: 24px;
            height: 24px;
            line-height: 24px;
            text-align: center;
            border-radius: 50%;
            z-index: 5;
        }
        .delete-product:hover {
            background-color: #e74c3c;
            color: white;
        }
        .product-info {
            flex: 2;
            min-width: 200px;
        }
        .product-spec {
            flex: 2;
            min-width: 200px;
        }
        .product-quantity {
            flex: 1;
            min-width: 80px;
        }
        .product-unit {
            flex: 0.5;
            min-width: 60px;
        }
        .product-price {
            flex: 1;
            min-width: 100px;
        }
        .product-total {
            flex: 1;
            min-width: 100px;
            font-weight: bold;
        }
        .product-row input[type="number"] {
            width: 80px;
            padding: 5px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .product-row select {
            width: 100%;
            padding: 5px;
        }
        .selected-product-info {
            font-weight: bold;
            margin-bottom: 3px;
        }
        .row-section {
            display: flex;
            flex-direction: column;
        }
        .row-section-label {
            font-size: 12px;
            color: #666;
            margin-bottom: 3px;
        }
        .row-section-label span {
            display: none; /* 在大屏幕上隐藏标签文本 */
        }
        .spec-info {
            margin-top: 2px;
            font-size: 12px;
            color: #666;
        }
        
        /* 在小屏幕上的响应式布局 */
        @media (max-width: 768px) {
            .product-row {
                flex-direction: column;
                align-items: flex-start;
            }
            .product-info, .product-spec, .product-quantity, 
            .product-unit, .product-price, .product-total {
                width: 100%;
                min-width: 100%;
                margin-bottom: 8px;
            }
            .row-section-label span {
                display: inline; /* 在小屏幕上显示标签文本 */
            }
            .product-list-header {
                display: none !important; /* 在小屏幕上隐藏表头 */
            }
        }
        .add-product-btn {
            background-color: #4CAF50;
            color: white;
            padding: 10px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-bottom: 15px;
            font-size: 14px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            transition: background-color 0.2s;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        .add-product-btn:hover {
            background-color: #45a049;
        }
        .total-section {
            margin-top: 20px;
            padding: 10px;
            background-color: #eee;
            font-weight: bold;
        }
        #product-container {
            margin-bottom: 20px;
        }
        .productlist {
            display: none;
            position: absolute;
            background: white;
            border: 1px solid #ccc;
            max-height: 200px;
            overflow-y: auto;
            width: 100%;
            z-index: 1000;
            box-shadow: 0 3px 8px rgba(0,0,0,0.25);
            border-radius: 0 0 4px 4px;
            top: 100%;
            left: 0;
        }
        .productlist ul {
            list-style: none;
            padding: 0;
            margin: 0;
        }
        .productlist li {
            padding: 10px 12px;
            cursor: pointer;
            border-bottom: 1px solid #eee;
            transition: background-color 0.2s;
        }
        .productlist li:hover {
            background-color: #f0f0f0;
        }
        .productlist li:last-child {
            border-bottom: none;
        }
        .productinput {
            position: relative;
        }
        .productlist li .category-tag {
            color: #777;
            font-size: 12px;
            font-style: italic;
            margin-left: 5px;
        }
        /* Specification select styling */
        .spec-select {
            width: 100%;
            padding: 6px;
            margin-top: 5px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }
        .spec-select:disabled {
            background-color: #f9f9f9;
        }
        .spec-price {
            font-weight: bold;
            color: #d9534f;
        }
    </style>
</head>
<body>
<div id="man_zone">
    <form name="form1" id="form1" method="post" action="order_save.php?<?= $hrefstr ?>" onsubmit="return validateOrderForm()">
        <table width="100%" border="0" cellpadding="3" cellspacing="1" class="table1">
            <tbody>
            <tr>
                <th width="8%">订单编号</th>
                <td>
                    <input type="text" id="order_code" name="order_code" value="<?= htmlspecialcharsFix($order['order_code']) ?>" class="txt1" />
                    <input type="hidden" name="id" value="<?= $id ?>" />
                </td>
            </tr>
            <tr>
                <th width="8%">客户选择</th>
                <td>
                    <div style="display: flex; width: 60%; position: relative; align-items: center;" class="customerinput">
                        <div style="flex: 1; position: relative;">
                            <input type="text" class="customer-search fastsearch" placeholder="输入客户编码或名称搜索..." style="width: 100%;" value="<?= htmlspecialcharsFix(isset($order['cs_code']) && $order['cs_code'] ? $order['cs_code'] . ' - ' . $order['cs_company'] : $order['cs_company']) ?>">
                            <div class="customerlist" style="display: none; position: absolute; background: white; border: 1px solid #ccc; max-height: 200px; overflow-y: auto; width: 100%; z-index: 1000; box-shadow: 0 2px 5px rgba(0,0,0,0.2);">
                                <ul style="list-style: none; padding: 0; margin: 0;"></ul>
                            </div>
                            <input type="hidden" name="customer_id" id="customer_id" value="<?= $order['customer_id'] ?>">
                            <div class="selected-customer-info" style="margin-top: 5px; font-weight: bold;"></div>
                        </div>
                        <span class="delete-customer" style="margin-left: 10px; color: #e74c3c; font-weight: bold; font-size: 18px; cursor: pointer; width: 24px; height: 24px; line-height: 24px; text-align: center; border-radius: 50%;">×</span>
                    </div>
                </td>
            </tr>
            <tr>
                <th width="8%">订单日期</th>
                <td>
                    <input type="date" id="order_date" name="order_date" value="<?= substr($order['order_date'], 0, 10) ?>" class="txt1" />
                </td>
            </tr>
            <tr>
                <th width="8%" valign="top">产品列表</th>
                <td>
                    <button type="button" id="add-product-btn" class="add-product-btn">添加产品</button>
                    
                    <div class="product-list-header" style="display: flex; background-color: #eee; padding: 8px 15px; margin-bottom: 10px; border-radius: 4px; font-weight: bold; color: #555; font-size: 13px; gap: 8px;">
                        <div style="flex: 2; min-width: 200px;">产品</div>
                        <div style="flex: 2; min-width: 200px;">规格</div>
                        <div style="flex: 1; min-width: 80px;">数量</div>
                        <div style="flex: 0.5; min-width: 60px;">单位</div>
                        <div style="flex: 1; min-width: 100px;">单价</div>
                        <div style="flex: 1; min-width: 100px;">总价</div>
                    </div>
                    
                    <div id="product-container">
                        <?php foreach ($orderItems as $index => $item): ?>
                            <div class="product-row" data-index="<?= $index ?>">
                                <span class="delete-product">×</span>
                                
                                <div class="row-section product-info">
                                    <div class="row-section-label"><span>产品</span></div>
                                        <input type="hidden" name="items[<?= $index ?>][product_id]" class="product-id-input" value="<?= $item['product_id'] ?>">
                                    <input type="text" class="product-search" placeholder="输入产品名称搜索..." style="width: 100%; padding: 5px; border: 1px solid #ddd; border-radius: 4px; display: none;">
                                    <div class="productlist" style="width: 100%; max-height: 200px;"><ul></ul></div>
                                    <div class="selected-product-info" style="cursor: pointer;" title="点击重新选择产品">
                                            <?= htmlspecialcharsFix($item['ProductName'] ?? '') ?>
                                            <?php if (!empty($item['category_name'])): ?>
                                            <span class="category-tag">(<?= htmlspecialcharsFix($item['category_name']) ?>)</span>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                
                                <div class="row-section product-spec">
                                    <div class="row-section-label"><span>规格</span></div>
                                    <input type="hidden" name="items[<?= $index ?>][spec_id]" class="spec-id-input" value="<?= $item['specification_id'] ?? 0 ?>">
                                    <!-- 规格选择框将在加载产品时填充 -->
                                    <select class="spec-select" name="items[<?= $index ?>][spec_select]" style="display: none;">
                                        <option value="">请选择规格</option>
                                    </select>
                                    <div class="spec-info" style="cursor: pointer;" title="点击修改规格">
                                        <?php if (!empty($item['spec_name'])): ?>
                                            <?= htmlspecialcharsFix($item['spec_name']) ?>: <?= htmlspecialcharsFix($item['spec_value'] ?? '') ?>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                
                                <div class="row-section product-quantity">
                                    <div class="row-section-label"><span>数量</span></div>
                                    <input type="number" name="items[<?= $index ?>][quantity]" value="<?= $item['quantity'] ?>" min="1" class="quantity-input" onchange="calculateItemTotal(this)">
                                </div>

                                <div class="row-section product-unit">
                                    <div class="row-section-label"><span>单位</span></div>
                                    <span class="unit-label"><?= htmlspecialcharsFix($item['unit']) ?></span>
                                    <input type="hidden" name="items[<?= $index ?>][unit]" value="<?= htmlspecialcharsFix($item['unit']) ?>" class="unit-input">
                                </div>
                                
                                <div class="row-section product-price">
                                    <div class="row-section-label"><span>单价</span></div>
                                    <input type="number" step="0.01" name="items[<?= $index ?>][unit_price]" value="<?= $item['unit_price'] ?>" class="price-input" onchange="calculateItemTotal(this)">
                    </div>
                    
                                <div class="row-section product-total">
                                    <div class="row-section-label"><span>总价</span></div>
                                    <span class="total-price-display" style="display: inline-block; background-color: #f0f0f0; border: 1px solid #ddd; padding: 2px 8px; min-width: 60px; text-align: right;"><?= number_format($item['total_price'], 2) ?></span>
                                    <input type="hidden" name="items[<?= $index ?>][total_price]" value="<?= $item['total_price'] ?>" class="total-price-input">
                                </div>
                                
                                <!-- 保留隐藏的折扣字段以便后端兼容 -->
                                <input type="hidden" name="items[<?= $index ?>][discount_amount]" value="0" class="discount-amount-input">
                                <input type="hidden" name="items[<?= $index ?>][discount_percent]" value="0" class="discount-percent-input">
                                <input type="hidden" name="items[<?= $index ?>][notes]" value="<?= htmlspecialcharsFix($item['notes'] ?? '') ?>">
                            </div>
                        <?php endforeach; ?>
                        <!-- 产品行将通过搜索添加 -->
                        <?php if (count($orderItems) == 0): ?>
                        <div id="no-products-message" style="padding: 15px; text-align: center; color: #777; background-color: #f5f5f5; border: 1px dashed #ddd; border-radius: 4px; margin-bottom: 15px; display: block;">
                            <i class="fa fa-info-circle"></i> 请点击"添加产品"按钮添加产品
                        </div>
                        <?php endif; ?>
                    </div>
                    <div class="total-section" style="margin-top: 20px; padding: 15px; background-color: #f5f5f5; border-radius: 4px; box-shadow: 0 1px 3px rgba(0,0,0,0.1);">
                        <div style="display: flex; justify-content: flex-end; align-items: center;">
                            <label style="font-size: 16px; margin-right: 10px;">订单总额:</label>
                            <span id="total-amount" style="font-size: 18px; font-weight: bold; color: #e74c3c;"><?= number_format($order['total_amount'], 2) ?></span>
                            <input type="hidden" name="total_amount" id="total-amount-input" value="<?= $order['total_amount'] ?>">
                            <input type="hidden" name="subtotal" id="subtotal-input" value="<?= $order['subtotal'] ?>">
                            <input type="hidden" name="discount_amount" id="order-discount" value="0">
                        </div>
                    </div>
                </td>
            </tr>
            <tr>
                <th width="8%">订单备注</th>
                <td>
                    <textarea name="notes" rows="3" style="width: 90%;"><?= htmlspecialcharsFix($order['notes']) ?></textarea>
                </td>
            </tr>
            <tr>
                <th></th>
                <td>
                    <input type="submit" name="save" value="保存订单" class="btn1">
                    <input type="button" value="返回" class="btn1" onClick="location.href='order.php?<?= $hrefstr ?>'" />
                </td>
            </tr>
            </tbody>
        </table>
    </form>

    <script>
        var productIndex = <?= count($orderItems) ?>;

        $(document).ready(function() {
            // 初始化计算
            calculateOrderTotal();
            
            // 初始化无产品消息
            updateNoProductsMessage();
            
            // 初始化现有产品的规格选择
            $('.product-row').each(function() {
                var row = $(this);
                var productId = row.find('.product-id-input').val();
                var specId = row.find('.spec-id-input').val();
                console.log("初始化行 - 行索引:", row.data('index'), "产品ID:", productId, "规格ID:", specId);
                
                if (productId) {
                    // 加载产品规格
                    getProductSpecifications(productId, row);
                }
            });
            
            // 添加客户删除按钮事件
            $('.delete-customer').on('click', function() {
                // if(confirm('确定要清除当前选择的客户吗?')) {
                    // 清空客户ID和客户名称
                    $('#customer_id').val('');
                    $('.customer-search').val('').focus();
                    $('.selected-customer-info').text('');
                // }
            });
            
            // 添加样式到客户删除按钮
            $('.delete-customer').hover(
                function() { $(this).css('background-color', '#e74c3c').css('color', 'white'); },
                function() { $(this).css('background-color', '').css('color', '#e74c3c'); }
            );
            
            // 添加产品行按钮点击事件
            $('#add-product-btn').on('click', function() {
                addEmptyProductRow();
                updateNoProductsMessage();
            });
            
            // 删除产品行
            $(document).on('click', '.delete-product', function() {
                if ($('.product-row').length > 1) {
                    $(this).closest('.product-row').remove();
                    reindexProductRows();
                    calculateOrderTotal();
                    updateNoProductsMessage();
                } else {
                    // 如果只剩最后一个产品行,则清空它而不是删除
                    $(this).closest('.product-row').remove();
                    updateNoProductsMessage();
                    calculateOrderTotal(); // 确保在删除最后一个产品时也更新总额
                }
            });

            // 客户搜索功能
            var customerSearchTimeout = null;
            $(document).on('keyup', '.customer-search', function() {
                var $this = $(this);
                var searchTerm = $this.val().trim();
                var customerList = $('.customerlist');
                
                // 清除之前的超时
                clearTimeout(customerSearchTimeout);
                
                // 隐藏之前的结果
                customerList.hide();
                
                // 如果搜索词少于2个字符,不执行搜索
                if (searchTerm.length < 2) {
                    return;
                }
                
                // 设置一个300毫秒的超时,以减少请求数量
                customerSearchTimeout = setTimeout(function() {
                    $.ajax({
                        url: 'get_customer_search.php',
                        type: 'GET',
                        data: {search: searchTerm},
                        dataType: 'json',
                        success: function(data) {
                            var ul = customerList.find('ul');
                            ul.empty();
                            
                            if (data && data.customers && data.customers.length > 0) {
                                $.each(data.customers, function(i, customer) {
                                    var displayText = customer.cs_company;
                                    if (customer.cs_code) {
                                        displayText = customer.cs_code + ' - ' + displayText;
                                    }
                                    ul.append('<li data-id="' + customer.id + '" data-code="' + (customer.cs_code || '') + '">' + 
                                              displayText + '</li>');
                                });
                                customerList.show();
                            }
                        },
                        error: function() {
                            console.log('搜索客户失败,请重试');
                        }
                    });
                }, 300);
            });
            
            // 点击选择客户
            $(document).on('click', '.customerlist li', function() {
                var $this = $(this);
                var customerId = $this.data('id');
                var customerName = $this.text();
                var customerCode = $this.data('code') || '';
                
                // 设置选中的客户ID和名称
                $('#customer_id').val(customerId);
                $('.customer-search').val(customerName);
                $('.selected-customer-info').text(customerName);
                $('.customerlist').hide();
            });

            // 产品搜索框聚焦时显示搜索提示
            $(document).on('focus', '.product-search', function() {
                // 隐藏所有已打开的产品搜索列表
                $('.productlist').hide();
                
                // 当前搜索框的值
                var searchTerm = $(this).val().trim();
                if (searchTerm.length >= 2) {
                    // 找到当前行的产品列表并显示
                    $(this).siblings('.productlist').show();
                }
            });
            
            // 产品搜索功能 - 行内搜索
            var productSearchTimeouts = {};
            $(document).on('keyup', '.product-search', function() {
                var $this = $(this);
                var rowIndex = $this.closest('.product-row').data('index');
                var searchTerm = $this.val().trim();
                var productList = $this.siblings('.productlist');
                
                // 清除之前的超时
                clearTimeout(productSearchTimeouts[rowIndex]);
                
                // 隐藏之前的结果
                productList.hide();
                
                // 如果搜索词少于2个字符,不执行搜索
                if (searchTerm.length < 2) {
                    return;
                }
                
                // 设置一个300毫秒的超时,以减少请求数量
                productSearchTimeouts[rowIndex] = setTimeout(function() {
                    $.ajax({
                        url: 'get_product_info.php',
                        type: 'GET',
                        data: {search: searchTerm},
                        dataType: 'json',
                        success: function(data) {
                            var ul = productList.find('ul');
                            ul.empty();
                            
                            if (data && data.products && data.products.length > 0) {
                                $.each(data.products, function(i, product) {
                                    ul.append('<li data-id="' + product.id + '">' + 
                                              product.ProductName + 
                                              (product.category_name ? ' <span class="category-tag">(' + product.category_name + ')</span>' : '') + 
                                              '</li>');
                                });
                                productList.show();
                            }
                        },
                        error: function() {
                            console.log('搜索产品失败,请重试');
                        }
                    });
                }, 300);
            });
            
            // 点击选择产品 - 行内搜索结果
            $(document).on('click', '.productlist li', function() {
                var $this = $(this);
                var productId = $this.data('id');
                var productName = $this.text(); // 这会包含分类名,需要清理
                var categoryTag = $this.find('.category-tag').text();
                var row = $this.closest('.product-row');
                
                // 清理产品名称,移除分类信息
                if (categoryTag) {
                    productName = productName.replace(categoryTag, '').trim();
                }
                
                // 设置产品ID和名称
                row.find('.product-id-input').val(productId);
                row.find('.product-search').hide();
                
                // 显示包含分类的完整产品信息
                var displayName = productName;
                if (categoryTag) {
                    displayName += ' <span class="category-tag">' + categoryTag + '</span>';
                }
                row.find('.selected-product-info').html(displayName).show();
                
                // 隐藏产品搜索结果
                row.find('.productlist').hide();
                
                // 获取产品规格信息
                getProductSpecifications(productId, row);
            });
            
            // 规格选择改变事件
            $(document).on('change', '.spec-select', function() {
                var $this = $(this);
                var row = $this.closest('.product-row');
                var specId = $this.val();
                var specData = $this.find('option:selected').data();
                
                if (specId) {
                    // 检查是否已存在相同的产品规格组合
                    var isDuplicate = false;
                    $('.spec-select').not($this).each(function() {
                        if ($(this).val() == specId) {
                            isDuplicate = true;
                            return false; // 跳出循环
                        }
                    });
                    
                    if (isDuplicate) {
                        alert('该产品规格已添加,不能重复添加');
                        $this.val(''); // 重置选择
                        return;
                    }
                    
                    // 设置规格ID到隐藏字段
                    row.find('.spec-id-input').val(specId);
                    
                    // 获取选中项的文本内容作为显示信息
                    var displayText = $this.find('option:selected').text();
                    row.find('.spec-info').html(displayText).show();
                    
                    // 隐藏下拉框
                    $this.hide();
                    
                    // 存储规格价格作为最低价格限制
                    var minPrice = specData.price || 0;
                    var priceInput = row.find('.price-input');
                    priceInput.attr('data-min-price', minPrice);
                    if (minPrice > 0) {
                        priceInput.attr('placeholder', '输入单价');
                    } else {
                        priceInput.attr('placeholder', '输入单价');
                    }
                    
                    // 设置最小订购数量
                    var minQty = specData.minQty || 1;
                    var qtyInput = row.find('.quantity-input');
                    if (parseInt(qtyInput.val()) < minQty) {
                        qtyInput.val(minQty);
                    }
                    qtyInput.attr('min', minQty);
                    
                    // 重新计算总价
                    calculateItemTotal(row.find('.price-input')[0]);
                } else {
                    // 清除规格相关信息
                    row.find('.spec-id-input').val('');
                    row.find('.price-input').attr('data-min-price', '0').attr('placeholder', '输入单价');
                    row.find('.spec-info').html('').hide();
                    calculateItemTotal(row.find('.price-input')[0]);
                }
            });
            
            // 点击其他地方隐藏下拉列表
            $(document).on('click', function(e) {
                if (!$(e.target).closest('.product-search').length && !$(e.target).closest('.productlist').length) {
                    $('.productlist').hide();
                }
                if (!$(e.target).closest('.customerinput').length) {
                    $('.customerlist').hide();
                }
            });
            
            // 点击已选产品名显示的标签时,切换回搜索模式
            $(document).on('click dblclick', '.selected-product-info', function() {
                var row = $(this).closest('.product-row');
                var productId = row.find('.product-id-input').val();
                
                // 只有当已经选择了产品时才允许重新选择
                if (productId) {
                    if (confirm('确定要重新选择产品吗?这将清除当前选择的产品及其规格信息。')) {
                        // 清空产品ID和选择的规格
                        row.find('.product-id-input').val('');
                        row.find('.spec-id-input').val('');
                        
                        // 隐藏产品信息,显示搜索框
                        $(this).hide();
                        row.find('.product-search').val('').show();
                        
                        // 隐藏并清空规格选择
                        row.find('.spec-select').hide().empty();
                        row.find('.spec-info').html('');
                        
                        // 清除单位信息
                        row.find('.unit-input').val('');
                        row.find('.unit-label').text('');
                        
                        // 清除价格信息并重新计算总额
                        row.find('.price-input').val('');
                        calculateItemTotal(row.find('.price-input')[0]);
                    }
                }
            });
            
            // 点击规格信息时显示规格选择下拉框
            $(document).on('click', '.spec-info', function() {
                var row = $(this).closest('.product-row');
                var specSelect = row.find('.spec-select');
                
                if (specSelect.find('option').length > 1) {
                    // 隐藏规格信息,显示规格选择下拉框
                    $(this).hide();
                    specSelect.show().focus();
                }
            });
        });

        function addEmptyProductRow() {
            var html = `
            <div class="product-row" data-index="${productIndex}">
                <span class="delete-product">×</span>
                
                <div class="row-section product-info">
                    <div class="row-section-label"><span>产品</span></div>
                    <input type="hidden" name="items[${productIndex}][product_id]" class="product-id-input" value="">
                    <input type="text" class="product-search" placeholder="输入产品名称搜索..." style="width: 100%; padding: 5px; border: 1px solid #ddd; border-radius: 4px;">
                    <div class="productlist" style="width: 100%; max-height: 200px;"><ul></ul></div>
                    <div class="selected-product-info" style="cursor: pointer; display: none;" title="点击重新选择产品"></div>
                </div>
                
                <div class="row-section product-spec">
                    <div class="row-section-label"><span>规格</span></div>
                    <input type="hidden" name="items[${productIndex}][spec_id]" class="spec-id-input" value="">
                    <select class="spec-select" name="items[${productIndex}][spec_select]" style="display: none;">
                        <option value="">请选择规格</option>
                    </select>
                    <div class="spec-info" style="cursor: pointer;" title="点击修改规格"></div>
                </div>
                
                <div class="row-section product-quantity">
                    <div class="row-section-label"><span>数量</span></div>
                    <input type="number" name="items[${productIndex}][quantity]" value="1" min="1" class="quantity-input" onchange="calculateItemTotal(this)">
                </div>
                
                <div class="row-section product-unit">
                    <div class="row-section-label"><span>单位</span></div>
                    <span class="unit-label" style="display: inline-block; padding: 2px 5px; min-width: 30px;"></span>
                    <input type="hidden" name="items[${productIndex}][unit]" class="unit-input" value="">
                </div>
                
                <div class="row-section product-price">
                    <div class="row-section-label"><span>单价</span></div>
                    <input type="number" step="0.01" name="items[${productIndex}][unit_price]" value="" class="price-input" placeholder="输入单价" onchange="calculateItemTotal(this)">
                </div>
                
                <div class="row-section product-total">
                    <div class="row-section-label"><span>总价</span></div>
                    <span class="total-price-display" style="display: inline-block; background-color: #f0f0f0; border: 1px solid #ddd; padding: 2px 8px; min-width: 60px; text-align: right;">0.00</span>
                    <input type="hidden" name="items[${productIndex}][total_price]" value="0.00" class="total-price-input">
                </div>
                
                <!-- 保留隐藏的字段以便后端兼容 -->
                <input type="hidden" name="items[${productIndex}][discount_amount]" value="0" class="discount-amount-input">
                <input type="hidden" name="items[${productIndex}][discount_percent]" value="0" class="discount-percent-input">
                <input type="hidden" name="items[${productIndex}][notes]" value="">
            </div>
            `;

            $('#product-container').append(html);
            productIndex++;
            return productIndex - 1; // 返回新添加行的索引
        }
        
        function addProductRowWithProduct(productId, productName, categoryTag) {
            // 添加空行
            var rowIndex = addEmptyProductRow();
            var row = $('.product-row[data-index="' + rowIndex + '"]');
            
            // 设置产品ID和名称
            row.find('.product-id-input').val(productId);
            
            // 显示包含分类的完整产品信息
            var displayName = productName;
            if (categoryTag) {
                displayName += ' <span class="category-tag">' + categoryTag + '</span>';
            }
            row.find('.selected-product-info').html(displayName).show();
            row.find('.product-search').hide();
            
            // 获取产品规格信息
            getProductSpecifications(productId, row);
            
            // 更新无产品消息显示
            updateNoProductsMessage();
        }

        function reindexProductRows() {
            $('.product-row').each(function(index) {
                $(this).attr('data-index', index);
                $(this).find('select, input').each(function() {
                    var name = $(this).attr('name');
                    if (name) {
                        name = name.replace(/items\[\d+\]/, 'items[' + index + ']');
                        $(this).attr('name', name);
                    }
                });
            });
            productIndex = $('.product-row').length;
        }

        function getProductSpecifications(productId, row) {
            if (!productId) return;
            
            // 获取当前选中的规格ID(如果有的话)
            var currentSpecId = row.find('.spec-id-input').val();
            console.log("加载规格 - 产品ID:", productId, "当前规格ID:", currentSpecId);
            
            $.ajax({
                url: 'get_product_info.php',
                type: 'GET',
                data: {product_id: productId},
                dataType: 'json',
                success: function(data) {
                    if (data && data.product && data.specifications) {
                        console.log("获取到规格数据:", data.specifications);
                        // 设置单位信息
                        if (data.product.unit) {
                            row.find('.unit-input').val(data.product.unit);
                            row.find('.unit-label').text(data.product.unit);
                        }
                        
                        // 处理规格信息
                        var specifications = data.specifications;
                        console.log("获取到的规格列表详情:", JSON.stringify(specifications)); // 打印完整的规格对象
                        if (specifications.length === 0) {
                            // 如果是编辑现有产品,不显示警告
                            if (!currentSpecId) {
                                alert('此产品没有规格信息,请添加规格后再选择');
                                // 重置产品选择
                                row.find('.product-id-input').val('');
                                row.find('.selected-product-info').hide();
                                row.find('.product-search').val('').show();
                            }
                            return;
                        }
                        
                        // 填充规格选择下拉框
                        var specSelect = row.find('.spec-select');
                        specSelect.empty();
                        specSelect.append('<option value="">请选择规格</option>');
                        
                        var foundSelectedSpec = false;
                        
                        $.each(specifications, function(i, spec) {
                            var displayText = spec.spec_name + ': ' + spec.spec_value;
                            if (spec.price) {
                                displayText += ' (¥' + spec.price + ')';
                            }
                            
                            var option = $('<option></option>')
                                .attr('value', spec.id)
                                .text(displayText)
                                .data('price', spec.price)
                                .data('minQty', spec.min_order_quantity)
                                .data('code', spec.spec_code);
                            
                            // 如果是当前选中的规格,设置selected属性
                            if (currentSpecId && parseInt(spec.id) === parseInt(currentSpecId)) {
                                console.log("找到匹配的规格 - 规格ID:", spec.id, "当前规格ID:", currentSpecId, 
                                           "规格名称:", spec.spec_name, "规格值:", spec.spec_value);
                                option.prop('selected', true);
                                foundSelectedSpec = true;
                                
                                // 更新规格信息显示
                                row.find('.spec-info').html(displayText);
                                
                                // 设置参考价格
                                var priceInput = row.find('.price-input');
                                priceInput.attr('data-min-price', spec.price || 0);
                            } else {
                                console.log("规格不匹配 - 规格ID:", spec.id, "当前规格ID:", currentSpecId, 
                                           "类型:", typeof spec.id, typeof currentSpecId);
                            }
                            
                            specSelect.append(option);
                        });
                        
                        // 显示规格选择下拉框并隐藏spec-info
                        if (!currentSpecId || !foundSelectedSpec) {
                            // 如果没有选中规格,显示下拉框
                            specSelect.show();
                            row.find('.spec-info').hide();
                        } else {
                            // 如果已选中规格,显示规格信息
                            specSelect.hide();
                            row.find('.spec-info').show();
                        }
                        
                        // 如果在规格列表中找不到已选择的规格
                        if (currentSpecId && !foundSelectedSpec) {
                            console.log("在规格列表中找不到已选择的规格ID:", currentSpecId);
                            // 不清除规格ID,保留数据库中的值
                            // row.find('.spec-id-input').val('');
                            
                            // 隐藏规格选择下拉框,保留现有规格信息
                            specSelect.hide();
                            row.find('.spec-info').show();
                        }
                    } else {
                        // 如果是编辑现有产品,不显示警告
                        if (!currentSpecId) {
                            alert('获取产品规格失败');
                            // 重置产品选择
                            row.find('.product-id-input').val('');
                            row.find('.selected-product-info').hide();
                            row.find('.product-search').val('').show();
                        }
                    }
                },
                error: function() {
                    // 如果是编辑现有产品,不显示警告
                    if (!currentSpecId) {
                        alert('获取产品规格失败,请重试');
                        // 重置产品选择
                        row.find('.product-id-input').val('');
                        row.find('.selected-product-info').hide();
                        row.find('.product-search').val('').show();
                    }
                }
            });
        }

        function getProductInfo(productId, row) {
            if (!productId) return;
            
            $.ajax({
                url: 'get_product_info.php',
                type: 'GET',
                data: {id: productId},
                dataType: 'json',
                success: function(data) {
                    if (data) {
                        row.find('.unit-input').val(data.unit);
                        row.find('.unit-label').text(data.unit);
                        // 只有当数据库中有价格信息时才设置价格
                        if (data.price && data.price !== '0' && data.price !== '0.00') {
                            //默认不设置单价
                            //row.find('.price-input').val(data.price);
                        }
                        calculateItemTotal(row.find('.price-input')[0]);
                    }
                }
            });
        }

        function calculateItemTotal(element) {
            var row = $(element).closest('.product-row');
            var quantity = parseInt(row.find('.quantity-input').val()) || 0;
            var priceInput = row.find('.price-input');
            var priceValue = priceInput.val().trim();
            var price = (priceValue === '') ? 0 : (parseFloat(priceValue) || 0);

            var total = quantity * price;
            if (total < 0) total = 0;

            // 更新显示元素和隐藏输入框
            row.find('.total-price-display').text(total.toFixed(2));
            row.find('.total-price-input').val(total.toFixed(2));

            calculateOrderTotal();
        }

        function calculateOrderTotal() {
            var total = 0;
            $('.total-price-input').each(function() {
                total += parseFloat($(this).val()) || 0;
            });

            // 更新总额和隐藏的小计字段
            $('#total-amount').text(total.toFixed(2));
            $('#total-amount-input').val(total.toFixed(2));
            $('#subtotal-input').val(total.toFixed(2)); // 为兼容性保留
        }

        function validateOrderForm() {
            var orderCode = $('#order_code').val();
            var customerId = $('#customer_id').val();
            var customerName = $('.customer-search').val();
            var hasProducts = false;
            var allSpecsSelected = true;
            var allPricesValid = true;
            var allPricesHighEnough = true;
            var firstInvalidField = null;

            // 检查是否有产品行
            if ($('.product-row').length === 0) {
                alert('请至少添加一个产品');
                $('#add-product-btn').focus();
                return false;
            }

            $('.product-row').each(function() {
                var productId = $(this).find('.product-id-input').val();
                var specId = $(this).find('.spec-id-input').val();
                var priceInput = $(this).find('.price-input');
                var priceValue = priceInput.val().trim();
                var price = parseFloat(priceValue) || 0;
                var minPrice = parseFloat(priceInput.attr('data-min-price')) || 0;
                var specSelect = $(this).find('.spec-select');
                var productSearch = $(this).find('.product-search');
                
                // 检查产品是否已选择
                if (!productId) {
                    if (!firstInvalidField) {
                        firstInvalidField = productSearch;
                    }
                    return true; // continue
                }
                
                hasProducts = true;
                
                // 检查规格是否已选择
                if (!specId && specSelect.is(':visible')) {
                    allSpecsSelected = false;
                    if (!firstInvalidField) {
                        firstInvalidField = specSelect;
                    }
                }
                
                // 检查单价是否有效
                if (priceValue === '' || isNaN(parseFloat(priceValue))) {
                    allPricesValid = false;
                    if (!firstInvalidField) {
                        firstInvalidField = priceInput;
                    }
                }
                
                // 检查单价是否大于等于规格价格
                if (minPrice > 0 && price < minPrice) {
                    allPricesHighEnough = false;
                    if (!firstInvalidField) {
                        firstInvalidField = priceInput;
                    }
                }
            });

            if (!orderCode) {
                alert('订单编号不能为空');
                $('#order_code').focus();
                return false;
            }

            if (!customerId || customerId == '0') {
                alert('请选择客户');
                $('.customer-search').focus();
                return false;
            }

            if (!customerName) {
                alert('客户名称不能为空');
                $('.customer-search').focus();
                return false;
            }
            
            if (!hasProducts) {
                alert('请至少添加一个有效的产品');
                if (firstInvalidField) {
                    firstInvalidField.focus();
                } else {
                    $('#add-product-btn').focus();
                }
                return false;
            }
            
            if (!allSpecsSelected) {
                alert('请为所有产品选择规格');
                if (firstInvalidField) {
                    firstInvalidField.focus();
                }
                return false;
            }
            
            if (!allPricesValid) {
                alert('请为所有产品输入有效的单价');
                if (firstInvalidField) {
                    firstInvalidField.focus();
                }
                return false;
            }
            
            if (!allPricesHighEnough) {
                alert('单价不能低于规格设定的参考价格');
                if (firstInvalidField) {
                    firstInvalidField.focus();
                }
                return false;
            }

            return true;
        }
        
        function updateNoProductsMessage() {
            if ($('.product-row').length > 0) {
                $('#no-products-message').hide();
            } else {
                $('#no-products-message').show();
            }
        }
    </script>
</div>
</body>
</html>