<?php

declare(strict_types=1);

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

namespace App\Filament\Resources\DberpSalesQuotes;

use App\Business\Sales\Enums\SalesQuoteStatus;
use App\Business\Sales\SalesQuoteService;
use App\Filament\Concerns\InteractsWithDberpPermissions;
use App\Filament\Contracts\DberpFilamentCreateSaveFirstGuidance;
use App\Filament\Contracts\DberpFilamentFormEditability;
use App\Filament\Resources\Concerns\HasDberpExportAction;
use App\Filament\Resources\DberpSalesQuotes\Pages\CreateDberpSalesQuote;
use App\Filament\Resources\DberpSalesQuotes\Pages\EditDberpSalesQuote;
use App\Filament\Resources\DberpSalesQuotes\Pages\ListDberpSalesQuotes;
use App\Filament\Resources\DberpSalesQuotes\RelationManagers\ItemsRelationManager;
use App\Models\DberpCustomer;
use App\Models\DberpEmployee;
use App\Models\DberpSalesQuote;
use App\Services\DberpPermissionService;
use App\Support\DberpNumberFormatter;
use BackedEnum;
use Filament\Forms\Components\DatePicker;
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\SelectFilter;
use Filament\Tables\Table;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use UnitEnum;

class DberpSalesQuoteResource extends Resource implements DberpFilamentCreateSaveFirstGuidance, DberpFilamentFormEditability
{
    use HasDberpExportAction;
    use InteractsWithDberpPermissions;

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

    protected static ?string $recordTitleAttribute = 'code';

    protected static ?int $navigationSort = 10;

