<?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\SalesReportService;
use App\Filament\Resources\DberpCustomerReceivables\DberpCustomerReceivableResource;
use App\Filament\Resources\DberpSalesOrders\DberpSalesOrderResource;
use App\Models\DberpCustomer;
use App\Models\DberpProduct;
use App\Models\DberpProductSku;
use App\Models\DberpSalesOrder;

final class DberpSalesStatisticsFilamentSupport
{
    public static function salesOrderEditUrl(DberpSalesOrder $record): string
    {
        return DberpSalesOrderResource::getUrl('edit', ['record' => $record]);
    }

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

    /**
     * @param  array<string, mixed>  $tableFilters
     */
    public static function salesOrderIndexUrlForCustomerRanking(DberpCustomer $customer, array $tableFilters): string
    {
        $merged = $tableFilters;
        $merged['customer_id'] = ['value' => (int) $customer->getKey()];

        return DberpFilamentListPageUrl::append(
            DberpSalesOrderResource::getUrl('index'),
            self::tableFiltersForSalesOrderIndex($merged),
        );
    }

    /**
     * @param  array<string, mixed>  $tableFilters
     */
    public static function salesOrderIndexUrlForProductRanking(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(
            DberpSalesOrderResource::getUrl('index'),
            self::tableFiltersForSalesOrderIndex($merged),
        );
    }

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

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

    /**
     * @param  array<string, mixed>  $tableFilters
     * @return array<string, mixed>
     */
    public static function tableFiltersForSalesOrderIndex(array $tableFilters, ?DberpSalesOrder $record = null): array
    {
        $parsed = SalesReportService::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,
            ]);
        }

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

        $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 tableFiltersForCustomerReceivableIndex(array $tableFilters, ?DberpSalesOrder $record = null): array
    {
        $parsed = SalesReportService::filtersFromTableState($tableFilters);
        $filters = [];

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

        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,
            ]);
        }

        return $filters;
    }
}
