<?php
/**
 * Created by PhpStorm.
 * User: hanle
 * Date: 2018/8/16
 * Time: 16:30
 */

namespace App\Http\Controllers;
use App\Models\Department;
use App\Services\BrainstormingService;
use App\Services\DepartmentService;
use App\Services\PkService;
use App\Services\PushMessageService;
use App\Services\TopService;
use App\Services\UserService;
use Laravel\Lumen\Routing\Controller as BaseController;

use Illuminate\Http\Request;
use App\Models\PkRoom;
use App\Models\User;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\DB;

//class PkApiController extends BaseController
class PkApiController extends Controller
{
    const ONLINE_KEY        = 'bs_online_list:';
    const USER_STATUS_KEY   = 'bs_user_current_work:';
    const PK_READY          = 'bs_pk_ready:';

//    protected $userId;
//    protected $activityId;
//    protected $user;
//
//    public function __construct()
//    {
//        $this->userId       = 723613;
//        $this->activityId   = 521;
//        $this->user         = UserService::getInstance()->getUser($this->userId);
//    }

    /**
     * 获取活动在线人员信息及状态
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getOnlineUsers(Request $request){
        $params = $request->all();

        $activityId = $this->activityId;
        $keyword    = empty($params['keyword'])?'':$params['keyword'];
        $user_id    = $this->userId;
        $onlineUsers= Redis::hgetAll(self::ONLINE_KEY.$activityId);                                                    //获取活动在线人员

        //获取段位配置
        $activityInfo = BrainstormingService::getInstance()->get($activityId);
        $level_start_config = json_decode($activityInfo['level_star_config'], true);

        if(!empty($onlineUsers)) {
            $userIds = array_keys($onlineUsers);
            $onlineUsersInfo = TopService::getInstance()->getUsers($activityId, $userIds);

            //数据组装
            $data = [];
            foreach ($onlineUsersInfo as $k => $v) {
                //模糊搜索判断
                if (!empty($keyword)) {
                    $is_search_word = strstr($v['name'], $keyword);
                    if (!$is_search_word) {
                        continue;
                    }
                }
                //如果为null则跳过
                if(empty($v)){
                    continue;
                }

                //剔除自己并获取自己的排名信息
                if ($user_id == $v['user_id']) {
                    continue;
                }

                $user = $v;
                $curWork = Redis::hGetAll(self::USER_STATUS_KEY . $v['user_id']);                                                        //获取用户状态 存在则为正忙，不存在则为正闲

                if ($curWork) {
                    switch ($curWork["channel"]) {
                        case "pk":
                            $user["is_busy"] = 1;
                            $user["busy_message"] = "正在PK";
                            break;
                        case "blockade":
                            $user["is_busy"] = 1;
                            $user["busy_message"] = "正在答题";
                            break;
                    }
                } else {
                    //用户的被邀请状态
                    $invite_status = Redis::get(self::PK_READY . $this->userId . ":" . $v['user_id']);
                    if ($invite_status) {
                        $user['is_invite'] = 1;
                    }

                    $user["is_busy"] = 0;
                }

                $user['user_level_name'] = $level_start_config[$v['user_level']]['name'];
                $user['user_name'] = $user['name'];

                $data[] = $user;
            }

            //只返回一百条
            $result_status = collect($data)->sortBy('is_busy')->values()->all();
        } else {
            //只返回一百条
            $result_status = [];
        }

        //获取当前用户的排名
        $user_self['user_level_name']   = isset($level_start_config[$this->user['user_level']]['name']) ? $level_start_config[$this->user['user_level']]['name'] : '无';
        $user_self['level_need_star']   = intval($level_start_config[$this->user['user_level']]['star']);
        $user_self['user_level']        = intval($this->user['user_level']);
        $user_self['user_star']         = intval($this->user['user_star']);
        $user_self['avatar']            = $this->user['avatar'];
        $user_self['name']              = $this->user['name'];
        $user_self['department_name']   = $this->user['department_name'];
        $user_self['index']             = intval(TopService::getInstance()->getPkRank($this->activityId, $this->userId));

        return response()->json([
            "error"     =>0,
            "message"   =>"OK",
            "data"      =>[
                'online_users'  =>collect($result_status)->take(100),
                'user_self'     =>$user_self
            ]
        ]);
    }

    /**
     * 获取排行榜信息与当前用户信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getTop(Request $request){
        $activity_id = $this->activityId;

        //获取排行信息
        $topUsers = TopService::getInstance()->getPkTop($activity_id);

        //获取段位配置信息
        $activityInfo = BrainstormingService::getInstance()->get($activity_id);
        $levelStartConfig = json_decode($activityInfo['level_star_config'], true);

        //获取当前用户的排行等信息
        $userSelfInfoAll = UserService::getInstance()->getUser($this->userId);
        $userSelfInfo['index'] = TopService::getInstance()->getPkRank($activity_id, $this->userId);
        $userSelfInfo['user_level_name'] = isset($levelStartConfig[$userSelfInfoAll['user_level']]['name'])?$levelStartConfig[$userSelfInfoAll['user_level']]['name']:'无';
        $userSelfInfo['level_need_star'] = intval($levelStartConfig[$userSelfInfoAll['user_level']]['star']);

        //排行榜用户信息组装
        foreach ($topUsers as $k=>$v) {
            $topUsers[$k]['user_level_name'] = isset($levelStartConfig[$v['user_level']]['name'])?$levelStartConfig[$v['user_level']]['name']:'无';
        }

        return response()->json([
            "error"     =>0,
            "message"   =>"OK",
            "data"      =>[
                'top'=>collect($topUsers)->take(100),
                'user_self'=>$userSelfInfo
            ]
        ]);
    }

    /**
     * 发起PK
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function postChallenge(Request $request){
        $params = $request->all();

        //参数过滤
        if(empty($params['invite_user_id'])){
            return response()->json([
                "error"     =>1,
                "message"   =>"参数不全，无法发起PK"
            ]);
        }

        $sponsor_user_id  = $this->userId;                   //挑战者ID
        $invite_user_id  = $params['invite_user_id'];       //被挑战者ID

        Redis::del(self::USER_STATUS_KEY.$sponsor_user_id);                                                              //清除用户状态缓存（默认可操作邀请，则状态为空闲状态）
        $invite_status      = Redis::hGetAll(self::USER_STATUS_KEY.$invite_user_id);
        $sponsor_user_info  = UserService::getInstance()->getUser($sponsor_user_id);
        $invite_user_info   = UserService::getInstance()->getUser($invite_user_id);

        if($invite_status){
            return response()->json([
                "error"     =>1,
                "message"   =>"对方正忙，无法发起PK"
            ]);
        }
        if($sponsor_user_info['status'] == 0 || $invite_user_info['status'] == 0){
            return response()->json([
                "error"     =>1,
                "message"   =>"用户不存在，无法发起PK"
            ]);
        }

        $data = [
            'sponsor_user_id'   =>$sponsor_user_id,          //发起挑战者
            'invite_user_id'    =>$invite_user_id,           //被挑战者
            'name'              =>$sponsor_user_info['name']
        ];
        //挑战消息推送
        PushMessageService::getInstance()->pushByUserId('pk','inviteNotify',$data, $invite_user_id);
        //建立被邀请关系
        Redis::setex(self::PK_READY.$sponsor_user_id.":".$invite_user_id, 10, $invite_user_id);
        return response()->json([
            "error"     =>0,
            "message"   =>"OK",
        ]);
    }

    /**
     * PK响应接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function postPkResponse(Request $request){
        $params = $request->all();

        //参数过滤
        if(empty($params['sponsor_user_id'])){
            return response()->json([
                "error"     =>1,
                "message"   =>"参数不全，无法接受PK"
            ]);
        }

        $answer = empty($params['answer'])?0:$params['answer'];

        if($answer == 1){                    //同意进行PK
            $res = PkService::getInstance()->startPk($this->activityId, $params['sponsor_user_id'], $this->userId);
            if(!empty($res)){
                return response()->json([
                    'error'=>0,
                    'message'=>'OK',
                    "data"=>[
                        'roomId'=>$res
                    ]
                ]);
            } else {
                return response()->json([
                    'error'=>1,
                    'message'=>'PK开启失败'
                ]);
            }
        } elseif($answer == 2) {            //响应超时
            $data = [
                'sponsor_user_id'   =>$params['sponsor_user_id'],          //发起挑战者
                'name'              =>$this->user['name'],
                'message'           =>'对方无应答'
            ];
            //挑战消息推送
            PushMessageService::getInstance()->pushByUserId('pk','timeoutNotify',$data, $params['sponsor_user_id']);
            return response()->json([
                'error'=>1,
                'message'=>'对方无应答，请稍后邀请！！'
            ]);
        } else {                            //拒绝PK
            $sponsor_info = $this->user;
            $data = [
                'sponsor_user_id'   =>$params['sponsor_user_id'],          //发起挑战者
                'name'              =>$sponsor_info['name'],
                'message'           =>'邀请被拒绝'
            ];
            //挑战消息推送
            PushMessageService::getInstance()->pushByUserId('pk','refuseNotify',$data, $params['sponsor_user_id']);

            return response()->json([
                'error'=>1,
                'message'=>'邀请已拒绝！！'
            ]);
        }
    }
}
?>