<?php

declare(strict_types=1);

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

namespace App\Filament\Widgets;

use App\Business\Sales\SalesControlReminderService;
use App\Filament\Pages\DberpCustomerCreditControlPage;
use App\Filament\Resources\DberpAuditLogs\DberpAuditLogResource;
use App\Filament\Resources\DberpCustomerPriceRules\DberpCustomerPriceRuleResource;
use App\Filament\Resources\DberpSalesOrders\DberpSalesOrderResource;
use App\Filament\Resources\DberpSalesQuotes\DberpSalesQuoteResource;
use App\Filament\Support\DberpShortcutRegistry;
use App\Services\DberpPermissionService;
use Filament\Widgets\Widget;
use Illuminate\Support\Facades\Auth;

class SalesControlWorkbenchLinksWidget extends Widget
{
    protected static bool $isLazy = true;

    protected string $view = 'filament.widgets.sales-control-workbench-links-widget';

    protected int|string|array $columnSpan = 'full';

    public static function canView(): bool
    {
        return app(DberpPermissionService::class)->allows(Auth::user(), DberpPermissionService::VIEW_WORKBENCH_OVERVIEW);
    }

    /**
     * @return list<array<string, string|int>>
     */
    public function reminderItems(): array
    {
        $items = app(SalesControlReminderService::class)->reminderItems();

        return array_values(array_filter(array_map(function (array $item): array {
            $item['url'] = $this->urlForReminderKey((string) $item['key']);

            return $item;
        }, $items), fn (array $item): bool => $this->canAccessSalesReminderKey((string) $item['key'])));
    }

    /**
     * @return list<array<string, string>>
     */
    public function shortcutLinks(): array
    {
        $links = app(DberpShortcutRegistry::class)->shortcutViewRowsForWorkbenchKeys(
            ['erp.sales_orders', 'erp.sales_outbounds'],
            Auth::user(),
        );

        if (DberpSalesQuoteResource::canViewAny()) {
            $links[] = ['title' => (string) __('dberp.widgets.sales_workbench.shortcut_quotes'), 'url' => DberpSalesQuoteResource::getUrl('index')];
        }
        if (DberpCustomerPriceRuleResource::canViewAny()) {
            $links[] = ['title' => (string) __('dberp.widgets.sales_workbench.shortcut_prices'), 'url' => DberpCustomerPriceRuleResource::getUrl('index')];
        }
        if (DberpCustomerCreditControlPage::canAccess()) {
            $links[] = ['title' => (string) __('dberp.widgets.sales_workbench.shortcut_credit'), 'url' => DberpCustomerCreditControlPage::getUrl()];
        }

        if (DberpAuditLogResource::canViewAny()) {
            $links[] = ['title' => (string) __('dberp.widgets.sales_workbench.shortcut_audit'), 'url' => $this->auditUrl('dberp.sales_')];
        }

        return $links;
    }

    /**
     * @return list<array<string, string>>
     */
    public function exceptionLinks(): array
    {
        $links = [];

        if (DberpSalesQuoteResource::canViewAny()) {
            $links[] = ['title' => (string) __('dberp.widgets.sales_workbench.exception_expired_quote'), 'url' => $this->quoteUrl('expired')];
            $links[] = ['title' => (string) __('dberp.widgets.sales_workbench.exception_long_unconverted'), 'url' => $this->quoteUrl('long_unconverted')];
        }
        if (DberpCustomerCreditControlPage::canAccess()) {
            $links[] = ['title' => (string) __('dberp.widgets.sales_workbench.exception_blocked_credit'), 'url' => $this->creditControlUrl('blocked')];
        }
        if (DberpSalesOrderResource::canViewAny()) {
            $links[] = ['title' => (string) __('dberp.widgets.sales_workbench.exception_released_order'), 'url' => $this->salesOrderUrl('released_by_override')];
        }
        if (DberpCustomerPriceRuleResource::canViewAny()) {
            $links[] = ['title' => (string) __('dberp.widgets.sales_workbench.exception_expired_price'), 'url' => $this->priceRuleUrl('expired')];
        }

        if (DberpAuditLogResource::canViewAny()) {
            $links[] = ['title' => (string) __('dberp.widgets.sales_workbench.exception_audit'), 'url' => $this->auditUrl('dberp.sales_')];
        }

        return $links;
    }

    /**
     * 与 urlForReminderKey 目标一致：无权限的提醒不展示，避免点击进入 403。
     */
    private function canAccessSalesReminderKey(string $key): bool
    {
        return match ($key) {
            'pending_effective_quote', 'expiring_quote', 'expired_quote', 'long_unconverted_quote' => DberpSalesQuoteResource::canViewAny(),
            'blocked_credit_customer', 'near_limit_customer' => DberpCustomerCreditControlPage::canAccess(),
            'released_override_order' => DberpSalesOrderResource::canViewAny(),
            'expiring_price_rule', 'expired_price_rule' => DberpCustomerPriceRuleResource::canViewAny(),
            default => DberpSalesQuoteResource::canViewAny(),
        };
    }

    private function urlForReminderKey(string $key): string
    {
        return match ($key) {
            'pending_effective_quote' => $this->quoteUrl('pending_effective'),
            'expiring_quote' => $this->quoteUrl('expiring_soon'),
            'expired_quote' => $this->quoteUrl('expired'),
            'long_unconverted_quote' => $this->quoteUrl('long_unconverted'),
            'blocked_credit_customer' => $this->creditControlUrl('blocked'),
            'near_limit_customer' => $this->creditControlUrl('near_limit'),
            'released_override_order' => $this->salesOrderUrl('released_by_override'),
            'expiring_price_rule' => $this->priceRuleUrl('expiring_soon'),
            'expired_price_rule' => $this->priceRuleUrl('expired'),
            default => DberpSalesQuoteResource::getUrl('index'),
        };
    }

    private function quoteUrl(string $attentionStatus): string
    {
        return DberpSalesQuoteResource::getUrl('index').'?'.http_build_query([
            'filters' => [
                'attention_status' => [
                    'value' => $attentionStatus,
                ],
            ],
        ]);
    }

    private function priceRuleUrl(string $attentionStatus): string
    {
        return DberpCustomerPriceRuleResource::getUrl('index').'?'.http_build_query([
            'filters' => [
                'attention_status' => [
                    'value' => $attentionStatus,
                ],
            ],
        ]);
    }

    private function salesOrderUrl(string $attentionStatus): string
    {
        return DberpSalesOrderResource::getUrl('index').'?'.http_build_query([
            'filters' => [
                'attention_status' => [
                    'value' => $attentionStatus,
                ],
            ],
        ]);
    }

    private function creditControlUrl(string $attentionStatus): string
    {
        return DberpCustomerCreditControlPage::getUrl().'?'.http_build_query([
            'attention_status' => $attentionStatus,
        ]);
    }

    private function auditUrl(string $keyword): string
    {
        return DberpAuditLogResource::getUrl('index').'?'.http_build_query([
            'filters' => [
                'action' => [
                    'value' => $keyword,
                ],
            ],
        ]);
    }
}
