<?php

declare(strict_types=1);

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

namespace App\Filament\Resources\DberpPurchaseInquiryQuotes;

use App\Business\Purchase\Enums\PurchaseInquiryQuoteStatus;
use App\Filament\Concerns\InteractsWithDberpPermissions;
use App\Filament\Resources\DberpPurchaseInquiryQuotes\Pages\CreateDberpPurchaseInquiryQuote;
use App\Filament\Resources\DberpPurchaseInquiryQuotes\Pages\EditDberpPurchaseInquiryQuote;
use App\Filament\Resources\DberpPurchaseInquiryQuotes\Pages\ListDberpPurchaseInquiryQuotes;
use App\Filament\Resources\DberpPurchaseInquiryQuotes\Pages\ViewDberpPurchaseInquiryQuote;
use App\Filament\Support\DberpFilamentNumberFields;
use App\Models\DberpPurchaseInquiryQuote;
use App\Models\DberpPurchaseRequestItem;
use App\Models\DberpSupplier;
use App\Services\DberpPermissionService;
use App\Support\DberpLineProductSkuFormFields;
use App\Support\DberpNumberFormatter;
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\Hidden;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Infolists\Components\IconEntry;
use Filament\Infolists\Components\TextEntry;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Components\Utilities\Set;
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\Table;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use UnitEnum;

class DberpPurchaseInquiryQuoteResource extends Resource
{
    use InteractsWithDberpPermissions;

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

    protected static ?string $recordTitleAttribute = 'code';

    protected static ?int $navigationSort = 11;

    public static function form(Schema $schema): Schema
    {
        return $schema->components([
            Section::make(__('dberp.sections.purchase_inquiry_quote'))
                ->schema(array_merge([
                    TextInput::make('code')
                        ->label(__('dberp.fields.purchase_inquiry_quote_code'))
                        ->disabled(),
                    Select::make('purchase_request_item_id')
                        ->label(__('dberp.fields.purchase_request_item'))
                        ->options(fn (): array => DberpPurchaseRequestItem::query()
                            ->with(['request', 'product'])
                            ->orderByDesc('id')
                            ->get()
                            ->mapWithKeys(fn (DberpPurchaseRequestItem $item): array => [
                                $item->getKey() => trim(($item->request?->code ?? '-').' / '.($item->product?->name ?? '-').(($item->product?->spec_model ? ' / '.$item->product->spec_model : ''))),
                            ])
                            ->all())
                        ->searchable()
                        ->preload()
                        ->live()
                        ->afterStateUpdated(function (Set $set, Get $get): void {
                            DberpLineProductSkuFormFields::applyFromPurchaseRequestItemSelection($set, (int) ($get('purchase_request_item_id') ?? 0) ?: null);
                        })
                        ->required(),
                    Hidden::make('product_id'),
                ], DberpLineProductSkuFormFields::specificationComboFields('product_id', false), [
                    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(),
                    TextInput::make('source_system')
                        ->label(__('dberp.fields.source_system'))
                        ->default('dberp')
                        ->maxLength(32),
                    TextInput::make('external_reference_id')
                        ->label(__('dberp.fields.external_reference_id'))
                        ->maxLength(128),
                    DatePicker::make('quote_date')
                        ->label(__('dberp.fields.quote_date'))
                        ->default(now()->toDateString())
                        ->required(),
                    DatePicker::make('valid_until')
                        ->label(__('dberp.fields.valid_until')),
                    DberpFilamentNumberFields::moneyInput(
                        TextInput::make('unit_price')
                            ->label(__('dberp.fields.unit_price'))
                            ->required(),
                        withHelperText: false,
                        minValue: 0.0,
                    ),
                    DberpFilamentNumberFields::quantityInput(
                        TextInput::make('min_order_quantity')
                            ->label(__('dberp.fields.min_order_quantity'))
                            ->default(0),
                        withHelperText: false,
                        minValue: 0.0,
                    ),
                    TextInput::make('lead_time_days')
                        ->label(__('dberp.fields.lead_time_days'))
                        ->numeric()
                        ->minValue(0),
                    TextInput::make('tax_rate')
                        ->label(__('dberp.fields.tax_rate'))
                        ->numeric()
                        ->minValue(0)
                        ->default(0),
                    TextInput::make('external_sku')
                        ->label(__('dberp.fields.external_sku'))
                        ->maxLength(128),
                    Toggle::make('is_tax_included')
                        ->label(__('dberp.fields.is_tax_included')),
                    Toggle::make('is_recommended')
                        ->label(__('dberp.fields.is_recommended')),
                    Textarea::make('quote_note')
                        ->label(__('dberp.fields.quote_note'))
                        ->rows(3)
                        ->columnSpanFull(),
                    Textarea::make('remark')
                        ->label(__('dberp.fields.remark'))
                        ->rows(2)
                        ->columnSpanFull(),
                ]))
                ->columns(3),
        ])->columns(1);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->defaultSort('quote_date', 'desc')
            ->columns([
                TextColumn::make('code')
                    ->label(__('dberp.fields.purchase_inquiry_quote_code'))
                    ->searchable(),
                TextColumn::make('purchase_request_code')
                    ->label(__('dberp.fields.purchase_request_code'))
                    ->searchable(),
                TextColumn::make('purchaseInquiry.code')
                    ->label(__('dberp.fields.purchase_inquiry_code'))
                    ->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('product_name_snapshot')
                    ->label(__('dberp.fields.product_name'))
                    ->searchable(),
                TextColumn::make('product_spec_snapshot')
                    ->label(__('dberp.fields.spec_model'))
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('external_sku')
                    ->label(__('dberp.fields.external_sku'))
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('supplier_name_snapshot')
                    ->label(__('dberp.fields.supplier'))
                    ->searchable(),
                TextColumn::make('unit_price')
                    ->label(__('dberp.fields.unit_price'))
                    ->formatStateUsing(fn ($state): string => DberpNumberFormatter::price($state)),
                TextColumn::make('lead_time_days')
                    ->label(__('dberp.fields.lead_time_days')),
                IconColumn::make('is_recommended')
                    ->label(__('dberp.fields.is_recommended'))
                    ->boolean(),
                TextColumn::make('status')
                    ->label(__('dberp.fields.status'))
                    ->badge()
                    ->formatStateUsing(fn (?string $state): string => PurchaseInquiryQuoteStatus::tryFrom((string) $state)?->label() ?? (string) $state),
                TextColumn::make('quote_date')
                    ->label(__('dberp.fields.quote_date'))
                    ->date(),
                TextColumn::make('valid_until')
                    ->label(__('dberp.fields.valid_until'))
                    ->date(),
            ])
            ->filters([
                SelectFilter::make('status')
                    ->label(__('dberp.fields.status'))
                    ->options(PurchaseInquiryQuoteStatus::options()),
                SelectFilter::make('supplier_id')
                    ->label(__('dberp.fields.supplier'))
                    ->relationship('supplier', 'name'),
                DberpProductSkuSelectOptions::configureProductRelationshipTableFilter(
                    SelectFilter::make('product_id')
                        ->label(__('dberp.fields.product')),
                ),
                SelectFilter::make('is_recommended')
                    ->label(__('dberp.fields.is_recommended'))
                    ->options([
                        '1' => '建议成交',
                        '0' => '非建议成交',
                    ])
                    ->query(function (Builder $query, array $data): Builder {
                        $value = $data['value'] ?? null;

                        return match ($value) {
                            '1' => $query->where('is_recommended', true),
                            '0' => $query->where('is_recommended', false),
                            default => $query,
                        };
                    }),
                Filter::make('quote_date_range')
                    ->schema([
                        DatePicker::make('from')->label(__('dberp.fields.purchase_inquiry_filter_from')),
                        DatePicker::make('until')->label(__('dberp.fields.purchase_inquiry_filter_until')),
                    ])
                    ->query(function (Builder $query, array $data): Builder {
                        return $query
                            ->when($data['from'] ?? null, fn (Builder $builder, $date): Builder => $builder->whereDate('quote_date', '>=', $date))
                            ->when($data['until'] ?? null, fn (Builder $builder, $date): Builder => $builder->whereDate('quote_date', '<=', $date));
                    }),
            ])
            ->recordActions([
                ViewAction::make(),
                EditAction::make(),
            ]);
    }

