<?php


namespace App\Http\Controllers\Api;

use App\dao\Pay\AccountPayInfo;
use App\Facade\TableName;
use App\Http\helper\NumConfig;
use App\Http\logic\api\CashPayLogic;
use App\Http\logic\api\RechargeLogic;
use App\Models\AccountsInfo;
use App\Models\Order;
use App\Models\Platform\MonthCard;
use App\Models\PrivateMail;
use App\Models\RecordUserDataStatistics;
use App\Services\ApkService;
use App\Util;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use function GuzzleHttp\Psr7\rewind_body;

class RechargeController
{
    protected $JumpOut = [2, 4, 9, 13, 12, 14];
    protected $Sdk = [];

    // 返回支付档位
    public function gear()
    {
        $names = DB::table('agent.dbo.admin_configs')
            ->where([
                'type' => 'pay_method',
                'status' => 1,
            ])
            ->selectRaw('id, name, status, new_pay_type as type')
            ->orderByDesc('sort')->get()->toArray();

        $list = DB::table('agent.dbo.recharge_gear')
            ->where('first_pay', 0)
            ->orderBy('money', 'asc')->where('status', 1)->get();
        foreach ($list as $val) {
            $val->favorable_price = $val->favorable_price + $val->give;
            $gear = $names;
            $val->gear = \GuzzleHttp\json_encode($gear);
        }

        return apiReturnSuc($list);
    }

    // 返回支付档位
    public function gearAct(Request $request)
    {
        $UserID=$request->UserID??"";
        if(empty($UserID)){
            return apiReturnFail(__('messages.api.pay.payment_error'));
        }

        $RechargeTimes=DB::table(TableName::QPRecordDB() . 'RecordUserTotalStatistics')->where('UserID', $UserID)->value('RechargeTimes')??0;

        if($RechargeTimes>=4) {
            $Status = 1;
        }else{
            $Status=$RechargeTimes+3;
        }

        $names = DB::table('agent.dbo.admin_configs')
            ->where([
                'type' => 'pay_method',
                'status' => 1,
            ])
            ->selectRaw('id, name, status, new_pay_type as type')
            ->orderByDesc('sort')->get()->toArray();

        $list = DB::table('agent.dbo.recharge_gear')
            ->where('first_pay', 0)
            ->orderBy('money', 'asc')->where('status', $Status)->get();
        foreach ($list as $val) {
            $val->favorable_price = $val->favorable_price + $val->give;
            $gear = $names;
            $val->gear = \GuzzleHttp\json_encode($gear);
        }

        return apiReturnSuc($list);
    }


    // 根据支付档位获取渠道
    public function getPayChannel(Request $request)
    {
        $id = $request->id ?: '';
        $ChannelNumber = $request->ChannelNumber ?: '';
        if (empty($id)) {
            return apiReturnFail(__('messages.api.pay.payment_error'));
        }


        $key="get_channel_{$id}_{$ChannelNumber}";

//        if(Redis::exists($key)) {
//            $result=json_decode(Redis::get($key));
//        }else {
            $first = DB::table('agent.dbo.recharge_gear')
                ->where('status','>=', 1)
                ->where('id', $id)
                ->first();

            if (empty($first)) {
                return apiReturnFail(__('messages.api.pay.payment_error'));
            }

            $UserID=$request->UserID??"";
        $RechargeTimes=DB::table(TableName::QPRecordDB() . 'RecordUserTotalStatistics')->where('UserID', $UserID)->value('RechargeTimes')??0;

        if($RechargeTimes>=4) {
            $Status = 1;
        }else{
            $Status=$RechargeTimes+3;
        }

        //充值对不上
        if($first->status!=$Status){
//            return apiReturnFail('reloadList','reloadList');
        }

        $first->favorable_price = $first->favorable_price + $first->give;


            $names = DB::table('agent.dbo.admin_configs')
                ->where('type', 'pay_method')
                ->where('status', '1')
                ->select('id', 'name', 'new_pay_type')
                ->orderByDesc('sort')->get()
                ->map(function ($value) {
                    return (array)$value;
                })->toArray();

            // 渠道
            if ($ChannelNumber != '') {
                $switch = Redis::get("recharge_config_switch_{$ChannelNumber}");
                if ($switch) {
                    $list = DB::connection('write')->table('QPPlatformDB.dbo.ChannelOpenRecharge as go')
                        ->join('agent.dbo.admin_configs as cf', 'go.ConfigID', '=', 'cf.id')
                        ->where('go.Channel', $ChannelNumber)
                        ->where('go.Status', 1)
                        ->where('cf.type', 'pay_method')
                        ->orderByDesc('go.Sort')
                        ->select('go.Sort', 'ConfigID')
                        ->pluck('Sort', 'ConfigID')->toArray();
                }
            }

            if (!isset($list) || count($list) < 1) {  // 默认配置
                $list = DB::connection('write')->table('agent.dbo.admin_configs')
                    ->where('type', 'pay_method')
                    ->where('status', 1)
                    ->select('sort as Sort', 'id as ConfigID')
                    ->pluck('Sort', 'ConfigID')->toArray();
            }

            $data = [];

            foreach ($names as $k => $va) {
                if (isset($list[$va['id']])) {
                    $type = $va['new_pay_type'] == 1 ? 3 : 2;

                    if ($va['new_pay_type'] == 4) {
                        $type = 0;
                    }
                    // type = 1 sdk跳转 type=2 外跳链接  type=0  默认 type=3 复制信息到APP支付
                    $data[] = ['id' => $va['id'],
                        'name' => $va['name'], 'status' => 1, 'type' => $type, 'sort' => $list[$va['id']]];
                }
            }

//        $first->cpf_first=0;
//        if($ChannelNumber==103)$first->cpf_first=1;

            $gear = array_values($data);
            $gear = collect($gear)->sortByDesc('sort')->toArray();
            $first->kefu_switch = 1;
            $gear = array_values($gear);
            $first->gear = \GuzzleHttp\json_encode($gear);
            $result = apiReturnSuc($first);
//            Redis::set($key,json_encode($result));
//            Redis::expire($key,60);
//        }
//        $dir = $path = app()->basePath() . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR . 'cache';
//        if (!file_exists($dir)) {
//            mkdir($dir, 0777);
//        }
//        $path = $dir . DIRECTORY_SEPARATOR . "get_channel_{$id}_{$ChannelNumber}.json";
//        file_put_contents($path, json_encode($result));
        return $result;
    }