    public static function isRecordFormEditableForFilament(Model $record): bool
    {
        if (! $record instanceof DberpSalesQuote) {
            return false;
        }

        return in_array($record->currentStatus(), [SalesQuoteStatus::Draft, SalesQuoteStatus::PendingEffective], true);
    }

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

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                Section::make(__('dberp.sections.sales_quote'))
                    ->schema([
                        TextInput::make('code')
                            ->label(__('dberp.fields.quote_code'))
                            ->maxLength(64)
                            ->unique(ignoreRecord: true)
                            ->helperText(__('dberp.hints.auto_code'))
                            ->disabled(fn (?DberpSalesQuote $record): bool => $record !== null && ! in_array($record->currentStatus(), [SalesQuoteStatus::Draft, SalesQuoteStatus::PendingEffective], true)),
                        Select::make('customer_id')
                            ->label(__('dberp.fields.customer'))
                            ->options(fn (): array => DberpCustomer::query()
                                ->where('is_enabled', true)
                                ->orderBy('sort_order')
                                ->orderBy('id')
                                ->pluck('name', 'id')
                                ->all())
                            ->searchable()
                            ->preload()
                            ->required()
                            ->disabled(fn (?DberpSalesQuote $record): bool => $record !== null && ! in_array($record->currentStatus(), [SalesQuoteStatus::Draft, SalesQuoteStatus::PendingEffective], true)),
                        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 (?DberpSalesQuote $record): bool => $record !== null && ! in_array($record->currentStatus(), [SalesQuoteStatus::Draft, SalesQuoteStatus::PendingEffective], true)),
                        DatePicker::make('quote_date')
                            ->label(__('dberp.fields.quote_date'))
                            ->default(now()->toDateString())
                            ->required()
                            ->disabled(fn (?DberpSalesQuote $record): bool => $record !== null && ! in_array($record->currentStatus(), [SalesQuoteStatus::Draft, SalesQuoteStatus::PendingEffective], true)),
                        DatePicker::make('valid_from')
                            ->label(__('dberp.fields.valid_from'))
                            ->required()
                            ->disabled(fn (?DberpSalesQuote $record): bool => $record !== null && ! in_array($record->currentStatus(), [SalesQuoteStatus::Draft, SalesQuoteStatus::PendingEffective], true)),
                        DatePicker::make('valid_until')
                            ->label(__('dberp.fields.valid_until'))
                            ->required()
                            ->afterOrEqual('valid_from')
                            ->disabled(fn (?DberpSalesQuote $record): bool => $record !== null && ! in_array($record->currentStatus(), [SalesQuoteStatus::Draft, SalesQuoteStatus::PendingEffective], true)),
                        TextInput::make('suggested_payment_term_days')
                            ->label(__('dberp.fields.suggested_payment_term_days'))
                            ->numeric()
                            ->minValue(0)
                            ->disabled(fn (?DberpSalesQuote $record): bool => $record !== null && ! in_array($record->currentStatus(), [SalesQuoteStatus::Draft, SalesQuoteStatus::PendingEffective], true)),
                        Select::make('status')
                            ->label(__('dberp.fields.status'))
                            ->options(SalesQuoteStatus::options())
                            ->default(SalesQuoteStatus::Draft->value)
                            ->disabled()
                            ->dehydrated(false),
                        TextInput::make('source_system')
                            ->label(__('dberp.fields.source_system'))
                            ->helperText(__('dberp.hints.source_system_guidance'))
                            ->default('dberp')
                            ->maxLength(32)
                            ->disabled(fn (?DberpSalesQuote $record): bool => $record !== null && ! in_array($record->currentStatus(), [SalesQuoteStatus::Draft, SalesQuoteStatus::PendingEffective], true)),
                        TextInput::make('external_reference_id')
                            ->label(__('dberp.fields.external_reference_id'))
                            ->maxLength(128)
                            ->disabled(fn (?DberpSalesQuote $record): bool => $record !== null && ! in_array($record->currentStatus(), [SalesQuoteStatus::Draft, SalesQuoteStatus::PendingEffective], true)),
                        Textarea::make('remark')
                            ->label(__('dberp.fields.remark'))
                            ->rows(3)
                            ->columnSpanFull()
                            ->disabled(fn (?DberpSalesQuote $record): bool => $record !== null && ! in_array($record->currentStatus(), [SalesQuoteStatus::Draft, SalesQuoteStatus::PendingEffective], true)),
                    ])
                    ->columns(3),
            ])->columns(1);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->defaultSort('quote_date', 'desc')
            ->columns([
                TextColumn::make('code')
                    ->label(__('dberp.fields.quote_code'))
                    ->searchable(),
                TextColumn::make('customer.name')
                    ->label(__('dberp.fields.customer'))
                    ->searchable(),
                TextColumn::make('status')
                    ->label(__('dberp.fields.status'))
                    ->badge()
                    ->state(fn (DberpSalesQuote $record): string => app(SalesQuoteService::class)->resolveCurrentStatus($record)->value)
                    ->formatStateUsing(fn (?string $state): string => SalesQuoteStatus::tryFrom((string) $state)?->label() ?? (string) $state),
                TextColumn::make('handlerEmployee.name')
                    ->label(__('dberp.fields.handler_employee')),
                TextColumn::make('quote_date')
                    ->label(__('dberp.fields.quote_date'))
                    ->date(),
                TextColumn::make('valid_until')
                    ->label(__('dberp.fields.valid_until'))
                    ->date(),
                TextColumn::make('final_amount')
                    ->label(__('dberp.fields.final_amount'))
                    ->formatStateUsing(fn ($state): string => DberpNumberFormatter::money($state)),
                TextColumn::make('suggested_payment_term_days')
                    ->label(__('dberp.fields.suggested_payment_term_days'))
                    ->numeric(decimalPlaces: 0)
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('converted_sales_order_no')
                    ->label(__('dberp.fields.converted_sales_order_no'))
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                SelectFilter::make('status')
                    ->label(__('dberp.fields.status'))
                    ->options(SalesQuoteStatus::options()),
                SelectFilter::make('customer_id')
                    ->label(__('dberp.fields.customer'))
                    ->relationship('customer', 'name'),
                SelectFilter::make('handler_employee_id')
                    ->label(__('dberp.fields.handler_employee'))
                    ->options(fn (): array => DberpEmployee::selectOptionsForFilament())
                    ->searchable()
                    ->preload(),
                SelectFilter::make('attention_status')
                    ->label(__('dberp.fields.attention_status'))
                    ->options(__('dberp.options.sales_quote_attention_status'))
                    ->query(function (Builder $query, array $data): Builder {
                        $value = $data['value'] ?? null;

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

                        $today = now()->toDateString();
                        $dueSoonDate = now()->addDays((int) config('dberp.sales.reminders.quote_expiry_soon_days', 7))->toDateString();
                        $longUnconvertedDate = now()->subDays((int) config('dberp.sales.reminders.long_unconverted_days', 15))->toDateString();

                        $query->whereNotIn('status', [
                            SalesQuoteStatus::Draft->value,
                            SalesQuoteStatus::Converted->value,
                            SalesQuoteStatus::Voided->value,
                        ]);

                        return match ($value) {
                            'pending_effective' => $query->whereDate('valid_from', '>', $today),
                            'expiring_soon' => $query->whereNull('converted_sales_order_id')->whereDate('valid_from', '<=', $today)->whereBetween('valid_until', [$today, $dueSoonDate]),
                            'expired' => $query->whereDate('valid_until', '<', $today),
                            'long_unconverted' => $query->whereNull('converted_sales_order_id')->whereDate('valid_from', '<=', $today)->whereDate('valid_until', '>=', $today)->whereDate('quote_date', '<=', $longUnconvertedDate),
                            default => $query,
                        };
                    }),
            ])
            ->headerActions([
                static::makeExportAction('sales-quote'),
            ]);
    }

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

    public static function canViewAny(): bool
    {
        return static::allowsAnyPermission([
            DberpPermissionService::VIEW_SALES_QUOTE,
            DberpPermissionService::CREATE_SALES_QUOTE,
            DberpPermissionService::EDIT_SALES_QUOTE,
            DberpPermissionService::ACTIVATE_SALES_QUOTE,
            DberpPermissionService::VOID_SALES_QUOTE,
            DberpPermissionService::CONVERT_SALES_QUOTE,
        ]);
    }

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

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

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

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

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

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

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