<?php
/**
 * User: Owen
 */

use \GatewayWorker\Lib\Gateway;
require_once "./GatewayWorker/Function/Init.php";
class ChatCrazyWorker extends Init {
    public function Init($client_id,$data){
        $uid = intval($data['uid']);
        $message = $this->redis->hGetAll(okeys::Chat($uid));
        $out = [];
        foreach ($message as $key=>$row){
            $out[] = json_decode($row,true);
        }

        Gateway::sendToClient($client_id,$this->encryp(json_encode(['cmd'=>array_search('Chat_Init_Rec',ocmd::$Cmd),'code'=>1,'data'=>$out])));
    }

    public function sendToFriend($client_id,$data){
        $uid   = intval($data['uid']);
        $toUid = intval($data['toUid']);
        $type  = intval($data['type']);
        $content = $data['content'];

        if(empty($uid) || empty($toUid) || empty($type) || empty($content)){
            Gateway::sendToClient($client_id,$this->encryp(json_encode(['cmd'=>array_search('Chat_sendToFriend_Rec',ocmd::$Cmd),'code'=>-1,'msg'=>'參數錯誤'])));
            return false;
        }

        if($toUid == 1){
            $temp = [
                'user_id' => $uid,
                'content' => addslashes($content),
                'orientation' => 1,
                'have_read' => 0,
                'type' => 1,
                'created_at' => time(),
            ];
            $tb = otable::FeedBack2();
            $keys = [];
            $insert = [];
            foreach ($temp as $key=>$row){
                $keys[]    = $key;
                $insert[] = $row;
            }
            $keys = implode(',',$keys);
            $insert = "'".implode("','",$insert)."'";
            $sql = "INSERT INTO {$tb} ({$keys}) VALUES ({$insert})";
            $this->db->query($sql,false);
            $userInfo = $this->getUserInfo($uid);
            $userAssets = $this->getUserAssets($uid);
            $message = [
                'uid'=>$uid,
                'toUid'=>$toUid,
                'time'=>time(),
                'type'=>$type,
                'content'=>$content,
                'star'=>$userAssets['star'],
                'levelId'=>$userAssets['levelId'],
                's_picture'=>$userInfo['s_picture'],
                'nick'=>$userInfo['nick'],
                'isFb'=>intval($userInfo['isFb']),
                'u_flag'=>$userInfo['u_flag'],
                'signature'=>$userInfo['signature'],
                'sex'=>$userInfo['sex'],
                'money'=>$userAssets['money'],
                'vip'=>$userInfo['vip'],
                'vipLv'=>$userInfo['vipLv'],
                'vipExpire'=>$userInfo['vip_expire'],
                'avatar'=>intval($userInfo['avatar']),
            ];
            Gateway::sendToClient($client_id,$this->encryp(json_encode(['cmd'=>array_search('Chat_sendToFriend_message',ocmd::$Cmd),'code'=>1,'data'=>$message])));
            return false;
        }

        $userInfo = $this->getUserInfo($uid);
        $userAssets = $this->getUserAssets($uid);

        $time = time();
        $message = [
            'uid'=>$uid,
            'toUid'=>$toUid,
            'time'=>$time,
            'type'=>$type,
            'content'=>$content,
            'star'=>$userAssets['star'],
            'levelId'=>$userAssets['levelId'],
            's_picture'=>$userInfo['s_picture'],
            'nick'=>$userInfo['nick'],
            'isFb'=>intval($userInfo['isFb']),
            'u_flag'=>$userInfo['u_flag'],
            'signature'=>$userInfo['signature'],
            'sex'=>$userInfo['sex'],
            'money'=>$userAssets['money'],
          	'vip'=>$userInfo['vip'],
          	'vipLv'=>$userInfo['vipLv'],
          	'vipExpire'=>$userInfo['vip_expire'],
          	'avatar'=>intval($userInfo['avatar']),
        ];

        if($type == 2){
            $message['voiceTime'] = $data['voiceTime'];
        }

        $this->redis->hSet(okeys::Chat($toUid),$uid.'#'.$time,json_encode($message));
        $this->redis->expire(okeys::Chat($toUid),oo::redisRandomExpire(30*24*60*60));
        Gateway::sendToUid($toUid,$this->encryp(json_encode(['cmd'=>array_search('Chat_sendToFriend_message',ocmd::$Cmd),'code'=>1,'data'=>$message])));
        Gateway::sendToClient($client_id,$this->encryp(json_encode(['cmd'=>array_search('Chat_sendToFriend_message',ocmd::$Cmd),'code'=>1,'data'=>$message])));
    }