    // 返回支付渠道
    public function payChannel()
    {
        $list = DB::table('agent.dbo.admin_configs')->where('type', 'pay_method')
            ->where('status', 1)
            ->select('id', 'name', 'status')
            ->orderByDesc('sort')->get();

        foreach ($list as &$value) {
            if (in_array($value->id, $this->Sdk)) {
                $value->type = 0;
            } elseif (in_array($value->id, $this->JumpOut)) {
                $value->type = 2;
            } else {
                $value->type = 0;
            }
        }
        unset($value);
        return apiReturnSuc("$list");
    }

    // 首充可选择渠道
    public function firstPayConfig(Request $request)
    {
        // 推荐充值档位
        $recomendar_recharge = DB::table(TableName::QPAccountsDB() . 'SystemStatusInfo')
            ->where('StatusName', 'RecomendarRecharge')
            ->value('StatusValue');
        $first_pay = DB::table('agent.dbo.recharge_gear')->where('status', 1)
            ->where('first_pay', 1)->first();
        if (!$first_pay) {
            return apiReturnSuc(compact('first_pay', 'recomendar_recharge'));
        }
        $names = DB::table('agent.dbo.admin_configs')
            ->where('type', 'pay_method')
            ->where('status', 1)
            ->select('id', 'name', 'new_pay_type')->orderByDesc('sort')->get()->toArray();


        $first_pay->favorable_price = $first_pay->favorable_price + $first_pay->give;

        $data = [];

        foreach ($names as $k => $va) {
            $type = $va->new_pay_type == 1 ? 3 : 2;
            if($va->new_pay_type == 4){
                $type = 0;
            }
            // type = 1 sdk跳转 type=2 外跳链接  type=0  默认 type=3 复制信息到APP支付
            $data[] = ['id' => $va->id, 'name' => $va->name, 'status' => 1, 'type' => $type];
        }
        $gear = array_values($data);
        $first_pay->gear = \GuzzleHttp\json_encode($gear);

        $ChannelNumber = $request->ChannelNumber ?: '';
//        $first_pay->cpf_first=0;
//        if($ChannelNumber==103)$first_pay->cpf_first=1;

        return apiReturnSuc(compact('first_pay', 'recomendar_recharge'));
    }

