<?php


namespace App\Http\Controllers\Admin;

// 渠道管理
use App\Facade\TableName;
use App\Game\WebChannelConfig;
use App\Http\helper\Helper;
use App\Http\logic\admin\ChannelLogic;
use App\Http\logic\admin\RechargeLogic;
use App\Jobs\ClearCache;
use App\Models\AppSwitch;
use App\Models\SystemStatusInfo;
use App\Models\WithdrawalAgentRatioConfig;
use App\Models\WithdrawalChannelPositionConfig;
use App\Models\WithdrawalPositionConfig;
use App\Services\GameRoomInfo;
use App\Services\PayConfig;
use App\Util;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Validator;


class ChannelController
{
    public function index(Request $request)
    {

        $where = [];
        $name = $request->Name ?: '';
        !empty($name) && $where[] = ['Name', 'like', $name . '%'];
//        $notIn = [1, 2, 3, 4, 5, 7, 10, 13, 14, 15, 16, 17];
        $list = DB::connection('write')->table('QPPlatformDB.dbo.ChannelConfig')
//            ->whereNotIn('ChannelIndex', $notIn)
            ->where($where)
            ->paginate(10);


        return view('admin.channel.index', ['list' => $list, 'Name' => $name]);
    }

    public function channelAdd(Request $request)
    {
        if ($request->isMethod('post')) {
            $post = $request->post();
            $Channel = $post['Channel'];
            $post['ChannelType'] = 100;
            $post['ChannelIndex'] = $Channel - $post['ChannelType'];
            $post['ReviewState'] = 1;
            unset($post['Channel']);
            DB::connection('write')->table('QPPlatformDB.dbo.ChannelConfig')
                ->insert($post);

            // 同步添加渠道包
            DB::connection('write')->table('QPPlatformDB.dbo.ChannelRechargeGameOpen')
                ->insert(['ChannelPackageName' => $post['Name'], 'Channel' => $Channel]);
            return apiReturnSuc();
        } else {
            return view('admin.channel.channel_add');
        }
    }


    public function channelNew(Request $request)
    {
        if ($request->isMethod('post')) {
            $post = $request->post();
            $post['Remarks'] = $post['AliasName'];
            $post['AppKey']= Util::generateRandomString();
            while(DB::connection('write')->table('QPPlatformDB.dbo.ChannelPackageName')->where('AppKey', $post['AppKey'])->exists()) {
                $post['AppKey'] = Util::generateRandomString();
            }
            DB::connection('write')->table('QPPlatformDB.dbo.ChannelPackageName')
                ->insert($post);

            $channel = @$post['Channel'];
            if($channel){
                $createConfig = function () use($channel) {
                    $config = new WithdrawalChannelPositionConfig();
                    $config->channel = $channel;
                    return $config;
                };

                $config = WithdrawalChannelPositionConfig::query()->where('channel', $channel)->first() ?: $createConfig();
                $config->save();
            }


            return apiReturnSuc();
        } else {
            return view('admin.channel.channel_new');
        }
    }

    public function channelEdit(Request $request, $id)
    {
        $ChannelIndex = $request->ChannelIndex;
        $AndroidVersion = $request->AndroidVersion;
        $where = [
            ['ChannelType', '=', $id],
            ['ChannelIndex', '=', $ChannelIndex],
            ['AndroidVersion', '=', $AndroidVersion],

        ];

        if ($request->isMethod('post')) {
            $post = $request->post();
            //$post['ChannelIndex'] = $post['Channel'] - $post['ChannelType'];
            unset($post['Channel']);


            DB::connection('write')->table('QPPlatformDB.dbo.ChannelConfig')
                ->where($where)
                ->update($post);


            // 同步修改渠道包
            DB::connection('write')->table('QPPlatformDB.dbo.ChannelRechargeGameOpen')
                ->where('Channel', ($id + $ChannelIndex))
                ->update(['ChannelPackageName' => $post['Name']]);


            return apiReturnSuc();
        } else {
            $info = DB::connection('write')->table('QPPlatformDB.dbo.ChannelConfig')
                ->where($where)
                ->first();
            return view('admin.channel.channel_edit', compact('info', 'id', 'ChannelIndex', 'AndroidVersion'));
        }
    }

