<?php


namespace App\Jobs;

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\Log;
use App\Models\SportGameOrder;
use App\Models\Wallet;
use App\Models\FundsRecord;
use Illuminate\Support\Facades\DB;

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

    /**
     * 任务尝试次数
     */
    public $tries = 3;

    /**
     * 任务超时时间（秒）
     */
    public $timeout = 30;
    
    public $gameplayId = 0;

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

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        Log::error('开始执行足球游戏订单开奖结算任务: ' . now());
        
        //先把未中奖的标记为未中奖
        SportGameOrder::where('gameplay_id', '<>', $this->gameplayId)->where('status', 0)->update(['status' => 1]);

        $list = SportGameOrder::where('gameplay_id', $this->gameplayId)->where('status', 0)->get();
        foreach ($list as $item) {
            try {
                DB::beginTransaction();
                $item->status = 2;
                $item->win_amount = bcmul($item->amount, $item->odds, 2);
                $item->profit_and_loss = $item->win_amount - $item->amount;
                $item->updated_at = now();
                $item->save();

                $walletInfo = Wallet::where('member_id', $item->member_id)->first();
                if (!$walletInfo) continue;
                
                $before = $walletInfo->available_balance;
                $after = bcadd($walletInfo->available_balance, $item->win_amount, 2);
                $walletInfo->available_balance = $after;
                $walletInfo->save();

                FundsRecord::addData([
                    'change_type' => '足球游戏中奖',
                    'amount' => $item->win_amount,
                    'before_balance' => $before,
                    'after_balance' => $after,
                    'member_id' => $item->member_id,
                    'related_id' => $item->id,
                    'remark' => '足球游戏中奖',
                ]);
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                Log::error('足球游戏订单开奖结算任务执行异常: ' . $e->getMessage());
            }
        }
    }

    // 可选：失败处理
    public function failed(\Throwable $exception)
    {
        Log::error('足球游戏订单开奖结算任务执行异常: ' . $exception->getMessage());
    }
}
