<?php

namespace App\Filament\Resources\RoleResource\Pages;

use App\Filament\Resources\RoleResource;
use Filament\Actions;
use Filament\Resources\Pages\EditRecord;

class EditRole extends EditRecord
{
    protected static string $resource = RoleResource::class;

    protected function getHeaderActions(): array
    {
        return [
            Actions\ViewAction::make()
                ->label('查看'),
            Actions\DeleteAction::make()
                ->label('删除'),
        ];
    }

    protected function getRedirectUrl(): string
    {
        return $this->getResource()::getUrl('index');
    }

    protected function getSavedNotificationTitle(): ?string
    {
        return '角色更新成功';
    }

    protected function mutateFormDataBeforeSave(array $data): array
    {
        // 从 all_permissions 字段获取权限列表
        if (isset($data['all_permissions'])) {
            $permissions = $data['all_permissions'];
            unset($data['all_permissions']);
            
            // 保存权限到记录中，稍后在 afterSave 中同步
            $this->permissions = $permissions;
        }
        
        // 移除所有 permissions_* 字段
        foreach ($data as $key => $value) {
            if (str_starts_with($key, 'permissions_')) {
                unset($data[$key]);
            }
        }
        
        return $data;
    }

    protected function afterSave(): void
    {
        // 同步权限
        if (isset($this->permissions)) {
            $this->record->syncPermissions($this->permissions);
        }
    }
}