    public function switch_control(Request $request, $id)
    {
        $type = $request->type;
        $ChannelIndex = $request->ChannelIndex;
        $AndroidVersion = $request->AndroidVersion;

        $logic = new ChannelLogic();
        $res = $logic->switch_control($id, $ChannelIndex, $AndroidVersion, $type);

        if ($res === false) {
            return apiReturnFail($logic->getError());
        }
        return apiReturnSuc();
    }


    public function update(Request $request, $ChannelType)
    {
        $ChannelIndex = $request->ChannelIndex ?: '';
        $ChannelName = $request->ChannelName ?: '';
        $AndroidVersion = $request->AndroidVersion;
        $data = $request->data ?: '';
        $where[] = ['ChannelIndex', '=', $ChannelIndex];
        $where[] = ['ChannelType', '=', $ChannelType];
        $where[] = ['AndroidVersion', '=', $AndroidVersion];
        if ($request->isMethod('POST')) {

            DB::connection('write')->table('QPPlatformDB.dbo.ChannelConfig')
                ->where($where)
                ->updateOrInsert($where, $data);
            return apiReturnSuc();

        } else {

            $info = DB::connection('read')->table('QPPlatformDB.dbo.ChannelConfig')
                ->where($where)
                ->first();
            return view('admin.channel.update', [
                'info' => $info,
                'ChannelName' => $ChannelName
            ]);

        }


    }

    public function ChannelSaveLog()
    {
        $list = DB::connection('read')->table('agent.dbo.ChannelSaveLog as log')
            ->join('agent.dbo.admin_users as au', 'log.admin_id', '=', 'au.id')
            ->select('au.account', 'log.*')
            ->paginate(10);
        foreach ($list as &$val) {
            $ChannelName = '';
            switch ($val->channel) {
                case 0:
                    $ChannelName = '官方';
                    break;
                case 100:   // 谷歌渠道

                    switch ($val->ChannelIndex) {
                        case 0:
                            $ChannelName = '谷歌渠道';
                            break;
                        case 1:
                            $ChannelName = 'Teenpatti Royal';
                            break;
                        case 2:
                            $ChannelName = 'teenpatti club';
                            break;
                        case 3:
                            $ChannelName = 'Teenpatti.Champion';
                            break;
                        case 4:
                            $ChannelName = 'com.teempatti.Victory';
                            break;
                        case 5:
                            $ChannelName = 'com.teempatti.fun';
                            break;
                        case 6:
                            $ChannelName = 'teenpatti Exceed';
                            break;
                        case 7:
                            $ChannelName = 'com.teempatti.reward';
                            break;
                        case 8:
                            $ChannelName = 'com.teempatti.qplayer';
                            break;
                        case 9:
                            $ChannelName = 'com.teempatti.q3acard';
                            break;
                        case 10:
                            $ChannelName = 'com.teempatti.qnobles';
                            break;
                        case 11:
                            $ChannelName = 'com.teempatti.qgrandparty';
                            break;
                        case 12:
                            $ChannelName = 'com.teempatti.queen';
                            break;
                        case 13:
                            $ChannelName = 'com.teempatti.royalclub';
                            break;
                        case 14:
                            $ChannelName = 'com.teempatti.queencard';
                            break;
                        case 15:
                            $ChannelName = 'com.teempatti.queensnice';
                            break;
                        case 16:
                            $ChannelName = 'com.teempatti.queensplay';
                            break;
                        case 17:
                            $ChannelName = 'com.teempatti.queensclub';
                            break;

                    }
            }
            $val->ChannelName = $ChannelName;
        }
        return view('admin.channel.ChannelSaveLog', ['list' => $list]);
    }

    // 渠道审核屏蔽ID白名单
    public function ChannelShieldIDWhite()
    {
//        $list = DB::connection('write')->table('QPPlatformDB.dbo.ChannelShieldIDWhite')->paginate(10);

        $list = DB::connection('read')->table('QPAccountsDB.dbo.IDWhiteUser as white')
                  ->join('QPAccountsDB.dbo.AccountsInfo as acc', 'acc.UserID', '=', 'white.UserID')
                  ->select('acc.GameID', 'acc.UserID','white.Remarks')
                  ->paginate(100);
//        print_r($list);die;
        return view('admin.channel.channel_shield_id_white', compact('list'));
    }

