<?php

declare(strict_types=1);

/**
 * 本文件属于 DBErp 进销存系统。
 *
 * 版权所有 © 2026 北京珑大钜商科技有限公司。保留所有权利。
 *
 * 未经官方授权，不得删除、篡改或隐藏本文件中的版权声明、产品标识与来源信息。
 * 商业授权、官方更新与技术支持服务，请以珑大官方支持中心记录为准。
 *
 * @link https://support.loongdom.cn
 * @see  https://www.dberp.com.cn
 */

namespace App\Filament\Resources\DberpReceiptOrders\Pages;

use App\Business\Settlement\Enums\SettlementDocumentStatus;
use App\Business\Settlement\ReceiptService;
use App\Filament\Resources\DberpReceiptOrders\DberpReceiptOrderResource;
use App\Filament\Resources\Pages\EditRecord;
use App\Filament\Support\DberpPrintFilamentAction;
use App\Models\DberpReceiptOrder;
use App\Services\DberpPermissionService;
use App\Support\DberpFilamentSettlementVoidActionConfigurator;
use App\Support\PluginIntegration\LightApprovalDocumentGuardBridge;
use App\Support\PluginIntegration\LightApprovalFilamentBridge;
use App\Support\Print\Documents\ReceiptOrderPrintPresenter;
use Filament\Actions\Action;
use Filament\Actions\DeleteAction;
use Filament\Notifications\Notification;
use Illuminate\Support\Facades\Auth;

class EditDberpReceiptOrder extends EditRecord
{
    protected static string $resource = DberpReceiptOrderResource::class;

    /**
     * @param  array<string, mixed>  $data
     * @return array<string, mixed>
     */
    protected function mutateFormDataBeforeSave(array $data): array
    {
        $record = $this->getRecord();

        if (! $record instanceof DberpReceiptOrder) {
            return $data;
        }

        if ($record->status === SettlementDocumentStatus::Draft->value) {
            return $data;
        }

        if ($record->status === SettlementDocumentStatus::Submitted->value) {
            return [
                'attachment_paths' => $data['attachment_paths'] ?? $record->attachment_paths,
            ];
        }

        return $data;
    }

    protected function getHeaderActions(): array
    {
        $permissionService = app(DberpPermissionService::class);

        return [
            ...($this->record instanceof DberpReceiptOrder
                ? LightApprovalFilamentBridge::receiptEditHeaderActions($this->record)
                : []),
            DberpPrintFilamentAction::forDocument(
                ReceiptOrderPrintPresenter::DOCUMENT_KEY,
                fn (DberpReceiptOrder $record): bool => app(DberpPermissionService::class)->allows(
                    auth()->user(),
                    DberpPermissionService::VIEW_RECEIPT_ORDER,
                ),
            ),
            Action::make('submit')
                ->label(__('dberp.actions.submit_receipt'))
                ->requiresConfirmation()
                ->modalDescription(__('dberp.hints.receipt_order_submit'))
                ->visible(fn (DberpReceiptOrder $record): bool => $record->status === SettlementDocumentStatus::Draft->value && $permissionService->allows(Auth::user(), DberpPermissionService::CREATE_RECEIPT_ORDER))
                ->disabled(fn (DberpReceiptOrder $record): bool => ! LightApprovalDocumentGuardBridge::canConfirm(
                    LightApprovalDocumentGuardBridge::ADAPTER_RECEIPT,
                    $record,
                ))
                ->tooltip(fn (DberpReceiptOrder $record): ?string => LightApprovalDocumentGuardBridge::confirmBlockReason(
                    LightApprovalDocumentGuardBridge::ADAPTER_RECEIPT,
                    $record,
                ))
                ->action(function (): void {
                    app(ReceiptService::class)->submit($this->record);
                    $this->record->refresh();
                }),
            Action::make('confirm')
                ->label(__('dberp.actions.confirm_receipt'))
                ->requiresConfirmation()
                ->modalDescription(__('dberp.hints.receipt_order_confirm'))
                ->visible(fn (DberpReceiptOrder $record): bool => in_array($record->status, [SettlementDocumentStatus::Draft->value, SettlementDocumentStatus::Submitted->value], true) && $permissionService->allows(Auth::user(), DberpPermissionService::CONFIRM_RECEIPT_PAYMENT))
                ->disabled(fn (DberpReceiptOrder $record): bool => $record->status === SettlementDocumentStatus::Draft->value
                    && ! LightApprovalDocumentGuardBridge::canConfirm(
                        LightApprovalDocumentGuardBridge::ADAPTER_RECEIPT,
                        $record,
                    ))
                ->tooltip(fn (DberpReceiptOrder $record): ?string => $record->status === SettlementDocumentStatus::Draft->value
                    ? LightApprovalDocumentGuardBridge::confirmBlockReason(
                        LightApprovalDocumentGuardBridge::ADAPTER_RECEIPT,
                        $record,
                    )
                    : null)
                ->action(function (): void {
                    app(ReceiptService::class)->confirm($this->record);
                    $this->record->refresh();
                }),
            DberpFilamentSettlementVoidActionConfigurator::configureEffectiveSettlementVoidAction(
                Action::make('void')
                    ->label(__('dberp.actions.void_settlement'))
                    ->requiresConfirmation()
                    ->modalHeading(fn (): string => (string) __('dberp.hints.settlement_void_effective_heading'))
                    ->modalDescription(__('dberp.hints.settlement_void_effective_body'))
                    ->visible(fn (DberpReceiptOrder $record): bool => $record->status === SettlementDocumentStatus::Effective->value && $permissionService->allows(Auth::user(), DberpPermissionService::CONFIRM_RECEIPT_PAYMENT))
                    ->action(function (): void {
                        app(ReceiptService::class)->void($this->record);
                        $this->record->refresh();
                        Notification::make()
                            ->title((string) __('dberp.notifications.settlement_void_done'))
                            ->success()
                            ->send();
                    }),
            ),
            DeleteAction::make()
                ->visible(fn (DberpReceiptOrder $record): bool => $record->status === SettlementDocumentStatus::Draft->value && $permissionService->allows(Auth::user(), DberpPermissionService::CREATE_RECEIPT_ORDER)),
        ];
    }
}
