<?php

declare(strict_types=1);

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

namespace App\Filament\Resources\DberpInventoryBalances;

use App\Filament\Concerns\InteractsWithDberpPermissions;
use App\Filament\Resources\DberpInventoryBalances\Pages\EditDberpInventoryBalance;
use App\Filament\Resources\DberpInventoryBalances\Pages\ListDberpInventoryBalances;
use App\Filament\Support\DberpFilamentNumberFields;
use App\Filament\Support\DberpFilamentRecordTitles;
use App\Models\DberpInventoryBalance;
use App\Models\DberpProductCategory;
use App\Models\DberpProductSku;
use App\Models\DberpWarehouse;
use App\Services\DberpPermissionService;
use App\Support\DberpFilamentMasterDataSelectOptions;
use App\Support\DberpInventoryBalanceAuxiliaryDisplay;
use App\Support\DberpNumberFormatter;
use App\Support\DberpProductSkuSelectOptions;
use BackedEnum;
use Filament\Actions\EditAction;
use Filament\Forms\Components\TextInput;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\Summarizers\Sum;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Grouping\Group;
use Filament\Tables\Table;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use UnitEnum;

class DberpInventoryBalanceResource extends Resource
{
    use InteractsWithDberpPermissions;

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

    protected static ?int $navigationSort = 10;

    public static function hasRecordTitle(): bool
    {
        return true;
    }

    public static function getRecordTitle(?Model $record): string|Htmlable|null
    {
        if (! $record instanceof DberpInventoryBalance) {
            return parent::getRecordTitle($record);
        }

        return DberpFilamentRecordTitles::inventoryBalance($record);
    }

