<?php
/**
 * Created by PhpStorm.
 * User: guanxl
 * Date: 2018/3/25
 * Time: 15:30
 */

namespace App\Http\Controllers;

use DB;
use App\Models\Lottery;
use App\Models\LotteryBoxs;
use App\Models\Prize;
use App\Services\BrainstormingService;
use App\Services\GameTimeService;
use App\Services\UserService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;

class ApiController extends Controller
{

    public function lottery($id)
    {
        $userInfo = UserService::getInstance()->getUser($this->userId);
        $brainstorming = BrainstormingService::getInstance()->get($this->activityId);

        if($brainstorming["is_temp_stop"]==1){
            return response()->json([
                "error" => 1000,
                "message" => "活动已暂停!"
            ]);
        }

        if($brainstorming["is_open_prize"]==0){
            return response()->json([
                "error" => 1002,
                "message" => "本次活动未设置抽奖!"
            ]);
        }

        $lottery_level = intval($id);

        if(GameTimeService::getInstance()->isReachEndTime($this->activityId)){
            return response()->json([
                "error" => 1000,
                "message" => "活动已经结束!"
            ]);
        }

        if (empty($userInfo)) {
            return response()->json([
                "error" => 1000,
                "message" => config("errMsg.permission_denied")
            ]);
        }

        $knowledge_money = $userInfo["knowledge_money"];
        $boxs = LotteryBoxs::where("activity_id",$this->activityId)->where("status",1)->orderBy("lottery_level")->get();
        $lottery = [];
        $curHasChance = false;
        foreach ($boxs as $box){
            $has_chance = $knowledge_money>=$box["open_rule"]? true:false;
            if($box["lottery_level"]==$lottery_level&&$has_chance){
                $curHasChance = true;
            }
            array_push($lottery,[
                "lottery_level" => $box["lottery_level"],
                "lottery_name" => $box["lottery_name"],
                "lottery_icon" => $box["lottery_icon"],
                "has_chance" => $has_chance,
                'is_lottery' => false,
                "need_km" => $box["open_rule"]
            ]);
        }
        if (!$curHasChance) {
            return response()->json([
                "error" => 1000,
                "message" => "没有本等级开箱的权限"
            ]);
        }
        /*$lottery_level_1 = $brainstorming["copper_box_km"]==0? 100:$brainstorming["copper_box_km"];
        $lottery_level_2 = $brainstorming["silver_box_km"]==0? 500:$brainstorming["silver_box_km"];
        $lottery_level_3 = $brainstorming["gold_box_km"]==0? 1000:$brainstorming["gold_box_km"];

        $has_chance_1 = $knowledge_money >= $lottery_level_1 ? true : false;
        $has_chance_2 = $knowledge_money >= $lottery_level_2 ? true : false;
        $has_chance_3 = $knowledge_money >= $lottery_level_3 ? true : false;*/

        $lotterys = Lottery::where('user_id', $this->userId)
            ->orderBy('lottery_time', 'desc')
            ->get();

        if ($lotterys) {
            foreach ($lotterys as $lot) {
                if ($lot->lottery_level == $lottery_level) {
                    return response()->json([
                        "error" => 1000,
                        "message" => "该等级宝箱你已经开启过"
                    ]);
                }
            }
        }

        $prize = Prize::where("status", 1) ->where("activity_id",$this->activityId)-> where("lottery_level",$lottery_level)->get();
        if (empty($prize)) {
            return response()->json([
                "error" => 1000,
                "message" => "该级别没有设置任何奖项"
            ]);
        }

        $date = date("Ymd");
        $lottery_data = new Lottery;
        $lottery_data->user_id = $this->userId;
        $lottery_data->lottery_level = $lottery_level;
        $lottery_data->prize_id = 0;
        $lottery_data->prize_name = "谢谢参与";
        $lottery_data->prize_image_url = env("NO_PRIZE_IMG");
        $lottery_data->corp_id = $this->corpId;
        $lottery_data->activity_id = $this->activityId;
        $lottery_data->lottery_time = date("Y-m-d H:i:s");

        $data['prize_id'] = 0;
        $data['prize_name'] = "谢谢参与";
        $data['prize_image_url'] = env("NO_PRIZE_IMG");
        $min = 0;
        $probability = array();
        foreach ($prize as $p){
            $max = $p->prize_weights;
            $value = array( 'min' => $min,
                            'max' => $max,
                            'prize_id' => $p->prize_id,
                            'prize_name' => $p->prize_name,
                            'prize_image_url' => $p->prize_image_url,
                            'prize_day_rule' => $p->prize_day_rule,
                            'prize_count' => $p->prize_count,
                            'prize_grant_count' => $p->prize_grant_count);
            $probability[] = $value;
        }
        shuffle($probability);

        $rand = rand(1, 1000);
        foreach ($probability as $pr){
            $redisKey = 'bs_prize_count:'.$pr['prize_id'].':'.$date;
            if(!Redis::exists($redisKey)){
                $count = $pr["prize_day_rule"];
                Redis::set($redisKey,$count);
            }else{
                $count =  Redis::get($redisKey);
            }

            if ($rand > $pr['min'] && $rand <= $pr['max'] && $pr['prize_grant_count'] < $pr['prize_count'] && $count > 0){
                Redis::incrby($redisKey,-1);
                Prize::where('prize_id',$pr['prize_id'])->update(["prize_grant_count" => $pr['prize_grant_count']+1]);
                $lottery_data->prize_id = $pr['prize_id'];
                $lottery_data->prize_name = $pr['prize_name'];
                $lottery_data->prize_image_url = $pr['prize_image_url'];
                $data['prize_id'] = $pr['prize_id'];
                $data['prize_name'] = $pr['prize_name'];
                $data['prize_image_url'] = $pr['prize_image_url'];
                break;
            }
        }

        $lottery_data->save();
        return response()->json([
            "error" => "0",
            "data" => $data
        ]);

    }

