<?php

declare(strict_types=1);

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

namespace App\Filament\Resources\DberpPurchaseRequests;

use App\Business\Purchase\Enums\PurchaseRequestSourceType;
use App\Business\Purchase\Enums\PurchaseRequestStatus;
use App\Business\Purchase\Enums\PurchaseRequestUrgencyLevel;
use App\Filament\Concerns\InteractsWithDberpPermissions;
use App\Filament\Contracts\DberpFilamentCreateSaveFirstGuidance;
use App\Filament\Contracts\DberpFilamentFormEditability;
use App\Filament\Resources\DberpPurchaseRequests\Pages\CreateDberpPurchaseRequest;
use App\Filament\Resources\DberpPurchaseRequests\Pages\EditDberpPurchaseRequest;
use App\Filament\Resources\DberpPurchaseRequests\Pages\ListDberpPurchaseRequests;
use App\Filament\Resources\DberpPurchaseRequests\Pages\ViewDberpPurchaseRequest;
use App\Filament\Resources\DberpPurchaseRequests\RelationManagers\ItemsRelationManager;
use App\Models\DberpEmployee;
use App\Models\DberpPurchaseRequest;
use App\Models\DberpSupplier;
use App\Services\DberpPermissionService;
use App\Support\DberpNumberFormatter;
use App\Support\DberpSourceSystemLabels;
use App\Support\DberpSystemProfileBusinessDefaults;
use BackedEnum;
use Filament\Actions\EditAction;
use Filament\Actions\ViewAction;
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\Infolists\Components\TextEntry;
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 DberpPurchaseRequestResource extends Resource implements DberpFilamentCreateSaveFirstGuidance, DberpFilamentFormEditability
{
    use InteractsWithDberpPermissions;

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

    protected static ?string $recordTitleAttribute = 'code';

    protected static ?int $navigationSort = 10;

    public static function isRecordFormEditableForFilament(Model $record): bool
    {
        return $record instanceof DberpPurchaseRequest
            && in_array($record->status, [PurchaseRequestStatus::Draft->value, PurchaseRequestStatus::Pending->value], true);
    }

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

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->columns(1)
            ->components([
                Section::make(__('dberp.sections.purchase_request'))
                    ->schema([
                        TextInput::make('code')
                            ->label(__('dberp.fields.purchase_request_code'))
                            ->maxLength(64)
                            ->unique(ignoreRecord: true)
                            ->helperText(__('dberp.hints.auto_code'))
                            ->disabled(fn (?DberpPurchaseRequest $record): bool => $record instanceof DberpPurchaseRequest && $record->exists),
                        Select::make('source_type')
                            ->label(__('dberp.fields.source_type'))
                            ->options(PurchaseRequestSourceType::options())
                            ->default(fn (): string => DberpSystemProfileBusinessDefaults::defaultPurchaseRequestSourceType())
                            ->helperText(__('dberp.hints.purchase_request_source_type'))
                            ->disabled(fn (?DberpPurchaseRequest $record): bool => $record instanceof DberpPurchaseRequest && $record->exists),
                        TextInput::make('source_reference_no')
                            ->label(__('dberp.fields.source_reference_no'))
                            ->maxLength(128)
                            ->helperText(__('dberp.hints.purchase_request_source_reference_no'))
                            ->disabled(fn (?DberpPurchaseRequest $record): bool => $record instanceof DberpPurchaseRequest
                                && $record->exists
                                && $record->source_type !== PurchaseRequestSourceType::Manual->value),
                        TextInput::make('source_system')
                            ->label(__('dberp.fields.source_system'))
                            ->default('dberp')
                            ->maxLength(32)
                            ->helperText(__('dberp.hints.purchase_request_source_system')),
                        TextInput::make('external_reference_id')
                            ->label(__('dberp.fields.external_reference_id'))
                            ->maxLength(128)
                            ->helperText(__('dberp.hints.purchase_request_external_reference_id')),
                        DateTimePicker::make('request_time')
                            ->label(__('dberp.fields.request_time'))
                            ->default(now())
                            ->seconds(false)
                            ->required(),
                        TextInput::make('department_name')
                            ->label(__('dberp.fields.department_name'))
                            ->maxLength(120),
                        Select::make('applicant_employee_id')
                            ->label(__('dberp.fields.applicant_employee'))
                            ->options(fn (): array => DberpEmployee::selectOptionsForFilament(
                                fn (Builder $q) => $q->where('is_enabled', true),
                            ))
                            ->searchable()
                            ->preload(),
                        Select::make('suggested_supplier_id')
                            ->label(__('dberp.fields.suggested_supplier'))
                            ->options(fn (): array => DberpSupplier::query()
                                ->where('is_enabled', true)
                                ->orderBy('sort_order')
                                ->orderBy('id')
                                ->pluck('name', 'id')
                                ->all())
                            ->searchable()
                            ->preload()
                            ->helperText(__('dberp.hints.purchase_request_suggested_supplier')),
                        Select::make('urgency_level')
                            ->label(__('dberp.fields.urgency_level'))
                            ->options(PurchaseRequestUrgencyLevel::options())
                            ->default(PurchaseRequestUrgencyLevel::Normal->value)
                            ->required(),
                        DatePicker::make('expected_arrival_date')
                            ->label(__('dberp.fields.expected_arrival_date')),
                        TextInput::make('request_reason')
                            ->label(__('dberp.fields.request_reason'))
                            ->maxLength(255),
                        Textarea::make('remark')
                            ->label(__('dberp.fields.remark'))
                            ->rows(3)
                            ->columnSpanFull(),
                    ])
                    ->columns(2),
            ]);
    }

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

    public static function table(Table $table): Table
    {
        return $table
            ->defaultSort('request_time', 'desc')
            ->columns([
                TextColumn::make('code')
                    ->label(__('dberp.fields.purchase_request_code'))
                    ->searchable(),
                TextColumn::make('source_type')
                    ->label(__('dberp.fields.source_type'))
                    ->badge()
                    ->formatStateUsing(fn (?string $state): string => PurchaseRequestSourceType::tryFrom((string) $state)?->label() ?? (string) $state),
                TextColumn::make('source_reference_no')
                    ->label(__('dberp.fields.source_reference_no'))
                    ->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('department_name')
                    ->label(__('dberp.fields.department_name'))
                    ->searchable(),
                TextColumn::make('applicantEmployee.name')
                    ->label(__('dberp.fields.applicant_employee'))
                    ->searchable(),
                TextColumn::make('suggestedSupplier.name')
                    ->label(__('dberp.fields.suggested_supplier'))
                    ->searchable()
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('urgency_level')
                    ->label(__('dberp.fields.urgency_level'))
                    ->badge()
                    ->formatStateUsing(fn (?string $state): string => PurchaseRequestUrgencyLevel::tryFrom((string) $state)?->label() ?? (string) $state),
                TextColumn::make('status')
                    ->label(__('dberp.fields.status'))
                    ->badge()
                    ->formatStateUsing(fn (?string $state): string => PurchaseRequestStatus::tryFrom((string) $state)?->label() ?? (string) $state),
                TextColumn::make('total_quantity')
                    ->label(__('dberp.fields.request_quantity'))
                    ->formatStateUsing(fn ($state): string => DberpNumberFormatter::quantity($state)),
                TextColumn::make('converted_quantity')
                    ->label(__('dberp.fields.converted_quantity'))
                    ->formatStateUsing(fn ($state): string => DberpNumberFormatter::quantity($state)),
                TextColumn::make('remaining_quantity')
                    ->label(__('dberp.fields.remaining_quantity'))
                    ->formatStateUsing(fn ($state): string => DberpNumberFormatter::quantity($state)),
                TextColumn::make('request_time')
                    ->label(__('dberp.fields.request_time'))
                    ->dateTime(),
                TextColumn::make('expected_arrival_date')
                    ->label(__('dberp.fields.expected_arrival_date'))
                    ->date()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                SelectFilter::make('status')
                    ->label(__('dberp.fields.status'))
                    ->options(PurchaseRequestStatus::options()),
                SelectFilter::make('source_type')
                    ->label(__('dberp.fields.source_type'))
                    ->options(PurchaseRequestSourceType::options()),
                SelectFilter::make('urgency_level')
                    ->label(__('dberp.fields.urgency_level'))
                    ->options(PurchaseRequestUrgencyLevel::options()),
                SelectFilter::make('applicant_employee_id')
                    ->label(__('dberp.fields.applicant_employee'))
                    ->options(fn (): array => DberpEmployee::selectOptionsForFilament())
                    ->searchable()
                    ->preload(),
                SelectFilter::make('suggested_supplier_id')
                    ->label(__('dberp.fields.suggested_supplier'))
                    ->relationship('suggestedSupplier', 'name'),
                Filter::make('request_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('request_time', '>=', $date))
                            ->when($data['until'] ?? null, fn (Builder $builder, $date): Builder => $builder->whereDate('request_time', '<=', $date));
                    }),
            ])
            ->recordActions([
                ViewAction::make(),
                EditAction::make(),
            ]);
    }

    public static function infolist(Schema $schema): Schema
    {
        return $schema
            ->columns(1)
            ->components([
                Section::make(__('dberp.sections.purchase_request'))
                    ->schema([
                        TextEntry::make('code')->label(__('dberp.fields.purchase_request_code')),
                        TextEntry::make('source_type')
                            ->label(__('dberp.fields.source_type'))
                            ->badge()
                            ->formatStateUsing(fn (?string $state): string => PurchaseRequestSourceType::tryFrom((string) $state)?->label() ?? (string) $state),
                        TextEntry::make('source_reference_no')->label(__('dberp.fields.source_reference_no')),
                        TextEntry::make('source_system')
                            ->label(__('dberp.fields.source_system'))
                            ->formatStateUsing(fn (?string $state): string => DberpSourceSystemLabels::label($state)),
                        TextEntry::make('external_reference_id')->label(__('dberp.fields.external_reference_id')),
                        TextEntry::make('request_time')->label(__('dberp.fields.request_time'))->dateTime(),
                        TextEntry::make('department_name')->label(__('dberp.fields.department_name')),
                        TextEntry::make('applicantEmployee.name')->label(__('dberp.fields.applicant_employee')),
                        TextEntry::make('suggestedSupplier.name')->label(__('dberp.fields.suggested_supplier')),
                        TextEntry::make('urgency_level')
                            ->label(__('dberp.fields.urgency_level'))
                            ->badge()
                            ->formatStateUsing(fn (?string $state): string => PurchaseRequestUrgencyLevel::tryFrom((string) $state)?->label() ?? (string) $state),
                        TextEntry::make('expected_arrival_date')->label(__('dberp.fields.expected_arrival_date'))->date(),
                        TextEntry::make('status')
                            ->label(__('dberp.fields.status'))
                            ->badge()
                            ->formatStateUsing(fn (?string $state): string => PurchaseRequestStatus::tryFrom((string) $state)?->label() ?? (string) $state),
                        TextEntry::make('total_quantity')->label(__('dberp.fields.request_quantity'))->formatStateUsing(fn ($state): string => DberpNumberFormatter::quantity($state)),
                        TextEntry::make('converted_quantity')->label(__('dberp.fields.converted_quantity'))->formatStateUsing(fn ($state): string => DberpNumberFormatter::quantity($state)),
                        TextEntry::make('remaining_quantity')->label(__('dberp.fields.remaining_quantity'))->formatStateUsing(fn ($state): string => DberpNumberFormatter::quantity($state)),
                        TextEntry::make('request_reason')->label(__('dberp.fields.request_reason')),
                        TextEntry::make('remark')->label(__('dberp.fields.remark'))->columnSpanFull(),
                    ])
                    ->columns(2),
            ]);
    }

    public static function getRelations(): array
    {
        return [
            ItemsRelationManager::class,
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => ListDberpPurchaseRequests::route('/'),
            'create' => CreateDberpPurchaseRequest::route('/create'),
            'view' => ViewDberpPurchaseRequest::route('/{record}'),
            'edit' => EditDberpPurchaseRequest::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_request.label');
    }

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

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

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

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

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

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