    public static function infolist(Schema $schema): Schema
    {
        return $schema->components([
            Section::make(__('dberp.sections.purchase_inquiry_quote'))
                ->schema([
                    TextEntry::make('code')->label(__('dberp.fields.purchase_inquiry_quote_code')),
                    TextEntry::make('purchase_request_code')->label(__('dberp.fields.purchase_request_code')),
                    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('product_name_snapshot')->label(__('dberp.fields.product_name')),
                    TextEntry::make('product_spec_snapshot')->label(__('dberp.fields.spec_model')),
                    TextEntry::make('external_sku')->label(__('dberp.fields.external_sku')),
                    TextEntry::make('supplier_name_snapshot')->label(__('dberp.fields.supplier')),
                    TextEntry::make('unit_price')->label(__('dberp.fields.unit_price'))->formatStateUsing(fn ($state): string => DberpNumberFormatter::price($state)),
                    TextEntry::make('min_order_quantity')->label(__('dberp.fields.min_order_quantity'))->formatStateUsing(fn ($state): string => DberpNumberFormatter::quantity($state)),
                    TextEntry::make('lead_time_days')->label(__('dberp.fields.lead_time_days')),
                    TextEntry::make('tax_rate')->label(__('dberp.fields.tax_rate'))->formatStateUsing(fn ($state): string => DberpNumberFormatter::percent($state, false)),
                    IconEntry::make('is_tax_included')->label(__('dberp.fields.is_tax_included'))->boolean(),
                    IconEntry::make('is_recommended')->label(__('dberp.fields.is_recommended'))->boolean(),
                    TextEntry::make('status')
                        ->label(__('dberp.fields.status'))
                        ->badge()
                        ->formatStateUsing(fn (?string $state): string => PurchaseInquiryQuoteStatus::tryFrom((string) $state)?->label() ?? (string) $state),
                    TextEntry::make('quote_date')->label(__('dberp.fields.quote_date'))->date(),
                    TextEntry::make('valid_until')->label(__('dberp.fields.valid_until'))->date(),
                    TextEntry::make('quote_note')->label(__('dberp.fields.quote_note'))->columnSpanFull(),
                    TextEntry::make('remark')->label(__('dberp.fields.remark'))->columnSpanFull(),
                ])
                ->columns(3),
        ])->columns(1);
    }

    public static function getPages(): array
    {
        return [
            'index' => ListDberpPurchaseInquiryQuotes::route('/'),
            'create' => CreateDberpPurchaseInquiryQuote::route('/create'),
            'view' => ViewDberpPurchaseInquiryQuote::route('/{record}'),
            'edit' => EditDberpPurchaseInquiryQuote::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_inquiry_quote.label');
    }

    public static function getPluralModelLabel(): string
    {
        return __('dberp.resources.purchase_inquiry_quote.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 static::allowsPermission(DberpPermissionService::EDIT_PURCHASE_INQUIRY_QUOTE);
    }
}
