Files
fdesk/app/admin/service/BrandSeriesService.php
T
2025-09-16 12:04:12 +08:00

126 lines
3.5 KiB
PHP

<?php
namespace app\admin\service;
use app\admin\validate\BrandSeriesValidate;
use app\common\model\Brand;
use app\common\traits\crud\CrudServiceTrait;
use app\common\model\BrandSeries;
use support\Request;
class BrandSeriesService
{
use CrudServiceTrait;
/**
* 指定当前要操作的模型
*/
protected string $modelClass = BrandSeries::class;
/**
* 验证器
*/
protected $validator = BrandSeriesValidate::class;
/**
* 获取验证器
*/
public function getValidator()
{
return new $this->validator;
}
/**
* 构建查询条件
*/
protected function buildQueryConfig(Request $request, string $scene = 'default'): array
{
$p = $request->all();
$config = [];
$config['model'] = $this->modelClass;
switch ($scene) {
case 'index':
// ====== ====== 排序 ====== ======
$config['order']['sort'] = 'desc';
$config['order']['id'] = 'desc';
// ====== ====== 筛选 ====== ======
$config['where']['brand_id'] = $p['brand_id'];
// 状态
if (isset($p['status']) && in_array($p['status'], [0,1])) {
$config['where']['status'] = $p['status'];
}
// 关键字
if (isset($p['keyword']) && $p['keyword']) {
$k = '%' . $p['keyword'] . '%';
foreach (['series_code','series_name'] as $col) {
$config['orWhere'][] = [$col, 'like', $k];
}
}
//$config['where']['status'] = 1;
break;
case 'show':
$config['where']['id'] = $p['id'];
//$config['where']['status'] = 1;
break;
case 'store':
break;
case 'update':
$config['where']['id'] = $p['id'];
break;
case 'destroy':
$config['where']['id'] = $p['id'];
break;
}
return $config;
}
/**
* 生成唯一的7位颜色编码
* 格式:C + (O/I) + 5位字母数字组合
*
* @param int $type 类型
* @return string 7位唯一编码
*/
public function generateUniqueModificationCode($brand_id)
{
$chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$maxAttempts = 10; // 防止无限循环
$brand_code = Brand::where('id', $brand_id)->value('brand_code');
$brand_code = $brand_code??'BS';
for ($attempt = 0; $attempt < $maxAttempts; $attempt++) {
// 生成后5位随机字符
$suffix = '';
for ($i = 0; $i < 6; $i++) {
$suffix .= $chars[rand(0, strlen($chars) - 1)];
}
$code = $brand_code . $suffix;
// 检查是否已存在
$existing = BrandSeries::where('series_code', $code)->first();
if (!$existing) {
return $code;
}
}
// 如果1000次尝试后仍然重复,使用时间戳确保唯一性
$timestamp = substr(time(), -6);
return $brand_code . $timestamp;
}
/**
* 添加前置处理
*/
public function beforeServiceStore($data, Request $request)
{
$brand_id = $data['brand_id'] ?? 0;
$data['series_code'] = $this->generateUniqueModificationCode($brand_id);
return $data;
}
}