    // 渠道审核屏蔽ID白名单 -- 添加ID
    public function add(Request $request)
    {
        if ($request->isMethod('post')) {

            $post = $request->post();
            $userid = DB::connection('write')->table('QPAccountsDB.dbo.AccountsInfo')
                ->where('GameID', $post['GameID'])
                ->select('UserID')
                ->first()->UserID;
            if (!$userid) {
                return apiReturnFail('用户ID不存在');
            }

            $first = DB::connection('write')->table('QPAccountsDB.dbo.IDWhiteUser')
                ->where('UserID', $userid)
                ->first();
            if ($first) {
                return apiReturnFail('用户已经存在');
            }

            DB::connection('write')->table('QPAccountsDB.dbo.IDWhiteUser')
                ->insert(['UserID'=>$userid,'Remarks'=>$post['Remarks']]);
            return apiReturnSuc();
        }
        return view('admin.channel.channel_shield_id_white_add');
    }

    // 渠道审核屏蔽ID白名单 -- 修改ID
    public function edit(Request $request, $ID)
    {
        if ($request->isMethod('post')) {

            $post = $request->post();

            DB::connection('write')->table('QPAccountsDB.dbo.IDWhiteUser')
                ->where('UserID', $ID)
                ->update($post);
            return apiReturnSuc();
        }
        $info = DB::connection('write')->table('QPAccountsDB.dbo.IDWhiteUser')
            ->where('UserID', $ID)
            ->first();
        return view('admin.channel.channel_shield_id_white_add', compact('info'));
    }

    // 渠道审核屏蔽ID白名单 -- 删除ID
    public function del($ID)
    {
        DB::connection('write')->table('QPAccountsDB.dbo.IDWhiteUser')
            ->where('UserID', $ID)
            ->delete();
        return apiReturnSuc();
    }

    // 渠道审核屏蔽ID白名单 -- 修改状态
    public function updateState(Request $request)
    {
        $State = (int)$request->State;
        $State = DB::connection('write')->table('QPAccountsDB.dbo.SystemStatusInfo')
            ->where('StatusName', 'ChannelShieldIDWhite')
            ->update(['StatusValue' => $State]);
        return apiReturnSuc();
    }

    // 渠道包配置充值和游戏
    public function rechargeGame(Request $request)
    {
        $ChannelPackageName = $request->ChannelPackageName ?: '';

        $list = (new ChannelLogic())->rechargeGame($ChannelPackageName);
        return view('admin.channel.recharge_game', compact('list'));
    }

