107 lines
3.0 KiB
PHP
107 lines
3.0 KiB
PHP
<?php
|
|
|
|
namespace App\Admin\Forms;
|
|
|
|
use App\Enums\DrawActivityStatus;
|
|
use App\Exceptions\BizException;
|
|
use App\Models\DrawActivity;
|
|
use Dcat\Admin\Contracts\LazyRenderable;
|
|
use Dcat\Admin\Traits\LazyWidget;
|
|
use Dcat\Admin\Widgets\Form;
|
|
|
|
class DrawActivityPublish extends Form implements LazyRenderable
|
|
{
|
|
use LazyWidget;
|
|
|
|
public const METHOD_NONE = 1; // 暂不发布
|
|
public const METHOD_QUICK = 2; // 立即发布
|
|
public const METHOD_TIMER = 3; // 定时发布
|
|
|
|
/**
|
|
* @param Model|Authenticatable|HasPermissions|null $user
|
|
*
|
|
* @return bool
|
|
*/
|
|
protected function authorize($user): bool
|
|
{
|
|
return $user->can('dcat.admin.draw_activities.publish');
|
|
}
|
|
|
|
/**
|
|
* Handle the form request.
|
|
*
|
|
* @param array $input
|
|
*
|
|
* @return mixed
|
|
*/
|
|
public function handle(array $input)
|
|
{
|
|
$drawActivity = DrawActivity::findOrFail($this->payload['id']);
|
|
|
|
if ($drawActivity->isPublished()) {
|
|
throw new BizException('活动已发布');
|
|
}
|
|
|
|
$method = (int) $input['method'];
|
|
|
|
if ($method === static::METHOD_NONE) {
|
|
$drawActivity->update([
|
|
'status' => DrawActivityStatus::Created,
|
|
'published_at' => null,
|
|
]);
|
|
} else {
|
|
$prizes = $drawActivity->prizes()->get();
|
|
|
|
if ($prizes->isEmpty()) {
|
|
throw new BizException('活动未设置奖品');
|
|
}
|
|
|
|
if ($prizes->sum('weight') == 0) {
|
|
throw new BizException('活动奖品总权重值不能为0');
|
|
}
|
|
|
|
$drawActivity->update([
|
|
'status' => DrawActivityStatus::Running,
|
|
'published_at' => match ($method) {
|
|
static::METHOD_TIMER => $input['published_at'],
|
|
default => now(),
|
|
},
|
|
]);
|
|
}
|
|
|
|
return $this->response()
|
|
->success(__('admin.update_succeeded'))
|
|
->refresh();
|
|
}
|
|
|
|
/**
|
|
* Build a form here.
|
|
*/
|
|
public function form()
|
|
{
|
|
$this->radio('method', '发布方式')
|
|
->options([
|
|
static::METHOD_NONE => '暂不发布',
|
|
static::METHOD_QUICK => '立即发布',
|
|
static::METHOD_TIMER => '定时发布',
|
|
])
|
|
->when(static::METHOD_TIMER, function () {
|
|
$this->datetime('published_at')
|
|
->rules(['bail', 'required_if:method,'.static::METHOD_TIMER], ['required_if' => '不能为空']);
|
|
});
|
|
}
|
|
|
|
public function default()
|
|
{
|
|
$drawActivity = DrawActivity::findOrFail($this->payload['id']);
|
|
|
|
return [
|
|
'method' => match ($drawActivity->real_status) {
|
|
DrawActivityStatus::Publishing => static::METHOD_TIMER,
|
|
default => static::METHOD_QUICK,
|
|
},
|
|
'published_at' => $drawActivity->published_at,
|
|
];
|
|
}
|
|
}
|