KTV/app/Livewire/Forms/TextAdsForm.php

127 lines
3.3 KiB
PHP
Raw Normal View History

2025-07-24 16:59:25 +08:00
<?php
namespace App\Livewire\Forms;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
use WireUi\Traits\WireUiActions;
use App\Models\TextAd;
use App\Enums\TextAdColors;
class TextAdsForm extends Component
{
use WireUiActions;
protected $listeners = ['openModal','closeModal', 'deleteTextAd'];
public bool $canCreate;
public bool $canEdit;
public bool $canDelect;
public bool $showModal = false;
public ?int $textAdId = null;
public array $colorOptions =[];
public array $fields = [
'content' =>'',
'color' => 'black',
'duration' => 1,
'is_active' => 1,
];
public function mount()
{
$this->colorOptions = collect(TextAdColors::cases())->map(fn ($color) => [
'name' => $color->labels(),
'value' => $color->value,
])->toArray();
$this->canCreate = Auth::user()?->can('song-edit') ?? false;
$this->canEdit = Auth::user()?->can('song-edit') ?? false;
$this->canDelect = Auth::user()?->can('song-delete') ?? false;
}
public function openModal($id = null)
{
$this->resetFields();
if ($id) {
$textAd = TextAd::findOrFail($id);
$this->textAdId = $textAd->id;
$this->fields = $textAd->only(array_keys($this->fields));
}
$this->showModal = true;
}
public function closeModal()
{
$this->resetFields();
$this->showModal = false;
}
public function save()
{
if ($this->textAdId) {
if ($this->canEdit) {
$textAd = TextAd::findOrFail($this->textAdId);
$textAd->update($this->fields);
$this->notification()->send([
'icon' => 'success',
'title' => '成功',
'description' => '文字廣吿已更新',
]);
}
} else {
if ($this->canCreate) {
$textAd = TextAd::create($this->fields);
$this->notification()->send([
'icon' => 'success',
'title' => '成功',
'description' => '文字廣吿已新增',
]);
}
}
$this->resetFields();
$this->showModal = false;
$this->dispatch('pg:eventRefresh-text-ads-table');
}
public function deleteTextAd($id)
{
if ($this->canDelect) {
TextAd::findOrFail($id)->delete();
$this->notification()->send([
'icon' => 'success',
'title' => '成功',
'description' => '文字廣吿已刪除',
]);
$this->dispatch('pg:eventRefresh-text-ads-table');
}
}
public function resetFields()
{
foreach ($this->fields as $key => $value) {
if ($key == 'color') {
$this->fields[$key] = 'black';
} else if ($key == 'content'){
$this->fields[$key] = '';
} else {
$this->fields[$key] = 1;
}
}
$this->textAdId = null;
}
public function render()
{
return view('livewire.forms.text-ads-form');
}
}