<?php

declare(strict_types=1);

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

namespace App\Filament\Resources\DberpSalesOutbounds\Pages;

use App\Business\MasterData\DberpDocumentAddressSnapshotService;
use App\Filament\Resources\DberpSalesOutbounds\DberpSalesOutboundResource;
use App\Filament\Resources\Pages\CreateRecord;
use App\Models\DberpSalesOrder;
use App\Support\DberpDocumentRemarkPropagation;

class CreateDberpSalesOutbound extends CreateRecord
{
    protected static string $resource = DberpSalesOutboundResource::class;

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

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

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

        $salesOrderId = request()->integer('sales_order_id');

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

        $order = DberpSalesOrder::query()->find($salesOrderId);

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

        $this->form->fill([
            'sales_order_id' => $order->getKey(),
            'customer_id' => $order->customer_id,
            'handler_employee_id' => $order->handler_employee_id,
            'business_time' => now(),
            'remark' => DberpDocumentRemarkPropagation::trimmedOrNull($order->remark),
        ]);
    }
}
