<?php

namespace Kylin\Payment\Services;

use Illuminate\Contracts\Container\Container;
use Illuminate\Support\Facades\Cache;
use Kylin\Payment\Facades\Payment;

/**
 * 支付智能路由服务类
 */
class PaymentIntelligentRoutingService
{
    /**
     * 默认路由配置
     */
    const DEFAULT_ROUTING_CONFIG = [
        'enabled' => true, // 是否启用智能路由
        'cache_key' => 'payment_routing_cache', // 缓存键
        'cache_ttl' => 3600, // 缓存过期时间（秒）
        'default_gateway' => 'alipay', // 默认支付网关
        'fallback_gateway' => 'wechat', //  fallback支付网关
    ];

    /**
     * 路由规则
     */
    protected array $rules;

    /**
     * 构造函数
     */
    public function __construct(
        protected readonly Container $app,
        protected array $config = []
    ) {
        $this->config = array_merge(self::DEFAULT_ROUTING_CONFIG, $config);
        $this->rules = $this->loadRules();
    }

    /**
     * 加载路由规则
     */
    protected function loadRules(): array
    {
        // 尝试从缓存加载规则
        $cachedRules = Cache::get($this->config['cache_key']);
        if ($cachedRules) {
            return $cachedRules;
        }

        // 从数据库加载规则
        $rules = \Illuminate\Support\Facades\DB::table('payment_routing_rules')
            ->where('status', 'active')
            ->orderBy('priority', 'desc')
            ->get()
            ->toArray();

        // 转换规则格式
        $formattedRules = [];
        foreach ($rules as $rule) {
            $formattedRules[] = [
                'id' => $rule->id,
                'name' => $rule->name,
                'condition' => json_decode($rule->condition, true),
                'gateway' => $rule->gateway,
                'priority' => $rule->priority,
                'status' => $rule->status,
            ];
        }

        // 缓存规则
        Cache::put($this->config['cache_key'], $formattedRules, $this->config['cache_ttl']);

        return $formattedRules;
    }

