<?php

declare(strict_types=1);

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

namespace App\Filament\Pages;

use App\Business\Purchase\Enums\PurchaseInquiryQuoteStatus;
use App\Business\Purchase\PurchaseInquiryComparisonService;
use App\Filament\Concerns\InteractsWithDberpPermissions;
use App\Filament\Pages\Concerns\InteractsWithDberpNavigationGroupBreadcrumbs;
use App\Models\DberpPurchaseRequest;
use App\Services\DberpPermissionService;
use App\Support\DberpFilamentMasterDataSelectOptions;
use BackedEnum;
use Filament\Actions\Action;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Select;
use Filament\Pages\Page;
use Filament\Schemas\Components\Actions;
use Filament\Schemas\Components\Form;
use Filament\Schemas\Schema;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Support\Facades\Auth;
use UnitEnum;

/**
 * @property-read Schema $form
 */
final class DberpPurchaseInquiryComparisonPage extends Page
{
    use InteractsWithDberpNavigationGroupBreadcrumbs;
    use InteractsWithDberpPermissions;

    protected static ?string $slug = 'purchase-inquiry-comparison';

    protected static ?int $navigationSort = 12;

    protected string $view = 'filament.pages.dberp-purchase-inquiry-comparison-page';

    /**
     * @var array<string, mixed>|null
     */
    public ?array $data = [];

    /**
     * @var list<array<string, mixed>>
     */
    public array $rows = [];

    /**
     * @var array<string, int|string>
     */
    public array $totals = [];

    public function mount(): void
    {
        $this->form->fill([
            'purchase_request_id' => request()->integer('purchase_request_id') ?: null,
            'product_id' => request()->integer('product_id') ?: null,
            'supplier_id' => request()->integer('supplier_id') ?: null,
            'status' => request()->string('status')->toString() ?: null,
            'recommended_only' => request()->boolean('recommended_only') ? '1' : '0',
            'quote_date_from' => request()->string('quote_date_from')->toString() ?: null,
            'quote_date_until' => request()->string('quote_date_until')->toString() ?: null,
            'valid_until' => request()->string('valid_until')->toString() ?: null,
        ]);

        $this->refreshOverview();
    }

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

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

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

    public static function canAccess(): bool
    {
        return Auth::check() && self::allowsPermission(DberpPermissionService::NAV_PURCHASE_INQUIRY_COMPARISON);
    }

    public function getTitle(): string|Htmlable
    {
        return __('dberp.resources.purchase_inquiry_comparison.label');
    }

    public function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                Form::make([
                    DberpFilamentMasterDataSelectOptions::applyDeferredSearch(
                        Select::make('purchase_request_id')
                            ->label(__('dberp.fields.purchase_request'))
                            ->nullable(),
                        fn (): array => DberpPurchaseRequest::query()->orderByDesc('request_time')->pluck('code', 'id')->all(),
                    ),
                    DberpFilamentMasterDataSelectOptions::applyDeferredSearch(
                        Select::make('product_id')
                            ->label(__('dberp.fields.product'))
                            ->nullable(),
                        fn (): array => DberpFilamentMasterDataSelectOptions::products(enabledOnly: true),
                    ),
                    DberpFilamentMasterDataSelectOptions::applyDeferredSearch(
                        Select::make('supplier_id')
                            ->label(__('dberp.fields.supplier'))
                            ->nullable(),
                        fn (): array => DberpFilamentMasterDataSelectOptions::suppliers(enabledOnly: true),
                    ),
                    Select::make('status')
                        ->label(__('dberp.fields.status'))
                        ->options(PurchaseInquiryQuoteStatus::options())
                        ->nullable(),
                    Select::make('recommended_only')
                        ->label(__('dberp.fields.is_recommended'))
                        ->options([
                            '0' => '全部',
                            '1' => '仅建议成交',
                        ])
                        ->default('0')
                        ->nullable(),
                    DatePicker::make('quote_date_from')
                        ->label(__('dberp.fields.quote_date_from')),
                    DatePicker::make('quote_date_until')
                        ->label(__('dberp.fields.quote_date_until')),
                    DatePicker::make('valid_until')
                        ->label(__('dberp.fields.valid_until_before')),
                ])
                    ->columns(4)
                    ->livewireSubmitHandler('refreshOverview')
                    ->footer([
                        Actions::make([
                            Action::make('refreshOverview')
                                ->label(__('dberp.actions.refresh_purchase_inquiry_comparison'))
                                ->submit('refreshOverview'),
                        ]),
                    ]),
            ])
            ->statePath('data');
    }

    public function refreshOverview(): void
    {
        $payload = $this->form->getState();
        $payload['recommended_only'] = ($payload['recommended_only'] ?? '0') === '1';

        $overview = app(PurchaseInquiryComparisonService::class)->overview($payload);

        $this->rows = $overview['rows'];
        $this->totals = $overview['totals'];
    }
}
