<?php

declare(strict_types=1);

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

namespace App\Filament\Resources\DberpSupplierPurchaseRankings\Pages;

use App\Business\Report\PurchaseReportService;
use App\Filament\Resources\DberpSupplierPurchaseRankings\DberpSupplierPurchaseRankingResource;
use App\Models\DberpSupplier;
use Filament\Resources\Pages\ListRecords;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Pagination\LengthAwarePaginator;

class ListDberpSupplierPurchaseRankings extends ListRecords
{
    protected static string $resource = DberpSupplierPurchaseRankingResource::class;

    public function getSubheading(): string|Htmlable|null
    {
        return __('dberp.resources.supplier_purchase_ranking.scope_hint');
    }

    public function computeSupplierPurchaseRankingRank(DberpSupplier $record): int
    {
        $paginator = $this->getTableRecords();

        if (! $paginator instanceof LengthAwarePaginator) {
            return 0;
        }

        $perPage = max(1, $paginator->perPage());
        $offset = max(0, ($paginator->currentPage() - 1) * $perPage);

        foreach ($paginator->items() as $index => $item) {
            if ($item instanceof DberpSupplier && $item->getKey() === $record->getKey()) {
                return $offset + $index + 1;
            }
        }

        return 0;
    }

    protected function getTableQuery(): Builder
    {
        return app(PurchaseReportService::class)->supplierRankingQuery(
            PurchaseReportService::filtersFromTableState(
                is_array($this->tableFilters) ? $this->tableFilters : null,
            ),
        );
    }
}
