<?php
// 功能：后台商品列表 编辑 发布专用文件
// 作者：启肯科技
// Q Q：328493711
// 微信：13738373177（同手机）
// 官网：http://www.qiken.com
// 说明：QKCMS-轻量级AI智能内容管理建站系统
// 版权：© 2025 温州启肯网络有限公司 保留所有权利，盗版必究。

// 先引入common.php文件，确保所有函数可用
if (!defined('COMMON_LOADED')) {
    require_once '../common.php';
}

// 安全检查：确保在 admin.php 中被调用或直接处理POST/AJAX请求
if (!defined('ADMIN_LOADED')) {
    // 允许AJAX GET请求（action=get_goods_list 或 action=get_goods_info）
    $allowed_get_actions = ['get_goods_list', 'get_goods_info'];
    $is_ajax_request = isset($_GET['action']) && in_array($_GET['action'], $allowed_get_actions);

    if ($_SERVER['REQUEST_METHOD'] === 'POST' || $is_ajax_request) {
        require_once dirname(__DIR__) . '/common.php';
        if (!defined('COMMON_LOADED')) {
            define('COMMON_LOADED', true);
        }
        // 初始化数据库连接
        global $conn;
        $conn = get_db_connection();
        define('ADMIN_LOADED', true);
    } else {
        header('HTTP/1.1 403 Forbidden');
        exit('Access Denied');
    }
}

start_admin_session();
check_admin_access();

if (!defined('DEFAULT_THUMBNAIL_PATH')) {
    define('DEFAULT_THUMBNAIL_PATH', '/assets/images/moren.jpg');
}

// 初始化设置
$settings = initializeSettings();

// 通用函数
function checkDbConnection()
{
    global $conn;
    return isset($conn) && is_object($conn) && !isset($conn->connect_error);
}

function updateGoodsField($goodsId, $field, $value)
{
    if (!$goodsId || !$field) {
        return false;
    }

    // 确保数据库连接已初始化
    global $conn;
    if (!isset($conn) || !is_object($conn) || isset($conn->connect_error)) {
        // 直接调用 get_db_connection() 函数获取数据库连接
        $conn = get_db_connection();
        if (!isset($conn) || !is_object($conn) || isset($conn->connect_error)) {
            return false;
        }
    }

    // 构建SQL语句
    $sql = "UPDATE goods SET $field = ? WHERE id = ?";
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        return false;
    }

    // 根据字段类型绑定参数
    if ($field === 'price') {
        $stmt->bind_param('di', $value, $goodsId);
    } else if (in_array($field, ['category_id', 'status', 'stock', 'sales'])) {
        $stmt->bind_param('ii', $value, $goodsId);
    } else {
        $stmt->bind_param('si', $value, $goodsId);
    }

    // 执行SQL语句
    $result = $stmt->execute();

    // 关闭语句
    $stmt->close();
    return $result;
}

function processTempImage($imageUrl)
{
    // 如果不是临时图片也不是已上架商品图片，则不处理
    if (strpos($imageUrl, '/uploads/Temp/') === false && strpos($imageUrl, '/uploads/goods/') === false) {
        return $imageUrl;
    }

    $parsedUrl = parse_url($imageUrl);
    if (!isset($parsedUrl['path'])) {
        return $imageUrl;
    }

    $fileName = basename($parsedUrl['path']);

    // 确定源文件路径
    $sourcePath = '';
    if (strpos($imageUrl, '/uploads/Temp/') !== false) {
        $sourcePath = TEMP_UPLOAD_DIR . $fileName;
    } else {
        $sourcePath = $_SERVER['DOCUMENT_ROOT'] . '/uploads/goods/' . $fileName;
    }

    if (!file_exists($sourcePath)) {
        return $imageUrl;
    }

    $goodsUploadDir = $_SERVER['DOCUMENT_ROOT'] . '/uploads/goods/';
    if (!file_exists($goodsUploadDir)) {
        mkdir($goodsUploadDir, 0755, true);
    }

    // 为新发布的商品生成全新的唯一文件名，满足用户“按新商品重新命名”的需求
    $fileExt = pathinfo($fileName, PATHINFO_EXTENSION);
    $newFileName = 'goods_content_' . uniqid('', true) . '.' . $fileExt;
    $finalPath = $goodsUploadDir . $newFileName;

    // 使用 copy 而不是 rename，以便在同一页面多次发布时（例如改标题后重新发布）源文件依然可用
    if (copy($sourcePath, $finalPath)) {
        return qk_build_relative_upload_path($newFileName, '/uploads/goods/');
    }

    return $imageUrl;
}

function processContentImages($content)
{
    if (empty($content)) {
        return $content;
    }

    return preg_replace_callback(
        '/<img[^>]+src=["\']([^"\']+)["\'][^>]*>/i',
        function ($matches) {
            $imgTag = $matches[0];
            $src = $matches[1];
            $newSrc = processTempImage($src);
            return str_replace($src, $newSrc, $imgTag);
        },
        $content
    );
}

function processGalleryImages($images, $isEdit = false)
{
    $processedImages = [];
    $currentIndex = 1;

    foreach ($images as $img) {
        // 如果是临时图片，或者是在“发布”模式下的已上架商品图片（可能是从同一页面的上一次发布重用的）
        if (strpos($img, '/uploads/Temp/') !== false || (!$isEdit && strpos($img, '/uploads/goods/') !== false)) {
            $parsedUrl = parse_url($img);
            if (isset($parsedUrl['path'])) {
                $fileName = basename($parsedUrl['path']);

                // 确定源文件路径
                $sourcePath = '';
                if (strpos($img, '/uploads/Temp/') !== false) {
                    $sourcePath = TEMP_UPLOAD_DIR . $fileName;
                } else {
                    $sourcePath = $_SERVER['DOCUMENT_ROOT'] . '/uploads/goods/' . $fileName;
                }

                $goodsUploadDir = $_SERVER['DOCUMENT_ROOT'] . '/uploads/goods/';
                if (!file_exists($goodsUploadDir)) {
                    mkdir($goodsUploadDir, 0755, true);
                }

                // 总是生成新名称，满足用户“按新商品重新命名”的需求
                $fileExt = pathinfo($fileName, PATHINFO_EXTENSION);
                $newFileName = 'thumbnail_' . $currentIndex . '_' . uniqid('', true) . '.' . $fileExt;
                $finalPath = $goodsUploadDir . $newFileName;

                if (file_exists($sourcePath)) {
                    // 使用 copy 而不是 rename，以便在同一页面多次发布时源文件依然可用
                    if (copy($sourcePath, $finalPath)) {
                        $processedImages[] = qk_build_relative_upload_path($newFileName, '/uploads/goods/');
                        $currentIndex++;
                    } else {
                        // 复制失败，保留原始图片URL
                        $processedImages[] = $img;
                    }
                } else {
                    // 临时文件不存在，保留原始图片URL
                    $processedImages[] = $img;
                }
            } else {
                // 无效的URL路径，保留原始图片URL
                $processedImages[] = $img;
            }
        } else {
            // 非临时图片，直接添加
            $processedImages[] = $img;
        }
    }

    return $processedImages;
}

function processSpecImages($specs)
{
    if (!is_array($specs)) {
        return $specs;
    }

    foreach ($specs as &$spec) {
        if (isset($spec['image']) && !empty($spec['image'])) {
            $spec['image'] = processTempImage($spec['image']);
        }
    }

    return $specs;
}

// 处理商品URL参数
handle_goods_url_params();

// 处理商品图片上传
if (isset($_POST['action']) && $_POST['action'] === 'upload_image' && isset($_FILES['file'])) {
    ensureUploadDirectories();
    $file = $_FILES['file'];
    $fileName = $file['name'];
    $fileTmpName = $file['tmp_name'];
    $fileSize = $file['size'];
    $fileError = $file['error'];
    $fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
    $allowedExts = ['jpg', 'jpeg', 'png', 'gif', 'webp'];

    if ($fileError !== UPLOAD_ERR_OK) {
        return_json(false, '文件上传失败');
    }

    if (!in_array($fileExt, $allowedExts)) {
        return_json(false, '不支持的文件类型');
    }

    $maxFileSize = 1 * 1024 * 1024;
    if ($fileSize > $maxFileSize) {
        return_json(false, '文件大小超过1MB限制');
    }

    // 根据类型使用不同的前缀
    if (isset($_POST['type']) && $_POST['type'] === 'goods') {
        // 商品图片
        if (isset($_POST['image_type']) && $_POST['image_type'] === 'thumbnail') {
            // 商品缩略图 - 上传时不使用序号，发布时再排序
            $prefix = 'thumbnail_';
        } else if (isset($_POST['image_type']) && $_POST['image_type'] === 'spec') {
            // 规格图片
            $prefix = 'spec_';
        } else {
            // 商品详情图片
            $prefix = 'goods_';
        }
    } else {
        // 文章图片
        $prefix = 'article_';
    }
    $newFileName = $prefix . uniqid('', true) . '.' . $fileExt;
    $destination = TEMP_UPLOAD_DIR . $newFileName;

    if (move_uploaded_file($fileTmpName, $destination)) {
        $imageUrl = qk_build_relative_upload_path($newFileName, '/uploads/Temp/');
        return_json(true, '图片上传成功', array('url' => $imageUrl));
    } else {
        return_json(false, '文件保存失败');
    }
    exit;
}

// 处理删除图片
if (isset($_POST['action']) && $_POST['action'] === 'delete_image' && isset($_POST['image_url'])) {
    $imageUrl = $_POST['image_url'];
    $success = false;

    try {
        // 解析图片URL，获取文件名
        $parsedUrl = parse_url($imageUrl);
        if (isset($parsedUrl['path'])) {
            $fileName = basename($parsedUrl['path']);

            // 检查是否是临时目录的图片
            if (strpos($imageUrl, '/uploads/Temp/') !== false) {
                // 删除临时目录中的图片
                $tempPath = TEMP_UPLOAD_DIR . $fileName;
                if (file_exists($tempPath)) {
                    $success = unlink($tempPath);
                }
            } else if (strpos($imageUrl, '/uploads/goods/') !== false) {
                // 删除goods目录中的图片
                $goodsPath = $_SERVER['DOCUMENT_ROOT'] . '/uploads/goods/' . $fileName;
                if (file_exists($goodsPath)) {
                    $success = unlink($goodsPath);
                }
            }

            // 同时检查临时目录和goods目录，确保图片被删除
            $tempPath = TEMP_UPLOAD_DIR . $fileName;
            $goodsPath = $_SERVER['DOCUMENT_ROOT'] . '/uploads/goods/' . $fileName;

            if (file_exists($tempPath)) {
                $success = unlink($tempPath) || $success;
            }
            if (file_exists($goodsPath)) {
                $success = unlink($goodsPath) || $success;
            }
        }

        return_json(true, $success ? '图片删除成功' : '图片删除失败');
    } catch (Exception $e) {
        return_json(false, '删除图片时发生错误');
    }
    exit;
}

/**
 * 保存商品Base64图片到临时目录
 * @param string $base64Data Base64编码的图片数据
 * @param string $imageType 图片类型
 * @return string 图片URL，失败返回空字符串
 */
function saveGoodsBase64Image($base64Data, $imageType = 'detail')
{
    try {
        if (preg_match('/^data:image\/(jpeg|jpg|png|gif);base64,/', $base64Data, $matches)) {
            $imageExt = $matches[1];
            $imageData = base64_decode(str_replace('data:image/' . $imageExt . ';base64,', '', $base64Data));

            // 检查文件大小（1MB限制）
            $maxFileSize = 1 * 1024 * 1024;
            if (strlen($imageData) > $maxFileSize) {
                return '';
            }

            // 根据类型使用不同的前缀
            if ($imageType === 'thumbnail') {
                $prefix = 'thumbnail_1_';
            } else {
                $prefix = 'goods_';
            }

            $fileName = $prefix . uniqid('', true) . '.' . $imageExt;
            $filePath = TEMP_UPLOAD_DIR . $fileName;
            if (file_put_contents($filePath, $imageData) !== false) {
                return qk_build_relative_upload_path($fileName, '/uploads/Temp/');
            } else {
                return '';
            }
        } else {
            return '';
        }
    } catch (Exception $e) {
        return '';
    }
}

/**
 * 处理商品内容中的Base64图片并替换为URL
 * @param string $content HTML内容
 * @return string 处理后的内容
 */
function processGoodsBase64ImagesInContent($content)
{
    if (!$content || !is_string($content)) {
        return $content;
    }
    $processedContent = preg_replace_callback(
        '/<img[^>]+src=["\']data:image\/(jpeg|jpg|png|gif);base64,[^"\']+["\'][^>]*>/i',
        function ($matches) {
            $imgTag = $matches[0];
            preg_match('/src=["\'](data:image\/[^;]+;base64,[^"\']+)["\']/', $imgTag, $srcMatch);
            if (isset($srcMatch[1])) {
                $base64Data = $srcMatch[1];
                $imageUrl = saveGoodsBase64Image($base64Data, 'detail');
                if ($imageUrl) {
                    $newImgTag = str_replace($base64Data, $imageUrl, $imgTag);
                    return $newImgTag;
                }
            }
            return $imgTag;
        },
        $content
    );
    return $processedContent;
}

// ==================== 处理请求 ====================

/**
 * 处理商品URL参数
 * 将action和id存储到session，用于商品发布和编辑页面
 */
