<?php

declare(strict_types=1);

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

namespace App\Filament\Resources\DberpSettlementStatements;

use App\Business\Settlement\Enums\SettlementStatementStatus;
use App\Filament\Concerns\InteractsWithDberpPermissions;
use App\Filament\Contracts\DberpFilamentCreateSaveFirstGuidance;
use App\Filament\Contracts\DberpFilamentFormEditability;
use App\Filament\Resources\DberpSettlementStatements\Pages\CreateDberpSettlementStatement;
use App\Filament\Resources\DberpSettlementStatements\Pages\EditDberpSettlementStatement;
use App\Filament\Resources\DberpSettlementStatements\Pages\ListDberpSettlementStatements;
use App\Filament\Resources\DberpSettlementStatements\RelationManagers\ItemsRelationManager;
use App\Filament\Support\DberpFilamentNumberFields;
use App\Models\DberpCustomer;
use App\Models\DberpEmployee;
use App\Models\DberpSettlementStatement;
use App\Models\DberpSupplier;
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\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 DberpSettlementStatementResource extends Resource implements DberpFilamentCreateSaveFirstGuidance, DberpFilamentFormEditability
{
    use InteractsWithDberpPermissions;

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

    protected static ?string $recordTitleAttribute = 'code';

    protected static ?int $navigationSort = 70;

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

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

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                Section::make(__('dberp.sections.settlement_statement'))
                    ->schema([
                        TextInput::make('code')
                            ->label(__('dberp.fields.statement_code'))
                            ->disabled()
                            ->dehydrated(false)
                            ->visible(fn (?DberpSettlementStatement $record): bool => $record !== null),
                        Select::make('settlement_side')
                            ->label(__('dberp.fields.settlement_side'))
                            ->options(__('dberp.options.settlement_business_side'))
                            ->default('receivable')
                            ->required()
                            ->disabled(fn (?DberpSettlementStatement $record): bool => $record !== null),
                        Select::make('counterparty_id')
                            ->label(__('dberp.fields.counterparty'))
                            ->options(function (callable $get): array {
                                return $get('settlement_side') === 'payable'
                                    ? DberpSupplier::query()->where('is_enabled', true)->orderBy('sort_order')->orderBy('id')->pluck('name', 'id')->all()
                                    : DberpCustomer::query()->where('is_enabled', true)->orderBy('sort_order')->orderBy('id')->pluck('name', 'id')->all();
                            })
                            ->searchable()
                            ->preload()
                            ->required()
                            ->disabled(fn (?DberpSettlementStatement $record): bool => $record !== null),
                        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 (?DberpSettlementStatement $record): bool => $record !== null),
                        DatePicker::make('statement_date')
                            ->label(__('dberp.fields.statement_date'))
                            ->default(now()->toDateString())
                            ->required()
                            ->disabled(fn (?DberpSettlementStatement $record): bool => $record !== null),
                        DatePicker::make('period_start_date')
                            ->label(__('dberp.fields.period_start_date'))
                            ->required()
                            ->disabled(fn (?DberpSettlementStatement $record): bool => $record !== null),
                        DatePicker::make('period_end_date')
                            ->label(__('dberp.fields.period_end_date'))
                            ->required()
                            ->disabled(fn (?DberpSettlementStatement $record): bool => $record !== null),
                        DberpFilamentNumberFields::displayMoney(
                            TextInput::make('opening_balance')
                                ->label(__('dberp.fields.opening_balance'))
                                ->disabled()
                                ->dehydrated(false)
                                ->visible(fn (?DberpSettlementStatement $record): bool => $record !== null),
                        ),
                        DberpFilamentNumberFields::displayMoney(
                            TextInput::make('period_increase_amount')
                                ->label(__('dberp.fields.period_increase_amount'))
                                ->disabled()
                                ->dehydrated(false)
                                ->visible(fn (?DberpSettlementStatement $record): bool => $record !== null),
                        ),
                        DberpFilamentNumberFields::displayMoney(
                            TextInput::make('period_decrease_amount')
                                ->label(__('dberp.fields.period_decrease_amount'))
                                ->disabled()
                                ->dehydrated(false)
                                ->visible(fn (?DberpSettlementStatement $record): bool => $record !== null),
                        ),
                        DberpFilamentNumberFields::displayMoney(
                            TextInput::make('closing_balance')
                                ->label(__('dberp.fields.closing_balance'))
                                ->disabled()
                                ->dehydrated(false)
                                ->visible(fn (?DberpSettlementStatement $record): bool => $record !== null),
                        ),
                        TextInput::make('item_count')
                            ->label(__('dberp.fields.item_count'))
                            ->disabled()
                            ->dehydrated(false)
                            ->visible(fn (?DberpSettlementStatement $record): bool => $record !== null),
                        Textarea::make('remark')
                            ->label(__('dberp.fields.remark'))
                            ->rows(2)
                            ->columnSpanFull()
                            ->disabled(fn (?DberpSettlementStatement $record): bool => $record !== null),
                    ])
                    ->columns(2),
            ])->columns(1);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->defaultSort('statement_date', 'desc')
            ->columns([
                TextColumn::make('code')
                    ->label(__('dberp.fields.statement_code'))
                    ->searchable(),
                TextColumn::make('settlement_side')
                    ->label(__('dberp.fields.settlement_side'))
                    ->badge()
                    ->formatStateUsing(fn (?string $state): string => __('dberp.options.settlement_business_side')[$state] ?? (string) $state),
                TextColumn::make('counterparty_name')
                    ->label(__('dberp.fields.counterparty'))
                    ->searchable(),
                TextColumn::make('period_start_date')
                    ->label(__('dberp.fields.period_start_date'))
                    ->date(),
                TextColumn::make('period_end_date')
                    ->label(__('dberp.fields.period_end_date'))
                    ->date(),
                TextColumn::make('opening_balance')
                    ->label(__('dberp.fields.opening_balance'))
                    ->formatStateUsing(fn ($state): string => DberpNumberFormatter::money($state))
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('closing_balance')
                    ->label(__('dberp.fields.closing_balance'))
                    ->formatStateUsing(fn ($state): string => DberpNumberFormatter::money($state)),
                TextColumn::make('statement_status')
                    ->label(__('dberp.fields.status'))
                    ->badge()
                    ->formatStateUsing(fn (?string $state): string => SettlementStatementStatus::tryFrom((string) $state)?->label() ?? (string) $state),
                TextColumn::make('last_exported_at')
                    ->label(__('dberp.fields.last_exported_at'))
                    ->dateTime()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                SelectFilter::make('settlement_side')
                    ->label(__('dberp.fields.settlement_side'))
                    ->options(__('dberp.options.settlement_business_side')),
                SelectFilter::make('statement_status')
                    ->label(__('dberp.fields.status'))
                    ->options(SettlementStatementStatus::options()),
                Filter::make('statement_period')
                    ->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('statement_date', '>=', $date))
                            ->when($data['until'] ?? null, fn (Builder $builder, $date): Builder => $builder->whereDate('statement_date', '<=', $date));
                    }),
            ]);
    }

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

    public static function canViewAny(): bool
    {
        return static::allowsAnyPermission([
            DberpPermissionService::VIEW_SETTLEMENT_STATEMENT,
            DberpPermissionService::CONFIRM_SETTLEMENT_STATEMENT,
            DberpPermissionService::EXPORT,
        ]);
    }

    public static function canView(Model $record): bool
    {
        return static::canViewAny();
    }

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

    public static function canEdit(Model $record): bool
    {
        return static::allowsAnyPermission([
            DberpPermissionService::CONFIRM_SETTLEMENT_STATEMENT,
            DberpPermissionService::EXPORT,
        ]);
    }

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

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

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

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

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

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

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