<?php

namespace App\Console\Commands\Goodnight;

use App\Models\Goodnight\TopicModel;
use App\Models\Goodnight\VoiceModel;
use Illuminate\Console\Command;

class RankCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'goodnight:rank {rank}';

    /**
     * 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()
    {
        //
        $rank = $this->argument('rank');
        switch ($rank) {
            case "total":
                $this->total();
                break;
            case "topic":
                $this->topic();
                break;
            case "daily":
                $this->daily();
                break;
        }
    }


    public function total()
    {
        $voices = VoiceModel::select('id', 'uid', 'voice', 'like', 'topic_id')
            ->where('check', 1)->where('like', '>', 0)
            ->orderBy('like', 'desc')
            ->limit(100)
            ->get();
        foreach ($voices as $key => $voice) {
            $voice->rank = $key + 1;
            $voice->user;
            $voice->topic = TopicModel::where('id', $voice->topic_id)->value('topic');
        }
        \Cache::forever("goodnight:rank:total", $voices);
    }


    public function daily()
    {
        $voices = VoiceModel::selectRaw("kdgx_goodnight_voice.`id`, kdgx_goodnight_voice.`uid`, kdgx_goodnight_voice.`voice`,kdgx_goodnight_voice.`topic_id`, COUNT(*) as `like`")
            ->join("kdgx_goodnight_voice_thumb", "kdgx_goodnight_voice.id", '=', "kdgx_goodnight_voice_thumb.voice_id")
            ->where("kdgx_goodnight_voice_thumb.created_at", ">", mktime(0, 0, 0))
            ->groupBy("voice_id")
            ->orderBy("like", "desc")
            ->limit(100)
            ->get();
        foreach ($voices as $key => $voice) {
            $voice->rank = $key + 1;
            $voice->user;
            $voice->topic = TopicModel::where('id', $voice->topic_id)->value('topic');
        }
        \Cache::forever("goodnight:rank:daily:" . date("Y-m-d"), $voices);
    }


    public function topic()
    {
        $voices = VoiceModel::select('id', 'uid', 'voice', 'like', 'topic_id')->where('topic_id', 1)->where(
            'check',
            1
        )->where('like', '>', 0)->orderBy('like', 'desc')->limit(100)->get();
        foreach ($voices as $key => $voice) {
            $voice->rank = $key + 1;
            $voice->user;
            $voice->topic = TopicModel::where('id', $voice->topic_id)->value('topic');
        }
        \Cache::forever("goodnight:rank:topic", $voices);
    }
}
