<?php

declare(strict_types=1);

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

namespace App\Filament\Resources\DberpPurchaseStatistics;

use App\Business\Purchase\Enums\PurchaseOrderStatus;
use App\Business\Report\PurchaseReportService;
use App\Business\Settlement\Enums\PayableStatus;
use App\Filament\Concerns\InteractsWithDberpPermissions;
use App\Filament\Resources\Concerns\HasDberpExportAction;
use App\Filament\Resources\DberpPurchaseOrders\DberpPurchaseOrderResource;
use App\Filament\Resources\DberpPurchaseStatistics\Pages\ListDberpPurchaseStatistics;
use App\Models\DberpEmployee;
use App\Models\DberpPurchaseOrder;
use App\Services\DberpPermissionService;
use App\Support\DberpFilamentMasterDataSelectOptions;
use App\Support\DberpNumberFormatter;
use App\Support\DberpProductSkuSelectOptions;
use App\Support\DberpPurchaseStatisticsFilamentSupport;
use BackedEnum;
use Filament\Actions\Action;
use Filament\Forms\Components\DatePicker;
use Filament\Resources\Resource;
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\Table;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Database\Eloquent\Builder;
use UnitEnum;

class DberpPurchaseStatisticResource extends Resource
{
    use HasDberpExportAction;
    use InteractsWithDberpPermissions;

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

    protected static ?string $recordTitleAttribute = 'code';

    protected static ?int $navigationSort = 40;

    public static function form(Schema $schema): Schema
    {
        return $schema->components([]);
    }

    public static function getEloquentQuery(): Builder
    {
        return app(PurchaseReportService::class)->statisticsQuery();
    }

    public static function table(Table $table): Table
    {
        return $table
            ->defaultSort('business_time', 'desc')
            ->columns([
                TextColumn::make('code')->label(__('dberp.fields.purchase_order_code'))->searchable(),
                TextColumn::make('supplier.name')->label(__('dberp.fields.supplier'))->searchable(),
                TextColumn::make('handlerEmployee.name')->label(__('dberp.fields.handler_employee')),
                TextColumn::make('status')
                    ->label(__('dberp.fields.status'))
                    ->badge()
                    ->formatStateUsing(fn (?string $state): string => __('dberp.options.purchase_order_status')[$state] ?? (string) $state),
                TextColumn::make('business_time')->label(__('dberp.fields.business_time'))->dateTime(),
                TextColumn::make('total_quantity')
                    ->label(__('dberp.fields.total_quantity'))
                    ->formatStateUsing(fn ($state): string => DberpNumberFormatter::quantity($state))
                    ->summarize(Sum::make()->label(__('dberp.fields.table_sum_label'))),
                TextColumn::make('total_amount')
                    ->label(__('dberp.fields.total_amount'))
                    ->formatStateUsing(fn ($state): string => DberpNumberFormatter::money($state))
                    ->summarize(Sum::make()->label(__('dberp.fields.table_sum_label'))),
                TextColumn::make('payable_amount')
                    ->label(__('dberp.fields.payable_amount'))
                    ->formatStateUsing(fn ($state): string => DberpNumberFormatter::money($state))
                    ->summarize(Sum::make()->label(__('dberp.fields.table_sum_label'))),
                TextColumn::make('paid_amount')
                    ->label(__('dberp.fields.paid_amount'))
                    ->formatStateUsing(fn ($state): string => DberpNumberFormatter::money($state))
                    ->summarize(Sum::make()->label(__('dberp.fields.table_sum_label'))),
                TextColumn::make('unpaid_amount')
                    ->label(__('dberp.fields.unpaid_amount'))
                    ->formatStateUsing(fn ($state): string => DberpNumberFormatter::money($state))
                    ->summarize(Sum::make()->label(__('dberp.fields.table_sum_label'))),
                TextColumn::make('payable_status')
                    ->label(__('dberp.fields.payable_status'))
                    ->badge()
                    ->formatStateUsing(fn (?string $state): string => PayableStatus::tryFrom((string) $state)?->label() ?? (string) $state),
            ])
            ->filters([
                DberpFilamentMasterDataSelectOptions::applyDeferredSearchForFilter(
                    SelectFilter::make('supplier_id')->label(__('dberp.fields.supplier')),
                    fn (): array => DberpFilamentMasterDataSelectOptions::suppliers(),
                ),
                SelectFilter::make('status')->label(__('dberp.fields.status'))->options(PurchaseOrderStatus::statisticsScopeOptions()),
                SelectFilter::make('handler_employee_id')->label(__('dberp.fields.handler_employee'))->options(fn (): array => DberpEmployee::selectOptionsForFilament()),
                DberpFilamentMasterDataSelectOptions::applyDeferredSearchForFilter(
                    SelectFilter::make('category_id')->label(__('dberp.fields.category')),
                    fn (): array => DberpFilamentMasterDataSelectOptions::productCategories(),
                )->query(fn (Builder $query, array $data): Builder => ($data['value'] ?? null) ? $query->whereHas('items.product', fn (Builder $productQuery) => $productQuery->where('category_id', (int) $data['value'])) : $query),
                DberpFilamentMasterDataSelectOptions::applyDeferredSearchForFilter(
                    SelectFilter::make('product_id')->label(__('dberp.fields.product')),
                    fn (): array => DberpFilamentMasterDataSelectOptions::products(),
                )->query(fn (Builder $query, array $data): Builder => ($data['value'] ?? null) ? $query->whereHas('items', fn (Builder $itemQuery) => $itemQuery->where('product_id', (int) $data['value'])) : $query),
                DberpProductSkuSelectOptions::configureProductSkuTableFilter(
                    SelectFilter::make('product_sku_id')
                        ->label(__('dberp.fields.product_spec')),
                )->query(fn (Builder $query, array $data): Builder => ($data['value'] ?? null) ? $query->whereHas('items', fn (Builder $itemQuery) => $itemQuery->where('product_sku_id', (int) $data['value'])) : $query),
                Filter::make('business_time')
                    ->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('business_time', '>=', $date))
                            ->when($data['until'] ?? null, fn (Builder $builder, $date): Builder => $builder->whereDate('business_time', '<=', $date));
                    }),
            ])
            ->headerActions([
                static::makeExportAction('purchase-statistics'),
            ])
            ->recordActions([
                Action::make('view_purchase_order')
                    ->label(__('dberp.actions.view_source_document'))
                    ->url(fn (DberpPurchaseOrder $record): string => DberpPurchaseStatisticsFilamentSupport::purchaseOrderEditUrl($record))
                    ->visible(fn (DberpPurchaseOrder $record): bool => DberpPurchaseOrderResource::canEdit($record)),
                Action::make('view_supplier_payables')
                    ->label(__('dberp.resources.purchase_statistics.link_supplier_payables'))
                    ->url(fn (DberpPurchaseOrder $record, ListDberpPurchaseStatistics $livewire): string => DberpPurchaseStatisticsFilamentSupport::supplierPayableIndexUrl(
                        $record,
                        is_array($livewire->tableFilters ?? null) ? $livewire->tableFilters : [],
                    ))
                    ->visible(fn (): bool => static::allowsPermission(DberpPermissionService::VIEW_SUPPLIER_PAYABLE)),
            ]);
    }

    public static function getPages(): array
    {
        return ['index' => ListDberpPurchaseStatistics::route('/')];
    }

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

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

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

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

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