<?php

declare(strict_types=1);

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

namespace App\Filament\Resources\DberpPurchaseReceipts\Pages;

use App\Business\MasterData\DberpDocumentAddressSnapshotService;
use App\Business\Purchase\PurchaseOrderRequestedWarehouseResolver;
use App\Filament\Resources\DberpPurchaseReceipts\DberpPurchaseReceiptResource;
use App\Filament\Resources\Pages\CreateRecord;
use App\Models\DberpPurchaseOrder;
use App\Support\DberpDocumentRemarkPropagation;
use Filament\Notifications\Notification;

class CreateDberpPurchaseReceipt extends CreateRecord
{
    protected static string $resource = DberpPurchaseReceiptResource::class;

    protected function mutateFormDataBeforeCreate(array $data): array
    {
        $snapshotService = app(DberpDocumentAddressSnapshotService::class);
        $data = $snapshotService->applySupplierSnapshotForPurchaseReceiptCreate($data);

        return $snapshotService->fillWarehouseSnapshot($data);
    }

    public function mount(): void
    {
        parent::mount();

        $purchaseOrderId = request()->integer('purchase_order_id');

        if ($purchaseOrderId <= 0) {
            return;
        }

        $order = DberpPurchaseOrder::query()->with('items')->find($purchaseOrderId);

        if ($order === null) {
            return;
        }

        $resolver = app(PurchaseOrderRequestedWarehouseResolver::class);
        $fill = [
            'purchase_order_id' => $order->getKey(),
            'supplier_id' => $order->supplier_id,
            'handler_employee_id' => $order->handler_employee_id,
            'business_time' => now(),
            'arrival_date' => now()->toDateString(),
        ];

        $defaultWarehouseId = $resolver->resolveDefaultReceiptWarehouseId($order);

        if ($defaultWarehouseId !== null) {
            $fill['warehouse_id'] = $defaultWarehouseId;
        }

        $remark = DberpDocumentRemarkPropagation::trimmedOrNull($order->remark);

        if ($remark !== null) {
            $fill['remark'] = $remark;
        }

        $this->form->fill($fill);

        if ($resolver->hasMixedRequestedWarehouses($order)) {
            Notification::make()
                ->title((string) __('dberp.notifications.warning'))
                ->body((string) __('dberp.messages.purchase_receipt_mixed_requested_warehouse'))
                ->warning()
                ->send();
        }
    }
}