function handle_goods_url_params()
{
    if (isset($_GET['tab']) && $_GET['tab'] === 'adgoods') {
        if (isset($_GET['action'])) {
            $_SESSION['goodsAction'] = $_GET['action'];
        }
        if (isset($_GET['id'])) {
            $_SESSION['goodsId'] = $_GET['id'];
        }
    }
}

// 处理GET请求
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    // 清空临时目录（访问商品管理页面时）
    if (!isset($_GET['action']) && !isset($_GET['delete_goods']) && !isset($_GET['ajax'])) {
        clearTempDirectory();
    }

    // 删除单个商品
    if (isset($_GET['delete_goods'])) {
        global $conn;
        $goods_id = intval($_GET['delete_goods']);
        if ($goods_id <= 0) {
            if (isset($_GET['ajax']) && $_GET['ajax'] == 1) {
                echo 'error';
                exit;
            } else {
                echo '<script>showToast(\'无效的商品ID\', \'error\');</script>';
                exit;
            }
        }
        try {
            if (deleteGoods($goods_id)) {
                if (isset($_GET['ajax']) && $_GET['ajax'] == 1) {
                    echo 'success';
                    exit;
                } else {
                    echo '<script>showToast(\'商品删除成功\', \'success\'); setTimeout(function() { window.location.reload(); }, 1500);</script>';
                    exit;
                }
            } else {
                if (isset($_GET['ajax']) && $_GET['ajax'] == 1) {
                    echo 'error';
                    exit;
                } else {
                    echo '<script>showToast(\'商品删除失败\', \'error\');</script>';
                    exit;
                }
            }
        } catch (Exception $e) {
            if (isset($_GET['ajax']) && $_GET['ajax'] == 1) {
                echo 'error';
                exit;
            } else {
                echo '<script>showToast(\'系统错误：' . $e->getMessage() . '\', \'error\');</script>';
                exit;
            }
        }
    }
}

// 处理POST请求
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    global $conn;

    // 统一处理商品字段更新
    $updateActions = [
        'update_goods_category' => ['field' => 'category_id', 'validator' => function ($value) {
            return $value >= 0;
        }, 'error' => '分类ID无效'],
        'update_goods_status' => ['field' => 'status', 'validator' => function ($value) {
            return in_array($value, [0, 1]);
        }, 'error' => '状态值无效'],
        'update_goods_title' => ['field' => 'title', 'validator' => function ($value) use ($_POST) {
            if (empty($value)) return false;
            if (checkGoodsTitleExists($value, intval($_POST['goods_id']))) return false;
            return true;
        }, 'error' => '标题不能为空或重复'],
        'update_goods_price' => ['field' => 'price', 'validator' => function ($value) {
            return $value >= 0;
        }, 'error' => '价格不能为负数'],
        'update_goods_stock' => ['field' => 'stock', 'validator' => function ($value) {
            return $value >= 0;
        }, 'error' => '库存不能为负数'],
        'update_goods_sales' => ['field' => 'sales', 'validator' => function ($value) {
            return $value >= 0;
        }, 'error' => '销量不能为负数'],
        'update_goods_image' => ['field' => 'image', 'validator' => function ($value) {
            return true;
        }, 'error' => '图片更新失败']
    ];

    foreach ($updateActions as $action => $config) {
        if (isset($_POST[$action]) && isset($_POST['goods_id']) && isset($_POST[$config['field']])) {
            $goods_id = intval($_POST['goods_id']);
            $value = $_POST[$config['field']];

            if ($goods_id <= 0) {
                return_json(false, '无效的商品ID');
                exit;
            }

            // 类型转换
            if (in_array($config['field'], ['category_id', 'status', 'stock', 'sales'])) {
                $value = intval($value);
            } else if ($config['field'] === 'price') {
                $value = floatval($value);
            } else {
                $value = trim($value);
            }

            // 处理图片字段中的临时图片
            if ($config['field'] === 'image' && !empty($value)) {
                $images = explode('|', $value);
                $processedImages = [];
                $currentIndex = 1;

                foreach ($images as $img) {
                    if (strpos($img, '/uploads/Temp/') !== false) {
                        $parsedUrl = parse_url($img);
                        if (isset($parsedUrl['path'])) {
                            $fileName = basename($parsedUrl['path']);
                            $sourcePath = TEMP_UPLOAD_DIR . $fileName;

                            $goodsUploadDir = $_SERVER['DOCUMENT_ROOT'] . '/uploads/goods/';
                            if (!file_exists($goodsUploadDir)) {
                                mkdir($goodsUploadDir, 0755, true);
                            }

                            $fileExt = pathinfo($fileName, PATHINFO_EXTENSION);
                            $newFileName = 'thumbnail_' . $currentIndex . '_' . uniqid('', true) . '.' . $fileExt;
                            $finalPath = $goodsUploadDir . $newFileName;

                            if (file_exists($sourcePath)) {
                                if (copy($sourcePath, $finalPath)) {
                                    $processedImages[] = qk_build_relative_upload_path($newFileName, '/uploads/goods/');
                                    $currentIndex++;
                                } else {
                                    $processedImages[] = $img;
                                }
                            } else {
                                $processedImages[] = $img;
                            }
                        } else {
                            $processedImages[] = $img;
                        }
                    } else {
                        $processedImages[] = $img;
                    }
                }

                $value = implode('|', $processedImages);
            }

            // 验证
            if (!$config['validator']($value)) {
                return_json(false, $config['error']);
                exit;
            }

            try {
                if (updateGoodsField($goods_id, $config['field'], $value)) {
                    return_json(true, ucfirst(str_replace('_', ' ', $config['field'])) . '更新成功');
                } else {
                    return_json(false, ucfirst(str_replace('_', ' ', $config['field'])) . '更新失败');
                }
            } catch (Exception $e) {
                return_json(false, '系统错误：' . $e->getMessage());
            }
            exit;
        }
    }

    // 批量操作处理函数
    function batchUpdateGoods($field, $value, $ids)
    {
        if (empty($ids)) {
            return ['success' => false, 'message' => '未选择要操作的商品'];
        }

        // 确保数据库连接已初始化
        global $conn;
        if (!checkDbConnection()) {
            $conn = get_db_connection();
            if (!checkDbConnection()) {
                return ['success' => false, 'message' => '数据库连接失败'];
            }
        }

        $placeholders = implode(',', array_fill(0, count($ids), '?'));
        $sql = "UPDATE goods SET $field = ? WHERE id IN ($placeholders)";
        $stmt = $conn->prepare($sql);

        if (!$stmt) {
            return ['success' => false, 'message' => 'SQL语句准备失败'];
        }

        // 绑定参数
        $params = array_merge([$value], $ids);
        if ($field === 'price') {
            $types = 'd' . str_repeat('i', count($ids));
        } else {
            $types = 'i' . str_repeat('i', count($ids));
        }

        $stmt->bind_param($types, ...$params);

        if ($stmt->execute()) {
            $affected_rows = $stmt->affected_rows;
            $stmt->close();
            return ['success' => true, 'affected_rows' => $affected_rows];
        } else {
            $error = $conn->error;
            $stmt->close();
            return ['success' => false, 'message' => '操作失败：' . $error];
        }
    }

    // 删除单个商品
    if (isset($_POST['delete_goods']) && isset($_POST['goods_id'])) {
        $goods_id = intval($_POST['goods_id']);
        if ($goods_id <= 0) {
            echo '无效的商品ID';
            exit;
        }
        try {
            if (deleteGoods($goods_id)) {
                echo 'success';
            } else {
                echo '删除商品失败';
            }
        } catch (Exception $e) {
            echo '系统错误：' . $e->getMessage();
        }
        exit;
    }

    // 批量删除商品
    if (isset($_POST['batch_delete_goods']) && isset($_POST['goods_ids'])) {
        $goods_ids = $_POST['goods_ids'];
        $ids = array_filter(array_map('intval', explode(',', $goods_ids)));

        if (empty($ids)) {
            return_json(false, '未选择要删除的商品');
        }

        try {
            $success_count = 0;
            foreach ($ids as $id) {
                if (deleteGoods($id)) {
                    $success_count++;
                }
            }

            if ($success_count > 0) {
                return_json(true, "成功删除 {$success_count} 件商品");
            } else {
                return_json(false, '删除失败');
            }
        } catch (Exception $e) {
            return_json(false, '系统错误：' . $e->getMessage());
        }
    }

    // 批量修改商品库存
    if (isset($_POST['batch_update_stock']) && isset($_POST['goods_ids']) && isset($_POST['stock'])) {
        $goods_ids = $_POST['goods_ids'];
        $stock = intval($_POST['stock']);
        $ids = array_filter(array_map('intval', explode(',', $goods_ids)));

        if (empty($ids)) {
            return_json(false, '未选择要修改的商品');
        }

        if ($stock < 0) {
            return_json(false, '库存不能为负数');
        }

        try {
            $result = batchUpdateGoods('stock', $stock, $ids);
            if ($result['success']) {
                return_json(true, "成功修改 {$result['affected_rows']} 件商品的库存");
            } else {
                return_json(false, $result['message']);
            }
        } catch (Exception $e) {
            return_json(false, '系统错误：' . $e->getMessage());
        }
    }

    // 批量移动商品到分类
    if (isset($_POST['batch_move_goods']) && isset($_POST['goods_ids']) && isset($_POST['category_id'])) {
        $goods_ids = $_POST['goods_ids'];
        $category_id = intval($_POST['category_id']);
        $ids = array_filter(array_map('intval', explode(',', $goods_ids)));

        if (empty($ids)) {
            return_json(false, '未选择要移动的商品');
        }

        if ($category_id <= 0) {
            return_json(false, '无效的分类ID');
        }

        try {
            $result = batchUpdateGoods('category_id', $category_id, $ids);
            if ($result['success']) {
                return_json(true, "成功移动 {$result['affected_rows']} 件商品到分类");
            } else {
                return_json(false, $result['message']);
            }
        } catch (Exception $e) {
            return_json(false, '系统错误：' . $e->getMessage());
        }
        exit;
    }

    // 批量设置商品状态
    if (isset($_POST['batch_update_goods_status']) && isset($_POST['goods_ids']) && isset($_POST['status'])) {
        $goods_ids = $_POST['goods_ids'];
        $status = intval($_POST['status']);
        $ids = array_filter(array_map('intval', explode(',', $goods_ids)));

        if (empty($ids)) {
            return_json(false, '未选择要设置状态的商品');
        }

        try {
            $result = batchUpdateGoods('status', $status, $ids);
            if ($result['success']) {
                return_json(true, "成功设置 {$result['affected_rows']} 件商品的状态");
            } else {
                return_json(false, $result['message']);
            }
        } catch (Exception $e) {
            return_json(false, '系统错误：' . $e->getMessage());
        }
        exit;
    }

    // 发布新商品
    if (isset($_POST['publish_goods'])) {
        $title = trim($_POST['title']);
        $keywords = trim($_POST['keywords']);
        $description = trim($_POST['description']);
        $mp4url = trim($_POST['mp4url']);
        $template = trim($_POST['template']);
        $category_id = intval($_POST['category_id']);
        $parent_id = isset($_POST['parent_id']) ? trim($_POST['parent_id']) : '0';
        $price = floatval($_POST['price']);
        $stock = intval($_POST['stock']);
        // 生成随机销量 1-10
        $sales = rand(1, 10);
        $content = trim($_POST['content']);

        // 验证必填字段
        if (empty($title)) {
            return_json(false, '商品标题不能为空');
        }

        // 检查内容是否为空，允许只包含图片的情况
        $isContentEmpty = empty($content);
        $hasImage = false;
        if (!$isContentEmpty) {
            // 检查是否包含图片标签
            $hasImage = preg_match('/<img[^>]+src=["\']([^"\']+)["\'][^>]*>/i', $content);
        }
        if ($isContentEmpty && !$hasImage) {
            return_json(false, '商品详情不能为空');
        }

        // 检查标题是否重复
        if (checkGoodsTitleExists($title)) {
            return_json(false, '标题不能重复请修改');
        }

        try {
            if (!checkDbConnection()) {
                return_json(false, '数据库连接失败');
            }

            // 处理文件上传 - 从隐藏字段获取图片URL数组
            $images = array();
            // 处理新增的图片
            if (isset($_POST['gallery']) && is_array($_POST['gallery'])) {
                $images = $_POST['gallery'];
            }
            // 处理现有的图片
            if (isset($_POST['existing_images']) && is_array($_POST['existing_images'])) {
                $images = array_merge($images, $_POST['existing_images']);
            }

            // 处理 Base64 图片
            $processedContent = processGoodsBase64ImagesInContent($content);
            if ($processedContent) {
                $content = $processedContent;
            }

            // 处理内容中的临时图片
            $content = processContentImages($content);

            // 处理所有临时图片
            $processedImages = processGalleryImages($images, false);

            // 取第一张图片作为主缩略图
            $image = !empty($processedImages) ? $processedImages[0] : '';
            // 如果有多个图片，使用 | 分隔存储到 image 字段
            if (count($processedImages) > 1) {
                $image = implode('|', $processedImages);
            }

            // 处理规格属性
            $specs = '';
            if (isset($_POST['specs']) && is_array($_POST['specs'])) {
                $processedSpecs = processSpecImages($_POST['specs']);
                $specs = json_encode($processedSpecs);
            }

            // 发布商品
            $status = 1; // 默认上架状态
            $images_json = ''; // 缩略图JSON数据
            $goodsId = publishGoods($title, $content, $status, $category_id, $image, $images_json, $keywords, $description, $price, $stock, $sales, $parent_id, $specs, $mp4url, $template);

            if ($goodsId) {
                // 清除session中的临时销量变量，以便下次重新生成
                unset($_SESSION['goods_sales']);
                // 注释掉清空临时目录，以便在同一页面多次发布（例如改标题后重新发布）时图片依然可用
                // clearTempDirectory();
                return_json(true, '商品发布成功', ['goods_id' => $goodsId]);
            } else {
                return_json(false, '商品发布失败');
            }
        } catch (Exception $e) {
            return_json(false, '系统错误：' . $e->getMessage());
        }
        exit;
    }

    // 更新商品
    if (isset($_POST['update_goods']) && isset($_POST['goods_id'])) {
        $goods_id = intval($_POST['goods_id']);
        $title = trim($_POST['title']);
        $keywords = trim($_POST['keywords']);
        $description = trim($_POST['description']);
        $mp4url = trim($_POST['mp4url']);
        $template = trim($_POST['template']);
        $category_id = intval($_POST['category_id']);
        $parent_id = isset($_POST['parent_id']) ? trim($_POST['parent_id']) : '0';
        $price = floatval($_POST['price']);
        $stock = intval($_POST['stock']);
        $sales = intval($_POST['sales']);
        $content = trim($_POST['content']);

        // 验证必填字段
        if (empty($title)) {
            return_json(false, '商品标题不能为空');
        }

        // 检查内容是否为空，允许只包含图片的情况
        $isContentEmpty = empty($content);
        $hasImage = false;
        if (!$isContentEmpty) {
            // 检查是否包含图片标签
            $hasImage = preg_match('/<img[^>]+src=["\']([^"\']+)["\'][^>]*>/i', $content);
        }
        if ($isContentEmpty && !$hasImage) {
            return_json(false, '商品详情不能为空');
        }

        // 检查标题是否重复（排除当前商品）
        if (checkGoodsTitleExists($title, $goods_id)) {
            return_json(false, '标题不能重复请修改');
        }

        try {
            if (!checkDbConnection()) {
                return_json(false, '数据库连接失败');
            }

            // 获取当前商品信息
            $sql = "SELECT image FROM goods WHERE id = ?";
            $result = execute_query($conn, $sql, array($goods_id));
            $current_goods = $result->fetch_assoc();
            $result->close();

            $image = $current_goods['image'];

            // 处理文件上传 - 从隐藏字段获取图片URL数组
            $images = array();
            // 处理新增的图片
            if (isset($_POST['gallery']) && is_array($_POST['gallery'])) {
                $images = $_POST['gallery'];
            }
            // 处理现有的图片
            if (isset($_POST['existing_images']) && is_array($_POST['existing_images'])) {
                $images = array_merge($images, $_POST['existing_images']);
            }

            // 处理 Base64 图片
            $processedContent = processGoodsBase64ImagesInContent($content);
            if ($processedContent) {
                $content = $processedContent;
            }

            // 处理内容中的临时图片
            $content = processContentImages($content);

            // 处理所有图片
            $processedImages = processGalleryImages($images, true);

            // 取第一张图片作为主缩略图
            $image = !empty($processedImages) ? $processedImages[0] : '';
            // 如果有多个图片，使用 | 分隔存储到 image 字段
            if (count($processedImages) > 1) {
                $image = implode('|', $processedImages);
            }

            // 处理规格属性
            $specs = '';
            if (isset($_POST['specs']) && is_array($_POST['specs'])) {
                $processedSpecs = processSpecImages($_POST['specs']);
                $specs = json_encode($processedSpecs);
            }

            // 更新商品
            $status = 1; // 发布商品
            $images_json = ''; // 缩略图JSON数据
            $success = updateGoods($goods_id, $title, $content, $status, $category_id, $image, $images_json, $keywords, $description, $price, $stock, $sales, $parent_id, $specs, $mp4url, $template);

            if ($success) {
                // 清空临时目录
                clearTempDirectory();
                return_json(true, '商品更新成功');
            } else {
                return_json(false, '商品更新失败');
            }
        } catch (Exception $e) {
            return_json(false, '系统错误：' . $e->getMessage());
        }
        exit;
    }
}