    // 引导付费
    public function guidePayment(Request $request)
    {
        $UserID = $request->input('UserID');

        // 引导付费标识
//        $guide_payment_exists = DB::table(TableName::agent() . 'guide_payment')->where('UserID', $UserID)->first();
        $flag = false;

        // 查看用户有没有充值过【只要充值过，引导付费就不能充值】
        $user_recharge = DB::table(TableName::QPAccountsDB() . 'YN_VIPAccount')
            ->where('UserID', $UserID)
            ->value('Recharge') ?: 0;

        if ($user_recharge > 0) {
            $flag = true;
        }

        // 引导付费礼包列表
        $guidePayment = (new RechargeLogic())->guidePayment($this->JumpOut);
        // 日期 -- 倒计时【小时】
        $countdown = 24;
        return apiReturnSuc(['is_pay' => true, 'countdown' => $countdown, 'guidePayment' => $guidePayment]);
    }
    public static function getVipConfig()
    {
        if(Redis::exists('vipConfigNew')) {
            $res=json_decode(Redis::get('vipConfigNew'),true);
        }else{
            $res = DB::table('QPAccountsDB.dbo.ProtectLevel')
                ->orderBy('Recharge')->get();
            Redis::setex('vipConfigNew',600,json_encode($res));
        }
        return $res;
    }
    // 充值Vip等级
    public function vipConfigNew(Request $request)
    {

        $config=self::getVipConfig();
    }

    // 充值Vip等级
    public function vipConfig(Request $request)
    {
        $res=self::getVipConfig();
        $list = [];
        foreach ($res as $v) {
            $v=(object)$v;
            $list[] = [
                'id' => $v->ID,
                'money' => $v->Recharge,
                'num' => $v->ID - 1,
                'relief_money' => $v->GrantNum/100,
                'vip' => $v->ID - 1,
            ];
        }
        // 充值礼包
        $monthCards = MonthCard::query()
            ->select('CardID', 'CardName', 'Price', 'FirstReward', 'DayReward', 'gear', 'CardState')
            ->where(['CardType' => 1,])
            ->get();
        // 充值渠道过滤
        $UserID = $request->input('UserID');
        $accountInfo = AccountsInfo::query()->where('UserID', $UserID)->first();
        $channel = $accountInfo->Channel ?? 0;
        $switch = Redis::get("recharge_config_switch_{$channel}");
        if ($channel && $switch) {
            $channels = DB::connection('write')->table('QPPlatformDB.dbo.ChannelOpenRecharge as go')
                ->join('agent.dbo.admin_configs as cf', 'go.ConfigID', '=', 'cf.id')
                ->where('go.Channel', $channel)
                ->where('go.Status', 1)
                ->where('cf.type', 'pay_method')
                ->orderByDesc('go.Sort')
                ->select(
                    DB::raw('cf.id as id'),
                    'name',
                    'config_value',
                    'new_pay_type',
                    DB::raw('go.Sort as sort')
                )
                ->get()
                ->toArray();
        }

        if (empty($channels)) {
            $channels = DB::table('agent.dbo.admin_configs')
                ->select('id', 'name', 'config_value', 'new_pay_type', 'sort')
                ->where([
                    'type' => 'pay_method',
                    'status' => 1
                ])
                ->orderByDesc('sort')
                ->get()->toArray();
        }

        foreach ($monthCards as $k => $v) {
            $monthCards[$k]['CardID'] = $monthCards[$k]['CardID'] + 100;
            $monthCards[$k]['FirstReward'] = $v['FirstReward']/100;
            $monthCards[$k]['DayReward'] = $v['DayReward']/100;
            $cardChannels = [];
            foreach ($channels as $channel) {
                $channel->type = $channel->new_pay_type == 4?0: ($channel->new_pay_type == 1 ? 3 : 2);
                $cardChannels[] = [
                    'id' => $channel->id,
                    'name' => $channel->name,
                    'pic' => $channel->config_value,
                    'status' => 1,
                    'type' => $channel->new_pay_type == 4?0: ($channel->new_pay_type == 1 ? 3 : 2),
                    'new_pay_type' => $channel->new_pay_type,
                    'sort' => $channel->sort
                ];
            }
            usort($cardChannels, function ($a, $b) {
                return $a['sort'] > $b['sort'] ? -1 : 1;
            });
            $monthCards[$k]['gear'] = json_encode($cardChannels);
        }
        return apiReturnSuc(compact('list', 'monthCards'));
    }

