<?php

declare(strict_types=1);

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

namespace App\Filament\Resources\DberpPurchaseInquiries\Pages;

use App\Business\Purchase\PurchaseInquiryGenerationService;
use App\Filament\Resources\DberpPurchaseInquiries\Concerns\ProvidesDberpPurchaseInquiryFromRequestFormFields;
use App\Filament\Resources\DberpPurchaseInquiries\DberpPurchaseInquiryResource;
use App\Filament\Resources\Pages\CreateRecord;
use App\Models\DberpPurchaseRequest;
use Filament\Schemas\Schema;
use Filament\Support\Enums\Width;
use Illuminate\Database\Eloquent\Model;

class CreateDberpPurchaseInquiry extends CreateRecord
{
    use ProvidesDberpPurchaseInquiryFromRequestFormFields;

    protected static string $resource = DberpPurchaseInquiryResource::class;

    protected Width|string|null $maxContentWidth = Width::Full;

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

        $purchaseRequestId = request()->integer('purchase_request_id') ?: null;

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

        $this->form->fill([
            'purchase_request_id' => $purchaseRequestId,
            'inquiry_date' => now()->toDateString(),
            'lines' => $this->buildInquiryLinesFromPurchaseRequest($purchaseRequestId),
            'handler_employee_id' => DberpPurchaseRequest::query()->whereKey($purchaseRequestId)->value('applicant_employee_id'),
            'supplier_ids' => ($supplierId = DberpPurchaseRequest::query()->whereKey($purchaseRequestId)->value('suggested_supplier_id'))
                ? [(int) $supplierId]
                : [],
        ]);
    }

    public function form(Schema $schema): Schema
    {
        return $schema
            ->columns(1)
            ->components($this->purchaseInquiryFromRequestFormSections());
    }

    protected function getRedirectUrl(): string
    {
        $record = $this->getRecord();
        $resource = static::getResource();

        if ($resource::hasPage('view') && $resource::canView($record)) {
            return $this->getResourceUrl('view', $this->getRedirectUrlParameters());
        }

        return parent::getRedirectUrl();
    }

    /**
     * @param  array<string, mixed>  $data
     */
    protected function handleRecordCreation(array $data): Model
    {
        $request = DberpPurchaseRequest::query()->findOrFail((int) $data['purchase_request_id']);

        return app(PurchaseInquiryGenerationService::class)->generateFromPurchaseRequest(
            request: $request,
            itemQuantities: $this->extractInquiryLineQuantitiesFromForm($data),
            supplierIds: array_values(array_map(intval(...), (array) ($data['supplier_ids'] ?? []))),
            handlerEmployeeId: ($data['handler_employee_id'] ?? null) ? (int) $data['handler_employee_id'] : null,
            inquiryDate: $data['inquiry_date'] ?? now()->toDateString(),
            remark: $data['remark'] ?? null,
        );
    }
}
