<?php

namespace App\Console\Commands;

use App\Modules\Welfare\Services\WelfarePriceSerivce;
use Illuminate\Console\Command;
use DB;

class WelfareNextDay extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'welfare:nextday {--today}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '分销每天的抽奖次数';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $today = $this->option('today');
        if($today){
            $this->start(true);
        }else{
            $this->start(false);
        }
    }

    private function start(bool $is_today):void{
        $account = $this->getOfficialAccount();
        if($account){
            foreach ($account as $v){
                $this->createRecord($v->channel_user_id,$v->count,$is_today);
            }
        }
    }

    /**
     * 获取公众号
     * @return mixed
     */
    private function getOfficialAccount(){
        $res = DB::table('official_accounts')->join('distribution_channels','official_accounts.distribution_channel_id','=','distribution_channels.id')
            ->groupBy('distribution_channels.channel_user_id')
            ->select(DB::raw('count(*) as `count`'),'distribution_channels.channel_user_id')
            ->where('official_accounts.is_auth',1)
            ->get();
        return $res;
    }

    /**
     * 计算抽奖次数
     * @param int $official_count
     * @return int
     */
    private function getCount(int $official_count):int{
        if($official_count <= 0){
            return 0;
        }
        if($official_count <= 3){
            return 1;
        }elseif ($official_count <= 9){
            return 2;
        }else{
            return 3;
        }
    }

    /**
     * 保存记录
     * @param int $channel_user_id
     * @param int $official_count
     */
    private function createRecord(int $channel_user_id,int $official_count,bool $is_today):void{
        //$count = $this->getCount($official_count);
        $count = 1;
        if($is_today){
            $date = date('Y-m-d');
        }else{
            $date = date('Y-m-d',time()+86400);
        }
        WelfarePriceSerivce::create([
            'channel_user_id'=>$channel_user_id,
            'date'=>$date,
            'num'=>$count,
            'left'=>$count,
        ]);
    }
}
