getPdo(); $chk = $pdo->prepare("SELECT id, industry FROM companies WHERE id = ?"); $chk->execute([$companyId]); $company = $chk->fetch(); if (!$company) { Response::error('企业不存在'); } $pdo->beginTransaction(); try { $ins = $pdo->prepare( "INSERT INTO company_products (company_id, category_name, category_description, positioning, series, is_core, is_active) VALUES (?, ?, ?, ?, ?, ?, ?)" ); $ins->execute([ $companyId, $categoryName, strOrNull($_POST['category_description'] ?? null), strOrNull($_POST['positioning'] ?? null), strOrNull($_POST['series'] ?? null), !empty($_POST['is_core']) ? 1 : 0, isset($_POST['is_active']) && (int)$_POST['is_active'] === 0 ? 0 : 1, ]); $productId = (int)$pdo->lastInsertId(); // EAV 参数值 $attrs = json_decode($_POST['attrs'] ?? '[]', true); if (is_array($attrs) && $attrs) { // 校验 attr 属于该公司行业 $valid = $pdo->prepare("SELECT id, attr_type FROM company_products_attr WHERE id = ? AND industry = ? AND is_active = 1"); $insV = $pdo->prepare( "INSERT INTO company_products_attr_value (product_id, attr_id, value_string, value_number, value_boolean, value_date) VALUES (?, ?, ?, ?, ?, ?)" ); foreach ($attrs as $a) { $attrId = (int)($a['attr_id'] ?? 0); if ($attrId <= 0) { continue; } $valid->execute([$attrId, $company['industry']]); $def = $valid->fetch(); if (!$def) { continue; } $val = trim((string)($a['value'] ?? '')); if ($val === '') { continue; } $vStr = $vNum = $vBool = $vDate = null; switch ($def['attr_type']) { case 'number': $vNum = is_numeric($val) ? $val : null; if ($vNum === null) { $vStr = $val; } break; case 'boolean': $vBool = (in_array($val, ['1', 'true', '是', 'yes', 'Y', 'y', '支持'], true)) ? 1 : 0; break; case 'date': $vDate = (strtotime($val) !== false) ? date('Y-m-d', strtotime($val)) : null; if ($vDate === null) { $vStr = $val; } break; default: $vStr = $val; } $insV->execute([$productId, $attrId, $vStr, $vNum, $vBool, $vDate]); } } $pdo->commit(); } catch (Exception $e) { $pdo->rollBack(); Response::error('产品保存失败:' . $e->getMessage()); } logCurrent('add', 'product', 'company_products', $productId, ['company_id' => $companyId, 'category_name' => $categoryName]); Response::success(['id' => $productId], '新增成功');