// 商品相关函数

function checkGoodsTitleExists($title, $excludeId = 0)
{
    if (!is_string($title) || empty($title)) {
        return false;
    }
    $excludeId = intval($excludeId);

    global $conn;
    try {
        if (!checkDbConnection()) {
            return false;
        }

        $sql = "SELECT COUNT(*) as count FROM goods WHERE title = ?";
        $params = array($title);
        if ($excludeId > 0) {
            $sql .= " AND id != ?";
            $params[] = $excludeId;
        }
        $row = get_single_row($conn, $sql, $params);
        return $row && $row['count'] > 0;
    } catch (Exception $e) {
        return false;
    }
}

function checkGoodsCustomUrlExists($customUrl, $excludeId = 0)
{
    if (!is_string($customUrl) || empty($customUrl)) {
        return false;
    }
    $excludeId = intval($excludeId);

    global $conn;
    try {
        if (!checkDbConnection()) {
            return false;
        }

        $sql = "SELECT COUNT(*) as count FROM goods WHERE custom_url = ?";
        $params = array($customUrl);
        if ($excludeId > 0) {
            $sql .= " AND id != ?";
            $params[] = $excludeId;
        }
        $row = get_single_row($conn, $sql, $params);
        return $row && $row['count'] > 0;
    } catch (Exception $e) {
        return false;
    }
}

function publishGoods($title, $content, $status, $categoryId, $image, $images_json = '', $keywords = '', $description = '', $price = 0, $stock = 0, $sales = 0, $parentId = '0', $specs = '', $mp4url = '', $template = 'goods.php')
{
    if (!is_string($title) || empty($title) || !is_string($content) || empty($content)) {
        return false;
    }

    $status = intval($status);
    $categoryId = intval($categoryId);
    $price = floatval($price);
    $stock = intval($stock);
    $sales = intval($sales);
    $parentId = is_string($parentId) ? trim($parentId) : '0';

    $image = is_string($image) ? $image : '';
    $keywords = is_string($keywords) ? $keywords : '';
    $description = is_string($description) ? $description : '';
    $specs = is_string($specs) ? $specs : '';

    global $conn;
    try {
        if (!isset($conn) || !is_object($conn) || isset($conn->connect_error)) {
            return false;
        }

        $sql = "INSERT INTO goods (title, content, status, category_id, image, keywords, description, price, stock, sales, parent_id, specs, mp4url, template, create_time, update_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())";
        $params = array($title, $content, $status, $categoryId, $image, $keywords, $description, $price, $stock, $sales, $parentId, $specs, $mp4url, $template);
        $result = execute_non_query($conn, $sql, $params);
        if ($result !== false && $result['affected_rows'] > 0) {
            return $result['insert_id'];
        }
        // 检查数据库错误
        if (isset($conn->error)) {
        }
        return false;
    } catch (Exception $e) {
        return false;
    }
}

function updateGoods($goodsId, $title, $content, $status, $categoryId, $image, $images_json = '', $keywords = '', $description = '', $price = 0, $stock = 0, $sales = 0, $parentId = '0', $specs = '', $mp4url = '', $template = 'goods.php')
{
    $goodsId = intval($goodsId);
    if ($goodsId <= 0 || !is_string($title) || empty($title) || !is_string($content) || empty($content)) {
        return false;
    }

    $status = intval($status);
    $categoryId = intval($categoryId);
    $price = floatval($price);
    $stock = intval($stock);
    $sales = intval($sales);
    $parentId = is_string($parentId) ? trim($parentId) : '0';

    $image = is_string($image) ? $image : '';
    $keywords = is_string($keywords) ? $keywords : '';
    $description = is_string($description) ? $description : '';
    $specs = is_string($specs) ? $specs : '';

    global $conn;
    try {
        if (!isset($conn) || !is_object($conn) || isset($conn->connect_error)) {
            return false;
        }

        $sql = "UPDATE goods SET title = ?, content = ?, status = ?, category_id = ?, image = ?, keywords = ?, description = ?, price = ?, stock = ?, sales = ?, parent_id = ?, specs = ?, mp4url = ?, template = ?, update_time = NOW() WHERE id = ?";
        $params = array($title, $content, $status, $categoryId, $image, $keywords, $description, $price, $stock, $sales, $parentId, $specs, $mp4url, $template, $goodsId);
        $result = execute_non_query($conn, $sql, $params);
        return $result !== false && $result['affected_rows'] > 0;
    } catch (Exception $e) {
        return false;
    }
}

function getGoodsCount()
{
    return get_table_count('goods', 'goods_count', 0);
}

function getGoodsProperties($enabled_only = true)
{
    $cache_key = $enabled_only ? 'goods_properties_enabled' : 'goods_properties_all';
    $cached = get_cache($cache_key);
    if ($cached !== false && $cached !== null) {
        return $cached;
    }

    $conn = get_db_connection();
    if (!$conn) {
        return [];
    }

    $sql = "SELECT id, name, color, is_system, is_enabled, sort_order FROM properties";
    if ($enabled_only) {
        $sql .= " WHERE is_enabled = 1";
    }
    $sql .= " ORDER BY sort_order ASC, id ASC";

    $result = $conn->query($sql);
    $properties = [];

    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $properties[$row['id']] = $row;
        }
        $result->close();
    }

    set_cache($cache_key, $properties);
    return $properties;
}

function getGoodsPropertyName($property_id)
{
    $properties = getGoodsProperties();
    return isset($properties[$property_id]) ? $properties[$property_id]['name'] : null;
}

function clearGoodsPropertiesCache()
{
    delete_cache('goods_properties_enabled');
    delete_cache('goods_properties_all');
}

function getGoodsTemplates()
{
    if (function_exists('qk_get_template_options_by_page_type')) {
        $templates = qk_get_template_options_by_page_type('goods');
        foreach ($templates as $path => $name) {
            if (strpos($path, 'skin/') !== 0 && strpos($name, '（默认）') !== false) {
                $templates[$path] = '0_' . ltrim((string)$name, '0_');
            }
        }
        return $templates;
    }
    return array('goods.php' => '0_goods.php（默认）');
}

function getGoods($limit = 0, $offset = 0, $search = '', $category_id = 0, $exclude_id = 0)
{
    $limit = max(0, intval($limit));
    $offset = max(0, intval($offset));
    $category_id = intval($category_id);
    $exclude_id = intval($exclude_id);

    global $conn;

    try {
        if ($conn && !isset($conn->connect_error)) {
            $sql = "SELECT g.id, g.title, g.content, g.image, g.create_time, g.update_time, 
                   g.price, g.stock, g.sales, g.status, g.category_id, g.keywords, g.description, 
                   g.parent_id, g.mp4url, g.template
                   FROM goods g 
                   WHERE 1=1";

            $params = array();
            if (!empty($search) && is_string($search)) {
                if (has_forbidden_words($search)) {
                    return array();
                }
                $sql .= " AND g.title LIKE ?";
                $searchTerm = '%' . $search . '%';
                $params[] = $searchTerm;
            }

            // 排除指定ID的商品
            if ($exclude_id > 0) {
                $sql .= " AND g.id != ?";
                $params[] = $exclude_id;
            }

            $sql .= " ORDER BY g.id DESC";

            if ($limit > 0) {
                $sql .= " LIMIT ? OFFSET ?";
                $params[] = $limit;
                $params[] = $offset;
            }

            $result = execute_query($conn, $sql, $params);

            if ($result !== false) {
                $goods = array();
                while ($row = $result->fetch_assoc()) {
                    $goods[] = $row;
                }
                $result->close();
                return $goods;
            }
        }
    } catch (Exception $e) {
    }

    return array();
}

function getTotalGoods($search = '', $category_id = 0, $exclude_id = 0)
{
    global $conn;
    try {
        if ($conn && !isset($conn->connect_error)) {
            $sql = "SELECT COUNT(*) as count FROM goods g WHERE 1=1";
            $params = array();
            if (!empty($search)) {
                if (has_forbidden_words($search)) {
                    return 0;
                }
                $sql .= " AND g.title LIKE ?";
                $searchTerm = '%' . $search . '%';
                $params[] = $searchTerm;
            }

            // 排除指定ID的商品
            if ($exclude_id > 0) {
                $sql .= " AND g.id != ?";
                $params[] = $exclude_id;
            }

            $result = execute_query($conn, $sql, $params);
            if ($result !== false) {
                $row = $result->fetch_assoc();
                $result->close();
                return intval($row['count']);
            }
        }
        return 0;
    } catch (Exception $e) {
        return 0;
    }
}

