<?php
/**
 * Created by PhpStorm.
 * User: gevnc
 * Date: 2018/7/3
 * Time: 11:23
 */

namespace App\Services;


use App\Models\OnlineLimits;
use App\Traits\Singleton;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class OnlineLimitService
{
    use Singleton;

    const REDIS_ONLINE = "bs_online";
    const REDIS_ONLINE_LIMIT = "bs_online_limit";
    const REDIS_APPS = "agh_apps";

    /**
     * 判断是否超过在线人数
     */
    public function isOverOnline($activityId){
        $onlineLimitNumber = 0;
        if(!Redis::exists(self::REDIS_ONLINE_LIMIT.":".$activityId)){
            $brainstorming = BrainstormingService::getInstance()->get($activityId);
            if(isset($brainstorming["activity_type"])){
                $freeNum = $this->getFreeNum();
                if($brainstorming["activity_type"]==1){
                    $onlineLimitNumber = $freeNum;
                }
            }
            Redis::setex(self::REDIS_ONLINE_LIMIT.":".$activityId,300,$onlineLimitNumber);
        }else{
            $onlineLimitNumber = Redis::get(self::REDIS_ONLINE_LIMIT.":".$activityId);
        }

        if($onlineLimitNumber>0){
            $onlineCount = Redis::get(self::REDIS_ONLINE.":".$activityId);
            if($onlineCount>=$onlineLimitNumber){
                return true;
            }
        }
        return false;
    }

    public function onlineLimitCount($activityId){
        return Redis::get(self::REDIS_ONLINE_LIMIT.":".$activityId);
    }

    public function getFreeNum(){
        $freeNum = 0;
        if(!Redis::exists(self::REDIS_APPS.":brainstorming")){
            $app = DB::table("agh_apps")->where("app_code","brainstorming")->first();
            if($app){
                $freeNum = $app->free_num;
                Redis::setex(self::REDIS_APPS.":brainstorming",300,json_encode($app,256));
            }
        }
        return $freeNum;
    }
}