<?php

declare(strict_types=1);

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

namespace App\Filament\Resources\DberpPurchaseInquiries;

use App\Business\Purchase\Enums\PurchaseInquiryStatus;
use App\Business\Purchase\Enums\PurchaseRequestStatus;
use App\Filament\Concerns\InteractsWithDberpPermissions;
use App\Filament\Resources\DberpPurchaseInquiries\Pages\CreateDberpPurchaseInquiry;
use App\Filament\Resources\DberpPurchaseInquiries\Pages\EditDberpPurchaseInquiry;
use App\Filament\Resources\DberpPurchaseInquiries\Pages\ListDberpPurchaseInquiries;
use App\Filament\Resources\DberpPurchaseInquiries\Pages\ViewDberpPurchaseInquiry;
use App\Filament\Resources\DberpPurchaseInquiries\RelationManagers\ItemsRelationManager;
use App\Filament\Resources\DberpPurchaseInquiries\RelationManagers\QuotesRelationManager;
use App\Models\DberpEmployee;
use App\Models\DberpPurchaseInquiry;
use App\Models\DberpPurchaseRequest;
use App\Services\DberpPermissionService;
use BackedEnum;
use Filament\Actions\EditAction;
use Filament\Actions\ViewAction;
use Filament\Forms\Components\DatePicker;
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\SelectFilter;
use Filament\Tables\Table;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use UnitEnum;

class DberpPurchaseInquiryResource extends Resource
{
    use InteractsWithDberpPermissions;

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

    protected static ?string $recordTitleAttribute = 'code';

    protected static ?int $navigationSort = 9;

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->columns(1)
            ->components([
                Section::make(__('dberp.sections.purchase_inquiry'))
                    ->schema([
                        TextInput::make('code')
                            ->label(__('dberp.fields.purchase_inquiry_code'))
                            ->disabled()
                            ->dehydrated(false)
                            ->visible(fn (?DberpPurchaseInquiry $record): bool => $record instanceof DberpPurchaseInquiry && $record->exists),
                        Select::make('purchase_request_id')
                            ->label(__('dberp.fields.purchase_request'))
                            ->options(fn (): array => static::selectablePurchaseRequestOptions())
                            ->searchable()
                            ->preload()
                            ->required()
                            ->disabled(fn (?DberpPurchaseInquiry $record): bool => $record instanceof DberpPurchaseInquiry && $record->exists),
                        DatePicker::make('inquiry_date')
                            ->label(__('dberp.fields.purchase_inquiry_date'))
                            ->default(fn () => now()->toDateString())
                            ->required()
                            ->disabled(fn (?DberpPurchaseInquiry $record): bool => $record instanceof DberpPurchaseInquiry
                                && $record->exists
                                && $record->status !== PurchaseInquiryStatus::Open->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 (?DberpPurchaseInquiry $record): bool => $record instanceof DberpPurchaseInquiry
                                && $record->exists
                                && $record->status !== PurchaseInquiryStatus::Open->value),
                        Select::make('status')
                            ->label(__('dberp.fields.status'))
                            ->options(PurchaseInquiryStatus::options())
                            ->default(PurchaseInquiryStatus::Open->value)
                            ->visible(fn (?DberpPurchaseInquiry $record): bool => $record instanceof DberpPurchaseInquiry && $record->exists)
                            ->disabled(fn (?DberpPurchaseInquiry $record): bool => $record instanceof DberpPurchaseInquiry
                                && $record->status !== PurchaseInquiryStatus::Open->value),
                        Textarea::make('remark')
                            ->label(__('dberp.fields.remark'))
                            ->rows(3)
                            ->columnSpanFull()
                            ->disabled(fn (?DberpPurchaseInquiry $record): bool => $record instanceof DberpPurchaseInquiry
                                && $record->exists
                                && $record->status !== PurchaseInquiryStatus::Open->value),
                    ])
                    ->columns(3),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->defaultSort('inquiry_date', 'desc')
            ->columns([
                TextColumn::make('code')
                    ->label(__('dberp.fields.purchase_inquiry_code'))
                    ->searchable(),
                TextColumn::make('purchase_request_code')
                    ->label(__('dberp.fields.purchase_request_code'))
                    ->searchable(),
                TextColumn::make('inquiry_date')
                    ->label(__('dberp.fields.purchase_inquiry_date'))
                    ->date(),
                TextColumn::make('handlerEmployee.name')
                    ->label(__('dberp.fields.handler_employee')),
                TextColumn::make('status')
                    ->label(__('dberp.fields.status'))
                    ->badge()
                    ->formatStateUsing(fn (?string $state): string => PurchaseInquiryStatus::tryFrom((string) $state)?->label() ?? (string) $state),
                TextColumn::make('items_count')
                    ->label(__('dberp.relations.purchase_inquiry_items'))
                    ->counts('items'),
                TextColumn::make('quotes_count')
                    ->label(__('dberp.relations.purchase_inquiry_quotes'))
                    ->counts('quotes'),
            ])
            ->filters([
                SelectFilter::make('status')
                    ->label(__('dberp.fields.status'))
                    ->options(PurchaseInquiryStatus::options()),
                SelectFilter::make('purchase_request_id')
                    ->label(__('dberp.fields.purchase_request'))
                    ->relationship('purchaseRequest', 'code'),
            ])
            ->recordActions([
                ViewAction::make(),
                EditAction::make(),
            ]);
    }

    public static function infolist(Schema $schema): Schema
    {
        return $schema->components([
            Section::make(__('dberp.sections.purchase_inquiry'))
                ->schema([
                    TextEntry::make('code')->label(__('dberp.fields.purchase_inquiry_code')),
                    TextEntry::make('purchase_request_code')->label(__('dberp.fields.purchase_request_code')),
                    TextEntry::make('inquiry_date')->label(__('dberp.fields.purchase_inquiry_date'))->date(),
                    TextEntry::make('handlerEmployee.name')->label(__('dberp.fields.handler_employee')),
                    TextEntry::make('status')
                        ->label(__('dberp.fields.status'))
                        ->badge()
                        ->formatStateUsing(fn (?string $state): string => PurchaseInquiryStatus::tryFrom((string) $state)?->label() ?? (string) $state),
                    TextEntry::make('remark')->label(__('dberp.fields.remark'))->columnSpanFull(),
                ])
                ->columns(3),
        ])->columns(1);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => ListDberpPurchaseInquiries::route('/'),
            'create' => CreateDberpPurchaseInquiry::route('/create'),
            'view' => ViewDberpPurchaseInquiry::route('/{record}'),
            'edit' => EditDberpPurchaseInquiry::route('/{record}/edit'),
        ];
    }

    /**
     * @return array<int, string>
     */
    public static function selectablePurchaseRequestOptions(): array
    {
        return DberpPurchaseRequest::query()
            ->whereIn('status', [
                PurchaseRequestStatus::Pending->value,
                PurchaseRequestStatus::PartiallyConverted->value,
            ])
            ->where('remaining_quantity', '>', 0)
            ->orderByDesc('request_time')
            ->pluck('code', 'id')
            ->all();
    }

    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_inquiry.label');
    }

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

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

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

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

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

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