    public static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()->with([
            'product.unit',
            'product.auxiliaryUnit',
            'product.category',
            'productSku',
            'warehouse',
        ]);
    }

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                Section::make(__('dberp.sections.inventory_account'))
                    ->schema([
                        DberpFilamentNumberFields::quantityInput(
                            TextInput::make('safety_stock')
                                ->label(__('dberp.fields.safety_stock'))
                                ->default(0)
                                ->required(),
                            withHelperText: false,
                            minValue: 0.0,
                        )->helperText((string) __('dberp.hints.inventory_balance_safety_stock_from_rule')),
                    ]),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->defaultSort('last_moved_at', 'desc')
            ->columns([
                TextColumn::make('product.code')
                    ->label(__('dberp.fields.product_code'))
                    ->searchable(),
                TextColumn::make('product.name')
                    ->label(__('dberp.fields.product_name'))
                    ->searchable(),
                TextColumn::make('productSku.sku_code')
                    ->label(__('dberp.fields.spec_combo_code'))
                    ->searchable(),
                TextColumn::make('productSku.spec_text')
                    ->label(__('dberp.fields.spec_combo_summary'))
                    ->limit(40)
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('product.category.name')
                    ->label(__('dberp.fields.category'))
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('warehouse.name')
                    ->label(__('dberp.fields.warehouse'))
                    ->searchable(),
                TextColumn::make('realtime_quantity')
                    ->label(__('dberp.fields.realtime_quantity'))
                    ->description(__('dberp.hints.inventory_balance_realtime_is_base'))
                    ->formatStateUsing(fn ($state): string => DberpNumberFormatter::quantity($state))
                    ->summarize(Sum::make()->label(__('dberp.fields.table_sum_label'))),
                TextColumn::make('auxiliary_reference_quantity')
                    ->label(__('dberp.fields.inventory_balance_auxiliary_reference'))
                    ->description(__('dberp.hints.inventory_balance_auxiliary_reference_note'))
                    ->state(fn (DberpInventoryBalance $record): string => DberpInventoryBalanceAuxiliaryDisplay::approximateAuxiliaryQuantity($record->product, $record->realtime_quantity))
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('available_quantity')
                    ->label(__('dberp.fields.available_quantity'))
                    ->formatStateUsing(fn ($state): string => DberpNumberFormatter::quantity($state))
                    ->summarize(Sum::make()->label(__('dberp.fields.table_sum_label'))),
                TextColumn::make('occupied_quantity')
                    ->label(__('dberp.fields.occupied_quantity'))
                    ->formatStateUsing(fn ($state): string => DberpNumberFormatter::quantity($state))
                    ->summarize(Sum::make()->label(__('dberp.fields.table_sum_label'))),
                TextColumn::make('safety_stock')
                    ->label(__('dberp.fields.safety_stock'))
                    ->formatStateUsing(fn ($state): string => DberpNumberFormatter::quantity($state))
                    ->summarize(Sum::make()->label(__('dberp.fields.table_sum_label')))
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('last_moved_at')
                    ->label(__('dberp.fields.last_moved_at'))
                    ->dateTime()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                SelectFilter::make('warehouse_id')
                    ->label(__('dberp.fields.warehouse'))
                    ->options(fn (): array => DberpWarehouse::query()->orderBy('sort_order')->orderBy('id')->pluck('name', 'id')->all())
                    ->query(fn (Builder $query, array $data): Builder => $query->when(
                        $data['value'] ?? null,
                        fn (Builder $builder, $value): Builder => $builder->where('warehouse_id', (int) $value),
                    )),
                DberpFilamentMasterDataSelectOptions::applyDeferredSearchForFilter(
                    SelectFilter::make('product_id')->label(__('dberp.fields.product')),
                    fn (): array => DberpFilamentMasterDataSelectOptions::products(),
                )->query(fn (Builder $query, array $data): Builder => $query->when(
                    $data['value'] ?? null,
                    fn (Builder $builder, $value): Builder => $builder->where('product_id', (int) $value),
                )),
                SelectFilter::make('product_sku_id')
                    ->label(__('dberp.fields.product_spec'))
                    ->relationship(
                        name: 'productSku',
                        titleAttribute: 'sku_code',
                        modifyQueryUsing: fn (Builder $query): Builder => $query->with(['product.unit'])->orderBy('product_id')->orderBy('id'),
                    )
                    ->getOptionLabelFromRecordUsing(fn (DberpProductSku $record): string => DberpProductSkuSelectOptions::labelForSku($record))
                    ->searchable()
                    ->query(fn (Builder $query, array $data): Builder => $query->when(
                        $data['value'] ?? null,
                        fn (Builder $builder, $value): Builder => $builder->where('product_sku_id', (int) $value),
                    )),
                SelectFilter::make('category_id')
                    ->label(__('dberp.fields.category'))
                    ->options(fn (): array => DberpProductCategory::query()->orderBy('sort_order')->orderBy('id')->pluck('name', 'id')->all())
                    ->query(fn ($query, array $data) => $query->when($data['value'] ?? null, fn ($builder, $value) => $builder->whereHas('product', fn ($productQuery) => $productQuery->where('category_id', $value)))),
                Filter::make('low_stock')
                    ->label(__('dberp.fields.low_stock_filter'))
                    ->query(fn ($query) => $query->lowStock()),
                Filter::make('zero_stock')
                    ->label(__('dberp.fields.zero_stock_filter'))
                    ->query(fn ($query) => $query->zeroStock()),
            ])
            ->groups([
                Group::make('product.name')->label(__('dberp.options.inventory_query_group.product')),
                Group::make('warehouse.name')->label(__('dberp.options.inventory_query_group.warehouse')),
            ])
            ->recordActions([
                EditAction::make()
                    ->visible(fn (): bool => static::allowsPermission(DberpPermissionService::EDIT_INVENTORY_BALANCE)),
            ]);
    }

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

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

    public static function canCreate(): bool
    {
        return false;
    }

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

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

    public static function getPages(): array
    {
        return [
            'index' => ListDberpInventoryBalances::route('/'),
            'edit' => EditDberpInventoryBalance::route('/{record}/edit'),
        ];
    }

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

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

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

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