    public function deleteCache($client_id,$data){
        $uid = intval($data['uid']);
        if(isset($data['toUid'])){
            $toUid = intval($data['toUid']);
            $message = $this->redis->hGetAll(okeys::Chat($uid));
            foreach ($message as $key=>$row){
                $temp = explode('#',$key);
                if($temp[0] == $toUid){
                    $info = json_decode($row,true);
                    if($info['type'] == 2){
                        $str = $info['content'];
                        $index = strpos($str,'storage');
                        if($index !== false){
                            $str = substr($str,$index,strlen($str));
                            @unlink(__DIR__.'/../../'.$str);
                        }
                    }
                    $this->redis->hDel(okeys::Chat($uid),$key);
                }
            }
        }else{
            $message = $this->redis->hGetAll(okeys::Chat($uid));
            foreach ($message as $key=>$row){
                $info = json_decode($row,true);
                if($info['type'] == 2){
                    $str = $info['content'];
                    $index = strpos($str,'storage');
                    if($index !== false){
                        $str = substr($str,$index,strlen($str));
                        @unlink(__DIR__.'/../../'.$str);
                    }
                }
                $this->redis->hDel(okeys::Chat($uid),$key);
            }
        }
        Gateway::sendToClient($client_id,$this->encryp(json_encode(['cmd'=>array_search('Chat_deleteCache_Rec',ocmd::$Cmd),'code'=>1])));
    }

    public function addToWorld($client_id,$data){
        Gateway::joinGroup($client_id,'WORLD');
        $out = [];
        $worldMessage = $this->redis->lGetRange(okeys::Chat('WORLD'),0,-1);
        if(isset($data['id'])){
            $id = intval($data['id']);
            foreach ($worldMessage as $row){
                $temp = json_decode($row,true);
                if($temp['id']>$id){
                    $out[] = $temp;
                }
            }
        }else{
            foreach ($worldMessage as $row){
                $out[] = json_decode($row,true);
            }
        }
        Gateway::sendToClient($client_id,$this->encryp(json_encode(['cmd'=>array_search('Chat_addToWorld_Rec',ocmd::$Cmd),'code'=>1,'data'=>$out])));
    }

    public function leaveWorld($client_id){
        Gateway::leaveGroup($client_id,'WORLD');
        Gateway::sendToClient($client_id,$this->encryp(json_encode(['cmd'=>array_search('Chat_leaveWorld_Rec',ocmd::$Cmd),'code'=>1])));
    }

