<?php

namespace App\Console\Commands\Welfare;

use Illuminate\Console\Command;
use App\Models\Welfare\TicketModel;
use App\Models\Welfare\LotteryModel;

class LotteryCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'welfare:lottery';

    /**
     * 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()
    {
        $drawed_at = mktime(20, 0, 0);
        $lottery = LotteryModel::where("drawed_at", $drawed_at)->first();
        if (!$lottery) {
            dd('活动不存在');
        }
        $tickets = TicketModel::where('lottery_id', $lottery->id)->get();
        $count = $tickets->count();
        if ($count < $lottery->real_count) {
            $tickets = $tickets->random($count);
        } else {
            $tickets = $tickets->random($lottery->real_count);
        }


        // 实际获奖名单
        foreach ($tickets as $ticket) {
            $ticket->update(['lucky' => 1]);
        }

        // 模拟用户获奖
        for ($i = $lottery->real_count; $i < $lottery->count; $i++) {
            TicketModel::create([
                'uid' => rand(20000001, 20010000),
                'type' => '领取',
                'lottery_id' => $lottery->id,
                'lucky' => 1,
                'ticket_code' => getChars(6),
            ]);
        }
    }
}
