<?php

declare(strict_types=1);

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

namespace App\Filament\Resources\DberpInventorySerialNumbers;

use App\Filament\Concerns\InteractsWithDberpPermissions;
use App\Filament\Resources\DberpInventorySerialNumbers\Pages\CreateDberpInventorySerialNumber;
use App\Filament\Resources\DberpInventorySerialNumbers\Pages\EditDberpInventorySerialNumber;
use App\Filament\Resources\DberpInventorySerialNumbers\Pages\ListDberpInventorySerialNumbers;
use App\Filament\Resources\DberpInventorySerialNumbers\Pages\ViewDberpInventorySerialNumber;
use App\Filament\Resources\DberpInventorySerialNumbers\RelationManagers\InventorySerialNumberExceptionsRelationManager;
use App\Filament\Resources\DberpInventorySerialNumbers\RelationManagers\InventorySerialNumberLogsRelationManager;
use App\Filament\Resources\DberpInventorySerialNumbers\RelationManagers\StocktakeSerialNumberDifferencesRelationManager;
use App\Filament\Support\DberpFilamentRelationshipSelectLimits;
use App\Models\DberpInventorySerialNumber;
use App\Services\DberpPermissionService;
use App\Support\DberpInventorySerialNumberPresentation;
use App\Support\DberpProductSkuSelectOptions;
use App\Support\DberpSourceSystemLabels;
use BackedEnum;
use Filament\Actions\EditAction;
use Filament\Actions\ViewAction;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Placeholder;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Infolists\Components\TextEntry;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Filters\TernaryFilter;
use Filament\Tables\Table;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use UnitEnum;

class DberpInventorySerialNumberResource extends Resource
{
    use InteractsWithDberpPermissions;

    protected static ?string $model = DberpInventorySerialNumber::class;

    protected static ?string $recordTitleAttribute = 'serial_no';

    protected static ?int $navigationSort = 120;

