<?php

namespace App\Models;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class WithdrawalAgentRatioConfig
{
    const STATUS_NAME = 'WithdrawAgentRatioConfig';
    const CACHE_KEY = 'withdrawal_agent_ratio_config';
    const CACHE_TTL = 600;
    const PIX_TYPE_CASH_SMALL = 'cash_small';

    public static function pixTypeOptions()
    {
        return [
            1 => 'CashApp',
            2 => 'PayPal',
            self::PIX_TYPE_CASH_SMALL => 'CashApp小额(<50)',
        ];
    }

    public static function all()
    {
        $cache = Redis::get(self::CACHE_KEY);
        if ($cache) {
            $config = json_decode($cache, true);
            if (is_array($config)) {
                return $config;
            }

            self::clearCache();
        }

        $json = DB::table('QPAccountsDB.dbo.SystemStatusInfo')
            ->where('StatusName', self::STATUS_NAME)
            ->value('StatusString');

        $config = json_decode($json ?: '', true);
        $config = is_array($config) ? $config : [];

        Redis::setex(self::CACHE_KEY, self::CACHE_TTL, json_encode($config));

        return $config;
    }

    public static function getGlobal()
    {
        $config = self::all();

        if (self::isRatioRules($config)) {
            return $config;
        }

        return $config['100'] ?? $config[100] ?? [];
    }

    public static function saveGlobal(array $rules)
    {
        self::saveAll(self::normalizeRules($rules));
    }

    public static function clearCache()
    {
        Redis::del(self::CACHE_KEY);
    }

    public static function normalizeRules(array $rules)
    {
        $result = [];

        foreach (array_keys(self::pixTypeOptions()) as $pixType) {
            foreach (($rules[$pixType] ?? []) as $agent => $ratio) {
                $ratio = (int)$ratio;
                if ($ratio <= 0) {
                    continue;
                }

                $result[$pixType][] = [
                    'agent' => (int)$agent,
                    'ratio' => $ratio,
                ];
            }
        }

        return $result;
    }

    private static function isRatioRules(array $config)
    {
        foreach (array_keys(self::pixTypeOptions()) as $pixType) {
            if (isset($config[$pixType])) {
                return true;
            }
        }

        return false;
    }

    private static function saveAll(array $config)
    {
        DB::table('QPAccountsDB.dbo.SystemStatusInfo')->updateOrInsert(
            ['StatusName' => self::STATUS_NAME],
            [
                'StatusValue' => 0,
                'StatusString' => json_encode($config),
                'StatusTip' => '提现免审代付比例配置',
                'StatusDescription' => '按提现方式配置自动免审代付比例',
            ]
        );

        self::clearCache();
    }
}