    public function lotteryResult(Request $request)
    {
        $userInfo = UserService::getInstance()->getUser($this->userId);
        //$brainstorming = BrainstormingService::getInstance()->get($this->activityId);

        if ($userInfo) {
            $knowledge_money = $userInfo["knowledge_money"];
            //获取宝箱参数
            $boxs = LotteryBoxs::where("activity_id",$this->activityId)->where("status",1)->orderBy("lottery_level")->get();

            /*$lottery_level_1 = $brainstorming["copper_box_km"]==0? 100:$brainstorming["copper_box_km"];
            $lottery_level_2 = $brainstorming["silver_box_km"]==0? 500:$brainstorming["silver_box_km"];
            $lottery_level_3 = $brainstorming["gold_box_km"]==0? 1000:$brainstorming["gold_box_km"];

            $has_chance_1 = $knowledge_money >= $lottery_level_1 ? true:false;
            $has_chance_2 = $knowledge_money >= $lottery_level_2 ? true:false;
            $has_chance_3 = $knowledge_money >= $lottery_level_3 ? true:false;*/
            $lottery = [];
            foreach ($boxs as $box){
                $has_chance = $knowledge_money>=$box["open_rule"]? true:false;
                array_push($lottery,[
                                            "lottery_level" => $box["lottery_level"],
                                            "lottery_name" => $box["lottery_name"],
                                            "lottery_icon" => $box["lottery_icon"],
                                            "has_chance" => $has_chance,
                                            'is_lottery' => false,
                                            "need_km" => $box["open_rule"]
                ]);
            }

            $guid = $userInfo["guid"];

            $lotterys = DB::table("bs_user_lotterys")
                            -> leftJoin("bs_users","bs_user_lotterys.user_id","=","bs_users.user_id")
                            -> where("bs_users.guid","=",$guid)
                            -> where("bs_user_lotterys.activity_id",">","28")
                            -> orderBy("bs_user_lotterys.lottery_time","desc")
                            -> get();

            $cur_lotterys = Lottery::where('user_id',$this->userId)
                       ->orderBy('lottery_time','desc')
                       ->get();
            if ($lotterys){
                /*$lottery = array(
                                array("lottery_level" => '1',"has_chance" => $has_chance_1,'is_lottery' => false,"need_km" => $lottery_level_1),
                                 array("lottery_level" => '2',"has_chance" => $has_chance_2,'is_lottery' => false,"need_km" => $lottery_level_2),
                                 array("lottery_level" => '3',"has_chance" => $has_chance_3,'is_lottery' => false,"need_km" => $lottery_level_3)
                );*/
                $prize = array();
                foreach ($lotterys as $lot){
                    $lotteryName = "";
                    foreach ($lottery as $lot_array){
                        if($lot->lottery_level == $lot_array['lottery_level'])
                        {
                            $lotteryName = $lot_array["lottery_name"];
                        }
                    }
                    $prize[] = [
                        'prize_id'=>$lot->prize_id,
                        'prize_name' => $lot->prize_name,
                        'prize_image_url' => $lot->prize_image_url,
                        'lottery_level' => $lot->lottery_level,
                        'lottery_name' => $lotteryName];
                }
                foreach ($cur_lotterys as $clot) {
                    foreach ($lottery as &$clot_array){
                        if($clot->lottery_level == $clot_array['lottery_level'])
                        {
                            $clot_array['has_chance'] = false;
                            $clot_array['is_lottery'] = true;
                        }
                    }
                }
                $resule = array('error' => 0, 'data' =>array( 'lottery' => $lottery,'prize' => $prize));
                return \response()->json($resule);
            }else{
                return \response()->json([
                    "error" => 0,
                    "data" => [
                        "lottery" => $lottery,
                        "prize" => [
                            "status" => 0
                        ]
                    ]
                ]);
            }
        } else {
            return response()->json([
                "error" => 401,
                "message" => config("errMsg.permission_denied")
            ]);
        }

    }
}