    public static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()->with([
            'product.defaultSku',
            'warehouse',
            'batch',
        ]);
    }

    public static function form(Schema $schema): Schema
    {
        return $schema->components([
            Section::make(__('dberp.sections.inventory_serial_number_governance'))
                ->description(__('dberp.hints.inventory_serial_number_governance_form'))
                ->schema([
                    Placeholder::make('_inventory_serial_governance_notice')
                        ->label(__('dberp.fields.governance_note'))
                        ->content(__('dberp.hints.inventory_serial_number_manual_maintenance_blocked'))
                        ->columnSpanFull(),
                    TextInput::make('sort_order')
                        ->label(__('dberp.fields.sort_order'))
                        ->numeric()
                        ->default(0)
                        ->required(),
                    Textarea::make('remark')
                        ->label(__('dberp.fields.remark'))
                        ->rows(3)
                        ->columnSpanFull(),
                ])
                ->columns(2),
        ])->columns(1);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->defaultSort('sort_order', 'asc')
            ->columns([
                TextColumn::make('serial_no')
                    ->label(__('dberp.fields.serial_no'))
                    ->searchable()
                    ->sortable(),
                TextColumn::make('product.code')
                    ->label(__('dberp.fields.product_code'))
                    ->searchable()
                    ->toggleable(),
                TextColumn::make('product.name')
                    ->label(__('dberp.fields.product_name'))
                    ->searchable(),
                TextColumn::make('product_sku_summary')
                    ->label(__('dberp.fields.document_line_product_spec_combo'))
                    ->state(fn (DberpInventorySerialNumber $record): string => DberpInventorySerialNumberPresentation::productSkuSummary($record->product))
                    ->wrap()
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('warehouse.name')
                    ->label(__('dberp.fields.warehouse')),
                TextColumn::make('batch.batch_no')
                    ->label(__('dberp.fields.batch_no'))
                    ->placeholder('—')
                    ->toggleable(),
                TextColumn::make('status')
                    ->label(__('dberp.fields.serial_number_status'))
                    ->badge()
                    ->color(fn (?string $state): string => DberpInventorySerialNumberPresentation::statusColor($state))
                    ->formatStateUsing(fn (?string $state): string => DberpInventorySerialNumberPresentation::statusLabel($state)),
                IconColumn::make('is_enabled')
                    ->label(__('dberp.fields.is_enabled'))
                    ->boolean()
                    ->getStateUsing(
                        fn (DberpInventorySerialNumber $record): bool => DberpInventorySerialNumberPresentation::isEnabledState(
                            $record->getAttribute('is_enabled'),
                        ),
                    ),
                TextColumn::make('source_document_no')
                    ->label(__('dberp.fields.source_document_no'))
                    ->searchable()
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('owner_summary')
                    ->label(__('dberp.fields.current_owner'))
                    ->state(fn (DberpInventorySerialNumber $record): string => DberpInventorySerialNumberPresentation::ownerSummary($record))
                    ->wrap()
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('inbound_at')
                    ->label(__('dberp.fields.inbound_at'))
                    ->dateTime()
                    ->sortable(),
                TextColumn::make('outbound_at')
                    ->label(__('dberp.fields.outbound_at'))
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                SelectFilter::make('warehouse_id')
                    ->label(__('dberp.fields.warehouse'))
                    ->relationship('warehouse', 'name'),
                DberpProductSkuSelectOptions::configureProductRelationshipTableFilter(
                    SelectFilter::make('product_id')->label(__('dberp.fields.product')),
                ),
                SelectFilter::make('batch_id')
                    ->label(__('dberp.fields.batch_no'))
                    ->relationship(
                        'batch',
                        'batch_no',
                        modifyQueryUsing: DberpFilamentRelationshipSelectLimits::limitInventoryBatchOptionsQuery(...),
                    ),
                SelectFilter::make('status')
                    ->label(__('dberp.fields.serial_number_status'))
                    ->options(__('dberp.options.inventory_serial_number_status')),
                TernaryFilter::make('is_enabled')
                    ->label(__('dberp.fields.is_enabled')),
                SelectFilter::make('current_owner_type')
                    ->label(__('dberp.fields.current_owner_type'))
                    ->options(__('dberp.options.inventory_serial_number_owner_type')),
                Filter::make('source_document_no')
                    ->schema([
                        TextInput::make('value')
                            ->label(__('dberp.fields.source_document_no')),
                    ])
                    ->query(function (Builder $query, array $data): Builder {
                        $value = trim((string) ($data['value'] ?? ''));

                        if ($value === '') {
                            return $query;
                        }

                        return $query->where('source_document_no', 'like', '%'.$value.'%');
                    }),
                Filter::make('inbound_at_range')
                    ->schema([
                        DatePicker::make('from')->label(__('dberp.fields.date_from')),
                        DatePicker::make('until')->label(__('dberp.fields.date_until')),
                    ])
                    ->query(function (Builder $query, array $data): Builder {
                        return $query
                            ->when($data['from'] ?? null, fn (Builder $builder, string $date): Builder => $builder->whereDate('inbound_at', '>=', $date))
                            ->when($data['until'] ?? null, fn (Builder $builder, string $date): Builder => $builder->whereDate('inbound_at', '<=', $date));
                    }),
                Filter::make('outbound_at_range')
                    ->schema([
                        DatePicker::make('from')->label(__('dberp.fields.date_from')),
                        DatePicker::make('until')->label(__('dberp.fields.date_until')),
                    ])
                    ->query(function (Builder $query, array $data): Builder {
                        return $query
                            ->when($data['from'] ?? null, fn (Builder $builder, string $date): Builder => $builder->whereDate('outbound_at', '>=', $date))
                            ->when($data['until'] ?? null, fn (Builder $builder, string $date): Builder => $builder->whereDate('outbound_at', '<=', $date));
                    }),
            ])
            ->recordActions([
                ViewAction::make(),
                EditAction::make()
                    ->visible(fn (DberpInventorySerialNumber $record): bool => static::canEdit($record)),
            ]);
    }

    public static function infolist(Schema $schema): Schema
    {
        return $schema->components([
            Section::make(__('dberp.sections.inventory_serial_number_identity'))
                ->description(__('dberp.hints.inventory_serial_number_detail_trace'))
                ->schema([
                    TextEntry::make('serial_no')
                        ->label(__('dberp.fields.serial_no'))
                        ->weight('bold')
                        ->size('lg')
                        ->columnSpanFull(),
                    TextEntry::make('status')
                        ->label(__('dberp.fields.serial_number_status'))
                        ->badge()
                        ->color(fn (?string $state): string => DberpInventorySerialNumberPresentation::statusColor($state))
                        ->formatStateUsing(fn (?string $state): string => DberpInventorySerialNumberPresentation::statusLabel($state)),
                    TextEntry::make('is_enabled')
                        ->label(__('dberp.fields.is_enabled'))
                        ->badge()
                        ->formatStateUsing(
                            fn (mixed $state): string => DberpInventorySerialNumberPresentation::enabledLabelFromState($state),
                        )
                        ->color(
                            fn (mixed $state): string => DberpInventorySerialNumberPresentation::isEnabledState($state) ? 'success' : 'danger',
                        ),
                    TextEntry::make('sort_order')
                        ->label(__('dberp.fields.sort_order')),
                ])
                ->columns(3),
            Section::make(__('dberp.sections.inventory_serial_number_product_location'))
                ->schema([
                    TextEntry::make('product.code')->label(__('dberp.fields.product_code')),
                    TextEntry::make('product.name')->label(__('dberp.fields.product_name')),
                    TextEntry::make('product_sku_summary')
                        ->label(__('dberp.fields.document_line_product_spec_combo'))
                        ->state(fn (DberpInventorySerialNumber $record): string => DberpInventorySerialNumberPresentation::productSkuSummary($record->product)),
                    TextEntry::make('warehouse.name')->label(__('dberp.fields.warehouse')),
                    TextEntry::make('batch.batch_no')
                        ->label(__('dberp.fields.batch_no'))
                        ->placeholder('—'),
                ])
                ->columns(3),
            Section::make(__('dberp.sections.inventory_serial_number_lifecycle'))
                ->schema([
                    TextEntry::make('inbound_at')
                        ->label(__('dberp.fields.inbound_at'))
                        ->dateTime()
                        ->placeholder('—'),
                    TextEntry::make('outbound_at')
                        ->label(__('dberp.fields.outbound_at'))
                        ->dateTime()
                        ->placeholder('—'),
                    TextEntry::make('source_document_summary')
                        ->label(__('dberp.fields.source_document'))
                        ->state(fn (DberpInventorySerialNumber $record): string => DberpInventorySerialNumberPresentation::sourceDocumentSummary($record)),
                    TextEntry::make('source_system')
                        ->label(__('dberp.fields.source_system'))
                        ->formatStateUsing(fn (mixed $state): string => DberpSourceSystemLabels::label($state))
                        ->placeholder('—'),
                    TextEntry::make('owner_summary')
                        ->label(__('dberp.fields.current_owner'))
                        ->state(fn (DberpInventorySerialNumber $record): string => DberpInventorySerialNumberPresentation::ownerSummary($record)),
                ])
                ->columns(3),
            Section::make(__('dberp.sections.inventory_serial_number_governance'))
                ->schema([
                    TextEntry::make('remark')
                        ->label(__('dberp.fields.remark'))
                        ->placeholder('—')
                        ->columnSpanFull(),
                    Placeholder::make('_governance_hint')
                        ->label(__('dberp.fields.governance_note'))
                        ->content(__('dberp.hints.inventory_serial_number_manual_maintenance_blocked'))
                        ->columnSpanFull(),
                ]),
        ]);
    }

    /**
     * @return array<class-string>
     */
    public static function getRelations(): array
    {
        return [
            InventorySerialNumberLogsRelationManager::class,
            InventorySerialNumberExceptionsRelationManager::class,
            StocktakeSerialNumberDifferencesRelationManager::class,
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => ListDberpInventorySerialNumbers::route('/'),
            'create' => CreateDberpInventorySerialNumber::route('/create'),
            'view' => ViewDberpInventorySerialNumber::route('/{record}'),
            'edit' => EditDberpInventorySerialNumber::route('/{record}/edit'),
        ];
    }

    public static function canViewAny(): bool
    {
        return static::allowsAnyPermission([
            DberpPermissionService::VIEW_INVENTORY_SERIAL_NUMBER,
            DberpPermissionService::MANAGE_INVENTORY_SERIAL_NUMBER,
            DberpPermissionService::DISABLE_INVENTORY_SERIAL_NUMBER,
        ]);
    }

    public static function canCreate(): bool
    {
        return false;
    }

    public static function canEdit(Model $record): bool
    {
        return $record instanceof DberpInventorySerialNumber
            && static::allowsPermission(DberpPermissionService::MANAGE_INVENTORY_SERIAL_NUMBER);
    }

    public static function canToggleEnabled(Model $record): bool
    {
        return $record instanceof DberpInventorySerialNumber
            && static::allowsAnyPermission([
                DberpPermissionService::MANAGE_INVENTORY_SERIAL_NUMBER,
                DberpPermissionService::DISABLE_INVENTORY_SERIAL_NUMBER,
            ]);
    }

    public static function canView(Model $record): bool
    {
        return static::canViewAny();
    }

    public static function canDelete(Model $record): bool
    {
        return false;
    }

    public static function getNavigationGroup(): string|UnitEnum|null
    {
        return __('dberp.nav.warehouse');
    }

    public static function getNavigationIcon(): string|BackedEnum|Htmlable|null
    {
        return null;
    }

    public static function getModelLabel(): string
    {
        return __('dberp.resources.inventory_serial_number.label');
    }

    public static function getPluralModelLabel(): string
    {
        return __('dberp.resources.inventory_serial_number.plural');
    }
}
