<?php

declare(strict_types=1);

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

namespace App\Filament\Resources\DberpTransferOrders\Pages;

use App\Business\Inventory\Enums\TransferDocumentStatus;
use App\Business\Inventory\TransferOrderService;
use App\Filament\Resources\DberpTransferOrders\DberpTransferOrderResource;
use App\Filament\Resources\Pages\EditRecord;
use App\Filament\Support\DberpPrintFilamentAction;
use App\Models\DberpTransferOrder;
use App\Support\DberpFilamentInventoryConfirmActionFeedback;
use App\Support\DberpFilamentInventoryVoidActionConfigurator;
use App\Support\Print\Documents\TransferOrderPrintPresenter;
use Filament\Actions\Action;
use Filament\Actions\DeleteAction;
use Illuminate\Contracts\Support\Htmlable;

class EditDberpTransferOrder extends EditRecord
{
    protected static string $resource = DberpTransferOrderResource::class;

    public function getSubheading(): string|Htmlable|null
    {
        $parent = parent::getSubheading();
        $record = $this->getRecord();

        if (! $record instanceof DberpTransferOrder) {
            return $parent;
        }

        if (! in_array($record->status, [TransferDocumentStatus::Effective->value, TransferDocumentStatus::Completed->value], true)) {
            return $parent;
        }

        $stockNote = (string) __('dberp.ui.transfer_order_stock_posted_subheading');

        if ($parent === null || $parent === '') {
            return $stockNote;
        }

        return $parent.' '.$stockNote;
    }

    protected function mutateFormDataBeforeSave(array $data): array
    {
        $data = app('App\\Business\\MasterData\\DberpDocumentAddressSnapshotService')->fillWarehouseSnapshot($data, 'from_warehouse_id', 'from_warehouse');

        return app('App\\Business\\MasterData\\DberpDocumentAddressSnapshotService')->fillWarehouseSnapshot($data, 'to_warehouse_id', 'to_warehouse');
    }

    protected function getHeaderActions(): array
    {
        return [
            DberpPrintFilamentAction::forDocument(
                TransferOrderPrintPresenter::DOCUMENT_KEY,
                fn (DberpTransferOrder $record): bool => DberpTransferOrderResource::canView($record),
            ),
            Action::make('apply')
                ->label(__('dberp.actions.confirm_take_effect'))
                ->requiresConfirmation()
                ->modalHeading(__('dberp.hints.transfer_apply_modal_heading'))
                ->modalDescription(__('dberp.hints.inventory_apply_transfer'))
                ->visible(fn (DberpTransferOrder $record): bool => $record->status === TransferDocumentStatus::Draft->value)
                ->action(function (): void {
                    DberpFilamentInventoryConfirmActionFeedback::runWithFailureNotification(function (): void {
                        app(TransferOrderService::class)->apply($this->record);
                    });
                    $this->record->refresh();
                }),
            Action::make('complete')
                ->label(__('dberp.actions.complete'))
                ->requiresConfirmation()
                ->modalHeading(__('dberp.hints.transfer_complete_modal_heading'))
                ->modalDescription(__('dberp.hints.transfer_complete'))
                ->visible(fn (DberpTransferOrder $record): bool => $record->status === TransferDocumentStatus::Effective->value)
                ->action(function (): void {
                    DberpFilamentInventoryConfirmActionFeedback::runWithFailureNotification(function (): void {
                        app(TransferOrderService::class)->complete($this->record);
                    });
                    $this->record->refresh();
                }),
            DberpFilamentInventoryVoidActionConfigurator::configureEffectiveInventoryVoidAction(
                Action::make('void')
                    ->requiresConfirmation()
                    ->visible(fn (DberpTransferOrder $record): bool => in_array($record->status, [TransferDocumentStatus::Effective->value, TransferDocumentStatus::Completed->value], true))
                    ->disabled(fn (): bool => ! DberpFilamentInventoryVoidActionConfigurator::inventoryVoidAllowed()
                        || ! DberpFilamentInventoryVoidActionConfigurator::inventoryRollbackAllowed())
                    ->tooltip(fn (): ?string => match (true) {
                        ! DberpFilamentInventoryVoidActionConfigurator::inventoryVoidAllowed() => (string) __('dberp.hints.inventory_void_policy_disabled_reason'),
                        ! DberpFilamentInventoryVoidActionConfigurator::inventoryRollbackAllowed() => (string) __('dberp.hints.transfer_void_requires_inventory_rollback'),
                        default => null,
                    })
                    ->modalDescription(fn (): string => DberpFilamentInventoryVoidActionConfigurator::inventoryRollbackAllowed()
                        ? (string) __('dberp.hints.transfer_void_with_rollback')
                        : (string) __('dberp.hints.inventory_void_mark_only_body'))
                    ->action(function (): void {
                        DberpFilamentInventoryConfirmActionFeedback::runWithFailureNotification(function (): void {
                            app(TransferOrderService::class)->void($this->record);
                        });
                        $this->record->refresh();
                        DberpFilamentInventoryVoidActionConfigurator::notifyInventoryRevokeSuccess();
                    }),
            ),
            DeleteAction::make()
                ->visible(fn (DberpTransferOrder $record): bool => $record->status === TransferDocumentStatus::Draft->value),
        ];
    }
}
