<?php

declare(strict_types=1);

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

namespace App\Filament\Resources\DberpPaymentOrders\Pages;

use App\Business\Settlement\Enums\SettlementDocumentStatus;
use App\Business\Settlement\PaymentService;
use App\Filament\Resources\DberpPaymentOrders\DberpPaymentOrderResource;
use App\Filament\Resources\Pages\EditRecord;
use App\Filament\Support\DberpPrintFilamentAction;
use App\Models\DberpPaymentOrder;
use App\Services\DberpPermissionService;
use App\Support\DberpFilamentSettlementVoidActionConfigurator;
use App\Support\PluginIntegration\LightApprovalDocumentGuardBridge;
use App\Support\PluginIntegration\LightApprovalFilamentBridge;
use App\Support\Print\Documents\PaymentOrderPrintPresenter;
use Filament\Actions\Action;
use Filament\Actions\DeleteAction;
use Filament\Notifications\Notification;
use Illuminate\Support\Facades\Auth;

class EditDberpPaymentOrder extends EditRecord
{
    protected static string $resource = DberpPaymentOrderResource::class;

    /**
     * 已提交单据仅允许更新凭证附件，避免通过篡改 Livewire 状态修改金额等字段。
     *
     * @param  array<string, mixed>  $data
     * @return array<string, mixed>
     */
    protected function mutateFormDataBeforeSave(array $data): array
    {
        $record = $this->getRecord();

        if (! $record instanceof DberpPaymentOrder) {
            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 DberpPaymentOrder
                ? LightApprovalFilamentBridge::paymentEditHeaderActions($this->record)
                : []),
            DberpPrintFilamentAction::forDocument(
                PaymentOrderPrintPresenter::DOCUMENT_KEY,
                fn (DberpPaymentOrder $record): bool => app(DberpPermissionService::class)->allows(
                    auth()->user(),
                    DberpPermissionService::VIEW_PAYMENT_ORDER,
                ),
            ),
            Action::make('submit')
                ->label(__('dberp.actions.submit_payment'))
                ->requiresConfirmation()
                ->modalDescription(__('dberp.hints.payment_order_submit'))
                ->visible(fn (DberpPaymentOrder $record): bool => $record->status === SettlementDocumentStatus::Draft->value && $permissionService->allows(Auth::user(), DberpPermissionService::CREATE_PAYMENT_ORDER))
                ->disabled(fn (DberpPaymentOrder $record): bool => ! LightApprovalDocumentGuardBridge::canConfirm(
                    LightApprovalDocumentGuardBridge::ADAPTER_PAYMENT,
                    $record,
                ))
                ->tooltip(fn (DberpPaymentOrder $record): ?string => LightApprovalDocumentGuardBridge::confirmBlockReason(
                    LightApprovalDocumentGuardBridge::ADAPTER_PAYMENT,
                    $record,
                ))
                ->action(function (): void {
                    app(PaymentService::class)->submit($this->record);
                    $this->record->refresh();
                }),
            Action::make('confirm')
                ->label(__('dberp.actions.confirm_payment'))
                ->requiresConfirmation()
                ->modalDescription(__('dberp.hints.payment_order_confirm'))
                ->visible(fn (DberpPaymentOrder $record): bool => in_array($record->status, [SettlementDocumentStatus::Draft->value, SettlementDocumentStatus::Submitted->value], true) && $permissionService->allows(Auth::user(), DberpPermissionService::CONFIRM_RECEIPT_PAYMENT))
                ->disabled(fn (DberpPaymentOrder $record): bool => $record->status === SettlementDocumentStatus::Draft->value
                    && ! LightApprovalDocumentGuardBridge::canConfirm(
                        LightApprovalDocumentGuardBridge::ADAPTER_PAYMENT,
                        $record,
                    ))
                ->tooltip(fn (DberpPaymentOrder $record): ?string => $record->status === SettlementDocumentStatus::Draft->value
                    ? LightApprovalDocumentGuardBridge::confirmBlockReason(
                        LightApprovalDocumentGuardBridge::ADAPTER_PAYMENT,
                        $record,
                    )
                    : null)
                ->action(function (): void {
                    app(PaymentService::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 (DberpPaymentOrder $record): bool => $record->status === SettlementDocumentStatus::Effective->value && $permissionService->allows(Auth::user(), DberpPermissionService::CONFIRM_RECEIPT_PAYMENT))
                    ->action(function (): void {
                        app(PaymentService::class)->void($this->record);
                        $this->record->refresh();
                        Notification::make()
                            ->title((string) __('dberp.notifications.settlement_void_done'))
                            ->success()
                            ->send();
                    }),
            ),
            DeleteAction::make()
                ->visible(fn (DberpPaymentOrder $record): bool => $record->status === SettlementDocumentStatus::Draft->value && $permissionService->allows(Auth::user(), DberpPermissionService::CREATE_PAYMENT_ORDER)),
        ];
    }
}
