<?php

namespace App\Jobs\Bonus;

use App\Models\Bouns;
use App\Models\BounsUserPerf;
use App\Models\Job;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;

class SendBounsJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue;

    public $queue = 'BONUS';

    public $delay = 0;

    public $tries = 1;

    public $timeout = 30;

    protected BounsUserPerf $bounsPerf;    //BounsUserPerf
    protected float         $price;//单价
    protected Bouns         $bouns;//单价

    public function __construct(BounsUserPerf $bounsPerf, float $price, Bouns $bouns)
    {
        $this->bounsPerf = $bounsPerf->fresh();
        $this->price     = $price;
        $this->bouns     = $bouns;
    }

    public function handle()
    {
        try {
            $perf = bcadd(bcmul($this->bounsPerf->old_perf, 0.3, 4),
                bcmul($this->bounsPerf->new_perf, 0.7, 4), 4);

            $this->bounsPerf->price  = $this->price;
            $this->bounsPerf->amount = $this->price * $perf;
            $this->bounsPerf->user->account->rule('star_balance', $this->bounsPerf->amount, false, [
                'remark' => Bouns::TYPES[$this->bouns->type],
                'star'   => $this->bouns->type,
            ]);
        } catch (\Exception $e) {
            $this->bounsPerf->status = BounsUserPerf::STATUS_ERROR;
        }
        $this->bounsPerf->save();
        if (Job::where('queue', 'BONUS')->where('payload', 'like', '%SendBounsJob%')->count() <= 1) {
            $this->bouns->doEnd();
        }
    }
}
