105 lines
2.7 KiB
PHP
105 lines
2.7 KiB
PHP
<?php
|
|
|
|
namespace app\admin\service;
|
|
|
|
use app\admin\validate\VehColorValidate;
|
|
use app\common\traits\crud\CrudServiceTrait;
|
|
use app\common\model\VehColor;
|
|
use app\common\utils\translation\service\TranslationService;
|
|
use app\queue\utils\Translat;
|
|
use support\Request;
|
|
|
|
class VehColorService
|
|
{
|
|
|
|
use CrudServiceTrait;
|
|
|
|
/**
|
|
* 指定当前要操作的模型
|
|
*/
|
|
protected string $modelClass = VehColor::class;
|
|
|
|
/**
|
|
* 验证器
|
|
*/
|
|
protected $validator = VehColorValidate::class;
|
|
|
|
public $translatFields = ['color_text'];
|
|
|
|
/**
|
|
* 获取验证器
|
|
*/
|
|
public function getValidator()
|
|
{
|
|
return new $this->validator;
|
|
}
|
|
|
|
public function afterServiceStore($res)
|
|
{
|
|
$sourceLocale = locale();
|
|
$data = $res->toArray();
|
|
$traitsourceFields = Translat::extractSourceFields($data, $this->translatFields);
|
|
|
|
(new TranslationService())->queueTranslations(
|
|
'veh_color_translation',
|
|
$res['id'],
|
|
$sourceLocale,
|
|
$traitsourceFields
|
|
);
|
|
}
|
|
|
|
/**
|
|
* 生成唯一的7位颜色编码
|
|
* 格式:C + (O/I) + 5位字母数字组合
|
|
*
|
|
* @param int $type 类型:2=I,其他=O
|
|
* @return string 7位唯一编码
|
|
*/
|
|
public function generateUniqueColorCode($type)
|
|
{
|
|
$secondChar = $type ==2 ? 'I' : 'O';
|
|
$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 = 'C' . $secondChar . $suffix;
|
|
|
|
// 检查是否已存在
|
|
$existing = VehColor::where('color_code', $colorCode)->first();
|
|
if (!$existing) {
|
|
return $colorCode;
|
|
}
|
|
}
|
|
|
|
// 如果1000次尝试后仍然重复,使用时间戳确保唯一性
|
|
$timestamp = substr(time(), -5);
|
|
return 'C' . $secondChar . $timestamp;
|
|
}
|
|
|
|
/**
|
|
* 添加前置处理
|
|
*/
|
|
public function beforeServiceStore($data, Request $request)
|
|
{
|
|
$type = $data['type'] ?? 0;
|
|
$data['color_code'] = $this->generateUniqueColorCode($type);
|
|
$data['created_by'] = $request->user->uid;
|
|
$data['updated_by'] = $request->user->uid;
|
|
return $data;
|
|
}
|
|
|
|
/**
|
|
* 添加前置处理
|
|
*/
|
|
public function beforeServiceUpdate($data, Request $request)
|
|
{
|
|
$data['updated_by'] = $request->user->uid;
|
|
return $data;
|
|
}
|
|
} |