<?php

namespace App\Console\Commands\Welfare;

use App\Services\Welfare\NoticeService;
use Illuminate\Console\Command;
use App\Models\User\UserModel;
use App\Models\Welfare\TicketModel;
use App\Models\Welfare\LotteryModel;
use App\Models\Welfare\JigsawFlowModel;
use App\Models\Welfare\PrizeModel;

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

    /**
     * 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()
    {
        $lottery = LotteryModel::whereRaw("from_unixtime(`drawed_at`, '%Y-%m-%d %H:00:00') = ?", [
            date('Y-m-d H:00:00')
        ])
            ->first();
        if (!$lottery) {
            dd('活动不存在');
        }

        // 发奖品
        $tickets = TicketModel::where('lottery_id', $lottery->id)
            ->whereNotIn('uid', [20000001, 20010000])
            ->where('lucky', 1)
            ->get();
        foreach ($tickets as $ticket) {
            PrizeModel::create([
                'uid' => $ticket->uid,
                'title' => $lottery->title,
                'cover_url' => $lottery->cover_url,
                'cost' => $lottery->cost,
            ]);
        }

        $n = new NoticeService();
        // 发碎片
        $users = TicketModel::where('lottery_id', $lottery->id)
            ->whereNotIn('uid', [20000001, 20010000])
            ->distinct()
            ->pluck('uid');
        foreach ($users as $uid) {
            UserModel::where('uid', $uid)->increment('jigsaw_amount');
            JigsawFlowModel::create([
                'uid' => $uid,
                'source' => '参与抽奖获得',
                'amount' => 1,
                'remains_amount' => 1
            ]);


            // 通知
            $n->afterLottery($uid, $lottery->id);
        }
    }
}
