<?php
/**
 * User.php
 * 文件描述
 * Created by: Owen
 * Created on: 2019/7/12 11:34
 * Description:
 *
 */
use \GatewayWorker\Lib\Gateway;
require_once "./GatewayWorker/Function/Init.php";
Class UserCrazyWorker extends Init {
    public function bind($client_id,$data){
        //已经绑定过token了
        if(isset($_SESSION[$client_id], $_SESSION[$client_id]['token'])){
            $str = json_encode(['cmd'=>array_search('User_bind_Rec',ocmd::$Cmd),'code'=>1]);
            if($data['encryp']){
                $str = $this->encryp($str);
            }
            Gateway::sendToClient($client_id, $str);
            return;
        }

        $version = oo::commonOprModel('user')->getUserVersion($data['uid']);
        if(!isset($data['token']) && oo::compareVersion($version,'1.7.4')){
            $str = $this->encryp(json_encode(['cmd'=>array_search('User_koken_Err',ocmd::$Cmd),'code'=>1]));
            Gateway::sendToClient($client_id, $str);
            Gateway::closeClient($client_id);
            oo::logs()->debug3(['data' => $data, 'time' => date('Y-m-d H:i:s')], 'wstoken_err1.log');
            return;
        }

        $redisToken = oo::commonOprRedis('common')->get(okeys::UserToken($data['uid']));
        //token验证不通过
        if($redisToken != $data['token'] && oo::compareVersion($version,'1.7.4')){
            //$str = $this->encryp(json_encode(['cmd'=>array_search('User_koken_Err',ocmd::$Cmd),'code'=>1]));
            //Gateway::sendToClient($client_id, $str);
            //Gateway::closeClient($client_id);
            oo::logs()->debug3(['token' => $redisToken, 'data' => $data, 'time' => date('Y-m-d H:i:s')], 'wstoken_err.log');
            //return false;
        }

        $clientIds = Gateway::getClientIdByUid($data['uid']);
        if(count($clientIds)){
            $path = "UserBind/";
            $name = 'UserBind'.date('Ymd').'.log';
            $str = $this->encryp(json_encode(['cmd'=>array_search('Repeat_Login_Rec',ocmd::$Cmd),'code'=>1]));

//            oo::logs()->debug5($data,$name,$path);

            foreach ($clientIds as $row){
                if($row != $client_id && Gateway::isOnline($row)){
                    $session = $_SESSION[$row];
                    oo::logs()->debug5(['uid'=>$data['uid'],'CurClientId'=>$client_id,'OnlineClientId'=>$row,"CurToken"=>$data['token'],'OnlineToken'=>$session['token'],'time'=>time(),'clientCount'=>count($clientIds),'From'=>WORKERNAME,],$name,$path);
                    Gateway::sendToClient($row, $str);
                    Gateway::closeClient($row);
                    unset($_SESSION[$row]); //清除session
                }
            }
        }
        //推送到其他服务器节点，通知玩家离线
        oo::commonOprModel('workerman')->pushFun('workerman', 'noticeOtherOffline', [$data['uid'], $client_id]);   

        Gateway::bindUid($client_id, $data['uid']);
        $_SESSION[$client_id] = [
            'uid'      =>$data['uid'],
            'encryp'   =>$data['encryp'],
            'loginTime'=>time(),
            'token'    =>$data['token'],
        ];

        //在线标志
        oo::commonOprModel('workerman')->online($data['uid']);
        $str = json_encode(['cmd'=>array_search('User_bind_Rec',ocmd::$Cmd),'code'=>1]);
        if($data['encryp']){
            $str = $this->encryp($str);
        }
        Gateway::sendToClient($client_id, $str);
//        $this->userConnectLog($data['uid'],1);//上线记录
    }

    public function Heartbeat($client_id,$data){
        $str = json_encode(['cmd'=>array_search('User_Heartbeat_Rec',ocmd::$Cmd),'code'=>1]);
        if($data['encryp']){
            $str = $this->encryp($str);
        }
        //更新在线标志
        if(isset($_SESSION[$client_id], $_SESSION[$client_id]['uid'])){
            oo::commonOprModel('workerman')->online($_SESSION[$client_id]['uid']);
        }
        Gateway::sendToClient($client_id, $str);
    }

    /**
     * 用户离线
     * @param $client_id
     * @param $data
     * @return bool
     * @throws Exception
     * Created by: Owen
     * Created on: 2019/9/4 12:24
     */
    public function Offline($client_id,$data){
        if(isset($_SESSION[$client_id], $_SESSION[$client_id]['uid'])){
            oo::commonOprModel('workerman')->offline($_SESSION[$client_id]['uid']); //更新离线
        }
        if(!isset($_SESSION[$client_id])){
            return;
        }
        $userSession = $_SESSION[$client_id];
        $uid = intval($userSession['uid']);
        unset($_SESSION[$client_id]); //清除session
        if(empty($uid)){
            return false;
        }
//        $this->userConnectLog($uid,2);//离线记录
        $onLineTime = time() - intval($userSession['loginTime']);
//        oo::commonOprModel('member')->saveStatistics($uid,'loginTime',$onLineTime);
        oo::commonOprModel('member')->saveUserBasicsStatistics($uid,'loginTime',$onLineTime);
        oo::commonOprModel('Statistics')->addUserStatistics($uid,['playTime'=>$onLineTime]);
        $this->redis->hIncrBy(okeys::LoginTime($uid),$uid,$onLineTime);
        Gateway::unbindUid($client_id,$uid);
        $this->deleteKing($uid);
        oo::commonOprModel('landing')->gameinfo($uid);//落地用户重要数据
        oo::commonOprModel('landing')->unionLanding($uid);
        $assetsInfo = oo::commonOprModel('member')->getUserAssetsInfo($uid);
        $evenInfo   = oo::commonOprModel('ta')->getCommonEventProperty($uid);
        oo::commonOprModel('ta')->setEventData($uid,'user_set',[
            "current_star"  =>$assetsInfo['star'],
            "current_coin"  =>$assetsInfo['money'],
            "current_spin"  =>$assetsInfo['spins'],
            "current_shield"=>$assetsInfo['shield'],
            "total_play_time"       =>$evenInfo['total_play_time'],
            "total_login_days"      =>$evenInfo['total_login_days'],
            "continuity_login_days" =>$evenInfo['continuity_login_days'],
        ]);


    }

    /**
     * 移除richestKing 占位
     * Created by: Owen
     * Created on: 2019/7/17 14:00
     * Description:
     */
    public function deleteKing($uid){
        oo::commonOprModel('steal')->clearBindKing($uid);//移除绑定关系
    }
  
  	/**
     * 回归礼包 3-5关 恢复到离线状态
     * @param $uid
     * Created by: Owen
     * Created on: 2019/11/1 11:35
     */
    public function setLastOnlineElement($uid){
        $userLevelData= oo::commonOprModel('member')->getUserLevel($uid);
        $userElements = json_encode($userLevelData['element']);
        $level        = $userLevelData['levelId'];
        if($level>=3 && $level<=5){
            $this->redis->set(okeys::lastOnlineElement($uid),$userElements,86400*7);
        }
    }

    /**
     * 拉取用户财产信息
     * @param $client_id
     * @param $data
     * Created by: Owen
     * Created on: 2020/3/9 18:20
     */
    public function assetsInfo($client_id,$data){
        $uid = oo::functions()->uint($data['uid']);
        $userMoney = oo::commonOprModel('member')->getUserAssetsInfo($uid);
        Gateway::sendToClient($client_id,$this->encryp(json_encode(['cmd'=>ocmd::$send['User_assetsInfo'],'data'=>$userMoney])));
    }

    /**
     * Notes:
     * User: wsc
     * Time: 2020/12/24 15:56
     * @param $uid
     * @param int $do
     * @return bool
     */
    public function userConnectLog($uid,$do=1){
        if(!$uid){
            return true;
        }
        $ts = timeFuns::todaySecond();
        if($do==1) $key =okeys::apiLogs('wsJoin-'.$ts);
        if($do==2) $key =okeys::apiLogs('wsOut-'.$ts);
        oo::commonOprRedis('statistics')->hIncrBy($key,$uid,1);
    }
}