function deleteGoods($goodsId)
{
    global $conn;
    try {
        // 检查数据库连接
        if (!isset($conn) || !is_object($conn) || isset($conn->connect_error)) {
            return false;
        }

        $goodsIds = is_string($goodsId) && strpos($goodsId, ',') !== false ? array_map('intval', explode(',', $goodsId)) : array(intval($goodsId));

        $placeholders = implode(',', array_fill(0, count($goodsIds), '?'));
        $conn->begin_transaction();

        $result = execute_query($conn, "SELECT image, content, specs FROM goods WHERE id IN ($placeholders)", $goodsIds);

        $thumbnails = array();
        $contents = array();
        $specsList = array();
        if ($result) {
            while ($row = $result->fetch_assoc()) {
                if (!empty($row['image'])) {
                    $thumbnails[] = $row['image'];
                }
                if (!empty($row['content'])) {
                    $contents[] = $row['content'];
                }
                if (!empty($row['specs'])) {
                    $specsList[] = $row['specs'];
                }
            }
            $result->close();
        }

        $deleteResult = execute_non_query($conn, "DELETE FROM goods WHERE id IN ($placeholders)", $goodsIds);
        if (!$deleteResult) {
            $conn->rollback();
            return false;
        }
        $conn->commit();

        $documentRoot = $_SERVER['DOCUMENT_ROOT'];

        foreach ($thumbnails as $thumbnail) {
            // 检查是否包含多个图片（用|分隔）
            $thumbnailUrls = explode('|', $thumbnail);
            foreach ($thumbnailUrls as $thumbnailUrl) {
                $thumbnailUrl = trim($thumbnailUrl);
                if (!empty($thumbnailUrl) && strpos($thumbnailUrl, '/uploads/') !== false) {
                    $pathParts = parse_url($thumbnailUrl);
                    $relativePath = str_replace('/', DIRECTORY_SEPARATOR, $pathParts['path']);
                    $thumbnailPath = $documentRoot . $relativePath;
                    if (file_exists($thumbnailPath)) {
                        unlink($thumbnailPath);
                    }
                }
            }
        }

        foreach ($contents as $content) {
            $pattern = '/<img[^>]+src=["\']([^"\']+)["\'][^>]*>/i';
            if (preg_match_all($pattern, $content, $matches)) {
                foreach ($matches[1] as $imageUrl) {
                    if (strpos($imageUrl, '/uploads/') !== false) {
                        $pathParts = parse_url($imageUrl);
                        $relativePath = str_replace('/', DIRECTORY_SEPARATOR, $pathParts['path']);
                        $imagePath = $documentRoot . $relativePath;
                        if (file_exists($imagePath)) {
                            unlink($imagePath);
                        }
                    }
                }
            }
        }

        // 删除规格图片
        foreach ($specsList as $specs) {
            // 尝试解析specs为JSON
            $specsData = json_decode($specs, true);
            if (is_array($specsData)) {
                // 遍历规格数据，查找图片URL
                foreach ($specsData as $spec) {
                    if (is_array($spec)) {
                        // 检查规格中是否有图片
                        foreach ($spec as $key => $value) {
                            if (is_string($value) && strpos($value, '/uploads/') !== false) {
                                $pathParts = parse_url($value);
                                $relativePath = str_replace('/', DIRECTORY_SEPARATOR, $pathParts['path']);
                                $imagePath = $documentRoot . $relativePath;
                                if (file_exists($imagePath)) {
                                    unlink($imagePath);
                                }
                            }
                        }
                    }
                }
            } else {
                // 如果不是JSON，尝试直接查找图片URL
                $pattern = '/\/uploads\/[^\s"\']+/i';
                if (preg_match_all($pattern, $specs, $matches)) {
                    foreach ($matches[0] as $imageUrl) {
                        $relativePath = str_replace('/', DIRECTORY_SEPARATOR, $imageUrl);
                        $imagePath = $documentRoot . $relativePath;
                        if (file_exists($imagePath)) {
                            unlink($imagePath);
                        }
                    }
                }
            }
        }

        return true;
    } catch (Exception $e) {
        if (isset($conn) && $conn->in_transaction) {
            $conn->rollback();
        }
        return false;
    }
}



// AJAX接口：获取商品列表（用于无刷新分页）
if (isset($_GET['action']) && $_GET['action'] === 'get_goods_list') {
    header('Content-Type: application/json; charset=utf-8');

    $search = isset($_GET['search']) ? trim($_GET['search']) : '';
    $page = isset($_GET['page']) ? intval($_GET['page']) : 1;
    $page_size = isset($_GET['page_size']) ? intval($_GET['page_size']) : 30;
    $category_id = 0;
    $exclude_id = isset($_GET['exclude_id']) ? intval($_GET['exclude_id']) : 0;

    if ($page < 1) $page = 1;
    if ($page_size < 1) $page_size = 30;
    if ($page_size > 1000) $page_size = 1000;

    $offset = ($page - 1) * $page_size;

    $total_goods = getTotalGoods($search, $category_id, $exclude_id);
    $total_pages = $total_goods > 0 ? ceil($total_goods / $page_size) : 1;

    $goods = getGoods($page_size, $offset, $search, $category_id, $exclude_id);
    $categories = getCategories();

    // 处理商品数据
    $goods_data = [];
    foreach ($goods as $item) {
        $goods_data[] = [
            'id' => $item['id'],
            'title' => $item['title'],
            'image' => isset($item['image']) ? $item['image'] : '',
            'price' => $item['price'],
            'stock' => $item['stock'],
            'sales' => isset($item['sales']) ? $item['sales'] : 0,
            'status' => $item['status'],
            'category_id' => $item['category_id'],
            'create_time' => isset($item['create_time']) ? $item['create_time'] : ''
        ];
    }

    $categories_data = [];
    foreach ($categories as $cat) {
        $categories_data[] = [
            'id' => $cat['id'],
            'name' => $cat['name']
        ];
    }

    echo json_encode([
        'success' => true,
        'data' => [
            'goods' => $goods_data,
            'categories' => $categories_data,
            'total_pages' => $total_pages,
            'total' => $total_goods,
            'current_page' => $page,
            'page_size' => $page_size
        ]
    ]);
    exit;
}

// 获取商品信息
if (isset($_GET['action']) && $_GET['action'] === 'get_goods_info') {
    header('Content-Type: application/json; charset=utf-8');
    $goodsId = isset($_GET['id']) ? $_GET['id'] : '';
    $goodsIds = isset($_GET['ids']) ? $_GET['ids'] : '';

    global $conn;

    // 批量获取模式
    if (!empty($goodsIds)) {
        $ids = explode(',', $goodsIds);
        $ids = array_filter($ids, function ($id) {
            return is_numeric($id);
        });

        if (!empty($ids)) {
            $placeholders = implode(',', array_fill(0, count($ids), '?'));
            $sql = "SELECT id, title, image FROM goods WHERE id IN ($placeholders)";
            $result = execute_query($conn, $sql, $ids);

            $goods = array();
            if ($result !== false) {
                while ($row = $result->fetch_assoc()) {
                    $goods[] = $row;
                }
                $result->close();
            }

            echo json_encode(array(
                'success' => true,
                'data' => $goods
            ));
            exit;
        }
    }

    // 单个获取模式
    if (!empty($goodsId)) {
        $sql = "SELECT id, title, image FROM goods WHERE id = ?";
        $result = execute_query($conn, $sql, array($goodsId));
        if ($result !== false && $result->num_rows > 0) {
            $good = $result->fetch_assoc();
            $result->close();
            echo json_encode(array(
                'success' => true,
                'data' => $good
            ));
            exit;
        }
    }

    echo json_encode(array(
        'success' => false,
        'message' => '商品不存在'
    ));
    exit;
}

// 从GET中获取参数
$action = '';
$goodsId = '';

// 支持新的URL格式：edit_id{id} 和 add
foreach ($_GET as $key => $value) {
    if (strpos($key, 'edit_id') === 0) {
        $action = 'edit';
        $goodsId = substr($key, 7); // 去掉 'edit_id' 前缀
        break;
    } elseif ($key === 'add') {
        $action = 'add';
        break;
    }
}

// 向后兼容旧的URL格式
if (empty($action)) {
    $action = isset($_GET['action']) ? $_GET['action'] : (isset($_SESSION['goodsAction']) ? $_SESSION['goodsAction'] : '');
    $goodsId = isset($_GET['id']) ? $_GET['id'] : (isset($_SESSION['goodsId']) ? $_SESSION['goodsId'] : '');
}

// 无论如何都清空SESSION中的参数，确保它们只在当前请求中使用一次
if (isset($_SESSION['goodsAction'])) {
    unset($_SESSION['goodsAction']);
}
if (isset($_SESSION['goodsId'])) {
    unset($_SESSION['goodsId']);
}

// 设置显示表单的条件
$show_form = $action === 'add' || $action === 'edit' || $action === 'update';

// 如果是编辑商品，确保goodsId存在
if ($action === 'edit' && empty($goodsId)) {
    $action = '';
    $show_form = false;
}

// 获取商品列表数据
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$current_page = 1;
$goods_per_page = 30;
$category_id = 0;

// 优先解析新的简洁格式
foreach ($_GET as $key => $value) {
    // 解析页码、每页显示数量：p{page}_s{per_page}
    if (preg_match('/^p(\d+)_s(\d+)$/', $key, $matches)) {
        $current_page = intval($matches[1]);
        $goods_per_page = intval($matches[2]);
    }
}

// 向后兼容，支持旧格式
if (isset($_GET['page'])) {
    $current_page = intval($_GET['page']);
}
if (isset($_GET['goods_per_page'])) {
    $goods_per_page = intval($_GET['goods_per_page']);
}
if (isset($_GET['category_id'])) {
    $category_id = intval($_GET['category_id']);
}

if ($goods_per_page < 1) $goods_per_page = 1;
if ($goods_per_page > 1000) $goods_per_page = 1000;
$offset = ($current_page - 1) * $goods_per_page;

// 获取商品总数和列表
$total_goods = getTotalGoods($search, $category_id);
$total_pages = $total_goods > 0 ? ceil($total_goods / $goods_per_page) : 1;
if ($current_page < 1) $current_page = 1;
if ($current_page > $total_pages) $current_page = $total_pages;
$goods = getGoods($goods_per_page, $offset, $search, $category_id);

// 获取分类列表
$categories = getCategories();

// 获取商品属性
$properties = getGoodsProperties();

// 输出商品管理页面内容
?>

<style>
    .sp001 {
        width: 120px;
        height: 39px;
        white-space: nowrap;
        background-color: #fff;
        border-color: var(--primary-color);
        color: var(--primary-color);
        border: 1px solid var(--primary-color);
        box-shadow: 0 0 0 rgba(0, 0, 0, 0.1);
    }

    .sp001:hover {

        background-color: #fff;


    }

    /* 统一的输入框按钮样式 */
    .input-button {
        display: inline-flex;
        align-items: center;
        gap: 4px;
        padding: 4px 8px;
        border: 1px solid #ddd;
        border-radius: 4px;
        background-color: #f8f9fa;
        font-size: 12px;
        cursor: pointer;
        position: relative;
        transition: all 0.2s ease;
    }

    .input-button:hover {
        background: #e9ecef;
        border-color: #adb5bd;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
        transform: translateY(-1px);
    }

    .input-button span {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }

    /* 删除按钮样式 */
    .delete-btn {
        position: absolute;
        top: -6px;
        right: -6px;
        background: #e0e0e0;
        color: #666;
        border-radius: 50%;
        width: 16px;
        height: 16px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 12px;
        cursor: pointer;
        font-weight: bold;
        box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
        transition: all 0.2s ease;
    }

    .delete-btn:hover {
        background: #ff4d4f;
        color: white;
    }

    /* 绑定商品作为规格属性列表样式 */
    .admin-table.goods-select-table {
        table-layout: fixed !important;
    }

    .admin-table.goods-select-table tr {
        height: 55px !important;
        min-height: 55px !important;
    }

    .admin-table.goods-select-table th:first-child,
    .admin-table.goods-select-table td:first-child {
        width: 60px !important;
        min-width: 60px !important;
        max-width: 60px !important;
        text-align: center !important;
    }

    .admin-table.goods-select-table th:nth-child(2),
    .admin-table.goods-select-table td:nth-child(2) {
        width: 60px !important;
        min-width: 60px !important;
        max-width: 60px !important;
        text-align: center !important;
    }

    .admin-table.goods-select-table th:nth-child(3),
    .admin-table.goods-select-table td:nth-child(3) {
        width: 300px !important;
        min-width: 300px !important;
        max-width: 300px !important;
        overflow: hidden !important;
        text-overflow: ellipsis !important;
        white-space: nowrap !important;
    }

    .admin-table.goods-select-table th:last-child,
    .admin-table.goods-select-table td:last-child {
        position: relative !important;
        left: -20px !important;
    }

    .admin-table.goods-select-table th,
    .admin-table.goods-select-table td {
        padding: 8px 12px !important;
        border-bottom: 1px solid #ddd !important;
        vertical-align: middle !important;
    }

    .admin-table.goods-select-table th {
        background-color: #f5f5f5 !important;
        font-weight: 600 !important;
    }

    .admin-table.goods-select-table tr:hover {
        background-color: #f9f9f9 !important;
    }
</style>

<style>
    /* 列表右上角按钮样式 */
    .section-header-mobile-btn {
        width: 128px;
    }

    #batch-operation-btn,
    .section-header a.section-header-mobile-btn.btn-primary {
        margin-left: 0 !important;
        margin-right: 0 !important;
    }
    
    /* 列表右上角按钮手机端样式 - 使用更高优先级覆盖admin.css */
    @media (max-width: 768px) {
        .section-header .section-header-mobile-btn,
        .section-header .btn-danger.section-header-mobile-btn,
        .section-header .btn-primary.section-header-mobile-btn {
            width: 38px !important;
            height: 38px !important;
            min-width: 38px !important;
            padding: 0 !important;
            margin-left: 6px !important;
            line-height: 38px !important;
        }
        .section-header-mobile-btn .section-header-btn-text {
            display: none !important;
        }
        .section-header-mobile-btn .section-header-btn-icon {
            margin-right: 0 !important;
        }
    }