    // 用户总充值
    public function userTotalRecharge(Request $request)
    {
        $UserID = $request->input('UserID');
//        Util::WriteLog('login_header',$request->header());

        try{

            $user_total_recharge = DB::table(TableName::QPAccountsDB() . 'YN_VIPAccount')
                ->where('UserID', $UserID)
                ->value('Recharge') ?: 0;

            $userInfo = DB::table(TableName::QPAccountsDB() . 'AccountsInfo')
                ->where('UserID', $UserID)
                ->first();
            if(isset($userInfo)) {


                //发VIP奖励

                $oldvip=$userInfo->CustomID;

                $vipbonus=[];

                $newvip=0;
                $vipconfig=self::getVipConfig();
                foreach ($vipconfig as $v) {
                    $v=(array)$v;
                    if($user_total_recharge>$v['MinRecharge']&&$user_total_recharge<=$v['Recharge']) {
                        $newvip=$v['VIP'];
                        $vipbonus[]=$v;
                        break;
                    }
                    if($user_total_recharge>$v['Recharge']&&$v['VIP']>$oldvip){
                        $vipbonus[]=$v;
                    }

                }
                Util::WriteLog('vip',[$oldvip,$newvip,$vipbonus]);

                if($newvip>$oldvip) {

                    DB::table(TableName::QPAccountsDB() . 'AccountsInfo')
                        ->where('UserID', $UserID)
                        ->update(['CustomID' => $newvip]);

                    if(count($vipbonus)){
                        foreach ($vipbonus as $vip){
                            $amount = $vip['LevelUpBonus']*NumConfig::NUM_VALUE;
                            $TitleString = __('messages.vip.level_up_bonus', ['vip' => $vip['VIP']]);
                            $TextString = __('messages.vip.level_up_bonus_body', ['vip' => $vip['VIP']]);
                            PrivateMail::sendMail(2, $UserID, $TitleString, $TextString, '30000,'.$amount, '', $amount, 3);
                        }
                    }
                }




            }
        }catch (\Exception $exception){
            Util::WriteLog('control_old_user',$exception);
        }




        // 引导付费标识
//        $guide_payment_exists = DB::table(TableName::agent() . 'guide_payment')->where('UserID', $UserID)->first();
        $flag = false;

        // 查看用户有没有充值过【只要充值过，引导付费就不能充值】

        if ($user_total_recharge > 0) {
            $flag = true;
        }

        // 引导付费礼包列表
//        $guidePayment = (new RechargeLogic())->guidePayment($this->JumpOut);
        // 日期 -- 倒计时【小时】
        $countdown = 24;
        return apiReturnSuc(['user_total_recharge'=>$user_total_recharge,'is_pay' => $flag, 'countdown' => $countdown, 'guidePayment' => []]);
//        $AccountWithDrawInfo = DB::table(TableName::QPAccountsDB() . 'AccountWithDrawInfo')
//            ->lock('WITH(NOLOCK)')
//            ->where('UserID', $UserID)
//            ->first();
//
//
//        if (!$AccountWithDrawInfo) {
//            $cpf = $this->_getNewCpf($UserID);
//            if($cpf){
//                $dao = new AccountPayInfo();
//                $data = [
//                    'PixType' => 1,
//                    'BankUserName' => $dao->randUserName(0),
//                    'PixNum' => $cpf,
//                    'UserID' => $UserID,
//                    'Achieves' => 0,
//                    'HistoryWithDraw' => 0
//                ];
//
//                try {
//                    DB::table(TableName::QPAccountsDB() . 'AccountWithDrawInfo')
//                        ->where('UserID', $UserID)
//                        ->insert($data);
//
//                    try {
//                        DB::table(TableName::QPRecordDB() . 'RecordBankCardBind')
//                            ->insert([
//                                'UserID' => $UserID,
//                                'BankCard' => $cpf,
//                                'BindDate' => now()
//                            ]);
//                        Util::WriteLog('update_pix',[
//                            'UserID' => $UserID,
//                            'BankCard' => $cpf,
//                            'BindDate' => now()
//                        ]);
//                    } catch (\Exception $e) {
//                        Log::error('insert RecordBankCardBind failed', ['data' => $data]);
//                    }
//
//                } catch (\Exception $e) {
//                    Log::error('insert AccountWithDrawInfo failed', ['data' => $data]);
//                }
//            }
//
//        } else {
//            if(!$AccountWithDrawInfo->BankUserName || !$AccountWithDrawInfo->PixNum){
//
//                $cpf = $this->_getNewCpf($UserID);
//
//                if($cpf){
//                    $dao = new AccountPayInfo();
//                    $data = [
//                        'PixType' => 1,
//                        'BankUserName' => $dao->randUserName(0),
//                        'PixNum' => $cpf,
//                        'UserID' => $UserID,
//                        'Achieves' => 0,
//                        'HistoryWithDraw' => 0
//                    ];
//
//                    DB::table(TableName::QPAccountsDB() . 'AccountWithDrawInfo')
//                        ->where('UserID', $UserID)
//                        ->update($data);
//                }
//
//
//            }
//        }

    }

    private function _getNewCpf($UserID){
        return 0;
        $where[] = ['payment_code', 'cashPay'];
        $where[] = ['pay_status', 1];
        $where[] = ['UserID', $UserID];

        $build_sql = DB::connection('write')->table('order')
            ->where($where)
            ->first();
        if($build_sql){
            $cashPay = new CashPayLogic();
            return $cashPay->search($build_sql->order_sn);
        }
        return 0;

    }
}