    /**
     * 注册路由规则
     */
    public function registerRule(string $name, array $condition, string $gateway, int $priority = 0, string $status = 'active'): int
    {
        $ruleId = \Illuminate\Support\Facades\DB::table('payment_routing_rules')->insertGetId([
            'name' => $name,
            'condition' => json_encode($condition),
            'gateway' => $gateway,
            'priority' => $priority,
            'status' => $status,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        // 清除缓存
        $this->clearCache();

        return $ruleId;
    }

    /**
     * 清除缓存
     */
    public function clearCache(): void
    {
        Cache::forget($this->config['cache_key']);
        $this->rules = $this->loadRules();
    }

    /**
     * 智能选择支付网关
     */
    public function selectGateway(array $params): string
    {
        // 如果未启用智能路由，返回默认网关
        if (!$this->config['enabled']) {
            return $this->config['default_gateway'];
        }

        // 检查规则
        foreach ($this->rules as $rule) {
            if ($this->evaluateCondition($rule['condition'], $params)) {
                // 检查网关是否可用
                if ($this->isGatewayAvailable($rule['gateway'])) {
                    return $rule['gateway'];
                }
            }
        }

        // 检查默认网关是否可用
        if ($this->isGatewayAvailable($this->config['default_gateway'])) {
            return $this->config['default_gateway'];
        }

        // 返回fallback网关
        return $this->config['fallback_gateway'];
    }

    /**
     * 评估条件
     */
    protected function evaluateCondition(array $condition, array $params): bool
    {
        foreach ($condition as $key => $value) {
            if (!isset($params[$key])) {
                return false;
            }

            // 支持多种比较操作
            if (is_array($value)) {
                // 范围比较
                if (isset($value['min']) && isset($value['max'])) {
                    if ($params[$key] < $value['min'] || $params[$key] > $value['max']) {
                        return false;
                    }
                }
                // 包含比较
                if (isset($value['in'])) {
                    if (!in_array($params[$key], $value['in'])) {
                        return false;
                    }
                }
            } else {
                // 精确匹配
                if ($params[$key] !== $value) {
                    return false;
                }
            }
        }

        return true;
    }

    /**
     * 检查网关是否可用
     */
    protected function isGatewayAvailable(string $gateway): bool
    {
        try {
            // 检查网关配置是否存在
            $config = config("payment.{$gateway}");
            if (!$config) {
                return false;
            }

            // 检查网关是否启用
            if (isset($config['enabled']) && !$config['enabled']) {
                return false;
            }

            // 检查网关服务是否可用（这里可以添加更复杂的健康检查逻辑）
            // 例如：检查网关API是否响应、检查余额等

            return true;
        } catch (\Exception $e) {
            Payment::log('routing', 'gateway_unavailable', ['gateway' => $gateway], $e->getMessage());
            return false;
        }
    }

    /**
     * 获取路由决策
     */
    public function getRoutingDecision(array $params): array
    {
        $gateway = $this->selectGateway($params);
        $availableGateways = $this->getAvailableGateways();

        return [
            'selected_gateway' => $gateway,
            'available_gateways' => $availableGateways,
            'timestamp' => now()->toIso8601String(),
        ];
    }

    /**
     * 获取可用的支付网关
     */
    public function getAvailableGateways(): array
    {
        $availableGateways = [];
        $gateways = ['alipay', 'wechat', 'unionpay', 'douyin', 'jsbank', 'alipayintl', 'paypal', 'stripe', 'googlepay', 'applepay'];

        foreach ($gateways as $gateway) {
            if ($this->isGatewayAvailable($gateway)) {
                $availableGateways[] = $gateway;
            }
        }

        return $availableGateways;
    }

    /**
     * 更新路由规则
     */
    public function updateRule(int $ruleId, array $data): bool
    {
        $result = \Illuminate\Support\Facades\DB::table('payment_routing_rules')
            ->where('id', $ruleId)
            ->update(array_merge($data, [
                'updated_at' => now(),
            ]));

        // 清除缓存
        if ($result) {
            $this->clearCache();
        }

        return $result > 0;
    }

    /**
     * 删除路由规则
     */
    public function deleteRule(int $ruleId): bool
    {
        $result = \Illuminate\Support\Facades\DB::table('payment_routing_rules')
            ->where('id', $ruleId)
            ->delete();

        // 清除缓存
        if ($result) {
            $this->clearCache();
        }

        return $result > 0;
    }

    /**
     * 获取路由规则列表
     */
    public function getRules(): \Illuminate\Database\Eloquent\Collection
    {
        return \Illuminate\Support\Facades\DB::table('payment_routing_rules')
            ->orderBy('priority', 'desc')
            ->get();
    }

    /**
     * 获取路由统计信息
     */
    public function getRoutingStats(int $days = 30): array
    {
        $startDate = now()->subDays($days);

        // 获取路由决策记录
        $records = \Illuminate\Support\Facades\DB::table('payment_routing_decisions')
            ->where('created_at', '>=', $startDate)
            ->get();

        // 统计数据
        $stats = [
            'total_decisions' => $records->count(),
            'by_gateway' => [],
            'by_rule' => [],
            'success_rate' => 0,
        ];

        // 按网关统计
        foreach ($records as $record) {
            $gateway = $record->selected_gateway;
            $stats['by_gateway'][$gateway] = ($stats['by_gateway'][$gateway] ?? 0) + 1;

            // 按规则统计
            if ($record->matched_rule_id) {
                $ruleId = $record->matched_rule_id;
                $stats['by_rule'][$ruleId] = ($stats['by_rule'][$ruleId] ?? 0) + 1;
            }
        }

        return $stats;
    }

    /**
     * 记录路由决策
     */
    public function logDecision(array $params, string $selectedGateway, ?int $matchedRuleId = null): void
    {
        \Illuminate\Support\Facades\DB::table('payment_routing_decisions')->insert([
            'params' => json_encode($params),
            'selected_gateway' => $selectedGateway,
            'matched_rule_id' => $matchedRuleId,
            'created_at' => now(),
        ]);
    }

    /**
     * 获取路由配置
     */
    public function getConfig(): array
    {
        return $this->config;
    }

    /**
     * 设置路由配置
     */
    public function setConfig(array $config): self
    {
        $this->config = array_merge($this->config, $config);
        return $this;
    }

    /**
     * 启用智能路由
     */
    public function enable(): self
    {
        $this->config['enabled'] = true;
        return $this;
    }

    /**
     * 禁用智能路由
     */
    public function disable(): self
    {
        $this->config['enabled'] = false;
        return $this;
    }
}