</style>
<?php if (!$show_form): ?>
    <div class="section-header" style="display: flex; align-items: center; justify-content: space-between;">
        <h2>商品管理</h2>
        <div style="display: flex; align-items: center; gap: 10px;">
            <button id="batch-operation-btn" class="btn btn-danger action-button section-header-mobile-btn" style="margin-right: 0; display: inline-flex; align-items: center; justify-content: center;">
                <svg class="section-header-btn-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round" style="margin-right: 6px;">
                    <rect x="3" y="3" width="7" height="7" rx="1"></rect>
                    <rect x="14" y="3" width="7" height="7" rx="1"></rect>
                    <rect x="14" y="14" width="7" height="7" rx="1"></rect>
                    <rect x="3" y="14" width="7" height="7" rx="1"></rect>
                </svg>
                <span class="section-header-btn-text">批量操作</span>
            </button>
            <a href="?tab=adgoods&add" class="btn btn-primary action-button section-header-mobile-btn" style="display: inline-flex; align-items: center; justify-content: center;">
                <svg class="section-header-btn-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" style="margin-right: 6px;">
                    <circle cx="12" cy="12" r="10"></circle>
                    <line x1="12" y1="8" x2="12" y2="16"></line>
                    <line x1="8" y1="12" x2="16" y2="12"></line>
                </svg>
                <span class="section-header-btn-text">发布新商品</span>
            </a>
        </div>
    </div>


    <style>
        /* 商品列表样式，与文章列表保持一致 */
        .admin-table.section-manage th:first-child,
        .admin-table.section-manage td:first-child {
            width: 70px !important;
            min-width: 70px !important;
            max-width: 70px !important;
        }

        .admin-table.section-manage th:nth-child(2),
        .admin-table.section-manage td:nth-child(2) {
            width: 80px;
            min-width: 80px;
        }

        .admin-table.section-manage th:nth-child(3),
        .admin-table.section-manage td:nth-child(3) {
            width: 100px !important;
            min-width: 100px !important;
        }

        .admin-table.section-manage th:nth-child(4),
        .admin-table.section-manage td:nth-child(4) {
            width: 250px;
            min-width: 250px;
        }

        .admin-table.section-manage .goods-title-cell {
            white-space: nowrap !important;
            overflow: hidden !important;
            text-overflow: ellipsis !important;
        }

        .admin-table.section-manage .goods-title-cell .goods-title-display[data-qk-tip] {
            display: inline;
            line-height: 1.4 !important;
            vertical-align: middle;
            cursor: default;
        }

        .admin-table.section-manage th:nth-child(5),
        .admin-table.section-manage td:nth-child(5) {
            width: 130px;
            min-width: 130px;
        }

        .admin-table.section-manage th:nth-child(6),
        .admin-table.section-manage td:nth-child(6) {
            width: 110px;
            min-width: 110px;
        }

        .admin-table.section-manage th:nth-child(7),
        .admin-table.section-manage td:nth-child(7) {
            width: 80px;
            min-width: 80px;
        }

        .admin-table.section-manage th:nth-child(8),
        .admin-table.section-manage td:nth-child(8) {
            width: 80px;
            min-width: 80px;
        }

        .admin-table.section-manage th:nth-child(9),
        .admin-table.section-manage td:nth-child(9) {
            width: 160px;
            min-width: 160px;
        }

        .admin-table.section-manage th:last-child,
        .admin-table.section-manage td:last-child {
            width: 190px;
        }

        /* 固定操作列 */
        .admin-table.section-manage th.fixed-action-column,
        .admin-table.section-manage td.fixed-action-column {
            position: sticky;
            right: 0;
            background-color: #fff;
            z-index: 10;
            min-width: 150px;
            box-shadow: -2px 0 4px rgba(0, 0, 0, 0.1);
        }

        /* 表头固定操作列 */
        .admin-table.section-manage th.fixed-action-column {
            z-index: 11;
            background-color: #f8f9fa;
        }

        /* 悬停样式 */
        .admin-table.section-manage tr:hover th.fixed-action-column,
        .admin-table.section-manage tr:hover td.fixed-action-column {
            background-color: #f9fafb !important;
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08), -2px 0 4px rgba(0, 0, 0, 0.1);
            z-index: 100;
        }

        /* 手机端取消操作列固定 */
        @media (max-width: 768px) {
            .admin-table.section-manage {
                min-width: 1200px !important;
            }
            .admin-table.section-manage th.fixed-action-column,
            .admin-table.section-manage td.fixed-action-column {
                position: static !important;
                right: auto !important;
                left: auto !important;
                z-index: auto !important;
                background: transparent !important;
                box-shadow: none !important;
                min-width: auto !important;
                width: auto !important;
                display: table-cell !important;
            }
            .admin-table.section-manage th.fixed-action-column,
            .admin-table.section-manage td.fixed-action-column {
                width: 240px !important;
                min-width: 240px !important;
                padding-left: 8px !important;
                padding-right: 8px !important;
                white-space: nowrap !important;
                overflow: visible !important;
                text-overflow: clip !important;
            }
        }


        /* 表格容器样式 */
        .admin-table-wrapper {
            width: 100%;
            overflow-x: auto;
            margin-bottom: 0px;
        }

        .admin-table-scroll {
            scrollbar-width: none;
            -ms-overflow-style: none;
            position: relative;
            width: auto;
            min-width: 100%;
        }

        .admin-table-scroll::-webkit-scrollbar {
            display: none;
        }

        /* 状态下拉框宽度 */
        .admin-table.section-manage td .status-select {
            width: 70px !important;
        }

        /* 分页样式 */
        .pagination-container {
            margin-top: 20px;
            display: flex;
            justify-content: center;
        }

        .pagination-wrapper {
            display: flex;
            align-items: center;
            gap: 20px;
        }

        .pagination-buttons {
            display: flex;
            align-items: center;
            gap: 5px;
        }

        .pagination-btn.disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        .pagination-btn.disabled:hover {
            border-color: #ddd;
            color: #333;
        }

        .pagination-select {
            padding: 6px 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin: 0 5px;
        }

        .posts-per-page-select,
        .category-filter-select {
            padding: 4px 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }

        /* 自定义小按钮样式 */
        .btn-small {
            display: inline-block;
            vertical-align: middle;
            padding: 4px 8px;
            font-size: 14px;
            line-height: 1.5;
            border-radius: 4px;
            border: 1px solid transparent;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .btn-small.btn-primary {
            color: #fff;
            background-color: #007bff;
            border-color: #007bff;
        }

        .btn-small.btn-primary:hover {
            background-color: #0069d9;
            border-color: #0062cc;
        }

        .btn-small.btn-danger {
            color: #fff;
            background-color: #dc3545;
            border-color: #dc3545;
        }

        .btn-small.btn-danger:hover {
            background-color: #c82333;
            border-color: #bd2130;
        }

        .btn-small.btn-secondary {
            color: #fff;
            background-color: #6c757d;
            border-color: #6c757d;
        }

        .btn-small.btn-secondary:hover {
            background-color: #5a6268;
            border-color: #545b62;
        }
    </style>

    <div class="admin-card">
        <div class="table-container">
            <div class="admin-table-wrapper">
                <div class="admin-table-scroll">
                    <table class="admin-table section-manage">
                        <thead>
                            <tr>
                                <th style="width: 40px;">
                                    <input type="checkbox" id="select-all-header" class="form-checkbox" style="width: 18px; height: 18px;">
                                </th>
                                <th>ID</th>
                                <th>缩略图</th>
                                <th>商品名称</th>
                                <th>状态</th>
                                <th>价格</th>
                                <th>销量</th>
                                <th>库存</th>
                                <th>所属分类</th>
                                <th>发布时间</th>
                                <th class="fixed-action-column">操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($goods)): ?>
                                <?php foreach ($goods as $good): ?>
                                    <tr data-id="<?php echo $good['id']; ?>">
                                        <td style="width: 40px;">
                                            <input type="checkbox" class="item-checkbox" value="<?php echo $good['id']; ?>" style="width: 18px; height: 18px;">
                                        </td>
                                        <td><?php echo $good['id']; ?></td>
                                        <td style="display: flex; align-items: center; justify-content: center;">
                                            <?php
                                            // 处理商品缩略图，检查本地文件是否存在
                                            $thumbnail_url = $good['image'];
                                            if (!empty($thumbnail_url)) {
                                                // 提取第一张图片作为缩略图
                                                if (strpos($thumbnail_url, '|') !== false) {
                                                    $thumbnail_url = explode('|', $thumbnail_url)[0];
                                                }
                                                // 检查是否是云端图片（外部URL）
                                                if (strpos($thumbnail_url, '://') !== false) {
                                                    // 云端图片，直接使用，不进行本地文件检查
                                                } else {
                                                    // 本地图片，检查文件是否存在
                                                    $relative_path = $thumbnail_url;
                                                    $local_path = $_SERVER['DOCUMENT_ROOT'] . $relative_path;
                                                    if (!file_exists($local_path)) {
                                                        // 文件不存在，使用默认缩略图
                                                        $thumbnail_url = DEFAULT_THUMBNAIL_PATH;
                                                    }
                                                }
                                            }

                                            if (!empty($thumbnail_url)): ?>
                                                <img src="<?php echo escape($thumbnail_url); ?>" alt="<?php echo escape($good['title']); ?>" style="width: 60px; height: 45px; object-fit: cover; border-radius: 4px; cursor: pointer;" onclick="replaceListThumbnail(<?php echo $good['id']; ?>, this)">
                                            <?php else: ?>
                                                <img src="<?php echo DEFAULT_THUMBNAIL_PATH; ?>" alt="默认图片" style="width: 60px; height: 45px; object-fit: cover; border-radius: 4px; cursor: pointer;" onclick="replaceListThumbnail(<?php echo $good['id']; ?>, this)">
                                            <?php endif; ?>
                                        </td>
                                        <td class="goods-title-cell" data-goods-id="<?php echo $good['id']; ?>">
                                            <span class="goods-title-display" ondblclick="editGoodsTitle(<?php echo $good['id']; ?>)" data-qk-tip="<?php echo escape($good['title']); ?>" data-original-title="<?php echo escape($good['title']); ?>">
                                                <?php echo escape($good['title']); ?>
                                            </span>
                                            <input type="text" class="goods-title-input" style="display:none; width: 100%; padding: 4px; font-size: 13px; border: 1px solid var(--primary-color); outline: none; border-radius: 4px;"
                                                value="<?php echo escape($good['title']); ?>"
                                                onblur="saveGoodsTitle(<?php echo $good['id']; ?>, this)"
                                                onkeydown="if(event.key==='Enter'){this.blur();}if(event.key==='Escape'){cancelEditGoodsTitle(<?php echo $good['id']; ?>);}">
                                        </td>
                                        <td>
                                            <form method="post" class="inline-form">
                                                <input type="hidden" name="update_goods_status" value="1">
                                                <input type="hidden" name="goods_id" value="<?php echo $good['id']; ?>">
                                                <select name="status" data-previous-value="<?php echo $good['status']; ?>" onchange="updateGoodsStatus(this)" class="form-control status-select" style="margin-right: 15px; margin-left: -15px; width: auto;">
                                                    <option value="1" <?php echo $good['status'] == 1 ? 'selected' : ''; ?>>上架</option>
                                                    <option value="0" <?php echo $good['status'] == 0 ? 'selected' : ''; ?>>下架</option>
                                                </select>
                                            </form>
                                        </td>
                                        <td class="goods-price-cell" data-goods-id="<?php echo $good['id']; ?>">
                                            <span class="goods-price-display" ondblclick="editGoodsPrice(<?php echo $good['id']; ?>)" data-original-price="<?php echo $good['price']; ?>" style="color: #f96055; font-weight: 600;">
                                                ¥<?php echo number_format((float)$good['price'], 2); ?>
                                            </span>
                                            <input type="number" step="0.01" class="goods-price-input" style="display:none; width: 100px; padding: 4px; font-size: 13px; border: 1px solid var(--primary-color); outline: none; border-radius: 4px;"
                                                value="<?php echo $good['price']; ?>"
                                                onblur="saveGoodsPrice(<?php echo $good['id']; ?>, this)"
                                                onkeydown="if(event.key==='Enter'){this.blur();}if(event.key==='Escape'){cancelEditGoodsPrice(<?php echo $good['id']; ?>);}">
                                        </td>
                                        <td class="goods-sales-cell" data-goods-id="<?php echo $good['id']; ?>">
                                            <span class="goods-sales-display" ondblclick="editGoodsSales(<?php echo $good['id']; ?>)" data-original-sales="<?php echo isset($good['sales']) ? $good['sales'] : 0; ?>" style="color: #f59e0b; font-weight: 600;">
                                                <?php echo isset($good['sales']) ? $good['sales'] : 0; ?>
                                            </span>
                                            <input type="number" class="goods-sales-input" style="display:none; width: 80px; padding: 4px; font-size: 13px; border: 1px solid var(--primary-color); outline: none; border-radius: 4px;"
                                                value="<?php echo isset($good['sales']) ? $good['sales'] : 0; ?>"
                                                onblur="saveGoodsSales(<?php echo $good['id']; ?>, this)"
                                                onkeydown="if(event.key==='Enter'){this.blur();}if(event.key==='Escape'){cancelEditGoodsSales(<?php echo $good['id']; ?>);}">
                                        </td>
                                        <td class="goods-stock-cell" data-goods-id="<?php echo $good['id']; ?>">
                                            <span class="goods-stock-display" ondblclick="editGoodsStock(<?php echo $good['id']; ?>)" data-original-stock="<?php echo $good['stock']; ?>">
                                                <?php echo $good['stock']; ?>
                                            </span>
                                            <input type="number" class="goods-stock-input" style="display:none; width: 80px; padding: 4px; font-size: 13px; border: 1px solid var(--primary-color); outline: none; border-radius: 4px;"
                                                value="<?php echo $good['stock']; ?>"
                                                onblur="saveGoodsStock(<?php echo $good['id']; ?>, this)"
                                                onkeydown="if(event.key==='Enter'){this.blur();}if(event.key==='Escape'){cancelEditGoodsStock(<?php echo $good['id']; ?>);}">
                                        </td>
                                        <td>
                                            <form method="post" class="inline-form category-update-form">
                                                <input type="hidden" name="update_goods_category" value="1">
                                                <input type="hidden" name="goods_id" value="<?php echo $good['id']; ?>">
                                                <select name="category_id" data-previous-value="<?php echo $good['category_id']; ?>" onchange="updateGoodsCategory(this)" class="form-control category-select" style="margin-right: 15px; margin-left: -15px; width: auto;">
                                                    <option value="0">未分类</option>
                                                    <?php
                                                    $categories = getCategories();
                                                    foreach ($categories as $category) {
                                                        $selected = (isset($good['category_id']) && $good['category_id'] == $category['id']) ? 'selected' : '';
                                                        echo '<option value="' . $category['id'] . '" ' . $selected . '>' . escape($category['name']) . '</option>';
                                                    }
                                                    ?>
                                                </select>
                                            </form>
                                        </td>
                                        <td><?php echo date('Y-m-d', strtotime($good['create_time'])); ?></td>
                                        <td class="fixed-action-column">
                                            <a href="/goods_id<?php echo $good['id']; ?>.html" target="_blank" class="btn btn-sm btn-secondary">预览</a>
                                            <button type="button" class="btn btn-sm btn-primary edit-goods-btn" data-id="<?php echo $good['id']; ?>">编辑</button>
                                            <button type="button" class="btn btn-sm btn-danger" onclick="deleteGoodsItem(<?php echo $good['id']; ?>)">删除</button>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="10" style="text-align: center; padding: 60px 20px; color: #999;">
                                        <div>暂无商品数据</div>
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
                <!-- 自定义滚动条 -->
                <div class="counter-custom-scrollbar-container">
                    <div class="counter-custom-scrollbar-track">
                        <div class="counter-custom-scrollbar-thumb"></div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 批量操作模态框 -->
        <div id="batch-operation-modal" class="modal" style="display: none;">
            <div class="modal-backdrop"></div>
            <div class="modal-content" style="max-width: 500px; height: 450px; margin: 100px auto;">
                <div class="modal-header" style="display: flex; justify-content: space-between; align-items: center;>
                    <h3 class=" modal-title">批量操作</h3>
                    <button id="close-batch-modal" class="modal-close">&times;</button>
                </div>
                <div class="modal-body" style="padding: 40px;">
                    <div id="selected-count" style="margin-bottom: 20px; padding: 12px; background-color: #f8f9fa; border-radius: 4px; font-size: 14px; color: #666; border-left: 4px solid #007bff;">
                        当前已选择 <span id="count-number" style="font-weight: 600; color: #333;">0</span> 件商品
                    </div>
                    <div style="display: flex; flex-direction: column; gap: 15px;">
                        <div style="display: flex; align-items: center; gap: 10px;">
                            <select id="batch-category-select" class="form-control" style="width: 280px !important; min-width: 280px !important; height: 42px !important; padding: 8px 12px !important; padding-right: 26px !important; border: 1px solid #ddd !important; border-radius: 4px !important; box-sizing: border-box !important; background-image: url(data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath fill='none' stroke='%23000' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M3 6l5 5 5-5'/%3E%3C/svg%3E) !important; background-repeat: no-repeat !important; background-position: right 8px center !important; background-size: 14px !important; background-color: white !important;">
                                <option value="0">请选择分类</option>
                                <?php
                                $categories = getCategories();
                                foreach ($categories as $category) {
                                    echo '<option value="' . $category['id'] . '">' . escape($category['name']) . '</option>';
                                }
                                ?>
                            </select>
                            <button id="batch-move-btn" class="btn btn-primary" style="width: 130px !important; height: 42px !important;">批量移动商品</button>
                        </div>
                        <div style="display: flex; align-items: center; gap: 10px;">
                            <select id="batch-status-select" class="form-control" style="width: 280px !important; min-width: 280px !important; height: 42px !important; padding: 8px 12px !important; padding-right: 26px !important; border: 1px solid #ddd !important; border-radius: 4px !important; box-sizing: border-box !important; background-image: url(data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath fill='none' stroke='%23000' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M3 6l5 5 5-5'/%3E%3C/svg%3E) !important; background-repeat: no-repeat !important; background-position: right 8px center !important; background-size: 14px !important; background-color: white !important;">
                                <option value="-1">请选择状态</option>
                                <option value="1">上架</option>
                                <option value="0">下架</option>
                            </select>
                            <button id="batch-status-btn" class="btn btn-primary" style="width: 130px !important; height: 42px !important;">批量修改状态</button>
                        </div>
                        <div style="display: flex; align-items: center; gap: 10px;">
                            <input type="number" id="batch-stock-input" class="form-control" placeholder="请输入库存数量" min="0" style="width: 280px !important; min-width: 280px !important; height: 42px !important; padding: 8px 12px !important; border: 1px solid #ddd !important; border-radius: 4px !important; box-sizing: border-box !important;">
                            <button id="batch-stock-btn" class="btn btn-primary" style="width: 130px !important; height: 42px !important;">批量修改库存</button>
                        </div>
                        <div style="margin-top: 10px; text-align: right;">
                            <button id="batch-delete-btn" class="btn btn-danger" style="width: 130px !important; height: 42px !important;">批量删除</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

    </div>

