<?php

namespace App\Console\Commands;

use App\Jobs\Bonus\SendBounsJob;
use App\Models\Bouns;
use App\Models\BounsUserPerf;
use Illuminate\Console\Command;
use Exception;

class StartBounsCommand extends Command
{
    protected $signature = 'Bonus:StartMonth {star} {last?}';

    protected $description = '分红：开始分红 {1-5} {last?}';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $star = $this->argument('star') ?: 0;
        if (!in_array($star, Bouns::TYPEARRAY)) {
            throw new Exception('星级参数不正确');
        }
        $last = $this->argument('last') ?: 0;

        $time = now()->startOfMonth()->toDateTimeString();
        if ($last) {
            $time = now()->subMonth()->startOfMonth()->toDateTimeString();
        }
        $bouns = Bouns::where('date', $time)
                      ->where('type', $star)
                      ->where('status', Bouns::STATUS_INIT)
                      ->first();
        if (!$bouns) {
            throw new Exception('分红内容不存在或状态不正确');
        }
        $bounsUserPerf = BounsUserPerf::where('date', $bouns->date)
                                      ->where('star', '>=', $bouns->type)
                                      ->get();
        if ($bounsUserPerf->count() > 0) {
            $allOld  = bcmul($bounsUserPerf->sum('old_perf'), 0.3, 4);//累计业绩
            $allNew  = bcmul($bounsUserPerf->sum('new_perf'), 0.7, 4);//新增业绩
            $allPerf = bcadd($allOld, $allNew, 4);//总业绩
            $price   = bcdiv($bouns->total, $allPerf, 6);//单价
            $bouns->doIng();
            foreach ($bounsUserPerf as $bounsPerf) {
                SendBounsJob::dispatch($bounsPerf, $price, $bouns);
            }
        } else {
            $bouns->doEnd();
        }
    }
}
