KTV/app/Livewire/Admin/BranchForm.php

141 lines
3.7 KiB
PHP

<?php
namespace App\Livewire\Admin;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
use WireUi\Traits\WireUiActions;
use App\Models\Branch;
use App\Models\Room;
class BranchForm extends Component
{
use WireUiActions;
protected $listeners = ['openModal','closeModal', 'deleteBranch'];
public bool $canCreate;
public bool $canEdit;
public bool $canDelect;
public bool $showModal = false;
public ?int $branchId = null;
public array $fields = [
'name' =>'',
'external_ip' =>'',
'enable' => true,
'roomNotes' =>''
];
public function mount()
{
$this->canCreate = Auth::user()?->can('room-edit') ?? false;
$this->canEdit = Auth::user()?->can('room-edit') ?? false;
$this->canDelect = Auth::user()?->can('room-delete') ?? false;
}
public function openModal($id = null)
{
$this->resetFields();
if ($id) {
$branch = Branch::findOrFail($id);
$this->branchId = $branch->id;
$this->fields = $branch->only(array_keys($this->fields));
}
$this->showModal = true;
}
public function closeModal()
{
$this->resetFields();
$this->showModal = false;
}
public function save()
{
if ($this->branchId) {
if ($this->canEdit) {
$branch = Branch::findOrFail($this->branchId);
$branch->update($this->fields);
$this->notification()->send([
'icon' => 'success',
'title' => '成功',
'description' => '分店已更新',
]);
}
} else {
if ($this->canCreate) {
$branch = Branch::create([
'name' => $this->fields['name'],
'external_ip' => $this->fields['external_ip'],
'enable' => $this->fields['enable'],
]);
// 解析 roomNotes
$roomLines = explode("\n", trim($this->fields['roomNotes']));
$rooms = [];
foreach ($roomLines as $line) {
[$floor, $roomList] = explode(';', $line);
$roomNames = array_map('trim', explode(',', $roomList));
foreach ($roomNames as $roomName) {
$rooms[] = new Room([
'name' => $roomName,
]);
}
}
// 儲存所有 Room
$branch->rooms()->saveMany($rooms);
$this->notification()->send([
'icon' => 'success',
'title' => '成功',
'description' => '分店已新增',
]);
}
}
$this->resetFields();
$this->showModal = false;
$this->dispatch('pg:eventRefresh-branch-table');
}
public function deleteBranch($id)
{
if ($this->canDelect) {
Branch::findOrFail($id)->delete();
$this->notification()->send([
'icon' => 'success',
'title' => '成功',
'description' => '分店已刪除',
]);
$this->dispatch('pg:eventRefresh-branch-table');
}
}
public function resetFields()
{
foreach ($this->fields as $key => $value) {
if ($key == 'enable') {
$this->fields[$key] = true;
} else {
$this->fields[$key] = '';
}
}
$this->branchId = null;
}
public function render()
{
return view('livewire.admin.branch-form');
}
}