<?php


namespace App\Http\Controllers\Game;


use App\Facade\TableName;
use App\Game\Services\OuroGameService;
use App\Http\Controllers\Controller;
use App\Http\helper\NumConfig;
use App\Models\Order;
use App\Services\OrderServices;
use App\Utility\SetNXLock;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class PayRechargeController extends Controller
{
    // 充值记录
    public function orderList(Request $request)
    {

        $user_id = (int)$request->globalUser->UserID;//$request->get('user_id', 1);

        $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','Tente novamente mais tarde']);
        }
        $where[] = ['user_id', $user_id];
        $where[] = ['pay_status', 1];


        $cacheTime = 60 * rand(1, 2);
//        $list = cache()->remember($user_id . '_order_list', $cacheTime, function () use ($where, $pageSize) {
//
//            return Order::where($where)
//                ->orderBy('finished_at', 'desc')
//                ->selectRaw('amount,payment_code,order_sn as payment_sn,finished_at,created_at,pay_status')
//                ->paginate(15,['*'],'page',1);
//        });


        $list = Order::query()->where($where)
            ->orderBy('finished_at', 'desc')
            ->selectRaw('amount,payment_code,order_sn as payment_sn,finished_at,created_at,pay_status')
            ->paginate($pageSize);
//            ->paginate(15,['*'],'page',1);

        foreach ($list as &$val) {
            $val->amount = number_format($val->amount, 2, '.', '');
        }
        SetNXLock::release($redisKey);


        return apiReturnSuc($list);
    }

    // 首充
    public function firstPay(Request $request)
    {
        $user = $request->user();
        $user_recharge = DB::table(TableName::QPAccountsDB() . 'YN_VIPAccount')
            ->where('UserID', $user->UserID)
            ->value('Recharge') ?: 0;
        if($user_recharge)return apiReturnSuc();

        $firstPayGift = DB::table('agent.dbo.recharge_gift')
            ->where('gift_id', 301)->first();
        if(!$firstPayGift) return apiReturnFail();

        $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')
            ->select('id','money','favorable_price','give')
            ->orderBy('money', 'asc')->where('status', 1)->get();



        $gear=\GuzzleHttp\json_encode($names);
        foreach ($list as &$val) {
            $val->favorable_price = $val->favorable_price + $val->give;
            $val->gear = $gear;
            $val->recommend = 0;
            if($val->money == $firstPayGift->recommend){
                $val->recommend = 1;
            }
        }





        return apiReturnSuc(compact('list', 'firstPayGift'));
    }

    // 首充礼包（带倒计时逻辑）
    public function firstPayGift(Request $request)
    {
        $user = $request->user();
        
        // 检查用户是否已充值
        $user_recharge = DB::table(TableName::QPAccountsDB() . 'YN_VIPAccount')
            ->where('UserID', $user->UserID)
            ->value('Recharge') ?: 0;
        if ($user_recharge) {
            return apiReturnSuc([]); // 已充值用户返回空
        }

        // 获取首充礼包配置
        $firstPayGift = DB::table('agent.dbo.recharge_gift')
            ->where('gift_id', 301)
            ->first();
        
        if (!$firstPayGift) {
            return apiReturnFail('礼包配置不存在');
        }

        $redisKey = "first_pay_gift_timer_{$user->UserID}";
        $currentTime = time();

        // 检查Redis中的倒计时状态
        $timerData = Redis::get($redisKey);
        
        if ($timerData) {
            $timerData = json_decode($timerData, true);
            $firstRequestTime = $timerData['first_request_time'];
            $phase = $timerData['phase']; // 'first' 或 'daily'
            $lastExpireTime = $timerData['last_expire_time'] ?? 0;

            // 第一阶段：valid_h 倒计时
            if ($phase === 'first') {
                $expireTime = $firstRequestTime + ($firstPayGift->valid_h * 3600);
                
                // 检查是否在过期当天
                if ($currentTime >= $expireTime) {
                    $expireDate = date('Y-m-d', $expireTime);
                    $currentDate = date('Y-m-d', $currentTime);
                    
                    if ($expireDate === $currentDate) {
                        // 过期当天返回空
                        return apiReturnSuc([]);
                    } else {
                        // 进入第二阶段（每日循环）
                        $nextDayStart = strtotime($expireDate . ' +1 day 00:00:00');
                        $newExpireTime = $nextDayStart + ($firstPayGift->valid_h_2 * 3600);
                        
                        // 更新Redis状态为每日循环
                        $newTimerData = [
                            'first_request_time' => $firstRequestTime,
                            'phase' => 'daily',
                            'current_cycle_start' => $nextDayStart,
                            'last_expire_time' => $newExpireTime
                        ];
                        Redis::set($redisKey, json_encode($newTimerData));
                        
                        // 检查是否在新的过期时间之前
                        if ($currentTime < $newExpireTime) {
                            return $this->getFirstPayGiftData($firstPayGift, $newExpireTime - $currentTime);
                        } else {
                            // 检查是否在过期当天
                            $newExpireDate = date('Y-m-d', $newExpireTime);
                            if ($newExpireDate === $currentDate) {
                                return apiReturnSuc([]);
                            }
                        }
                    }
                } else {
                    // 第一阶段倒计时未结束，返回礼包数据
                    return $this->getFirstPayGiftData($firstPayGift, $expireTime - $currentTime);
                }
            }
            
            // 第二阶段：每日循环 valid_h_2
            if ($phase === 'daily') {
                $currentCycleStart = $timerData['current_cycle_start'];
                $expireTime = $currentCycleStart + ($firstPayGift->valid_h_2 * 3600);
                
                // 检查是否已过期
                if ($currentTime >= $expireTime) {
                    $expireDate = date('Y-m-d', $expireTime);
                    $currentDate = date('Y-m-d', $currentTime);
                    
                    if ($expireDate === $currentDate) {
                        // 过期当天返回空
                        return apiReturnSuc([]);
                    } else {
                        // 计算新的一天的倒计时
                        $todayStart = strtotime($currentDate . ' 00:00:00');
                        $newExpireTime = $todayStart + ($firstPayGift->valid_h_2 * 3600);
                        
                        // 更新Redis
                        $newTimerData = [
                            'first_request_time' => $firstRequestTime,
                            'phase' => 'daily',
                            'current_cycle_start' => $todayStart,
                            'last_expire_time' => $newExpireTime
                        ];
                        Redis::set($redisKey, json_encode($newTimerData));
                        
                        // 检查今天是否还在有效期内
                        if ($currentTime < $newExpireTime) {
                            return $this->getFirstPayGiftData($firstPayGift, $newExpireTime - $currentTime);
                        } else {
                            // 今天也已过期，返回空
                            $newExpireDate = date('Y-m-d', $newExpireTime);
                            if ($newExpireDate === $currentDate) {
                                return apiReturnSuc([]);
                            }
                        }
                    }
                } else {
                    // 当前周期未过期，返回礼包数据
                    return $this->getFirstPayGiftData($firstPayGift, $expireTime - $currentTime);
                }
            }
        }
        
        // 首次请求，初始化倒计时
        $expireTime = $currentTime + ($firstPayGift->valid_h * 3600);
        $timerData = [
            'first_request_time' => $currentTime,
            'phase' => 'first',
            'last_expire_time' => $expireTime
        ];
        Redis::set($redisKey, json_encode($timerData));
        
        return $this->getFirstPayGiftData($firstPayGift, $firstPayGift->valid_h * 3600);
    }

    /**
     * 获取首充礼包数据（包含充值档位列表）
     * @param $firstPayGift 礼包配置
     * @param $timeLeft 剩余秒数（已经是用户实际剩余时间）
     */
    private function getFirstPayGiftData($firstPayGift, $timeLeft)
    {
        // 获取支付方式
//        $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')
            ->select('money', 'favorable_price', 'give','gear')
            ->orderBy('money', 'asc')
            ->where('status', 1)
            ->get();

//        $gear = \GuzzleHttp\json_encode($names);
        foreach ($list as &$val) {
            $val->favorable_price = $val->favorable_price + $val->give;
//            $val->gear = $gear;
            $val->recommend = 0;
            if ($val->money == $firstPayGift->recommend) {
                $val->recommend = 1;
            }
        }

        return apiReturnSuc([
            'list' => $list,
            'gift_info' => [
                'gift_id' => $firstPayGift->gift_id,
                'gift_name' => $firstPayGift->gift_name,
                'total_bonus' => $firstPayGift->total_bonus,
                'bonus_instantly' => $firstPayGift->bonus_instantly,
                'day_rewards' => $firstPayGift->day_rewards?json_decode($firstPayGift->day_rewards):'',
                'betting_bonus' => $firstPayGift->betting_bonus?json_decode($firstPayGift->betting_bonus):'',
                'betting_task' => $firstPayGift->betting_task?json_decode($firstPayGift->betting_task):'',
            ],
            'time_left' => $timeLeft, // 剩余秒数
            'expire_at' => time() + $timeLeft // 过期时间戳
        ]);
    }

    public function firstPayMulti(Request $request)
    {
        $user = LoginController::checkLogin($request);
        if($user){
            if(env('CONFIG_24680_NFTD_99',0)==0)if($user->Channel==99)return apiReturnFail();
            $fpkey='Firstpay_'.$user->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', $user->UserID)
                ->value('Recharge') ?: 0;
            if($user_recharge)return apiReturnFail();
        }
        $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){
                $item->id=28;
            })->toArray();
        $default=count($items)-1;

        return apiReturnSuc(compact('items','default'));
    }
    public function getSecondGive(Request $request)
    {
        $user = $request->user();
        $fpkey='Firstpay_'.$user->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($user->UserID,$data['second_give']*NumConfig::NUM_VALUE,$cjReason);

                    //更新二次领钱记录
                    DB::table(TableName::agent() . 'guide_payment')->where('UserID',$user->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','Tente novamente mais tarde']);

    }


}