    public function sendToWorld($client_id,$data){
        $uid   = intval($data['uid']);
        $type  = intval($data['type']);
        $content = $data['content'];
        if(empty($uid) || empty($type) || empty($content)){
            Gateway::sendToClient($client_id,$this->encryp(json_encode(['cmd'=>array_search('Chat_sendToWorld_Rec',ocmd::$Cmd),'code'=>-1,'msg'=>'參數錯誤'])));
            return false;
        }

        if(oo::commonOprRedis('Userinfo')->get(okeys::chatLock($uid))){
            Gateway::sendToClient($client_id,$this->encryp(json_encode(['cmd'=>array_search('Chat_sendToWorld_Rec',ocmd::$Cmd),'code'=>-1,'msg'=>'參數錯誤'])));
            return;
        }

        if($type == 3){
            $gift = intval($data['gift']);
            $sendFlag = $this->redis->get(okeys::ChatGiftSend($uid,$gift));
            if($sendFlag){
                $ttl = $this->redis->ttl(okeys::ChatGiftSend($uid,$gift));
                Gateway::sendToClient($client_id,$this->encryp(json_encode(['cmd'=>array_search('Chat_sendToWorld_Rec',ocmd::$Cmd),'code'=>-2,'msg'=>'礼物时间','gift'=>$gift,'ttl'=>$ttl])));
                return false;
            }
          	if(intval($this->redis->hGet(okeys::chatGitfMaxNum(),okeys::chatGitfMaxNum($uid,$gift)))>=2){
                Gateway::sendToClient($client_id,$this->encryp(json_encode(['cmd'=>array_search('Chat_sendToWorld_Rec',ocmd::$Cmd),'code'=>-2,'msg'=>'礼物时间','gift'=>$gift,'ttl'=>0])));
                return false;
            }
        }

        $chatNum = 0;
        if($type == 1){
            $chatNum = intval(oo::commonOprRedis('common')->hGet(okeys::chatMaxNum(),$uid));
            if($chatNum>=1){
                Gateway::sendToClient($client_id,$this->encryp(json_encode(['cmd'=>array_search('Chat_sendToWorld_Rec',ocmd::$Cmd),'code'=>-3,'msg'=>'发言上限','maxNum'=>$chatNum])));
                return false;
            }
        }

        $userInfo = $this->getUserInfo($uid);
        $userAssets = $this->getUserAssets($uid);
        $time = time();
        list($msec, $sec) = explode(' ', microtime());
        $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        $message = [
            'id'=>date("Ymd").$msectime,
            'uid'=>$uid,
            'time'=>$time,
            'type'=>$type,
            'star'=>$userAssets['star'],
            'levelId'=>$userAssets['levelId'],
            's_picture'=>$userInfo['s_picture'],
            'nick'=>$userInfo['nick'],
            'isFb'=>intval($userInfo['isFb']),
            'u_flag'=>$userInfo['u_flag'],
            'signature'=>$userInfo['signature'],
            'sex'=>$userInfo['sex'],
            'money'=>$userAssets['money'],
          	'vip'=>$userInfo['vip'],
          	'vipLv'=>$userInfo['vipLv'],
          	'vipExpire'=>$userInfo['vip_expire'],
          	'avatar'=>intval($userInfo['avatar']),
        ];


        if($type == 3){
            $message['gift'] = $gift;
            if($gift != 3){
                $num = 0;
                $maxNum = 10;
                $str = date('YmdHis') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
                $message['giftId'] = $str;
                $message['num'] = $num;
                $message['maxNum'] = $maxNum;
                $this->redis->setex(okeys::ChatGift($str),json_encode([
                    'num'=>$num,
                    'maxNum'=>$maxNum,
                    'gift'=>$gift,
                    'uid'=>$uid,
                ]),24*60*60);
            }
            $this->redis->setex(okeys::ChatGiftSend($uid,$gift),1,10);
          	$this->redis->hSet(okeys::chatGitfMaxNum(),okeys::chatGitfMaxNum($uid,$gift),intval($this->redis->hGet(okeys::chatGitfMaxNum(),okeys::chatGitfMaxNum($uid,$gift)))+1);
        }else{
            $message['content'] = $content;
            if($type == 2){
                $message['voiceTime'] = $data['voiceTime'];
            }
            if($type == 1){
                oo::commonOprRedis('common')->hSet(okeys::chatMaxNum(),$uid,$chatNum+1);
            }
        }

        Gateway::sendToGroup('WORLD',$this->encryp(json_encode(['cmd'=>array_search('Chat_sendToWorld_message',ocmd::$Cmd),'code'=>1,'data'=>$message])));
        $this->redis->rPush(okeys::Chat('WORLD'),json_encode($message));

        oo::logs()->debug5($message,date('Ymd').'.log','Chat/');

        $len = @$this->redis->lSize(okeys::Chat('WORLD'));
        if($len>20){
            $lPop = $this->redis->lPop(okeys::Chat('WORLD'));
            $lPop = json_decode($lPop,true);
            if($lPop['type'] == 2){
                $str = $lPop['content'];
                $index = strpos($str,'storage');
                if($index !== false){
                    $str = substr($str,$index,strlen($str));
                    @unlink(__DIR__.'/../../'.$str);
                }
            }
        }
    }