    // 开放游戏配置修改 $Channel == -1 默认游戏配置
    // 开放游戏配置修改 $Channel == -1 默认游戏配置
    public function OpenGames(Request $request, $Channel)
    {

        $ChannelPackageName = $request->ChannelPackageName ?: '';
        if ($request->isMethod('post')) {

            $post = $request->all();

            $GameShareUrl = $post['ShareUrl'] ?? '';
            unset($post['ShareUrl']);
            $arr = [];
            if (isset($post['KindID'])) {
                for ($i = 0; $i < count($post['KindID']); $i++) {

                    if (isset($post['KindID'][$i]) && $post['KindID'][$i] >= 0) {
                        $arr[$i]['KindID'] = $post['KindID'][$i];
                        $arr[$i]['Status'] = $post['Status'][$i] ?? 1;
                        $arr[$i]['Sort'] = $post['Sort'][$i] ?? 0;
                        $arr[$i]['SecondStageStatus'] = $post['SecondStageStatus'][$i] ?? 0;
                        $arr[$i]['SecondStageSort'] = $post['SecondStageSort'][$i] ?? 0;
                        $arr[$i]['IconType'] = $post['IconType'][$i] ?? 1;
                        $arr[$i]['Channel'] = $Channel;
                        $arr[$i]['LimitCV'] = $post['LimitCV'][$i]??0;
                        $arr[$i]['VIP'] = $post['VIP'][$i]??0;
                    }

                }
            }
            DB::connection('write')->table('QPPlatformDB.dbo.ChannelGameOpen')
                ->where('Channel', $Channel)
                ->delete();

            DB::connection('write')->table('QPPlatformDB.dbo.ChannelGameOpen')
                ->insert($arr);

            // 修改默认游戏分享链接
            if (!empty($GameShareUrl)) {
                DB::table(TableName::QPAccountsDB() . 'SystemStatusInfo')
                    ->where('StatusName', 'GameShareUrl')
                    ->update(['StatusString' => $GameShareUrl]);
            }
            // ted提现开关
            if ($request->input('ted_switch', null) !== null) {
                $tedSwitch = AppSwitch::query()->firstOrNew(['name' => 'ted', 'scene' => 1, 'channel' => $Channel]);
                $tedSwitch->status = $request->input('ted_switch');
                $tedSwitch->save();
            }
            return apiReturnSuc();
        }


        $openGames = config('games.openKGame');
        $list = DB::connection('write')->table('QPPlatformDB.dbo.GameKindItem as gi')
            ->leftJoin('QPPlatformDB.dbo.ChannelGameOpen as cg', function ($join) use ($Channel) {
                $join->on('gi.KindID', 'cg.KindID');
                $join->where('Channel', $Channel);
            })
            ->whereIn('gi.KindID', $openGames)
            ->selectRaw('IsNull(Status,2) Status,KindName,gi.KindID,cg.Sort,SecondStageStatus,SecondStageSort,IconType,LimitCV,VIP')
            ->orderByDesc('Sort')
            ->get();
        // 游戏默认分享链接
        $GameShareUrl = DB::table(TableName::QPAccountsDB() . 'SystemStatusInfo')
            ->where('StatusName', 'GameShareUrl')
            ->value('StatusString');
        $tedSwitch = AppSwitch::query()->where([
            'name' => 'ted',
            'channel' => $Channel
        ])->first();
        return view(
            'admin.channel.open_games',
            compact('list', 'ChannelPackageName', 'Channel', 'GameShareUrl', 'tedSwitch')
        );
    }

    public function payMethods($channel, Request $request)
    {
        $list = DB::connection('write')->table('agent.dbo.admin_configs as ac')
            ->leftJoin('QPPlatformDB.dbo.ChannelOpenRecharge as oc', function ($join) use ($channel) {
                $join->on('ac.id', '=', 'oc.ConfigID');
                $join->where('Channel', $channel);
            })
            ->where('type', 'pay_method')
            ->selectRaw('IsNull(oc.Status,2) Status,name,ac.id,oc.Sort, ac.config_key')
            ->get();
        foreach ($list as $k => $v) {
            $channels = DB::table('agent.dbo.admin_configs as ac')->where([
                'type' => 'pay',
                'new_pay_type' => $v->config_key
            ])
                ->leftJoin('QPPlatformDB.dbo.ChannelOpenRecharge as oc', function ($join) use ($channel) {
                    $join->on('ac.id', '=', 'oc.ConfigID');
                    $join->where('Channel', $channel);
                })
                ->selectRaw('IsNull(oc.Status,2) Status,name,ac.id,oc.Sort, ac.config_key')
                ->get();
            $list[$k]->channels = $channels;
        }
        $switch = intval(Redis::get("recharge_config_switch_{$channel}"));
        return view('admin.channel.pay_methods', [
            'list' => $list,
            'channel' => $channel,
            'switch' => $switch
        ]);
    }

    public function updatePayConfig($channel, Request $request)
    {
        $switch = $request->input('switch', 0);
        Redis::set("recharge_config_switch_{$channel}", $switch);
        $switchOpened = DB::table('agent.dbo.admin_configs')->where([
            'type' => 'pay',
            'status' => 1,
        ])->pluck('id');
        $payMethodOpened = DB::table('agent.dbo.admin_configs')->where([
            'type' => 'pay_method',
            'status' => 1,
        ])->pluck('id');
        $inserts = [];
        foreach ($request->input('items') as $k => $v) {
            if (!in_array($v['id'], $payMethodOpened->toArray()) && $v['status'] == 1) {
                return apiReturnFail($v['id'] . '总开关已关闭，无法开启');
            }
            $inserts[] = [
                'ConfigID' => $v['id'],
                'Status' => $v['status'],
                'Sort' => $v['sort'],
                'Channel' => $channel
            ];
            $percent = 0;
            foreach ($v['channels'] ?? [] as $k1 => $v1) {
                if (!in_array($v1['id'], $switchOpened->toArray()) && $v1['status'] == 1) {
                    return apiReturnFail($v1['id'] . '总开关已关闭，无法开启');
                }
                $inserts[] = [
                    'ConfigID' => $v1['id'],
                    'Status' => $v1['status'],
                    'Sort' => $v1['sort'],
                    'Channel' => $channel
                ];
                $percent += $v1['sort'];
            }
            if ($percent != 100 && $v['status'] == 1) {
                return apiReturnFail('权重值分配不正确');
            }
        }

        DB::connection('write')->table('QPPlatformDB.dbo.ChannelOpenRecharge')
            ->where('Channel', $channel)
            ->delete();
        DB::connection('write')->table('QPPlatformDB.dbo.ChannelOpenRecharge')
            ->insert($inserts);
        ClearCache::dispatch();
        return apiReturnSuc();
    }

