<?php


namespace App\Http\Controllers\Api;


use App\Facade\TableName;
use App\Game\Services\OuroGameService;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Game\LoginController;
use App\Http\helper\NumConfig;
use App\Http\logic\api\PayRechargeLogic;
use App\Models\AccountsInfo;
use App\Models\Treasure\GameScoreInfo;
use App\Services\OrderServices;
use App\Services\PayMent;
use App\Utility\SetNXLock;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Yansongda\Pay\Pay;

class PayRechargeController extends Controller
{

    // 充值记录
    public function orderList(Request $request)
    {

        $user_id = $request->get('user_id', 1);
        if (!is_numeric($user_id)) {
            return apiReturnFail(['web.payment.invalid_params',__('messages.api.pay.invalid_params')]);
        }
        $page = $request->get('page', 1);
        $pageSize = $request->get('pageSize', 7);
        $redisKey = 'PayRecharge_orderList_'.$user_id;
        if (!SetNXLock::getExclusiveLock($redisKey)) {
            return apiReturnFail(['web.withdraw.try_again_later',__('messages.api.withdraw_info.try_again_later')]);
        }
        $list = (new PayRechargeLogic())->orderList($user_id, $pageSize);

        return apiReturnSuc($list);
    }

    // 首充
    public function firstPay()
    {
        $OrderServices = new OrderServices();
        // 充值金额
        $price = $OrderServices->FirstCharge;
        $give = $OrderServices->FirstChargeGive;

        // 首充
        $firstCharge = DB::connection('write')->table('QPAccountsDB.dbo.SystemStatusInfo')
            ->where('StatusName', 'FirstChargeGiftBag')
            ->first();
        $payConfigID = $firstCharge->StatusValue;

        $payConfigs = DB::table('agent.dbo.admin_configs')->where('id', $payConfigID)->select('id', 'name', 'new_pay_type')->first();

        $first_pay = [];
        if ($payConfigs) {
            if ($payConfigs->new_pay_type <= 1) {
                $first_pay = ['id' => $payConfigs->id, 'name' => $payConfigs->name, 'status' => 1, 'type' => 3, 'new_pay_type' => $payConfigs->new_pay_type];
            } else {
                $first_pay = ['id' => $payConfigs->id, 'name' => $payConfigs->name, 'status' => 1, 'type' => 0, 'new_pay_type' => $payConfigs->new_pay_type];
            }
        }
        return apiReturnSuc(compact('price', 'give','first_pay'));
    }


    public function timeBonus(Request $request)
    {

        $UserID=$request->UserID;
        if(empty($UserID)||!intval($UserID))return apiReturnFail();
        $user = AccountsInfo::find($UserID);
        if(!$user)return apiReturnFail();
        $user = $user->toArray();

//        if(env('VALID_COUNTRY')=='PK') {
//            $RechargeTimes = DB::table(TableName::QPRecordDB() . 'RecordUserTotalStatistics')->where('UserID', $UserID)->value('RechargeTimes') ?? 0;
//            if($RechargeTimes<4)return apiReturnFail();
//        }

        $data=['UserID'=>$user['UserID'],'Channel'=>$user['Channel'],'Score'=>GameScoreInfo::query()->select(['Score'])->where('UserID', $UserID)->first()->Score];
        LoginController::CheckTimeBonus($data);
        return apiReturnSuc($data);

    }
    public function firstPayMulti(Request $request)
    {
        $UserID=$request->UserID;
        if($UserID){

            $fpkey='Firstpay_'.$UserID;
            if(Redis::exists($fpkey)){
                $data=Redis::get($fpkey);
                $data=json_decode($data,true);
                $data['timeleft']=86400-(time()-$data['buytime']);
                return apiReturnSuc(['leftitem'=>$data]);
            }
            $user_recharge = DB::table(TableName::QPAccountsDB() . 'YN_VIPAccount')
                ->where('UserID', $UserID)
                ->value('Recharge') ?: 0;
            if($user_recharge)return apiReturnFail();
        }

        $fmkey='FirstMultiData1';
        $items=[];
        for($i=0;$i<5;$i++) {
            if (!Redis::exists($fmkey)) {
                $data = [];
                $names = DB::table('agent.dbo.admin_configs')
                    ->where('type', 'pay_method')
                    ->where('status', 1)
                    ->select('id', 'name', 'new_pay_type')->orderByDesc('sort')->get()->toArray();
                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);

                $items = DB::table('agent.dbo.recharge_gear')
                    ->where('status', 1)
//                ->where('second_give', '>', 0)
                    ->where('first_pay', '>=', 1)
                    ->select('gift_id', 'money', 'give', 'favorable_price', 'second_give')->get()->each(function ($item) use ($gear) {
                        $item->id = 28;
                        $item->gear = \GuzzleHttp\json_encode($gear);
                    })->toArray();
                Redis::setex($fmkey, 600, json_encode($items));
            } else {
                $items = json_decode(Redis::get($fmkey), true);
            }
            if(count($items))break;
        }

        $default=count($items)-1;

        return apiReturnSuc(compact('items','default'));
    }
    public function getSecondGive(Request $request)
    {
        $UserID=$request->UserID;
        $fpkey='Firstpay_'.$UserID;
        if(Redis::exists($fpkey)){
            $data=Redis::get($fpkey);
            $data=json_decode($data,true);
            $data['timeleft']=86400-(time()-$data['buytime']);
            if($data['timeleft']<=0) {
                Redis::del($fpkey);
                //加钱
                if($data['second_give']){
                    $czReason=$data['czReason'];
                    $cjReason=$data['cjReason'];
                    [$OrgScore,$NowScore]=OuroGameService::AddScore($UserID,$data['second_give']*NumConfig::NUM_VALUE,$cjReason);

                    //更新二次领钱记录
                    DB::table(TableName::agent() . 'guide_payment')->where('UserID',$UserID)->update([
                        'GetSecondTime' => now(),
                        'SecondScoreNum'=>$data['second_give']*NumConfig::NUM_VALUE
                    ]);
                    return apiReturnSuc(compact('OrgScore','NowScore'));
                }
                return apiReturnSuc();
            }


        }
        return apiReturnFail(['web.withdraw.try_again_later',__('messages.api.withdraw_info.try_again_later')]);

    }

}