    /**
     * 领取礼物
     * @param $param
     * @return false|mixed|string
     * Created by: Owen
     * Created on: 2019/8/30 15:11
     * Description:
     */
    public function gift($client_id,$data){
        $uid = intval($data['uid']);
        $giftId = intval($data['giftId']);
        $gift = $this->redis->get(okeys::ChatGift($giftId));
        if(empty($gift)){
            return json_encode(['code'=>-1,'msg'=>'gift error']);
        }
        $gift = json_decode($gift,true);

        // 判断参与人是否能领 -- 礼物ID限制
        $userGiftId = $this->redis->get(okeys::ChatGiftId($uid,$giftId));
        if($userGiftId != false){
            Gateway::sendToClient($client_id,$this->encryp(json_encode(['cmd'=>array_search('Chat_gift_Rec',ocmd::$Cmd),'code'=>-1,'msg'=>'已领取过礼物'])));
            return false;
        }

        // 判断参与人是否能领 -- 数量限制
        $userGift = $this->redis->get(okeys::ChatGiftRec($uid,$gift['gift'].'#participate'));
        $money = 5000;
        $spins = 1;

        if(empty($userGift)){
            if($gift['gift'] == 1){
                oo::commonOprModel('member')->optProperty($uid,array('money'=>$money),'+',106,'聊天礼物');
            }else if($gift['gift'] == 2){
                oo::commonOprModel('member')->optProperty($uid,array('spins'=>$spins),'+',106,'聊天礼物');
            }
            $this->redis->set(okeys::ChatGiftRec($uid,$gift['gift'].'#participate'),1);
            $this->redis->expireAt(okeys::ChatGiftRec($uid,$gift['gift'].'#participate'),strtotime('23:59:59'));
        }else{
            if($gift['gift'] == 1){
                if(intval($userGift)>=10){
                    Gateway::sendToClient($client_id,$this->encryp(json_encode(['cmd'=>array_search('Chat_gift_Rec',ocmd::$Cmd),'code'=>-2,'msg'=>'礼物已领满'])));
                    return false;
                }else{
                    oo::commonOprModel('member')->optProperty($uid,array('money'=>$money),'+',106,'聊天礼物');
                }
            }else if($gift['gift'] == 2){
                if(intval($userGift)>=10){
                    Gateway::sendToClient($client_id,$this->encryp(json_encode(['cmd'=>array_search('Chat_gift_Rec',ocmd::$Cmd),'code'=>-2,'msg'=>'礼物已领满'])));
                    return false;
                }else{
                    oo::commonOprModel('member')->optProperty($uid,array('spins'=>$spins),'+',106,'聊天礼物');
                }
            }else{
                Gateway::sendToClient($client_id,$this->encryp(json_encode(['cmd'=>array_search('Chat_gift_Rec',ocmd::$Cmd),'code'=>-3,'msg'=>'礼物类型异常'])));
                return false;
            }
            $this->redis->set(okeys::ChatGiftRec($uid,$gift['gift'].'#participate'),intval($userGift)+1);
            $this->redis->expireAt(okeys::ChatGiftRec($uid,$gift['gift'].'#participate'),strtotime('23:59:59'));
        }
//        // 判断发起人是否能领
//        $userGift = $this->redis->get(okeys::ChatGiftRec($gift['uid'],$gift['gift'].'#initiate'));
//        $initiate = false;
//        if(empty($userGift)){
//            if($gift['gift'] == 1){
//                oo::commonOprModel('member')->optProperty($gift['uid'],array('money'=>$money),'+','聊天礼物');
//            }else if($gift['gift'] == 2){
//                oo::commonOprModel('member')->optProperty($gift['uid'],array('spins'=>$spins),'+','聊天礼物');
//            }
//            $this->redis->set(okeys::ChatGiftRec($gift['uid'],$gift['gift'].'#initiate'),$spins);
//            $this->redis->expireAt(okeys::ChatGiftRec($gift['uid'],$gift['gift'].'#initiate'),strtotime('23:59:59'));
//            $initiate = true;
//        }else{
//            if(intval($userGift)<10){
//                if($gift['gift'] == 1){
//                    oo::commonOprModel('member')->optProperty($gift['uid'],array('money'=>$money),'+','聊天礼物');
//                }else if($gift['gift'] == 2){
//                    oo::commonOprModel('member')->optProperty($gift['uid'],array('spins'=>$spins),'+','聊天礼物');
//                }
//                $this->redis->set(okeys::ChatGiftRec($gift['uid'],$gift['gift'].'#initiate'),intval($userGift)+1);
//                $this->redis->expireAt(okeys::ChatGiftRec($gift['uid'],$gift['gift'].'#initiate'),strtotime('23:59:59'));
//                $initiate = true;
//            }
//        }

        $newNum = $gift['num']+1;
        $sData = [
            'num'=>$newNum,
            'maxNum'=>$gift['maxNum'],
            'gift'=>$gift['gift'],
            'uid'=>$gift['uid'],
            'giftId'=>$giftId,
            'recUid'=>$uid
        ];

//        if($initiate){
//            $sData['reward'] = [
//                'type'=>$gift['gift'],
//                'num'=>($gift['gift'] == 1)?$money:$spins,
//            ];
//        }

        $worldMessage = $this->redis->lGetRange(okeys::Chat('WORLD'),0,-1);
        foreach ($worldMessage as $key=>$row){
            $temp = json_decode($row,true);
            if($temp['type'] == 3 && $temp['giftId'] == $giftId){
                $temp['num'] = $newNum;
                $this->redis->lSet(okeys::Chat('WORLD'),$key,json_encode($temp));
            }
        }

        if($newNum>=10){
            $this->redis->delete(okeys::ChatGift($giftId));
        }else{
            $ttl = $this->redis->ttl(okeys::ChatGift($giftId));
            $this->redis->setex(okeys::ChatGift($giftId),json_encode($sData),$ttl);
        }
        $this->redis->setex(okeys::ChatGiftId($uid,$giftId),1,24*60*60);
		
		//聊天的人均金币体力领取次数统计
        oo::commonOprModel('statistics')->chatGiftSta($gift['gift']==1?'money':'spins');
		
        Gateway::sendToGroup('WORLD',$this->encryp(json_encode(['cmd'=>array_search('Chat_giftRec_message',ocmd::$Cmd),'code'=>1,'data'=>$sData])));
        Gateway::sendToClient($client_id,$this->encryp(json_encode(['cmd'=>array_search('Chat_gift_Rec',ocmd::$Cmd),'code'=>1,'data'=>[
            'type'=>$gift['gift'],
            'num'=>($gift['gift'] == 1)?$money:$spins,
        ]])));
    }

