<?php

namespace App\Jobs;

use App\Models\PartnerWallet;
use App\Models\PartnerWithdrawal;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

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

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

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        // 判断用户钱包余额是否足够提现
        $wallet = PartnerWallet::where('user_id', $this->partner_id)->first();
        if ($wallet->balance < $this->amount) {
            return;
        }

        // 更新用户钱包余额和提现记录
        $wallet->balance -= $this->amount;
        $wallet->withdrawn_amount += $this->amount;
        $wallet->save();

        $withdraw = new PartnerWithdrawal();
        $withdraw->partner_id = $this->user_id;
        $withdraw->amount = $this->amount;
        $withdraw->status = 0;  // 提现状态为待审核
        $withdraw->save();
    }
}
