<?php

declare(strict_types=1);

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

namespace App\Filament\Resources\DberpPurchaseOrders;

use App\Business\Purchase\Enums\PurchaseExceptionResolutionResult;
use App\Business\Purchase\Enums\PurchaseExceptionStatus;
use App\Business\Purchase\Enums\PurchaseOrderStatus;
use App\Filament\Concerns\InteractsWithDberpPermissions;
use App\Filament\Contracts\DberpFilamentCreateSaveFirstGuidance;
use App\Filament\Contracts\DberpFilamentFormEditability;
use App\Filament\Resources\Concerns\HasDberpDocumentAddressSnapshots;
use App\Filament\Resources\DberpPurchaseOrders\Concerns\ProvidesDberpPurchaseOrderOverviewFormSections;
use App\Filament\Resources\DberpPurchaseOrders\Pages\CreateDberpPurchaseOrder;
use App\Filament\Resources\DberpPurchaseOrders\Pages\EditDberpPurchaseOrder;
use App\Filament\Resources\DberpPurchaseOrders\Pages\ListDberpPurchaseOrders;
use App\Filament\Resources\DberpPurchaseOrders\RelationManagers\ExceptionsRelationManager;
use App\Filament\Resources\DberpPurchaseOrders\RelationManagers\ItemsRelationManager;
use App\Filament\Resources\DberpPurchaseOrders\RelationManagers\ReceiptsRelationManager;
use App\Models\DberpEmployee;
use App\Models\DberpPurchaseOrder;
use App\Models\DberpSupplier;
use App\Services\DberpPermissionService;
use App\Support\DberpFilamentMasterDataSelectOptions;
use App\Support\DberpNumberFormatter;
use App\Support\DberpProductSkuSelectOptions;
use App\Support\DberpSourceSystemLabels;
use App\Support\PluginIntegration\LightApprovalFilamentBridge;
use BackedEnum;
use Filament\Actions\EditAction;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use UnitEnum;

class DberpPurchaseOrderResource extends Resource implements DberpFilamentCreateSaveFirstGuidance, DberpFilamentFormEditability
{
    use HasDberpDocumentAddressSnapshots;
    use InteractsWithDberpPermissions;
    use ProvidesDberpPurchaseOrderOverviewFormSections;

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

    protected static ?string $recordTitleAttribute = 'code';

    protected static ?int $navigationSort = 20;

    protected static bool $isGloballySearchable = true;

    protected static ?int $globalSearchSort = 40;

    protected static int $globalSearchResultsLimit = 30;

    /**
     * @return array<int, string>
     */
    public static function getGloballySearchableAttributes(): array
    {
        return [
            'code',
            'supplier.name',
            'supplier_contact_person_snapshot',
            'supplier_mobile_snapshot',
            'supplier_phone_snapshot',
        ];
    }

    public static function getGlobalSearchEloquentQuery(): Builder
    {
        return parent::getEloquentQuery();
    }

