<?php

declare(strict_types=1);

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

namespace App\Filament\Resources\DberpPurchaseReceipts\RelationManagers;

use App\Business\Inventory\Enums\InventoryDocumentStatus;
use App\Business\Purchase\Enums\PurchaseExceptionType;
use App\Filament\Support\DberpFilamentNumberFields;
use App\Models\DberpPurchaseOrderItem;
use App\Models\DberpPurchaseReceiptOrder;
use App\Support\DberpDocumentLineInboundSerialNumberFormFields;
use App\Support\DberpDocumentLinePresentation;
use App\Support\DberpDocumentLineSerialNumberFormFields;
use App\Support\DberpDocumentLineSpecPresentation;
use App\Support\DberpDocumentLineUnitFormFields;
use App\Support\DberpLineProductSkuFormFields;
use App\Support\DberpNumberFormatter;
use App\Support\DberpProductInventoryRefinementFormFields;
use Filament\Actions\CreateAction;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Components\Utilities\Set;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Model;

class ItemsRelationManager extends RelationManager
{
    protected static string $relationship = 'items';

    public static function getTitle(Model $ownerRecord, string $pageClass): string
    {
        return __('dberp.relations.purchase_receipt_items');
    }

    protected static function getModelLabel(): ?string
    {
        return __('dberp.fields.purchase_receipt_item');
    }

    protected static function getPluralModelLabel(): ?string
    {
        return __('dberp.relations.purchase_receipt_items');
    }