    // 充值配置修改
    public function OpenRecharge(Request $request, $Channel)
    {

        $ChannelPackageName = $request->ChannelPackageName ?: '';
        if ($request->isMethod('post')) {


            $post = $request->all();
            $arr = [];

            if (isset($post['id'])) {
                for ($i = 0; $i < count($post['id']); $i++) {
                    $arr[$i]['ConfigID'] = $post['id'][$i] ?? 0;
                    $arr[$i]['Status'] = $post['Status'][$i] ?? 1;
                    $arr[$i]['Sort'] = $post['Sort'][$i] ?? 0;
                    $arr[$i]['Channel'] = $Channel;
                }
            }


            DB::connection('write')->table('QPPlatformDB.dbo.ChannelOpenRecharge')
                ->where('Channel', $Channel)
                ->delete();

            DB::connection('write')->table('QPPlatformDB.dbo.ChannelOpenRecharge')
                ->insert($arr);
            ClearCache::dispatch();
            return apiReturnSuc();
        }


        $list = DB::connection('write')->table('agent.dbo.admin_configs as ac')
            ->leftJoin('QPPlatformDB.dbo.ChannelOpenRecharge as oc', function ($join) use ($Channel) {
                $join->on('ac.id', '=', 'oc.ConfigID');
                $join->where('Channel', $Channel);
            })
            ->where('ac.status', 1)
            ->where('type', 'pay')
            ->selectRaw('IsNull(oc.Status,2) Status,name,ac.id,oc.Sort')
            ->get();


        return view('admin.channel.open_recharge', compact('list', 'ChannelPackageName', 'Channel'));
    }



    // 修改备注
    public function appkey(Request $request, $id)
    {


       $app=DB::connection('write')->table('QPPlatformDB.dbo.ChannelPackageName')
           ->where('ID', $id)->first();

       if(empty($app->AppKey)) {
           $AppKey=Util::generateRandomString(random_int(6,12));
           DB::connection('write')->table('QPPlatformDB.dbo.ChannelPackageName')
               ->where('ID', $id)
               ->update(['AppKey' => $AppKey]);

       }else{
           $AppKey=$app->AppKey;
       }
        return apiReturnSuc($AppKey);
    }


    // 修改备注
    public function app_key_set(Request $request, $id)
    {

        $config = DB::table('QPPlatformDB.dbo.ChannelPackageName')->where('ID', $id)->first();
        if ($request->method() == 'GET') {
            return view('admin.channel.app_key_set', [
                'config' => $config,
            ]);
        }

        $data=$request->all();
        $data['AdjustConfig']=$data['AdjustConfig']??"";
        DB::table('QPPlatformDB.dbo.ChannelPackageName')->where('ID', $id)->update($data);


        return apiReturnSuc();
    }


    // 修改备注
    public function review(Request $request, $id)
    {


        $review=$request->status?:0;

       DB::connection('write')->table('QPPlatformDB.dbo.ChannelPackageName')
           ->where('ID', $id)
           ->update(['InReview' => $review]);

       $app=DB::connection('write')->table('QPPlatformDB.dbo.ChannelPackageName')
            ->where('ID', $id)->first();
       Redis::del("InReview_{$id}");
       Redis::del("InReview_{$app->PackageName}");
       return apiReturnSuc($review);
    }