    public static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()->with(['supplier', 'handlerEmployee']);
    }

    /**
     * @return array<string, string>
     */
    public static function getGlobalSearchResultDetails(Model $record): array
    {
        if (! $record instanceof DberpPurchaseOrder) {
            return [];
        }

        $details = [
            (string) __('dberp.global_search.detail_document_code') => (string) $record->code,
        ];

        $supplierName = (string) ($record->supplier?->name ?? '');
        if ($supplierName !== '') {
            $details[(string) __('dberp.global_search.detail_counterparty')] = $supplierName;
        }

        return array_filter($details, static fn (string $v): bool => $v !== '');
    }

    public static function modifyGlobalSearchQuery(Builder $query, string $search): void
    {
        $query->with(['supplier']);
    }

    public static function isRecordFormEditableForFilament(Model $record): bool
    {
        return $record instanceof DberpPurchaseOrder
            && $record->status === PurchaseOrderStatus::Draft->value;
    }

    public static function createSaveFirstGuidanceTranslationKey(): ?string
    {
        return 'dberp.messages.save_document_first_then_manage_lines';
    }

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                ...static::purchaseOrderOverviewFormSections(),
                ...LightApprovalFilamentBridge::purchaseOrderFormSections(),
                Section::make(__('dberp.sections.purchase_document'))
                    ->schema([
                        TextInput::make('code')
                            ->label(__('dberp.fields.purchase_order_code'))
                            ->maxLength(64)
                            ->unique(ignoreRecord: true)
                            ->helperText(__('dberp.hints.auto_code'))
                            ->disabled(fn (?DberpPurchaseOrder $record): bool => $record !== null && $record->status !== PurchaseOrderStatus::Draft->value),
                        Select::make('supplier_id')
                            ->label(__('dberp.fields.supplier'))
                            ->options(fn (): array => DberpSupplier::query()
                                ->where('is_enabled', true)
                                ->orderBy('sort_order')
                                ->orderBy('id')
                                ->pluck('name', 'id')
                                ->all())
                            ->searchable()
                            ->preload()
                            ->required()
                            ->disabled(fn (?DberpPurchaseOrder $record): bool => $record !== null && $record->status !== PurchaseOrderStatus::Draft->value),
                        Select::make('handler_employee_id')
                            ->label(__('dberp.fields.handler_employee'))
                            ->options(fn (): array => DberpEmployee::selectOptionsForFilament(
                                fn (Builder $q) => $q->where('is_enabled', true),
                            ))
                            ->searchable()
                            ->preload()
                            ->disabled(fn (?DberpPurchaseOrder $record): bool => $record !== null && $record->status !== PurchaseOrderStatus::Draft->value),
                        DateTimePicker::make('business_time')
                            ->label(__('dberp.fields.business_time'))
                            ->default(now())
                            ->required()
                            ->seconds(false)
                            ->disabled(fn (?DberpPurchaseOrder $record): bool => $record !== null && $record->status !== PurchaseOrderStatus::Draft->value),
                        DatePicker::make('expected_arrival_date')
                            ->label(__('dberp.fields.expected_arrival_date'))
                            ->disabled(fn (?DberpPurchaseOrder $record): bool => $record !== null && in_array($record->status, [PurchaseOrderStatus::Closed->value, PurchaseOrderStatus::Voided->value], true)),
                        TextInput::make('source_system')
                            ->label(__('dberp.fields.source_system'))
                            ->helperText(__('dberp.hints.source_system_guidance'))
                            ->default('dberp')
                            ->maxLength(32)
                            ->disabled(fn (?DberpPurchaseOrder $record): bool => $record !== null && $record->status !== PurchaseOrderStatus::Draft->value),
                        TextInput::make('external_reference_id')
                            ->label(__('dberp.fields.external_reference_id'))
                            ->maxLength(128)
                            ->disabled(fn (?DberpPurchaseOrder $record): bool => $record !== null && $record->status !== PurchaseOrderStatus::Draft->value),
                        Textarea::make('remark')
                            ->label(__('dberp.fields.remark'))
                            ->rows(3)
                            ->columnSpanFull()
                            ->disabled(fn (?DberpPurchaseOrder $record): bool => $record !== null && $record->status !== PurchaseOrderStatus::Draft->value),
                    ])
                    ->columns(2),
                static::getDberpCounterpartySnapshotSection(__('dberp.fields.supplier_address_snapshot'), 'supplier'),
            ])->columns(1);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->defaultSort('business_time', 'desc')
            ->columns([
                TextColumn::make('code')
                    ->label(__('dberp.fields.purchase_order_code'))
                    ->searchable(),
                TextColumn::make('supplier.name')
                    ->label(__('dberp.fields.supplier'))
                    ->searchable(),
                TextColumn::make('source_system')
                    ->label(__('dberp.fields.source_system'))
                    ->badge()
                    ->formatStateUsing(fn (?string $state): string => DberpSourceSystemLabels::label($state))
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('external_reference_id')
                    ->label(__('dberp.fields.external_reference_id'))
                    ->searchable()
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('handlerEmployee.name')
                    ->label(__('dberp.fields.handler_employee'))
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('status')
                    ->label(__('dberp.fields.status'))
                    ->badge()
                    ->formatStateUsing(fn (?string $state): string => PurchaseOrderStatus::tryFrom((string) $state)?->label() ?? (string) $state),
                TextColumn::make('total_quantity')
                    ->label(__('dberp.fields.quantity'))
                    ->formatStateUsing(fn ($state): string => DberpNumberFormatter::quantity($state)),
                TextColumn::make('total_arrived_quantity')
                    ->label(__('dberp.fields.arrived_quantity'))
                    ->formatStateUsing(fn ($state): string => DberpNumberFormatter::quantity($state)),
                TextColumn::make('remaining_arrival_quantity')
                    ->label(__('dberp.fields.remaining_arrival_quantity'))
                    ->formatStateUsing(fn ($state): string => DberpNumberFormatter::quantity($state)),
                TextColumn::make('expected_arrival_date')
                    ->label(__('dberp.fields.expected_arrival_date'))
                    ->date()
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('last_arrival_date')
                    ->label(__('dberp.fields.last_arrival_date'))
                    ->date()
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('arrival_attention')
                    ->label(__('dberp.fields.arrival_attention'))
                    ->badge()
                    ->state(function (DberpPurchaseOrder $record): string {
                        if ((float) $record->remaining_arrival_quantity <= 0.00005) {
                            return '已完成';
                        }

                        if ($record->purchaseExceptions()->whereIn('status', [PurchaseExceptionStatus::Pending->value, PurchaseExceptionStatus::Processing->value])->where('resolution_result', PurchaseExceptionResolutionResult::Resupply->value)->exists()) {
                            return '待补送';
                        }

                        if ($record->purchaseExceptions()->whereIn('status', [PurchaseExceptionStatus::Pending->value, PurchaseExceptionStatus::Processing->value])->exists()) {
                            return '存在异常待处理';
                        }

                        if ($record->getRawOriginal('expected_arrival_date') !== null && (string) $record->getRawOriginal('expected_arrival_date') < now()->toDateString()) {
                            return '逾期待到货';
                        }

                        if ((float) $record->total_arrived_quantity > 0.00005) {
                            return '部分到货未完成';
                        }

                        return '待到货';
                    }),
                TextColumn::make('total_amount')
                    ->label(__('dberp.fields.line_amount'))
                    ->formatStateUsing(fn ($state): string => DberpNumberFormatter::money($state)),
                TextColumn::make('business_time')
                    ->label(__('dberp.fields.business_time'))
                    ->dateTime()
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('confirmed_at')
                    ->label(__('dberp.fields.confirmed_at'))
                    ->dateTime()
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('closed_at')
                    ->label(__('dberp.fields.closed_at'))
                    ->dateTime()
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('voided_at')
                    ->label(__('dberp.fields.voided_at'))
                    ->dateTime()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                SelectFilter::make('status')
                    ->label(__('dberp.fields.status'))
                    ->options(__('dberp.options.purchase_order_status')),
                SelectFilter::make('supplier_id')
                    ->label(__('dberp.fields.supplier'))
                    ->relationship('supplier', 'name'),
                SelectFilter::make('handler_employee_id')
                    ->label(__('dberp.fields.handler_employee'))
                    ->options(fn (): array => DberpEmployee::selectOptionsForFilament())
                    ->searchable()
                    ->preload(),
                Filter::make('product_id')
                    ->schema([
                        Select::make('product_id')
                            ->label(__('dberp.fields.product'))
                            ->options(fn (): array => DberpFilamentMasterDataSelectOptions::products(
                                enabledOnly: true,
                                scope: DberpProductSkuSelectOptions::PRODUCT_SCOPE_PURCHASABLE,
                            ))
                            ->searchable()
                            ->preload(),
                    ])
                    ->query(function (Builder $query, array $data): Builder {
                        return $query->when($data['product_id'] ?? null, fn (Builder $builder, $productId): Builder => $builder->whereHas('items', fn (Builder $itemQuery): Builder => $itemQuery->where('product_id', $productId)));
                    }),
                Filter::make('business_time_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, $date): Builder => $builder->whereDate('business_time', '>=', $date))
                            ->when($data['until'] ?? null, fn (Builder $builder, $date): Builder => $builder->whereDate('business_time', '<=', $date));
                    }),
                Filter::make('expected_arrival_date_range')
                    ->schema([
                        DatePicker::make('from')->label(__('dberp.fields.purchase_order_expected_from')),
                        DatePicker::make('until')->label(__('dberp.fields.purchase_order_expected_until')),
                    ])
                    ->query(function (Builder $query, array $data): Builder {
                        return $query
                            ->when($data['from'] ?? null, fn (Builder $builder, $date): Builder => $builder->whereDate('expected_arrival_date', '>=', $date))
                            ->when($data['until'] ?? null, fn (Builder $builder, $date): Builder => $builder->whereDate('expected_arrival_date', '<=', $date));
                    }),
                Filter::make('is_overdue')
                    ->label(__('dberp.fields.is_overdue'))
                    ->query(fn (Builder $query): Builder => $query
                        ->whereNotIn('status', [PurchaseOrderStatus::Draft->value, PurchaseOrderStatus::Closed->value, PurchaseOrderStatus::Voided->value])
                        ->where('remaining_arrival_quantity', '>', 0)
                        ->whereDate('expected_arrival_date', '<', now()->toDateString())),
                Filter::make('is_completed')
                    ->label(__('dberp.fields.is_completed'))
                    ->query(fn (Builder $query): Builder => $query->where('remaining_arrival_quantity', '<=', 0.00005)),
                Filter::make('has_pending_exception')
                    ->label(__('dberp.fields.has_pending_exception'))
                    ->query(fn (Builder $query): Builder => $query->whereHas('purchaseExceptions', fn (Builder $builder): Builder => $builder->whereIn('status', [PurchaseExceptionStatus::Pending->value, PurchaseExceptionStatus::Processing->value]))),
                Filter::make('pending_resupply')
                    ->label(__('dberp.fields.pending_resupply'))
                    ->query(fn (Builder $query): Builder => $query->whereHas('purchaseExceptions', fn (Builder $builder): Builder => $builder
                        ->whereIn('status', [PurchaseExceptionStatus::Pending->value, PurchaseExceptionStatus::Processing->value])
                        ->where('resolution_result', PurchaseExceptionResolutionResult::Resupply->value))),
            ])
            ->recordActions([
                EditAction::make(),
            ]);
    }

    public static function getRelations(): array
    {
        return [
            ItemsRelationManager::class,
            ReceiptsRelationManager::class,
            ExceptionsRelationManager::class,
            ...LightApprovalFilamentBridge::purchaseOrderRelationManagers(),
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => ListDberpPurchaseOrders::route('/'),
            'create' => CreateDberpPurchaseOrder::route('/create'),
            'edit' => EditDberpPurchaseOrder::route('/{record}/edit'),
        ];
    }

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

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

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

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

    public static function canViewAny(): bool
    {
        return static::allowsPermission(DberpPermissionService::VIEW_PURCHASE_ORDER);
    }

    public static function canView(Model $record): bool
    {
        return static::allowsPermission(DberpPermissionService::VIEW_PURCHASE_ORDER);
    }

    public static function canCreate(): bool
    {
        return static::allowsPermission(DberpPermissionService::CREATE_PURCHASE_ORDER);
    }

    public static function canEdit(Model $record): bool
    {
        return static::allowsPermission(DberpPermissionService::EDIT_PURCHASE_ORDER);
    }

    public static function canDelete(Model $record): bool
    {
        return static::allowsPermission(DberpPermissionService::EDIT_PURCHASE_ORDER);
    }
}
