<?php


namespace App\Services;

use App\Http\Controllers\Api\AegPayController;
use App\Http\Controllers\Api\AppleStorePayController;
use App\Http\Controllers\Api\CryptoController;
use App\Http\Controllers\Api\GooglePayController;
use App\Http\Controllers\Api\GoopagoController;
use App\Http\Controllers\Api\SitoBankController;
use App\Http\Controllers\Api\WiwiPayController;
use App\Http\Controllers\Api\WDPayController;
use App\Http\Controllers\Api\CoinPayController;
use App\Http\Controllers\Api\AiPayController;
use App\Http\Controllers\Api\PagYeepPayController;
use App\Http\Controllers\Api\SafePayController;
use App\Http\Controllers\Api\SfPayController;
use App\Http\Controllers\Api\AiNewPayController;
use App\Http\Controllers\Api\BotImPayController;
use App\Http\Controllers\Api\PayPlusController;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class PayMentService
{
    public static function pay_order($transport = null)
    {
        switch ($transport) {


            case 'WiwiPay':
                return new WiwiPayController();

            case 'WDPay':
                return new WDPayController();

            case 'CoinPay':
                return new CoinPayController();

            case 'AiPay':
                return new AiPayController();

            case 'PagYeepPay':
                return new PagYeepPayController();

            case 'AiNewPay':
                return new AiNewPayController();

            case 'PayPlus':
                return new PayPlusController();

            case 'SafePay':
                return new SafePayController();

            case 'SfPay':
                return new SfPayController();

            case 'BotImPay':
                return new BotImPayController();

            case 'apple':
                return new AppleStorePayController();

            case 'google':
                return new GooglePayController();

            default:
                throw new \Exception('unknown pay channel:'.$transport);
        }
    }

    /**
     * 根据支付方式随机获取充值渠道
     * @param $method
     * @param $channel
     * @return bool|mixed
     */
    /*public static function getServiceByPayMethod3($method, $channel)
    {
//        $switch = Redis::get("recharge_config_switch_{$channel}");
//        if ($channel && $switch) {
//            $services = DB::connection('write')
//                ->table('QPPlatformDB.dbo.ChannelOpenRecharge')
//                ->join(
//                    'agent.dbo.admin_configs',
//                    'admin_configs.id',
//                    '=',
//                    'ChannelOpenRecharge.ConfigID'
//                )
//                ->where('admin_configs.new_pay_type', $method)
//                ->where('admin_configs.type', 'pay')
//                ->where('admin_configs.status', 1)
//                ->where('ChannelOpenRecharge.Status', 1)
//                ->where('ChannelOpenRecharge.Channel', $channel)
//                ->where('ChannelOpenRecharge.Sort', '>', 0)
//                ->selectRaw('admin_configs.config_key, ChannelOpenRecharge.Sort as sort')
//                ->get();
//        }
        $services = DB::table('agent.dbo.admin_configs')->where([
            'new_pay_type' => $method,
            'type' => 'pay',
            'status' => 1,
        ])->get();
        if (!$services->count()) {
            Log::error('支付渠道配置异常', [
                'method' => $method,
            ]);
            return false;
        }
        $matrix = [];
        foreach ($services as $v) {
            for ($i = 0; $i < $v->sort; $i++) {
                $matrix[] = $v->config_key;
            }
        }
        $res = $matrix[mt_rand(0, count($matrix)-1)];
        return $res;
    }*/

    /**
     * 根据支付方式随机获取充值渠道
     * @param $method
     * @param $channel
     * @return bool|mixed
     */
    public static function getServiceByPayMethod($method, $payAmt,$pay_method)
    {
        $services = DB::table('agent.dbo.admin_configs')->where([
            'new_pay_type' => $method,
            'type' => 'pay',
            'status' => 1,
        ])->whereRaw('pay_types&'.$pay_method.'='.$pay_method)
            ->where('min_amount', '<=', $payAmt)
            ->where('max_amount', '>=', $payAmt)
            ->get();
        if (!$services->count()) {
            Log::error('支付渠道配置异常', [
                'method' => $method,
            ]);
            return false;
        }
        $matrix = [];
        foreach ($services as $v) {
            $remarks = [];
            if (!empty($v->remarks)) {
                $decoded = json_decode($v->remarks, true);
                if (is_array($decoded)) {
                    $remarks = $decoded;
                }
            }
            // 按支付类型校验金额是否在允许范围内：不满足则跳过该渠道
            if (isset($remarks['limit'])) {
                $typeKey = 'type_' . $pay_method;
                $limitConfig = $remarks['limit'][$typeKey] ?? null;
                if ($limitConfig !== null && !self::isAmountInLimit($payAmt, $limitConfig)) {
                    continue;
                }
            }
            // 新逻辑：优先按支付方式独立权重分配渠道；未配置时回退旧 sort 逻辑
            $weight = self::resolveMethodWeight($remarks, $pay_method, (int)$v->sort);
            if ($weight <= 0) {
                continue;
            }
            for ($i = 0; $i < $weight; $i++) {
                $matrix[] = $v->config_key;
            }
        }
        if(count($matrix)==0) {
            foreach ($services as $v) {
                for ($i = 0; $i < $v->sort; $i++) {
                    $matrix[] = $v->config_key;
                }
            }
        }
        $res = $matrix[mt_rand(0, count($matrix)-1)];
        return $res;
    }

    /**
     * 解析指定支付方式的渠道权重（从 remarks 读取），未配置时回退默认权重
     * remarks 支持：
     * {"weight":{"type_1":30,"type_2":20,"type_4":10,"type_8":40}}
     * {"weights":{"type_1":30,"type_2":20}}
     * @param array $remarks
     * @param int $payMethod
     * @param int $defaultWeight
     * @return int
     */
    public static function resolveMethodWeight(array $remarks, $payMethod, $defaultWeight = 0)
    {
        $typeKey = 'type_' . (int)$payMethod;
        $weightConfig = $remarks['weight'] ?? ($remarks['weights'] ?? null);
        if (is_array($weightConfig) && array_key_exists($typeKey, $weightConfig)) {
            return max(0, (int)$weightConfig[$typeKey]);
        }
        return max(0, (int)$defaultWeight);
    }

    /**
     * 判断支付金额是否在 limit 配置的取值范围内
     * @param float $payAmt 支付金额
     * @param mixed $limitConfig 配置：数组为允许金额列表；['min'=>x,'max'=>y] 为区间；'all' 或 ['全部'] 为不限制
     * @return bool
     */
    public static function isAmountInLimit($payAmt, $limitConfig)
    {
        if ($limitConfig === 'all' || $limitConfig === '全部' || $limitConfig === ['全部']) {
            return true;
        }
        if (isset($limitConfig['min']) && isset($limitConfig['max'])) {
            $min = (float)$limitConfig['min'];
            $max = (float)$limitConfig['max'];
            $amt = (float)$payAmt;
            return $amt >= $min && $amt <= $max;
        }
        if (is_array($limitConfig)) {
            $payAmtRounded = round((float)$payAmt, 2);
            foreach ($limitConfig as $allowed) {
                if (round((float)$allowed, 2) === $payAmtRounded) {
                    return true;
                }
            }
            return false;
        }
        return true;
    }

    /**
     * 根据支付方式随机获取充值渠道
     * @param $method
     * @param $channel
     * @return bool|mixed
     */
    public static function getServiceByPayCountry($method, $channel,$country,$except_channelName="")
    {
        $except_configKeys=[$except_channelName];
        $switch = Redis::get("recharge_config_switch_{$channel}");
        if ($channel && $switch) {
            $services = DB::connection('write')
                          ->table('QPPlatformDB.dbo.ChannelOpenRecharge')
                          ->join(
                              'agent.dbo.admin_configs',
                              'admin_configs.id',
                              '=',
                              'ChannelOpenRecharge.ConfigID'
                          )
                          ->where('admin_configs.new_pay_type', $method)
                          ->whereNotIn('admin_configs.config_key',$except_configKeys)
                          ->where('admin_configs.country', $country)
                          ->where('admin_configs.type', 'pay')
                          ->where('admin_configs.status', 1)
                          ->where('ChannelOpenRecharge.Status', 1)
                          ->where('ChannelOpenRecharge.Channel', $channel)
                          ->where('ChannelOpenRecharge.Sort', '>', 0)
                          ->selectRaw('admin_configs.config_key, ChannelOpenRecharge.Sort as sort')
                          ->get();
        }
        if (!isset($services) || !$services->count()) {
            $services = DB::table('agent.dbo.admin_configs')->where([
                                                                        'new_pay_type' => $method,
                                                                        'type' => 'pay',
                                                                        'status' => 1,
                                                                        'country' => $country,
                                                                    ])->get();
            if (!$services->count()) {
                Log::error('支付渠道配置异常', [
                    'method' => $method,
                ]);
                return false;
            }
        }
        $matrix = [];
        foreach ($services as $v) {
            for ($i = 0; $i < $v->sort; $i++) {
                if(Redis::exists("PayErro_".$v->config_key)) continue;
                $matrix[] = $v->config_key;
            }
        }
        if(count($matrix)==0) {
            foreach ($services as $v) {
                for ($i = 0; $i < $v->sort; $i++) {
                    $matrix[] = $v->config_key;
                }
            }
        }
        $res = $matrix[mt_rand(0, count($matrix)-1)];
        return $res;
    }
}