    // 修改备注
    public function remarks(Request $request, $id)
    {
        $remarks = $request->remark ?: '';

        DB::connection('write')->table('QPPlatformDB.dbo.ChannelPackageName')
            ->where('ID', $id)
            ->update(['Remarks' => $remarks,'AliasName'=>$remarks]);
        $cp=DB::connection('write')->table('QPPlatformDB.dbo.ChannelPackageName')
            ->where('ID', $id)->select('Channel','PackageName')->first();
        $Channel=$cp->Channel;
        $PackageName=$cp->PackageName;

        if(WebChannelConfig::where('Channel', $Channel)->exists()) {
            WebChannelConfig::where('Channel', $Channel)->update(['Remarks' => $remarks]);
        }else{
            $config=WebChannelConfig::getByChannel(50)->toArray();
            $config['Remarks']=$remarks;
            $config['Channel']=$Channel;
            $config['PackageName']=$PackageName;
            unset($config['ID']);
            WebChannelConfig::insert($config);
        }
        $dcatChannel=DB::connection('mysql')->table('dcat-admin.channel')->where('channel',$Channel);
        if($dcatChannel->exists()){
            $dcatChannel->update(['channel_name'=>$remarks]);
        }else{
            DB::connection('mysql')->table('dcat-admin.channel')->insert(['channel'=>$Channel,'channel_name'=>$remarks,'package_name'=>'','remark'=>'']);
        }

        $dcatChannel=DB::connection('mysql')->table('dcat-admin.channel_ownership')->where('channel',$Channel);
        if($dcatChannel->exists()){
            $dcatChannel->update(['name'=>$remarks]);
        }else{
            DB::connection('mysql')->table('dcat-admin.channel_ownership')->insert(['channel'=>$Channel,'name'=>$remarks]);
        }


        return apiReturnSuc();
    }

    // 分享url
    public function shareUrl(Request $request, $id, $field)
    {
        $ShareUrl = $request->ShareUrl ?: '';

        DB::connection('write')->table('QPPlatformDB.dbo.ChannelPackageName')
            ->where('ID', $id)
            ->update([$field => $ShareUrl]);

        return apiReturnSuc();
    }

    // 修改minScore
    public function minScore(Request $request, $id)
    {
        $MinScore = $request->MinScore ?: 0;

        DB::connection('write')->table('QPPlatformDB.dbo.ChannelPackageName')
            ->where('ID', $id)
            ->update(['MinScore' => $MinScore]);

        return apiReturnSuc();
    }

    // 修改ContrlScore
    public function contrlScore(Request $request, $id)
    {
        $ContrlScore = $request->ContrlScore ?: 0;

        DB::connection('write')->table('QPPlatformDB.dbo.ChannelPackageName')
            ->where('ID', $id)
            ->update(['ContrlScore' => $ContrlScore]);

        return apiReturnSuc();
    }

    // 修改Rate
    public function rateN(Request $request, $id)
    {
        $Rate = $request->Rate ?: 0;

        DB::connection('write')->table('QPPlatformDB.dbo.ChannelPackageName')
            ->where('ID', $id)
            ->update(['Rate' => $Rate]);

        return apiReturnSuc();
    }

    public function shareConfig(Request $request, $id)
    {
        $config = DB::table('QPPlatformDB.dbo.ChannelPackageName')->where('ID', $id)->first();
        if ($request->method() == 'GET') {
            return view('admin.channel.share_config', [
                'config' => $config,
            ]);
        }
        $validator = Validator::make($request->all(), [
            'UrlStatus' => 'required|in:0,1',
            'UrlSelect' => 'required|in:1,2',
            'ShareUrl' => 'nullable|url',
            'SpreadShareUrl' => 'nullable|url',
        ]);
        if ($validator->fails()) {
            return apiReturnFail($validator->errors()->first());
        }
        $data = $request->only(['UrlStatus', 'UrlSelect']);
        $data['ShareUrl'] = strval($request->input('ShareUrl'));
        $data['SpreadShareUrl'] = strval($request->input('SpreadShareUrl'));
        DB::table('QPPlatformDB.dbo.ChannelPackageName')->where('ID', $id)->update($data);
        return apiReturnSuc();
    }

