<?php

namespace App\Console\Commands;

use App\Facade\TableName;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class OnLineMax extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'online_max';

    /**
     * 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()
    {
        $carbon = Carbon::now();
        $Sql = DB::table(TableName::QPPlatformDB() . 'OnLineStreamInfo');
        $date = $carbon->format('Y-m-d');

        if (Redis::exists('LastID')) {
            $LastID = Redis::get('LastID');
            $Sql = $Sql->where('ID', '>=', $LastID)->whereDate('InsertDateTime', $date);
        } else {
            $Sql = $Sql->whereDate('InsertDateTime', $date);
        }

        $maxNum = $Sql->select('ID', 'OnLineCountSum')->orderBy('OnLineCountSum', 'desc')->first();

        if (!$maxNum) {
            return false;
        }

        Redis::set('LastID', $maxNum->ID);

        $first = DB::connection('write')->table(TableName::QPRecordDB() . 'RecordPlatformData')
            ->where('DateID', $carbon->format('Ymd'))
            ->where('Channel', -1)
            ->first();

        if ($first && $maxNum->OnLineCountSum > $first->MaxOnLine) {

            DB::connection('write')->table(TableName::QPRecordDB() . 'RecordPlatformData')
                ->where('DateID', $carbon->format('Ymd'))
                ->where('Channel', -1)
                ->update(['MaxOnLine' => $maxNum->OnLineCountSum]);
        }

        $lastAccountId = DB::connection('read')->table(TableName::QPAccountsDB() . 'AccountsInfo')
            ->max('UserID');

        $lastIdentifyId = DB::connection('read')->table(TableName::QPAccountsDB() . 'GameIdentifier')
            ->max('UserID');
        try {
            if($lastAccountId+3000>$lastIdentifyId && $lastIdentifyId>10000){
                $result = DB::connection('write')->select("SET NOCOUNT ON use QPAccountsDB exec GSP_GP_AddUserID 3000");
                Log::info('自动添加用户ID'.json_encode($result));
            }
        }catch (\Exception $e){
            Log::info('自动添加用户ID'.json_encode($e));
        }
    }
}
