<?php

declare(strict_types=1);

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

namespace App\Filament\Resources\DberpCustomerPriceRules;

use App\Business\Sales\Enums\CustomerPriceRuleStatus;
use App\Business\Sales\Enums\CustomerPriceRuleType;
use App\Filament\Concerns\InteractsWithDberpPermissions;
use App\Filament\Resources\Concerns\HasDberpExportAction;
use App\Filament\Resources\DberpCustomerPriceRules\Pages\CreateDberpCustomerPriceRule;
use App\Filament\Resources\DberpCustomerPriceRules\Pages\EditDberpCustomerPriceRule;
use App\Filament\Resources\DberpCustomerPriceRules\Pages\ListDberpCustomerPriceRules;
use App\Filament\Support\DberpFilamentNumberFields;
use App\Models\DberpCustomer;
use App\Models\DberpCustomerPriceRule;
use App\Services\DberpPermissionService;
use App\Support\DberpFilamentMasterDataSelectOptions;
use App\Support\DberpNumberFormatter;
use App\Support\DberpPriceLevelDictionary;
use App\Support\DberpProductSkuSelectOptions;
use BackedEnum;
use Closure;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Resources\Pages\EditRecord;
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 DberpCustomerPriceRuleResource extends Resource
{
    use HasDberpExportAction;
    use InteractsWithDberpPermissions;

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

    protected static ?string $recordTitleAttribute = 'rule_name';

    protected static ?int $navigationSort = 15;

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                Section::make(__('dberp.sections.sales_price_rule'))
                    ->schema([
                        TextInput::make('rule_name')
                            ->label(__('dberp.fields.rule_name'))
                            ->required()
                            ->maxLength(160),
                        Select::make('rule_type')
                            ->label(__('dberp.fields.rule_type'))
                            ->options(CustomerPriceRuleType::options())
                            ->default(CustomerPriceRuleType::Exclusive->value)
                            ->live()
                            ->required(),
                        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()
                            ->visible(fn (callable $get): bool => $get('rule_type') === CustomerPriceRuleType::Exclusive->value),
                        Select::make('price_level_code')
                            ->label(__('dberp.fields.price_level_code'))
                            ->options(function ($livewire): array {
                                $preserve = null;
                                if ($livewire instanceof EditRecord && $livewire->getRecord() instanceof DberpCustomerPriceRule) {
                                    $preserve = $livewire->getRecord()->price_level_code;
                                }

                                return DberpPriceLevelDictionary::optionsForSelect(
                                    is_string($preserve) && $preserve !== '' ? $preserve : null,
                                );
                            })
                            ->searchable()
                            ->preload()
                            ->required()
                            ->helperText(__('dberp.hints.customer_price_rule_price_level_code'))
                            ->visible(fn (callable $get): bool => $get('rule_type') === CustomerPriceRuleType::Level->value)
                            ->rules([
                                fn (): Closure => function (string $attribute, mixed $value, Closure $fail): void {
                                    if ($value === null || $value === '') {
                                        return;
                                    }

                                    if (! DberpPriceLevelDictionary::isEnabledCode((string) $value)) {
                                        $fail((string) __('dberp.errors.price_level_code_invalid'));
                                    }
                                },
                            ]),
                        Select::make('product_id')
                            ->label(__('dberp.fields.product'))
                            ->options(fn (): array => DberpFilamentMasterDataSelectOptions::products(
                                enabledOnly: true,
                                scope: DberpProductSkuSelectOptions::PRODUCT_SCOPE_SALABLE,
                            ))
                            ->searchable()
                            ->preload()
                            ->required(),
                        TextInput::make('external_sku')
                            ->label(__('dberp.fields.external_sku'))
                            ->maxLength(128),
                        DberpFilamentNumberFields::moneyInput(
                            TextInput::make('unit_price')
                                ->label(__('dberp.fields.unit_price'))
                                ->required(),
                            withHelperText: false,
                            minValue: 0.0,
                        ),
                        DatePicker::make('valid_from')
                            ->label(__('dberp.fields.valid_from'))
                            ->default(now()->toDateString())
                            ->required(),
                        DatePicker::make('valid_until')
                            ->label(__('dberp.fields.valid_until')),
                        Select::make('status')
                            ->label(__('dberp.fields.status'))
                            ->options(CustomerPriceRuleStatus::options())
                            ->default(CustomerPriceRuleStatus::Active->value)
                            ->required(),
                        TextInput::make('sort_order')
                            ->label(__('dberp.fields.sort_order'))
                            ->numeric()
                            ->default(0)
                            ->required(),
                        TextInput::make('source_system')
                            ->label(__('dberp.fields.source_system'))
                            ->default('dberp')
                            ->maxLength(32),
                        TextInput::make('channel_code')
                            ->label(__('dberp.fields.channel_code'))
                            ->maxLength(64),
                        TextInput::make('external_reference_id')
                            ->label(__('dberp.fields.external_reference_id'))
                            ->maxLength(128),
                        Textarea::make('remark')
                            ->label(__('dberp.fields.remark'))
                            ->rows(3)
                            ->columnSpanFull(),
                    ])
                    ->columns(3),
            ])->columns(1);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->defaultSort('sort_order', 'asc')
            ->columns([
                TextColumn::make('rule_name')
                    ->label(__('dberp.fields.rule_name'))
                    ->searchable(),
                TextColumn::make('rule_type')
                    ->label(__('dberp.fields.rule_type'))
                    ->badge()
                    ->formatStateUsing(fn (?string $state): string => CustomerPriceRuleType::tryFrom((string) $state)?->label() ?? (string) $state),
                TextColumn::make('customer.name')
                    ->label(__('dberp.fields.customer'))
                    ->placeholder('-'),
                TextColumn::make('price_level_code')
                    ->label(__('dberp.fields.price_level_code'))
                    ->formatStateUsing(fn (?string $state): string => $state === null || $state === ''
                        ? '-'
                        : DberpPriceLevelDictionary::displayLabel($state))
                    ->placeholder('-'),
                TextColumn::make('product.name')
                    ->label(__('dberp.fields.product'))
                    ->searchable(),
                TextColumn::make('unit_price')
                    ->label(__('dberp.fields.unit_price'))
                    ->formatStateUsing(fn ($state): string => DberpNumberFormatter::price($state)),
                TextColumn::make('status')
                    ->label(__('dberp.fields.status'))
                    ->badge()
                    ->formatStateUsing(fn (?string $state): string => CustomerPriceRuleStatus::tryFrom((string) $state)?->label() ?? (string) $state),
                TextColumn::make('valid_from')
                    ->label(__('dberp.fields.valid_from'))
                    ->date(),
                TextColumn::make('valid_until')
                    ->label(__('dberp.fields.valid_until'))
                    ->date(),
                TextColumn::make('sort_order')
                    ->label(__('dberp.fields.sort_order')),
            ])
            ->filters([
                SelectFilter::make('rule_type')
                    ->label(__('dberp.fields.rule_type'))
                    ->options(CustomerPriceRuleType::options()),
                SelectFilter::make('status')
                    ->label(__('dberp.fields.status'))
                    ->options(CustomerPriceRuleStatus::options()),
                SelectFilter::make('customer_id')
                    ->label(__('dberp.fields.customer'))
                    ->relationship('customer', 'name'),
                SelectFilter::make('attention_status')
                    ->label(__('dberp.fields.attention_status'))
                    ->options(__('dberp.options.customer_price_rule_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.price_rule_expiry_soon_days', 7))->toDateString();

                        $query->where('status', CustomerPriceRuleStatus::Active->value);

                        return match ($value) {
                            'expiring_soon' => $query->whereBetween('valid_until', [$today, $dueSoonDate]),
                            'expired' => $query->whereDate('valid_until', '<', $today),
                            default => $query,
                        };
                    }),
            ])
            ->headerActions([
                static::makeExportAction('customer-price-rule'),
            ]);
    }

    public static function canViewAny(): bool
    {
        return static::allowsAnyPermission([
            DberpPermissionService::VIEW_CUSTOMER_PRICE_RULE,
            DberpPermissionService::CREATE_CUSTOMER_PRICE_RULE,
            DberpPermissionService::EDIT_CUSTOMER_PRICE_RULE,
            DberpPermissionService::DISABLE_CUSTOMER_PRICE_RULE,
        ]);
    }

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

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

    public static function getPages(): array
    {
        return [
            'index' => ListDberpCustomerPriceRules::route('/'),
            'create' => CreateDberpCustomerPriceRule::route('/create'),
            'edit' => EditDberpCustomerPriceRule::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.customer_price_rule.label');
    }

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