    // 提现免审配置
    public function withdrawalConfigAll(Request $request)
    {

        $createConfig = function () {
            $config = new WithdrawalChannelPositionConfig();
            $config->channel = 100;
            return $config;
        };

        $config = WithdrawalChannelPositionConfig::query()->where('channel', 100)->first() ?: $createConfig();
        if ($request->method() == 'GET') {
            $agent = DB::table('agent.dbo.admin_configs')
                ->where('type', 'cash')
                ->where('status', 1)
                ->get();
            $this->markWithdrawalAgentFee($agent);
            return view('admin.channel.channel_withdrawal_configall', [
                'config' => $config,
                'agent' => $agent,
                'ratioConfig' => WithdrawalAgentRatioConfig::getGlobal(),
                'pixTypeOptions' => WithdrawalAgentRatioConfig::pixTypeOptions(),
            ]);
        }

        list($ratioValid, $ratioRules) = $this->withdrawalAgentRatioRules($request);
        if (!$ratioValid) {
            return apiReturnFail($ratioRules);
        }
        WithdrawalAgentRatioConfig::saveGlobal($ratioRules);

        return apiReturnSuc();
    }
    // 提现免审配置
    public function withdrawalSwitch(Request $request)
    {

        $key="WithDrawSwitch";

        if ($request->method() == 'GET') {
            $info=SystemStatusInfo::CacheValue($key);
            return view('admin.channel.channel_withdrawal_switch', [
                'State' => $info->StatusValue,
            ]);
        }

        $State = (int)$request->State;
        SystemStatusInfo::CacheValue($key,$State);
        return apiReturnSuc();
    }
    // 提现免审配置
    public function withdrawalConfig($channel, Request $request)
    {

        $createConfig = function () use($channel) {
            $config = new WithdrawalChannelPositionConfig();
            $config->channel = $channel;
            return $config;
        };

        $config = WithdrawalChannelPositionConfig::query()->where('channel', $channel)->first() ?: $createConfig();
        if ($request->method() == 'GET') {
            $agent = DB::table('agent.dbo.admin_configs')
                ->where('type', 'cash')
                ->where('status', 1)
                ->get();
            $this->markWithdrawalAgentFee($agent);
            return view('admin.channel.channel_withdrawal_config', [
                'config' => $config,
                'agent' => $agent,
                'ratioConfig' => WithdrawalAgentRatioConfig::getGlobal(),
                'pixTypeOptions' => WithdrawalAgentRatioConfig::pixTypeOptions(),
            ]);
        }

        list($ratioValid, $ratioRules) = $this->withdrawalAgentRatioRules($request);
        if (!$ratioValid) {
            return apiReturnFail($ratioRules);
        }
        WithdrawalAgentRatioConfig::saveGlobal($ratioRules);

        return apiReturnSuc();
    }

    private function withdrawalAgentRatioRules(Request $request)
    {
        $input = $request->input('agent_ratio', []);
        $rules = [];
        $pixTypeNames = WithdrawalAgentRatioConfig::pixTypeOptions();

        foreach ($pixTypeNames as $pixType => $pixTypeName) {
            $total = 0;

            foreach (($input[$pixType] ?? []) as $agent => $ratio) {
                if ($ratio === null || $ratio === '') {
                    $ratio = 0;
                }

                if (!is_numeric($ratio)) {
                    return [false, $pixTypeName . '比例必须是数字'];
                }

                $ratio = (int)$ratio;
                if ($ratio < 0 || $ratio > 100) {
                    return [false, $pixTypeName . '比例必须在0-100之间'];
                }

                $total += $ratio;
                if ($ratio > 0) {
                    $rules[$pixType][(int)$agent] = $ratio;
                }
            }

            if ($total != 100) {
                return [false, $pixTypeName . '比例总和必须为100'];
            }
        }

        return [true, $rules];
    }

    private function markWithdrawalAgentFee($agent)
    {
        foreach ($agent as $item) {
            $item->withdraw_fee_texts = $this->withdrawalAgentFeeTexts($item->config_value);
        }
    }

