<?php

namespace App\Jobs\Bonus;

use App\Models\BounsUserPerf;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Modules\User\Models\User;

class MonthPerfJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue;

    public $queue = 'BONUS';

    public $delay = 0;

    public $tries = 1;

    public $timeout = 30;

    protected $user;    //bonus

    protected $last; //bonus

    /**
     * @param  User  $user  用户
     * @param  bool  $last  是否上个月
     */
    public function __construct(User $user, bool $last)
    {
        $this->user = $user->fresh();
        $this->last = $last;
    }

    public function handle()
    {
        $time = [now()->startOfMonth()->toDateTimeString(), now()->endOfMonth()->toDateTimeString()];
        if ($this->last) {
            $time = [
                now()->subMonth()->startOfMonth()->toDateTimeString(),
                now()->subMonth()->endOfMonth()->toDateTimeString()
            ];
        }
        $old = $this->user->allPerf();
        $new = $this->user->allPerf($time);
        BounsUserPerf::updateOrCreate([
            'user_id' => $this->user->id,
            'date'    => $time[0],
        ], [
            'star'     => $this->user->identityFirst()->pivot->star,
            'old_perf' => $old,
            'new_perf' => $new,
        ]);
    }
}
