Files
bsh_sample/app/common/service/SkuService.php
T
2025-12-09 15:33:21 +08:00

115 lines
3.0 KiB
PHP

<?php
namespace app\common\service;
use app\common\model\SkuAttributeValue;
use app\common\validate\SkuValidate;
use app\common\traits\crud\CrudServiceTrait;
use app\common\model\Sku;
use support\Redis;
use support\Request;
class SkuService
{
use CrudServiceTrait;
/**
* 指定当前要操作的模型
*/
protected string $modelClass = Sku::class;
/**
* 验证器
*/
protected $validator = SkuValidate::class;
/**
* 获取验证器
*/
public function getValidator()
{
return new $this->validator;
}
/**
* 添加前置处理
*/
public function beforeServiceStore($data, Request $request)
{
$spec = [];
foreach ($data['spec'] as $key => $value) {
$specItem = [];
$specItem['category_id'] = $data['category_id'];
$specItem['attr_id'] = $value['attr_id'];
$specItem['attr_name'] = $value['attr_name'];
$specItem['attr_value'] = $value['attr_value'];
$spec[] = $specItem;
}
$spec_json = json_encode($spec,JSON_UNESCAPED_UNICODE);
Redis::set('sku_attr_'.$request->user->uid, $spec_json,30);
unset($data['spec']);
$data['spec_json'] = $spec_json;
$data['user_id'] = $request->user->uid;
$data['code'] = $this->generateUniqueCode();
return $data;
}
/**
* 添加后置处理
*/
public function afterServiceStore($res)
{
$specs = Redis::get('sku_attr_'.$res['user_id']);
$specs= json_decode($specs,true);
var_dump($specs);
$spec = [];
foreach ($specs as $key => $value) {
$spec['category_id'] = $res['category_id'];
$spec['sku_id'] = $res['id'];
$spec['attr_id'] = $value['attr_id'];
$spec['attr_name'] = $value['attr_name'];
$spec['attr_value'] = $value['attr_value'];
SkuAttributeValue::create($spec);
}
return $res;
}
/**
* 生成唯一的7位颜色编码
* 格式:C + (O/I) + 5位字母数字组合
*
* @param int $type 类型:2=I,其他=O
* @return string 7位唯一编码
*/
public function generateUniqueCode()
{
$chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$maxAttempts = 10; // 防止无限循环
for ($attempt = 0; $attempt < $maxAttempts; $attempt++) {
// 生成后5位随机字符
$suffix = '';
for ($i = 0; $i < 5; $i++) {
$suffix .= $chars[rand(0, strlen($chars) - 1)];
}
$colorCode = 'PN' . $suffix;
// 检查是否已存在
$existing = Sku::where('code', $colorCode)->first();
if (!$existing) {
return $colorCode;
}
}
// 如果1000次尝试后仍然重复,使用时间戳确保唯一性
$timestamp = substr(time(), -5);
return 'PN' . $timestamp;
}
}