    private function withdrawalAgentFeeTexts($agent)
    {
        $configKey = $this->withdrawalPayConfigKey($agent);
        $empty = [
            1 => '-',
            2 => '-',
            WithdrawalAgentRatioConfig::PIX_TYPE_CASH_SMALL => '-',
        ];

        if (!$configKey) {
            return $empty;
        }

        $config = (new PayConfig())->getConfig($configKey);
        $payRates = $config['pay_rate'] ?? null;
        if (empty($payRates) || !is_array($payRates)) {
            return $empty;
        }

        if (is_array(reset($payRates))) {
            return [
                1 => isset($payRates[1]) ? $this->formatWithdrawalPayRate($payRates[1]) : '-',
                2 => isset($payRates[2]) ? $this->formatWithdrawalPayRate($payRates[2]) : '-',
                WithdrawalAgentRatioConfig::PIX_TYPE_CASH_SMALL => isset($payRates[1]) ? $this->formatWithdrawalPayRate($payRates[1]) : '-',
            ];
        }

        $feeText = $this->formatWithdrawalPayRate($payRates);
        return [
            1 => $feeText,
            2 => $feeText,
            WithdrawalAgentRatioConfig::PIX_TYPE_CASH_SMALL => $feeText,
        ];
    }

    private function withdrawalPayConfigKey($agent)
    {
        $map = [
            99 => 'WiwiPayOut',
            100 => 'WDPayOut',
            103 => 'PagYeepPayOut',
            105 => 'AiNewPayOut',
            106 => 'SafePayOut',
            107 => 'BotImPayOut',
            109 => 'PayPlusOut',
        ];

        return $map[(int)$agent] ?? null;
    }

    private function formatWithdrawalPayRate($rate)
    {
        if (!is_array($rate)) {
            return '-';
        }

        $percent = $rate[0] ?? 0;
        $fixed = $rate[1] ?? 0;

        return $percent . '%+$' . $fixed;
    }

    public function quickCreateChannel(Request $request)
    {
        if ($request->isMethod('post')) {
            $packageName = $request->input('packageName');
            $channelName = $request->input('channelName');
            $adminSign = $request->input('adminSign', 'dk');

            // 检查包名是否已存在
            $exists = DB::connection('write')->table('QPPlatformDB.dbo.ChannelPackageName')
                ->where('PackageName', $packageName)
                ->exists();

            if ($exists) {
                return apiReturnFail('包名已存在');
            }

            try {
                // 调用自动创建渠道方法
                $autoApkController = new \App\Http\Controllers\Api\AutoApkController();
                $packageConfig = $autoApkController->autoCreateChannel($packageName, $channelName, $adminSign);
                $autoApkController->modifyRights($packageConfig, $adminSign);

                return apiReturnSuc(['message' => '渠道创建成功', 'channel' => $packageConfig['Channel']]);
            } catch (\Exception $e) {
                Util::WriteLog('quick_create_channel', $e->getMessage());
                return apiReturnFail('创建失败：' . $e->getMessage());
            }
        } else {
            // 获取最后一个包名和渠道名，用于生成默认值
            $lastPackage = DB::connection('read')->table('QPPlatformDB.dbo.ChannelPackageName')
                ->orderByDesc('ID')
                ->first();

            $defaultPackageName = '';
            $defaultChannelName = '';

            if ($lastPackage) {
                // 提取包名中的数字并+1
                if (preg_match('/^(.+?)(\d+)$/', $lastPackage->PackageName, $matches)) {
                    $defaultPackageName = $matches[1] . ($matches[2] + 1);
                } else {
                    $defaultPackageName = $lastPackage->PackageName . '1';
                }

                // 提取渠道名中的数字并+1
                $aliasName = $lastPackage->AliasName ?? $lastPackage->Remarks ?? '';
                // 去掉前缀（USA_、NEW_等），只保留下划线后面的部分
                if (strpos($aliasName, '_') !== false) {
                    $aliasName = substr($aliasName, strrpos($aliasName, '_') + 1);
                }
                if (preg_match('/^(.+?)(\d+)$/', $aliasName, $matches)) {
                    $defaultChannelName = $matches[1] . ($matches[2] + 1);
                } else {
                    $defaultChannelName = $aliasName . '1';
                }
            }

            return view('admin.channel.quick_create_channel', [
                'defaultPackageName' => $defaultPackageName,
                'defaultChannelName' => $defaultChannelName,
            ]);
        }
    }
}
