<?php

declare(strict_types=1);

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

namespace App\Filament\Resources\DberpSalesReturns\Pages;

use App\Business\Sales\SalesReturnReferenceDefaultsResolver;
use App\Filament\Resources\DberpSalesReturns\DberpSalesReturnResource;
use App\Filament\Resources\Pages\CreateRecord;
use App\Models\DberpSalesOrder;
use App\Models\DberpSalesOutboundOrder;

class CreateDberpSalesReturn extends CreateRecord
{
    protected static string $resource = DberpSalesReturnResource::class;

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

        $resolver = app(SalesReturnReferenceDefaultsResolver::class);
        $outboundId = request()->integer('sales_outbound_order_id');

        if ($outboundId > 0) {
            $outbound = DberpSalesOutboundOrder::query()->find($outboundId);

            if ($outbound instanceof DberpSalesOutboundOrder) {
                $this->form->fill(array_merge(
                    ['business_time' => now()],
                    $resolver->resolveFromSalesOutbound($outbound),
                ));

                return;
            }
        }

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

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

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

        if (! $order instanceof DberpSalesOrder) {
            return;
        }

        $this->form->fill(array_merge(
            [
                'sales_order_id' => $order->getKey(),
                'business_time' => now(),
            ],
            $resolver->resolveFromSalesOrder($order),
        ));
    }
}