<?php else: ?>
    <link rel="stylesheet" href="/assets/css/article.css">
    <link href="/assets/quill/quill.snow.css" rel="stylesheet">
    <style>
        /* 三个功能区横向排列容器 */
        .goods-features-container {
            display: flex;
            gap: 15px;
            padding: 0;
            margin-bottom: 15px;
        }

        .goods-features-container>div {
            width: calc((100% - 30px) / 3);
            flex: 0 0 calc((100% - 30px) / 3);
        }

        /* 单个功能区卡片 - 三等份布局 */
        .feature-card {
            width: 100%;
            background: white;
            border: 1px solid #d9d9d9;
            border-radius: 6px;
            padding: 10px;
            display: flex;
            flex-direction: column;
            gap: 0;
        }

        /* 商品缩略图区域 - 默认左对齐，6个时平均分 */
        #gallery-preview-new {
            display: flex;
            gap: 4px;
            padding: 5px 0;
            min-height: 55px;
            justify-content: flex-start;
            flex-wrap: nowrap;
            overflow: hidden;
            width: 100%;
            box-sizing: border-box;
        }

        #gallery-preview-new .feature-item {
            flex: 0 0 50px;
            height: 50px;
        }

        /* 5个或6个feature-item时都6等份 */
        #gallery-preview-new:has(.feature-item:nth-child(5)) .feature-item,
        #gallery-preview-new:has(.feature-item:nth-child(6)) .feature-item {
            flex: 0 0 50px;
            width: 50px;
            height: 50px;
        }

        /* 5个或6个feature-item时平均分布 */
        #gallery-preview-new:has(.feature-item:nth-child(5)),
        #gallery-preview-new:has(.feature-item:nth-child(6)) {
            justify-content: space-between;
        }

        /* 6个feature-item时隐藏添加按钮 */
        #gallery-preview-new:has(.feature-item:nth-child(6)) .add-item-btn {
            display: none !important;
        }

        /* 绑定商品区域 - 左对齐 */
        #goods-tags-area {
            display: flex;
            gap: 4px;
            padding: 5px 0;
            min-height: 55px;
            justify-content: flex-start;
            flex-wrap: nowrap;
            overflow: hidden;
            width: 100%;
            box-sizing: border-box;
        }

        #goods-tags-area .feature-item {
            flex: 0 0 50px;
            height: 50px;
        }

        /* 5个或6个feature-item时都6等份 */
        #goods-tags-area:has(.feature-item:nth-child(5)) .feature-item,
        #goods-tags-area:has(.feature-item:nth-child(6)) .feature-item {
            flex: 0 0 50px;
            width: 50px;
            height: 50px;
        }

        /* 5个或6个feature-item时平均分布 */
        #goods-tags-area:has(.feature-item:nth-child(5)),
        #goods-tags-area:has(.feature-item:nth-child(6)) {
            justify-content: space-between;
        }

        /* 6个feature-item时隐藏添加按钮 */
        #goods-tags-area:has(.feature-item:nth-child(6)) .add-item-btn {
            display: none !important;
        }

        /* 规格属性区域 - 不支持横向滚动，最多显示6个 */
        #specs-tags-area {
            display: flex;
            gap: 4px;
            padding: 5px 0;
            min-height: 55px;
            justify-content: flex-start;
            flex-wrap: nowrap;
            overflow: hidden;
            width: 100%;
            box-sizing: border-box;
        }

        /* 确保规格属性区域最多显示6个项目 */
        #specs-tags-area .feature-item:nth-child(n+7) {
            display: none;
        }

        /* 当有6个或更多规格时，隐藏添加按钮 */
        #specs-tags-area:has(.feature-item:nth-child(6)) .add-item-btn {
            display: none !important;
        }

        #specs-tags-area .feature-item {
            flex: 0 0 50px;
            height: 50px;
        }

        /* 6个feature-item时6等份 */
        #specs-tags-area:has(.feature-item:nth-child(6)):not(:has(.feature-item:nth-child(7))) .feature-item {
            flex: 0 0 50px;
            width: 50px;
            height: 50px;
        }

        /* 5个feature-item时6等份 */
        #specs-tags-area:has(.feature-item:nth-child(5)):not(:has(.feature-item:nth-child(6))) .feature-item {
            flex: 0 0 50px;
            width: 50px;
            height: 50px;
        }

        /* 5个或6个feature-item时平均分布 */
        #specs-tags-area:has(.feature-item:nth-child(5)):not(:has(.feature-item:nth-child(7))) {
            justify-content: space-between;
            gap: 0;
        }

        /* 空提示文字 */
        .empty-tip {
            color: #bbb;
            font-size: 16px;
            font-weight: 500;
            display: flex;
            align-items: center;
            justify-content: center;
            flex: 1;
            height: 50px;
            margin-right: 20px;
        }

        /* 统一的缩略图项 */
        .feature-item {
            position: relative;
            flex: 0 0 50px;
            height: 50px;
            border-radius: 50%;
            overflow: visible;
            cursor: pointer;
        }

        .feature-item img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            border-radius: 50%;
            filter: grayscale(100%);
            opacity: 0.7;
            transition: all 0.3s ease;
        }

        .feature-item:hover img {
            filter: grayscale(0%);
            opacity: 1;
        }

        .feature-item .delete-btn {
            position: absolute;
            top: -4px;
            right: -4px;
            width: 18px;
            height: 18px;
            background: rgba(255, 77, 79, 0.9);
            color: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 14px;
            font-weight: bold;
            cursor: pointer;
            line-height: 1;
            z-index: 10001;
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.4);
            transition: all 0.2s ease;
            border: 2px solid #fff;
            opacity: 0;
            visibility: hidden;
            pointer-events: auto;
        }

        .feature-item:hover .delete-btn {
            opacity: 1;
            visibility: visible;
        }

        .feature-item .delete-btn:hover {
            background: #ff7875;
            transform: scale(1.15);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.5);
        }

        /* 上传进度动画 */
        .feature-item.upload-progress {
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: #f0f0f0;
            border-radius: 50%;
            overflow: hidden;
            position: relative;
        }

        .upload-spinner {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            width: 100%;
            height: 100%;
            position: relative;
            z-index: 1;
        }

        .progress-ring {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: 0;
        }

        .progress-ring-circle {
            fill: none;
            stroke: #e0e0e0;
            stroke-width: 2;
        }

        .progress-ring-progress {
            fill: none;
            stroke: var(--primary-color);
            stroke-width: 2;
            stroke-linecap: round;
            transform: rotate(-90deg);
            transform-origin: 50% 50%;
            transition: stroke-dashoffset 0.3s ease;
        }

        .progress-text {
            font-size: 10px;
            color: #666;
            text-align: center;
            line-height: 1.2;
            z-index: 1;
        }

        /* 悬停大图预览 */
        .feature-item.has-preview:hover::after {
            content: '';
            position: fixed;
            width: 280px;
            height: 280px;
            background-image: var(--preview-image);
            background-size: cover;
            background-position: center;
            border-radius: 4px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
            z-index: 9999;
            pointer-events: none;
            left: var(--preview-left, 0);
            top: var(--preview-top, 0);
        }

        /* 箭头向上（预览在下方） */
        .feature-item.has-preview[style*="--arrow-direction: down"]:hover::before {
            content: '';
            position: fixed;
            width: 0;
            height: 0;
            border-style: solid;
            border-width: 0 10px 10px 10px;
            border-color: transparent transparent rgba(0, 0, 0, 0.3) transparent;
            z-index: 10000;
            pointer-events: none;
            left: var(--arrow-left, 0);
            top: var(--arrow-top, 0);
        }

        /* 箭头向下（预览在上方） */
        .feature-item.has-preview[style*="--arrow-direction: up"]:hover::before {
            content: '';
            position: fixed;
            width: 0;
            height: 0;
            border-style: solid;
            border-width: 10px 10px 0 10px;
            border-color: rgba(0, 0, 0, 0.3) transparent transparent transparent;
            z-index: 10000;
            pointer-events: none;
            left: var(--arrow-left, 0);
            top: var(--arrow-top, 0);
        }

        /* 圆形添加按钮 */
        .add-item-btn {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background-color: #f5f5f5;
            border: 2px dashed #ccc;
            color: #999;
            font-size: 24px;
            font-weight: bold;
            cursor: pointer;
            display: flex !important;
            align-items: center;
            justify-content: center;
            transition: all 0.2s ease;
            flex-shrink: 0;
            box-sizing: border-box;
            padding: 0;
            line-height: 1;
        }

        .add-item-btn:hover {
            background-color: #fff;
            border-color: var(--primary-color);
            color: var(--primary-color);
            border-style: solid;
        }

        /* 移动端自适应布局 */
        @media (max-width: 768px) {

            /* 商品标题和卖点描述在移动端各占一行 */
            .form-row:first-child {
                grid-template-columns: 1fr !important;
            }

            .form-row:first-child .form-group {
                margin-bottom: 15px !important;
            }

            /* 商品关键词和其他信息的布局 */
            .form-row:nth-child(2) {
                grid-template-columns: 1fr !important;
            }

            .form-row:nth-child(2) .form-group {
                margin-bottom: 15px !important;
            }

            .form-row:nth-child(2)>div:nth-child(2) {
                display: grid !important;
                grid-template-columns: 1fr 1fr !important;
                gap: 10px !important;
            }

            .form-row:nth-child(2)>div:nth-child(2)>div {
                grid-column: auto !important;
                margin-bottom: 15px !important;
            }

            /* 三个功能区在移动端垂直排列 */
            .goods-features-container {
                flex-direction: column;
                overflow-x: visible;
            }

            .goods-features-container>div {
                width: 100%;
                flex: 0 0 100%;
            }

            .feature-card {
                width: 100%;
            }

            /* 将编辑表单的网格在手机端改为纵向堆叠，每个字段独占一行 */
            #goods-form>div[style*="grid-template-columns"] {
                display: block !important;
            }

            #goods-form>div[style*="grid-template-columns"]>div {
                display: block !important;
                width: 100% !important;
                margin-bottom: 12px !important;
            }

            #goods-form>div[style*="grid-template-columns"]>div[style*="grid-template-columns"] {
                display: block !important;
            }

            #goods-form>div[style*="grid-template-columns"]>div[style*="grid-template-columns"]>div {
                display: block !important;
                width: 100% !important;
                margin-bottom: 12px !important;
            }

            #goods-form select,
            #goods-form input[type="text"],
            #goods-form input[type="number"] {
                width: 100% !important;
                box-sizing: border-box !important;
            }
        }
    </style>
    <script src="/assets/quill/quill.min.js"></script>
    <div class="section-header">
        <h2><?php echo $action === 'edit' ? '编辑商品' : '发布新商品'; ?></h2>
    </div>

    <div class="admin-card">
        <div id="goods-form-container">
            <form id="goods-form" name="goods-form" method="post" enctype="multipart/form-data" action="adgoods.php">
                <?php if ($action === 'edit'): ?>
                    <input type="hidden" name="goods_id" value="<?php echo intval($goodsId); ?>">
                    <?php
                    $edit_goods = null;
                    global $conn;
                    $sql = "SELECT * FROM goods WHERE id = ?";
                    $result = execute_query($conn, $sql, array($goodsId));
                    if ($result !== false) {
                        $edit_goods = $result->fetch_assoc();
                        $result->close();
                    }
                    ?>
                <?php endif; ?>

                <!-- 商品基本信息 -->
                <!-- 第1行：商品标题（2/3） + 分类、价格（1/3对半分） -->
                <div style="display: grid; grid-template-columns: 2fr 1fr; gap: 10px; margin-bottom: 15px; box-sizing: border-box;">
                    <div>
                        <label for="title" style="display: block; margin-bottom: 5px; font-weight: 500; color: #2c3e50; font-size: 14px;">商品标题</label>
                        <input type="text" id="title" name="title" class="form-control" placeholder="请输入商品标题" value="<?php echo isset($edit_goods) ? escape($edit_goods['title']) : ''; ?>" required style="width: 100%; box-sizing: border-box;">
                    </div>
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
                        <div>
                            <label for="category_id" style="display: block; margin-bottom: 5px; font-weight: 500; color: #2c3e50; font-size: 14px;">分类</label>
                            <select id="category_id" name="category_id" class="form-control" style="height: 39px; width: 100%; box-sizing: border-box;">
                                <?php
                                $categories = getCategories();
                                foreach ($categories as $category):
                                ?>
                                    <option value="<?php echo $category['id']; ?>" <?php echo (isset($edit_goods) && $edit_goods['category_id'] == $category['id']) ? 'selected' : ''; ?>> <?php echo escape($category['name']); ?> </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div>
                            <label for="price" style="display: block; margin-bottom: 5px; font-weight: 500; color: #2c3e50; font-size: 14px;">价格</label>
                            <input type="number" id="price" name="price" class="form-control" placeholder="0.00" value="<?php echo isset($edit_goods) ? $edit_goods['price'] : '0'; ?>" min="0" step="0.01" style="width: 100%; box-sizing: border-box;">
                        </div>
                    </div>
                </div>

                <!-- 第2行：关键词（2/3） + 库存、销量（1/3对半分） -->
                <div style="display: grid; grid-template-columns: 2fr 1fr; gap: 10px; margin-bottom: 15px; box-sizing: border-box;">
                    <div>
                        <label for="keywords" style="display: block; margin-bottom: 5px; font-weight: 500; color: #2c3e50; font-size: 14px;">商品关键词</label>
                        <input type="text" id="keywords" name="keywords" class="form-control" placeholder="用逗号分隔" value="<?php echo isset($edit_goods) ? escape($edit_goods['keywords']) : ''; ?>" style="width: 100%; box-sizing: border-box;">
                    </div>
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
                        <div>
                            <label for="stock" style="display: block; margin-bottom: 5px; font-weight: 500; color: #2c3e50; font-size: 14px;">库存</label>
                            <input type="number" id="stock" name="stock" class="form-control" placeholder="99" value="<?php echo isset($edit_goods) ? $edit_goods['stock'] : '99'; ?>" min="0" style="width: 100%; box-sizing: border-box;">
                        </div>
                        <div>
                            <label for="sales" style="display: block; margin-bottom: 5px; font-weight: 500; color: #2c3e50; font-size: 14px;">销量</label>
                            <input type="number" id="sales" name="sales" class="form-control" placeholder="0" value="<?php echo isset($edit_goods) ? (isset($edit_goods['sales']) ? $edit_goods['sales'] : '0') : rand(1, 10); ?>" min="0" style="width: 100%; box-sizing: border-box;">
                        </div>
                    </div>
                </div>

                <!-- 视频URL和模板绑定 -->
                <div style="display: grid; grid-template-columns: 2fr 1fr; gap: 10px; margin-bottom: 15px; box-sizing: border-box;">
                    <div>
                        <label for="mp4url" style="display: block; margin-bottom: 5px; font-weight: 500; color: #2c3e50; font-size: 14px;">商品视频URL</label>
                        <input type="text" id="mp4url" name="mp4url" class="form-control" placeholder="请输入视频URL" value="<?php echo isset($edit_goods) ? escape($edit_goods['mp4url']) : ''; ?>" style="width: 100%; box-sizing: border-box;">
                    </div>
                    <div>
                        <label for="template" style="display: block; margin-bottom: 5px; font-weight: 500; color: #2c3e50; font-size: 14px;">模板绑定</label>
                        <select id="template" name="template" class="form-control" style="height: 39px; width: 100%; box-sizing: border-box;">
                            <?php
                            $templates = getGoodsTemplates();
                            $currentTemplate = isset($edit_goods) ? $edit_goods['template'] : 'goods.php';
                            foreach ($templates as $templatePath => $templateName):
                            ?>
                                <option value="<?php echo $templatePath; ?>" <?php echo ($currentTemplate == $templatePath) ? 'selected' : ''; ?>><?php echo $templateName; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>

                <!-- 商品卖点描述 -->
                <div style="margin-bottom: 15px;">
                    <label for="description" style="display: block; margin-bottom: 5px; font-weight: 500; color: #2c3e50; font-size: 14px;">商品卖点描述</label>
                    <textarea id="description" name="description" class="form-control" placeholder="请输入商品卖点" style="width: 100%; box-sizing: border-box; height: 80px; resize: vertical;"><?php echo isset($edit_goods) ? escape($edit_goods['description']) : ''; ?></textarea>
                </div>

                <!-- 三个功能区横向排列 -->
                <div class="goods-features-container">
                    <!-- 商品缩略图 -->
                    <div>
                        <div style="margin-bottom: 5px; font-weight: 500; color: #2c3e50; font-size: 14px;">商品缩略图</div>
                        <div class="feature-card" style="min-height: 70px;">
                            <div id="gallery-preview-new" class="feature-content-area-fixed">
                                <?php
                                $image_count = 0;
                                if (isset($edit_goods) && !empty($edit_goods['image'])):
                                    $all_images = array();
                                    if (strpos($edit_goods['image'], '|') !== false) {
                                        $all_images = explode('|', $edit_goods['image']);
                                    } else {
                                        $all_images = array($edit_goods['image']);
                                    }
                                    usort($all_images, function ($a, $b) {
                                        $indexA = 0;
                                        $indexB = 0;
                                        if (preg_match('/thumbnail_(\d+)_/', basename($a), $matchesA)) {
                                            $indexA = intval($matchesA[1]);
                                        }
                                        if (preg_match('/thumbnail_(\d+)_/', basename($b), $matchesB)) {
                                            $indexB = intval($matchesB[1]);
                                        }
                                        return $indexA - $indexB;
                                    });
                                    $image_count = count($all_images);
                                    foreach ($all_images as $index => $image_url):
                                        $file_name = basename($image_url);
                                ?>
                                        <div class="feature-item" data-image-url="<?php echo $image_url; ?>">
                                            <img src="<?php echo $image_url; ?>" alt="商品缩略图">
                                            <span class="delete-btn">×</span>
                                            <input type="hidden" name="existing_images[]" value="<?php echo $image_url; ?>">
                                        </div>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                                <button type="button" class="add-item-btn" id="gallery-add-btn">+</button>
                                <span class="empty-tip" style="display: <?php echo ($image_count > 0) ? 'none' : 'flex'; ?>">无缩略图</span>
                            </div>
                            <input type="file" id="gallery" name="gallery[]" class="form-control-file" multiple accept="image/*" style="display: none;">
                        </div>
                    </div>

                    <!-- 绑定其他商品 -->
                    <div>
                        <div style="margin-bottom: 5px; font-weight: 500; color: #2c3e50; font-size: 14px;">绑定其他商品（可选）</div>
                        <div class="feature-card" style="min-height: 70px;">
                            <div id="goods-tags-area" class="feature-content-area-fixed">
                                <?php
                                $goods_count = 0;
                                if (isset($edit_goods) && !empty($edit_goods['parent_id']) && $edit_goods['parent_id'] !== '0'):
                                    $parent_ids = explode(',', $edit_goods['parent_id']);
                                    $parent_ids = array_filter($parent_ids, function ($id) {
                                        return is_numeric($id);
                                    });
                                    if (!empty($parent_ids)):
                                        global $conn;
                                        $placeholders = implode(',', array_fill(0, count($parent_ids), '?'));
                                        $sql = "SELECT id, title, image FROM goods WHERE id IN ($placeholders)";
                                        $result = execute_query($conn, $sql, $parent_ids);
                                        if ($result !== false):
                                            $goods_count = $result->num_rows;
                                            while ($good = $result->fetch_assoc()):
                                                $img = $good['image'];
                                                if (strpos($img, '|') !== false) {
                                                    $img = explode('|', $img)[0];
                                                }
                                                $img_url = $img && trim($img) !== '' && $img !== 'null' ? $img : DEFAULT_THUMBNAIL_PATH;
                                ?>
                                                <div class="feature-item" data-goods-id="<?php echo $good['id']; ?>" data-image="<?php echo htmlspecialchars($good['image'] ?? ''); ?>" title="<?php echo htmlspecialchars($good['title']); ?>">
                                                    <img src="<?php echo $img_url; ?>" alt="<?php echo htmlspecialchars($good['title']); ?>">
                                                    <span class="delete-btn">×</span>
                                                </div>
                                <?php
                                            endwhile;
                                            $result->close();
                                        endif;
                                    endif;
                                endif;
                                ?>
                                <button type="button" class="add-item-btn">+</button>
                                <span class="empty-tip" style="display: <?php echo ($goods_count > 0) ? 'none' : 'flex'; ?>">无绑定商品</span>
                            </div>
                            <input type="hidden" id="parent_id" name="parent_id" value="<?php echo isset($edit_goods) ? $edit_goods['parent_id'] : '0'; ?>">
                            <button type="button" id="select_parent_goods" style="display: none;">绑定商品</button>
                        </div>
                    </div>

                    <!-- 规格属性 -->
                    <div>
                        <div style="margin-bottom: 5px; font-weight: 500; color: #2c3e50; font-size: 14px;">规格属性（可选）</div>
                        <div class="feature-card" style="min-height: 70px;">
                            <div id="specs-tags-area" class="feature-content-area-scroll">
                                <?php
                                $spec_count = 0;
                                if (isset($edit_goods) && !empty($edit_goods['specs'])):
                                    $saved_specs = json_decode($edit_goods['specs'], true);
                                    if (!empty($saved_specs)):
                                        foreach ($saved_specs as $key => $spec):
                                            $spec_count++;
                                            $spec_name = $spec['name'] ?? '未命名';
                                            $spec_image = $spec['image'] ?? '';
                                            $img_url = $spec_image && trim($spec_image) !== '' ? $spec_image : DEFAULT_THUMBNAIL_PATH;
                                ?>
                                            <div class="feature-item" id="spec-btn-<?php echo $spec_count; ?>" data-spec-number="<?php echo $spec_count; ?>" data-spec-name="<?php echo htmlspecialchars($spec_name); ?>" title="<?php echo htmlspecialchars($spec_name); ?>">
                                                <img src="<?php echo $img_url; ?>" alt="<?php echo htmlspecialchars($spec_name); ?>">
                                                <span class="delete-btn">×</span>
                                            </div>
                                <?php
                                        endforeach;
                                    endif;
                                endif;
                                ?>
                                <button type="button" class="add-item-btn">+</button>
                                <?php
                                if ($spec_count === 0):
                                ?>
                                    <span class="empty-tip">无规格属性</span>
                                <?php endif; ?>
                            </div>
                            <div id="specs-container" style="display: none;">
                                <!-- 规格项将通过JavaScript动态添加 -->
                            </div>
                            <button type="button" id="add-spec-btn" style="display: none;">+ 添加规格</button>
                        </div>
                    </div>
                </div>

                <!-- 商品选择模态框 -->
                <div id="goods_select_modal" class="modal" style="display: none; z-index: 10000;">
                    <div class="modal-backdrop"></div>
                    <div class="modal-content" style="width: 800px; max-width: 90%; height: 580px; display: flex; flex-direction: column; ">
                        <div class="modal-header">
                            <h3 class="modal-title">绑定商品作为规格属性</h3>
                            <button type="button" class="modal-close">×</button>
                        </div>
                        <div class="modal-body" style="flex: 1; display: flex; flex-direction: column;    padding:30px;">
                            <div style="margin-bottom: 15px; display: flex; gap: 10px;">
                                <input type="text" id="goods_search" class="form-control" placeholder="搜索商品标题" style="flex: 1; box-sizing: border-box;">
                                <button type="button" class="btn btn-primary" style="white-space: nowrap;">搜索</button>
                            </div>
                            <div id="goods_list" style="flex: 1; overflow-y: auto;">
                                <!-- 商品列表将通过JavaScript动态加载 -->
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 规格添加模态弹窗 -->
                <div id="spec-modal" class="modal" style="display: none; z-index: 10000;">
                    <div class="modal-backdrop"></div>
                    <div class="modal-content" style="width:720px; max-width: 100%; height: 520px; display: flex; flex-direction: column;">
                        <div class="modal-header">
                            <h3 class="modal-title">添加规格</h3>
                            <button type="button" class="modal-close">×</button>
                        </div>
                        <div class="modal-body" style="flex: 1; display: flex; flex-direction: column; padding:30px;">
                            <div style="display: flex; justify-content: flex-start; gap: 10px; margin-bottom: 20px;">
                                <button type="button" class="btn btn-primary" style="padding: 8px 26px; background-color: var(--primary-color); border-color: var(--primary-color); color: white;">添加规格</button>
                                <button type="button" class="btn btn-primary" style="padding: 8px 26px; background-color: #1890ff; border-color: #1890ff; color: white;">保存规格</button>
                            </div>
                            <div id="spec-items-container" style="flex: 1; overflow-y: auto; border: 1px solid #ddd; border-radius: 4px; padding: 15px;">
                                <!-- 规格项将通过JavaScript动态添加 -->
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 商品详情 -->
                <div class="form-group" style="margin-bottom: 15px; box-sizing: border-box;">
                    <label for="content">商品详情</label>
                    <div class="editor-wrapper" style="border-radius:5px;">
                        <div id="quill-editor" style="height: 400px;"></div>
                    </div>
                    <textarea id="content" name="content" style="display: none;"><?php echo isset($edit_goods) ? escape($edit_goods['content']) : ''; ?></textarea>
                </div>

                <input type="hidden" name="form_mode" id="form_mode" value="<?php echo $action === 'edit' ? 'edit' : 'add'; ?>">
                <input type="hidden" name="goods_id" id="goods_id" value="<?php echo isset($edit_goods) ? $edit_goods['id'] : '' ?>">
                <!-- 操作按钮 -->
                <div class="form-actions" style="display: flex; gap: 10px; margin-top: 20px; justify-content: flex-start;">
                    <button type="submit" name="<?php echo $action === 'edit' ? 'update_goods' : 'publish_goods' ?>" id="submit-button" class="btn btn-primary" style="width: 100px;"><?php echo $action === 'edit' ? '更新商品' : '发布商品' ?></button>
                    <button type="button" id="preview-button" class="btn btn-primary ml-2" style="width: 70px;">预览</button>
                    <button type="button" id="cancel-button" class="btn btn-secondary ml-2" style="min-width: 70px; width: auto; white-space: nowrap;">取消</button>
                    <button type="button" id="continue-publish-button" class="btn btn-primary ml-2" style="display: none; min-width: 70px; width: auto; white-space: nowrap;">继续发布</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 视频插入模态框 -->
    <div id="videoInsertModal" class="modal">
        <div class="modal-backdrop"></div>
        <div class="modal-content" style="width: 450px; max-width: 450px; height: 510px; max-height: 510px;">
            <div class="modal-header">
                <h3 class="modal-title">视频属性</h3>
                <button type="button" class="modal-close">×</button>
            </div>
            <div class="modal-body" style="padding:32px;">
                <div class="form-group">
                    <label for="video-url">MP4视频地址</label>
                    <input type="text" id="video-url" placeholder="请输入MP4视频地址" class="form-control">
                </div>
                <div class="form-group">
                    <div style="display:flex;align-items:center;gap:20px;margin-bottom:10px;">
                        <div style="display:flex;align-items:center;gap:5px;">
                            <input type="checkbox" id="autoplay" style="margin:0;">
                            <label for="autoplay" style="margin:0;">自动播放</label>
                        </div>
                        <div style="display:flex;align-items:center;gap:5px;">
                            <input type="checkbox" id="videoPreserveAspectRatio" checked style="margin:0;">
                            <label for="videoPreserveAspectRatio" style="margin:0;">尺寸自适应</label>
                        </div>
                    </div>
                    <div style="display:flex;flex-direction:column;gap:10px;margin-bottom:10px;">
                        <div>
                            <label for="video-width">视频宽度</label>
                            <input type="number" id="video-width" value="790" min="100" max="1200" class="form-control">
                        </div>
                        <div>
                            <label for="video-height">视频高度</label>
                            <input type="number" id="video-height" value="550" min="100" max="800" class="form-control">
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-actions" style="padding:30px 32px 16px; border-top:1px solid #e0e0e0;display:flex;justify-content:flex-end;gap:10px; box-sizing: border-box;">
                <button type="button" class="btn btn-secondary">取消</button>
                <button type="button" class="btn btn-danger">删除</button>
                <button type="button" class="btn btn-primary">确认</button>
            </div>
        </div>
    </div>

    <!-- 图片属性修改模态框 -->
    <div id="imagePropertiesModal" class="modal">
        <div class="modal-backdrop"></div>
        <div class="modal-content" style="width: 420px; max-width: 420px;">
            <div class="modal-header" style="height:53px; line-height:53px">
                <h3 class="modal-title">图片属性</h3>
                <button type="button" id="closeModal" class="modal-close">&times;</button>
            </div>
            <div class="modal-body" style="padding-bottom:0px">
                <div class="form-group">
                    <label for="imageUrl">图片URL:</label>
                    <input type="text" id="imageUrl" placeholder="输入图片地址" class="form-control">
                </div>
                <div class="form-group">
                    <label for="imageWidth">宽度 (px):</label>
                    <input type="number" id="imageWidth" min="50" max="2000" class="form-control">
                </div>
                <div class="form-group">
                    <label for="imageHeight">高度 (px):</label>
                    <input type="number" id="imageHeight" min="50" max="2000" class="form-control">
                </div>
                <div class="form-group">
                    <label for="imageAlt">ALT 文本:</label>
                    <input type="text" id="imageAlt" placeholder="输入图片描述" class="form-control">
                </div>
            </div>
            <div class="modal-footer" style="display: flex; align-items: center; justify-content: space-between; padding-top:0px">
                <label style="margin: 0; display: flex; align-items: center;">
                    <input type="checkbox" id="preserveAspectRatio" checked style="margin-right: 8px; margin-left:13px">
                    保持宽高比
                </label>
                <div class="modal-actions" style="margin: 0; margin-right:8px; display:flex; gap:10px;">
                    <button type="button" id="cancelChanges" class="btn btn-secondary">取消</button>
                    <button type="button" id="applyChanges" class="btn btn-primary">应用</button>
                </div>
            </div>
        </div>
    </div>