    public function form(Schema $schema): Schema
    {
        $resolveProduct = DberpDocumentLineUnitFormFields::resolveProductFromPurchaseOrderItemField('purchase_order_item_id');

        return $schema
            ->components(array_merge([
                DberpDocumentLineUnitFormFields::wireProductDriver(
                    Select::make('purchase_order_item_id')
                        ->label(__('dberp.fields.purchase_order_item'))
                        ->options(function (): array {
                            /** @var DberpPurchaseReceiptOrder $owner */
                            $owner = $this->getOwnerRecord();

                            if ($owner->purchase_order_id === null) {
                                return [];
                            }

                            return DberpPurchaseOrderItem::query()
                                ->with(['product', 'productSku'])
                                ->where('order_id', $owner->purchase_order_id)
                                ->orderBy('sort_order')
                                ->orderBy('id')
                                ->get()
                                ->mapWithKeys(fn (DberpPurchaseOrderItem $item): array => [
                                    $item->getKey() => sprintf(
                                        '%s / %s / %s / 剩余未到 %s',
                                        (string) $item->product?->code,
                                        (string) $item->product?->name,
                                        trim(implode(' ', array_filter([(string) ($item->spec_text ?? ''), (string) ($item->sku_code ?? '')]))),
                                        DberpNumberFormatter::quantity($item->remaining_arrival_quantity),
                                    ),
                                ])
                                ->all();
                        })
                        ->searchable()
                        ->preload()
                        ->required(),
                    DberpDocumentLineUnitFormFields::resolveProductFromPurchaseOrderItemField('purchase_order_item_id'),
                    function (Set $set, Get $get) use ($resolveProduct): void {
                        DberpLineProductSkuFormFields::applyFromPurchaseOrderItemSelectionForReceipt(
                            $set,
                            (int) ($get('purchase_order_item_id') ?? 0) ?: null,
                        );
                        DberpDocumentLineUnitFormFields::syncUnitIdFromResolvedProduct($set, $get, $resolveProduct);
                    },
                ),
            ], DberpDocumentLineUnitFormFields::blocks(
                $resolveProduct,
                false,
                fn (): bool => DberpDocumentLineUnitFormFields::ownerStatusLocksDocumentLineFields(
                    $this->getOwnerRecord()->status,
                    InventoryDocumentStatus::Draft->value,
                ),
            ), DberpDocumentLineUnitFormFields::withApproxBasePreviewAfterQuantityField([
                DberpProductInventoryRefinementFormFields::constrainBatchField(
                    TextInput::make('batch_no')
                        ->label(__('dberp.fields.batch_no'))
                        ->maxLength(64),
                    $resolveProduct,
                ),
                DberpProductInventoryRefinementFormFields::constrainExpiryField(
                    DatePicker::make('production_date')
                        ->label(__('dberp.fields.production_date')),
                    $resolveProduct,
                ),
                DberpProductInventoryRefinementFormFields::constrainExpiryField(
                    DatePicker::make('expiry_date')
                        ->label(__('dberp.fields.expiry_date')),
                    $resolveProduct,
                ),
                DberpProductInventoryRefinementFormFields::constrainExpiryField(
                    TextInput::make('shelf_life_days')
                        ->label(__('dberp.fields.shelf_life_days'))
                        ->numeric()
                        ->minValue(0)
                        ->default(0),
                    $resolveProduct,
                ),
                DberpFilamentNumberFields::documentLineQuantityInput(
                    TextInput::make('arrival_quantity')
                        ->label(__('dberp.fields.arrival_quantity'))
                        ->helperText(__('dberp.hints.purchase_receipt_default_remaining_quantity'))
                        ->required(),
                    withHelperText: false,
                ),
                DberpDocumentLineSerialNumberFormFields::documentLineQuantityTrimsSerialNumbers(
                    DberpFilamentNumberFields::documentLineQuantityInput(
                        TextInput::make('received_quantity')
                            ->label(__('dberp.fields.receipt_quantity'))
                            ->helperText(__('dberp.hints.purchase_receipt_default_remaining_quantity'))
                            ->required(),
                        withHelperText: false,
                        minValue: 0.0,
                    ),
                    $resolveProduct,
                ),
                ...DberpDocumentLineInboundSerialNumberFormFields::inboundSerialNumberFields(
                    $resolveProduct,
                    'received_quantity',
                ),
                DberpFilamentNumberFields::moneyInput(
                    TextInput::make('unit_price')
                        ->label(__('dberp.fields.unit_price'))
                        ->helperText(__('dberp.hints.purchase_receipt_unit_price_from_order'))
                        ->default(0)
                        ->required(),
                    withHelperText: false,
                    minValue: 0.0,
                ),
                Select::make('exception_type')
                    ->label(__('dberp.fields.exception_type'))
                    ->options(PurchaseExceptionType::options()),
                Textarea::make('exception_reason_detail')
                    ->label(__('dberp.fields.reason_detail'))
                    ->rows(2)
                    ->columnSpanFull(),
                Textarea::make('handling_suggestion')
                    ->label(__('dberp.fields.handling_suggestion'))
                    ->rows(2)
                    ->columnSpanFull(),
                TextInput::make('sort_order')
                    ->label(__('dberp.fields.sort_order'))
                    ->numeric()
                    ->default(0)
                    ->required(),
                Textarea::make('remark')
                    ->label(__('dberp.fields.remark'))
                    ->rows(2)
                    ->columnSpanFull(),
            ], 'received_quantity', $resolveProduct)));
    }