    /**
     * 礼物通知
     * @param $client_id
     * @param $data
     * @return bool
     * Created by: Owen
     * Created on: 2019/9/4 12:26
     */
    public function giftReced($client_id,$data){
        $uid = intval($data['uid']);
        $toUid = intval($data['toUid']);
        $gift = intval($data['gift']);
        $time = intval($data['time']);
        if(empty($uid) || empty($toUid) || empty($gift)){
            Gateway::sendToClient($client_id,$this->encryp(json_encode(['cmd'=>array_search('Chat_giftReced_Rec',ocmd::$Cmd),'code'=>-1,'msg'=>'param error'])));
            return false;
        }
        Gateway::sendToUid($toUid,$this->encryp(json_encode(['cmd'=>array_search('Chat_giftReced_message',ocmd::$Cmd),'code'=>1,'data'=>['uid'=>$uid,'toUid'=>$toUid,'gift'=>$gift,'time'=>$time]])));
    }

    /**
     *  ---------------------------------------数据获取-----------------------------------------------
     */
    public function getUserInfo($uid){
        $userInfo = oo::commonOprModel('member')->getUserInfo($uid);
        return $userInfo;
    }

    public function getUserAssets($uid){
        return oo::commonOprModel('member')->getUserAssetsInfo($uid);
    }
}
