<?php

namespace App\Jobs;

use App\Facade\TableName;
use App\Game\Services\OuroGameService;
use App\Http\helper\NumConfig;
use App\Models\AccountsInfo;
use App\Models\PrivateMail;
use App\Services\Custom;
use App\Services\FirstPayStatService;
use App\Services\OrderServices;
use App\Services\VipService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class Order implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $data = [];
    public $tries = 5;      // 增加最大尝试次数
    public $timeout = 300;  // 设置最大执行时间为 300 秒

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($data = [])
    {
        $this->data = $data;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        if (empty($this->data)) return;

        // 接收数据
        [$user_id, $payAmt,$Score,$favorable_price,$GiftsID,$order_sn] = $this->data;

        try {
            //Log::info('接收数据'.\GuzzleHttp\json_encode($this->data));
            // 获取支付金额
            $service = new OrderServices();
//        [$give, $favorable_price, $Recharge, $czReason, $cjReason] = $service->getPayInfo($GiftsID, $user_id, $payAmt);

            // 发送邮件给玩家
            //PrivateMail::paySendMail($user_id, $order_sn, $favorable_price,$payAmt);

            // 增加充值记录
            //[$Score] = $service->addRecord($user_id,$payAmt,$favorable_price,$order_sn,$GiftsID,$Recharge,$czReason,$give,$cjReason);

            // 执行支付后存储过程
            $service->storedProcedure($user_id, $payAmt, $favorable_price, $Score, $GiftsID);

            // 发送通知邮件
            PrivateMail::paySendMail($user_id, $order_sn, $favorable_price, $payAmt);

            // 首次付费统计
            $service = new FirstPayStatService();
            $isfirst = $service->stat($order_sn);

            // VIP签到救济金天数重置
            $minRechargeValue = VipService::getKeepLevelMinRecharge();
            if ($minRechargeValue < $payAmt * NumConfig::NUM_VALUE) {
                DB::table('QPAccountsDB.dbo.UserVipState')->where('UserID', $user_id)
                    ->update(['ActiveDays' => 0, 'UpdateDate' => date('Y-m-d H:i:s')]);

            }

            Log::info("订单处理成功: {$order_sn}, 用户: {$user_id}, 金额: {$payAmt}, 到账: {$Score}");

        }catch (\Exception $e) {
            Log::error('订单处理失败：' . $e->getMessage());
        }

        try {

            $user = DB::connection('write')->table(TableName::QPAccountsDB() . 'AccountsInfo')
                ->where('UserID', $user_id)->select("Channel","RegisterDate")->first();

//            if($user->Channel>121&&$user->Channel<200) {

            //apk/checkpay用来统计
//                if($order->Channel>121&&$order->Channel<180) {
//                    //记录redisevent，24小时
//                    Redis::set("user_pay_first_".$order->user_id, json_encode(['order_sn' => $order_sn]));
//                }
            $item=[
                'regtime'=>strtotime($user->RegisterDate),
                'isd0'=>date("Ymd",strtotime($user->RegisterDate))==date("Ymd"),
//                'isd0' =>  (date('Ymd',strtotime($user->RegisterDate))==date('Ymd'))?1:0,
                'first' => $isfirst?1:0,
                'golds' => $payAmt,
                'udid' => md5($user_id),
                'order_sn' => $order_sn
            ];


            //通知24680
            OuroGameService::notifyWebHall($user_id,"","pay_finish",["Golds"=>$Score,"PayNum"=>$favorable_price*100,"event"=>"pay","params"=>$item]);

//            OuroGameService::notifyWebHall($user_id,"",'call_client',["type"=>"track","event"=>"pay","params"=>$item]);

            $data = [];
            if (Redis::exists("user_pay_order_$user_id")) {
                $data = json_decode(Redis::get("user_pay_order_$user_id"), true);
            }
            array_push($data, $item);
            AfEvent::dispatch([
                'UserID' => $user_id,
                'params' => $item,
            ]);

            Log::info('订单记录成功user_pay_order_：' . json_encode($data));
            //记录redisevent，24小时
            Redis::set("user_pay_order_$user_id", json_encode($data));
            Redis::expire("user_pay_order_$user_id", 86400);
//            }

            //新的邀请系统生效了
//            $callback = DB::table(TableName::agent() . 'UserCallBack')->where('UserID', $user_id)->first();
//            if($callback){
//                if($callback->call_state != 2){
//                    $update = [
//                        'call_state' => 2,
//                        //'CallbackDate' => date('Y-m-d H:i:s')
//                    ];
//                    DB::table(TableName::agent() . 'UserCallBack')->where('UserID', $user_id)->update($update);
//                    Custom::updateAdminBonus($callback->admin_id,30,2);
//                }
//
//
//            }


        }catch (\Exception $e){

        }
    }
}
