<?php

declare(strict_types=1);

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

namespace App\Support;

use App\Business\Report\PurchaseReportService;
use App\Filament\Resources\DberpPurchaseOrders\DberpPurchaseOrderResource;
use App\Filament\Resources\DberpSupplierPayables\DberpSupplierPayableResource;
use App\Models\DberpProduct;
use App\Models\DberpProductSku;
use App\Models\DberpPurchaseOrder;
use App\Models\DberpSupplier;

final class DberpPurchaseStatisticsFilamentSupport
{
    public static function purchaseOrderEditUrl(DberpPurchaseOrder $record): string
    {
        return DberpPurchaseOrderResource::getUrl('edit', ['record' => $record]);
    }

    /**
     * @param  array<string, mixed>  $tableFilters
     */
    public static function purchaseOrderIndexUrlFromTableState(array $tableFilters): string
    {
        return DberpFilamentListPageUrl::append(
            DberpPurchaseOrderResource::getUrl('index'),
            self::tableFiltersForPurchaseOrderIndex($tableFilters),
        );
    }

    /**
     * @param  array<string, mixed>  $tableFilters
     */
    public static function purchaseOrderIndexUrlForSupplierRanking(DberpSupplier $supplier, array $tableFilters): string
    {
        $merged = $tableFilters;
        $merged['supplier_id'] = ['value' => (int) $supplier->getKey()];

        return DberpFilamentListPageUrl::append(
            DberpPurchaseOrderResource::getUrl('index'),
            self::tableFiltersForPurchaseOrderIndex($merged),
        );
    }

    /**
     * @param  array<string, mixed>  $tableFilters
     */
    public static function purchaseOrderIndexUrlForProductPurchaseRanking(DberpProduct|DberpProductSku $record, array $tableFilters): string
    {
        $merged = $tableFilters;
        $productId = $record instanceof DberpProductSku
            ? (int) $record->product_id
            : (int) $record->getKey();
        $merged['product_id'] = ['value' => $productId];

        return DberpFilamentListPageUrl::append(
            DberpPurchaseOrderResource::getUrl('index'),
            self::tableFiltersForPurchaseOrderIndex($merged),
        );
    }

    /**
     * @param  array<string, mixed>  $tableFilters
     */
    public static function supplierPayableIndexUrlFromTableState(array $tableFilters): string
    {
        return DberpFilamentListPageUrl::append(
            DberpSupplierPayableResource::getUrl('index'),
            self::tableFiltersForSupplierPayableIndex($tableFilters),
        );
    }

    /**
     * @param  array<string, mixed>  $tableFilters
     */
    public static function supplierPayableIndexUrl(DberpPurchaseOrder $record, array $tableFilters = []): string
    {
        return DberpFilamentListPageUrl::append(
            DberpSupplierPayableResource::getUrl('index'),
            self::tableFiltersForSupplierPayableIndex($tableFilters, $record),
        );
    }

    /**
     * @param  array<string, mixed>  $tableFilters
     * @return array<string, mixed>
     */
    public static function tableFiltersForPurchaseOrderIndex(array $tableFilters, ?DberpPurchaseOrder $record = null): array
    {
        $parsed = PurchaseReportService::filtersFromTableState($tableFilters);
        $filters = [];

        if (! empty($parsed['business_time_from']) || ! empty($parsed['business_time_until'])) {
            $filters['business_time_range'] = array_filter([
                'from' => $parsed['business_time_from'] ?? null,
                'until' => $parsed['business_time_until'] ?? null,
            ]);
        }

        $supplierId = (int) ($parsed['supplier_id'] ?? 0);
        if ($supplierId <= 0 && $record !== null) {
            $supplierId = (int) $record->supplier_id;
        }
        if ($supplierId > 0) {
            $filters['supplier_id'] = ['value' => $supplierId];
        }

        $handlerEmployeeId = (int) ($parsed['handler_employee_id'] ?? 0);
        if ($handlerEmployeeId <= 0 && $record !== null) {
            $handlerEmployeeId = (int) ($record->handler_employee_id ?? 0);
        }
        if ($handlerEmployeeId > 0) {
            $filters['handler_employee_id'] = ['value' => $handlerEmployeeId];
        }

        if (! empty($parsed['status'])) {
            $filters['status'] = ['value' => (string) $parsed['status']];
        }

        $productId = (int) ($parsed['product_id'] ?? 0);
        if ($productId > 0) {
            $filters['product_id'] = ['product_id' => $productId];
        }

        return $filters;
    }

    /**
     * @param  array<string, mixed>  $tableFilters
     * @return array<string, mixed>
     */
    private static function tableFiltersForSupplierPayableIndex(array $tableFilters, ?DberpPurchaseOrder $record = null): array
    {
        $parsed = PurchaseReportService::filtersFromTableState($tableFilters);
        $filters = [];

        $supplierId = (int) ($parsed['supplier_id'] ?? 0);
        if ($supplierId <= 0 && $record !== null) {
            $supplierId = (int) $record->supplier_id;
        }
        if ($supplierId > 0) {
            $filters['supplier_id'] = ['value' => $supplierId];
        }

        if (! empty($parsed['business_time_from']) || ! empty($parsed['business_time_until'])) {
            $filters['business_time_range'] = array_filter([
                'from' => $parsed['business_time_from'] ?? null,
                'until' => $parsed['business_time_until'] ?? null,
            ]);
        }

        $handlerEmployeeId = (int) ($parsed['handler_employee_id'] ?? 0);
        if ($handlerEmployeeId <= 0 && $record !== null) {
            $handlerEmployeeId = (int) ($record->handler_employee_id ?? 0);
        }
        if ($handlerEmployeeId > 0) {
            $filters['handler_employee_id'] = ['value' => $handlerEmployeeId];
        }

        return $filters;
    }
}
