<?php
/**
 * Created by PhpStorm.
 * User: gevnc
 * Date: 2018/5/14
 * Time: 17:59
 */

namespace App\Services;

use App\Traits\Singleton;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Yansongda\Pay\Log;

class BrainstormingService
{
    use Singleton;

    const BRAINSTORMING = "bs_brainstorming";

    public function cache($activityId){
        $activity = DB::table("agh_activitys")->where("activity_id",$activityId)->first();
        $corp = DB::table("agh_corps")->where("corp_id",$activity->corp_id)->first();
        $config = DB::table("bs_configs")->where("activity_id",$activityId)->first();
        $brainstorming = collect($config)->toArray();
        $extendConfigs =[];
        if(!empty($brainstorming["extend_configs"])){
            $extendConfigs = json_decode($brainstorming["extend_configs"],true);
        }
        unset($brainstorming["extend_configs"]);
        $brainstorming = array_merge(collect($activity)->toArray(),$brainstorming);
        $brainstorming = array_merge($brainstorming,$extendConfigs);

        $brainstorming["title"] = $activity->title;
        $brainstorming["logo"] = $activity->logo;
        $brainstorming["regulation"] = $activity->regulation;
        $brainstorming["corp_name"] = $corp->corp_name;
        $brainstorming["corp_short_name"] = $corp->corp_short_name;
        $brainstorming["qy_corp_id"] = $corp->qy_corp_id;
        $brainstorming["gcorp_id"] = $corp->source_id;

        unset($brainstorming["update_time"]);
        unset($brainstorming["create_time"]);

        \Illuminate\Support\Facades\Log::info(json_encode($brainstorming,256));
        Redis::hMset(self::BRAINSTORMING.":".$activityId,$brainstorming);
        Redis::expire(self::BRAINSTORMING.":".$activityId,600);
        //缓存题目
        if(!Redis::exists("question_cache:".$activityId)){
            QuestionService::getInstance()->cache($activityId);
            Redis::setex("question_cache:".$activityId,86400,$activityId);
        }
        return $brainstorming;

    }

    public function get($activityId){
        $data = Redis::hGetall(self::BRAINSTORMING.":".$activityId);
        if($data){
            return $data;
        }else{
            return $this->cache($activityId);
        }
    }
}