<?php endif; ?>

<?php
// 为JavaScript准备的配置对象
$js_config = [
    'isEditMode' => isset($edit_goods),
    'savedSpecs' => (isset($edit_goods) && !empty($edit_goods['specs'])) ? json_decode($edit_goods['specs'], true) : new stdClass(),
    'pagination' => [
        'currentPage' => $current_page ?? 1,
        'pageSize' => $goods_per_page ?? 15,
        'totalGoods' => $total_goods ?? 0,
        'totalPages' => $total_pages ?? 1,
    ],
    'urls' => [
        'deleteGoods' => '/admin/admin.php?tab=adgoods&ajax=1&delete_goods=',
        'updateGoods' => '/admin/adgoods.php',
        'updateGoodsSelect' => '/admin/admin.php',
        'uploadImage' => '/admin/adgoods.php',
        'deleteImage' => '/admin/adgoods.php',
        'getGoodsList' => '/admin/adgoods.php?action=get_goods_list',
        'getGoodsInfo' => '/admin/adgoods.php?action=get_goods_info',
        'preview' => '/goods_id',
        'edit' => '?tab=adgoods&edit_id',
        'list' => '?tab=adgoods',
    ],
    'assets' => [
        'defaultImage' => '/assets/images/moren.jpg'
    ],
    'messages' => [
        'deleteSuccess' => '商品已成功删除',
        'deleteFail' => '删除商品失败：',
        'networkRequestFail' => '网络请求失败，请重试',
        'networkConnectError' => '网络连接错误，请检查您的网络',
        'parseResponseFail' => '解析响应失败',
        'requestFail' => '请求失败',
        'networkError' => '网络错误',
        'tryAgain' => '，请重试',
        'selectGoodsFirst' => '请先选择商品',
        'batchMoveSuccess' => '批量移动成功',
        'batchMoveFail' => '批量移动失败',
        'selectCategory' => '请选择分类',
        'batchMoving' => '移动中...',
        'batchMoveBtn' => '批量移动商品',
        'batchStatusSuccess' => '批量设置状态成功',
        'batchStatusFail' => '批量设置状态失败',
        'selectStatus' => '请选择状态',
        'batchStatusSetting' => '设置中...',
        'batchStatusBtn' => '批量修改状态',
        'batchStockSuccess' => '批量修改库存成功',
        'batchStockFail' => '批量修改库存失败',
        'invalidStock' => '请输入有效的库存数量',
        'batchStockUpdating' => '修改中...',
        'batchStockBtn' => '批量修改库存',
        'batchDeleteSuccess' => '批量删除成功',
        'batchDeleteFail' => '批量删除失败',
        'batchDeleting' => '删除中...',
        'batchDeleteBtn' => '批量删除',
        'previewAfterPublish' => '先发布商品再预览',
        'enterVideoUrl' => '请输入视频地址',
        'maxSpecs' => '最多只能添加6个规格',
        'addSpecFirst' => '请先添加规格',
        'enterSpecName' => '请输入规格{num}的名称',
        'fileTooLarge' => '文件大小超过1MB限制',
        'specUpdateSuccess' => '规格更新成功',
        'uploadSpecImageFail' => '上传规格图片失败',
        'imageReplaceSuccess' => '图片替换成功',
        'imageUploadFail' => '图片上传失败: ',
        'imageUploadRetry' => '图片上传失败，请重试',
        'selectImageFile' => '请选择图片文件',
        'loading' => '加载中...',
        'loadGoodsFail' => '无法加载商品列表',
        'loadFail' => '加载失败',
        'noGoodsFound' => '没有找到商品',
        'maxBoundGoods' => '最多只能绑定6个商品',
        'maxUploadImages' => '最多只能上传6张图片',
        'submitInProgress' => '提交中...',
        'operationSuccess' => '操作成功',
        'operationFail' => '操作失败',
        'submitFailRetry' => '提交失败，请重试',
    ]
];
?>
<script>
    const QK_GOODS_CONFIG = <?php echo json_encode($js_config, JSON_UNESCAPED_UNICODE | JSON_NUMERIC_CHECK); ?>;
</script>
<script src="../assets/js/goods.js"></script>