    public function table(Table $table): Table
    {
        return $table
            ->modifyQueryUsing(fn ($query) => $query->with(DberpDocumentLineSpecPresentation::eagerLoadsForDocumentLines(['baseUnit', 'auxiliaryUnit'])))
            ->recordTitleAttribute('product.name')
            ->defaultSort('sort_order', 'asc')
            ->columns([
                TextColumn::make('product.code')
                    ->label(__('dberp.fields.product_code')),
                TextColumn::make('product.name')
                    ->label(__('dberp.fields.product_name')),
                TextColumn::make('document_line_spec_summary')
                    ->label(__('dberp.fields.document_line_product_spec_combo'))
                    ->state(fn (Model $record): string => DberpDocumentLineSpecPresentation::lineSpecSummary($record))
                    ->wrap(),
                TextColumn::make('document_line_spec_code')
                    ->label(__('dberp.fields.document_line_spec_code'))
                    ->state(fn (Model $record): string => DberpDocumentLineSpecPresentation::lineSpecCode($record)),
                TextColumn::make('document_line_spec_abstract')
                    ->label(__('dberp.fields.document_line_spec_summary'))
                    ->state(fn (Model $record): string => DberpDocumentLineSpecPresentation::lineSpecAbstract($record))
                    ->wrap()
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('unit_name')
                    ->label(__('dberp.fields.document_line_entered_unit')),
                TextColumn::make('arrival_quantity')
                    ->label(__('dberp.fields.arrival_quantity'))
                    ->formatStateUsing(fn ($state): string => DberpNumberFormatter::quantity($state)),
                TextColumn::make('received_quantity')
                    ->label(__('dberp.fields.document_line_entered_quantity'))
                    ->formatStateUsing(fn ($state): string => DberpNumberFormatter::quantity($state)),
                TextColumn::make('document_line_primary_base_received')
                    ->label(__('dberp.fields.document_line_primary_base_quantity'))
                    ->state(fn ($record): string => DberpDocumentLinePresentation::primaryBaseQuantityDisplay($record))
                    ->toggleable(),
                TextColumn::make('document_line_primary_base_arrival')
                    ->label(__('dberp.fields.document_line_primary_base_arrival_quantity'))
                    ->state(fn ($record): string => DberpDocumentLinePresentation::receiptBaseArrivalDisplay($record))
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('document_line_conversion_snapshot')
                    ->label(__('dberp.fields.document_line_conversion_snapshot'))
                    ->state(fn ($record): string => DberpDocumentLinePresentation::conversionSnapshotLine($record))
                    ->wrap()
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('exception_type')
                    ->label(__('dberp.fields.exception_type'))
                    ->badge()
                    ->formatStateUsing(fn (?string $state): string => PurchaseExceptionType::options()[$state] ?? (string) $state),
                TextColumn::make('returned_quantity')
                    ->label(__('dberp.fields.returned_quantity'))
                    ->formatStateUsing(fn ($state): string => DberpNumberFormatter::quantity($state))
                    ->toggleable(isToggledHiddenByDefault: true),
                DberpProductInventoryRefinementFormFields::constrainBatchColumn(
                    TextColumn::make('batch_no')
                        ->label(__('dberp.fields.batch_no'))
                        ->toggleable(),
                ),
                DberpProductInventoryRefinementFormFields::constrainExpiryColumn(
                    TextColumn::make('expiry_date')
                        ->label(__('dberp.fields.expiry_date'))
                        ->date()
                        ->toggleable(isToggledHiddenByDefault: true),
                ),
                DberpProductInventoryRefinementFormFields::constrainSerialColumn(
                    TextColumn::make('serial_numbers_count')
                        ->label(__('dberp.fields.serial_number_count'))
                        ->state(fn ($record): int => count($record->serial_numbers ?? []))
                        ->toggleable(isToggledHiddenByDefault: true),
                ),
                TextColumn::make('unit_price')
                    ->label(__('dberp.fields.unit_price'))
                    ->formatStateUsing(fn ($state): string => DberpNumberFormatter::price($state)),
                TextColumn::make('line_amount')
                    ->label(__('dberp.fields.line_amount'))
                    ->formatStateUsing(fn ($state): string => DberpNumberFormatter::money($state)),
                TextColumn::make('exception_reason_detail')
                    ->label(__('dberp.fields.reason_detail'))
                    ->limit(20)
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('sort_order')
                    ->label(__('dberp.fields.sort_order')),
            ])
            ->headerActions([
                CreateAction::make()
                    ->visible(fn (): bool => $this->getOwnerRecord()->status === InventoryDocumentStatus::Draft->value),
            ])
            ->recordActions([
                EditAction::make()
                    ->visible(fn (): bool => $this->getOwnerRecord()->status === InventoryDocumentStatus::Draft->value),
                DeleteAction::make()
                    ->visible(fn (): bool => $this->getOwnerRecord()->status === InventoryDocumentStatus::Draft->value),
            ]);
    }
}
