<?php
/**
* 用户信息相关
*/
defined( 'IN_WEB') or die( 'Include Error!');

use GatewayWorker\Lib\Gateway;
include_once dirname(__FILE__) . "/Base.php";
define( 'SVR_UPDATE_SPINS',0x5001);
define( 'SVR_UPDATE_COINS',0x5002);
define( 'SVR_UPDATE_DIAMONDS',0x5003);

class User extends  Base{

    public $countryArr = array('tl' => 'tl主包', 'tw' => '繁体', 'en' => '英语', 'amh' => '奥马哈', 'th' => 'th主包', 'hi' => '印尼', 'hw'=>'华为', 'vi'=>'越南', 'ru'=>'俄语', 'kp'=>'靠谱', 'os' => '华为海外');

	/**
	*	获取用户信息
	*/
	public function getUserInfo($param)
	{
	    if(isset($param['uid'])){
            $uid = oo::functions()->uint($param['uid']);
            $userinfo = oo::commonOprModel('member')->getUserInfo($uid);//玩家基本信息
            if(empty($userinfo)){
                return false;
            }
            if( is_array($userinfo) ){
                $userinfo['createtime'] = date('Y-m-d H:i:s', $userinfo['createtime']);
                $userinfo['lasttime'] = date('Y-m-d H:i:s', $userinfo['lasttime']);

                $userinfo['login_plat'] = ( in_array($userinfo['login_plat'], array(11, 1)) ) ? 'android' : 'ios';

                $data = array_merge($userinfo);
            }
            $userinfo['sex'] = ($userinfo['sex'] == 'f')  ?  '女' : '男';
            //查询用户金币
            $AssetsInfo = oo::commonOprModel('member')->getUserAssetsInfo($uid);
            $data = array_merge($userinfo,$AssetsInfo);
            $data['isVistor'] = oo::commonOprModel('member')->isVistor($uid);
            $ghtable = otable::statistics($uid);
            $updateSrv = "SELECT * FROM {$ghtable} WHERE uid={$uid}";
            $ret = oo::commonOprDb('ghgames')->getOne($updateSrv,1);
            $data['loginTime'] = $this->secToTime($ret['loginTime']);
            $userLevel = oo::commonOprModel('member')->getUserLevel($uid);
            $data['element'] = $userLevel['element'];
            $data['chatLock']= oo::commonOprRedis('Userinfo')->get(okeys::chatLock($uid));
            $tb  = otable::payment($uid);
            $sql = "SELECT sum(pusd) as sum FROM {$tb} WHERE uid={$uid} AND status=2";
            $ret = oo::commonOprDb('payment')->getOne($sql,MYSQLI_ASSOC);
            $data['sumMoney'] = $ret['sum'];
			
			//今日获得金币
            $data['todayMoney'] = intval(oo::commonOprRedis('common')->hGet(okeys::todayDataRank('addMoney'),$uid));
            //今日获得体力
            $data['todaySpins'] = intval(oo::commonOprRedis('common')->hGet(okeys::todayDataRank('addSpins'),$uid));
            //好友数量
            $data['friendNumber'] = count(oo::commonOprModel('friend')->getUserAllFriend($uid));
			
			//是否在线
//            $data['isOnline'] = oo::commonOprModel('Workerman')->isUidOnline($uid);

            $userDynamicsData = oo::commonOprModel('member')->getUserDynamicsData($uid);
            if(empty($userDynamicsData['groupId2'])){
                $data['userGroupName'] = "未归类分组";
            }else{
                $tb  = otable::UserGroupConfig(2);
                $userGroup = trim($userDynamicsData['groupId2'],',');
                $sql = "SELECT name FROM {$tb} WHERE id IN ({$userGroup})";
                $ret = oo::commonOprDb('config')->getAll($sql,MYSQLI_ASSOC);
                $data['userGroupName'] = implode(',',array_column($ret,'name'));
            }
            if(empty($userDynamicsData['groupId3'])){
                $data['userGroupNameSS'] = "未归类分组";
            }else{
                $tb  = otable::UserGroupConfig(2);
                $userGroup = trim($userDynamicsData['groupId3'],',');
                $sql = "SELECT name FROM {$tb} WHERE id IN ({$userGroup})";
                $ret = oo::commonOprDb('config')->getAll($sql,MYSQLI_ASSOC);
                $data['userGroupNameSS'] = implode(',',array_column($ret,'name'));
            }

            $actInfo  = oo::commonOprModel('activitynew')->activityLock($uid,"traffic_permit",true);

            $gamePassInfoKey = okeys::GamePassInfo(intval($actInfo['activityData']['aid']), $uid);
            $data['trafficStatus'] = intval(oo::commonOprRedis('activity')->hGet($gamePassInfoKey, "buy"));

        }else if($param['nick']){
	        $nick = oo::functions()->escapeNick($param['nick']);
	        $data = [];
            $tb  = otable::userinfo(1);
            $sql = "SELECT * FROM {$tb} WHERE nick LIKE '%{$nick}%'";
            $ret = oo::commonOprDb('userinfo')->getAll($sql,MYSQLI_ASSOC);
            foreach ($ret as $row){
                $data[] = [
                    'uid'  =>$row['uid'],
                    'nick' =>$row['nick'],
                ];
            }
        }
		return json_encode($data);
	}


	/**
     *	操作用户金币
     */
    public function actionUser($param)
    {
        $data = array();
        $uid = oo::functions()->uint($param['uid']);
        $money = trim($param['money']);
        $spins = trim($param['spins']);//体力
        $shield = trim($param['shield']);//盾牌
      	$star = trim($param['star']);//星星
      	$diamond = trim($param['diamond']);//钻石
        $moneyMsg = $spinsMsg = $diamondMsg = false;
        //修改金币
        if($money > 0){
            $moneyMsg = true;
            oo::commonOprModel('member')->optProperty($uid,array('money'=>intval($money)),'+',999,'后台修改');
        }else if($money < 0){
            $moneyMsg = true;
            oo::commonOprModel('member')->optProperty($uid,array('money'=>abs($money)),'-',999,'后台修改');
        }

        //修改体力
        if($spins > 0){
            $spinsMsg = true;
            oo::commonOprModel('member')->optProperty($uid,array('spins'=>intval($spins)),'+',999,'后台修改');
        }else if($spins < 0){
            $spinsMsg = true;
            oo::commonOprModel('member')->optProperty($uid,array('spins'=>abs($spins)),'-',999,'后台修改');
        }

        //修改盾牌
        if($shield > 0){
            oo::commonOprModel('member')->optProperty($uid,array('shield'=>intval($shield)),'+',999,'后台修改');
        }else if($shield < 0){
            oo::commonOprModel('member')->optProperty($uid,array('shield'=>abs($shield)),'-',999,'后台修改');
        }
		
      	//修改星星
        if($star > 0){
            oo::commonOprModel('member')->optProperty($uid,array('star'=>intval($star)),'+',999,'后台修改');
        }else if($star < 0){
            oo::commonOprModel('member')->optProperty($uid,array('star'=>abs($star)),'-',999,'后台修改');
        }

      	//修改钻石
        if($diamond > 0){
            $diamondMsg = true;
            oo::commonOprModel('member')->optProperty($uid,array('diamond'=>intval($diamond)),'+',999,'后台修改');
        }else if($diamond < 0){
            $diamondMsg = true;
            oo::commonOprModel('member')->optProperty($uid,array('diamond'=>abs($diamond)),'-',999,'后台修改');
        }

        $data = oo::commonOprModel('member')->getUserAssetsInfo($uid);

        if($moneyMsg){
            oo::commonOprModel('Workerman')->push($uid,SVR_UPDATE_COINS,['num'=>intval($money)]);
        }

        if($spinsMsg){
            oo::commonOprModel('Workerman')->push($uid,SVR_UPDATE_SPINS,['num'=>intval($spins)]);
        }

        if($diamondMsg){
            oo::commonOprModel('Workerman')->push($uid,SVR_UPDATE_DIAMONDS,['num'=>intval($diamond)]);
        }

        return json_encode($data,JSON_NUMERIC_CHECK);
    }

	/**
	*	清空玩家账号 谨慎处理
	*/
	public function clearAccount($param)
	{
		$data = array();
		$uid = oo::functions()->uint($param['uid']);
		$uidList = array($uid);
		$ret = oo::commonOprModel('user')->delAccount($uidList);//玩家基本信息
		return json_encode(array('code' => $ret));
	}


    /**
     * 封玩家账号
     * @param $param
     * Created by: Owen
     * Created on: 2020/9/17 12:07
     */
	public function suspendAccount($param){
		$uid = oo::functions()->uint($param['uid']);
		if(empty($uid)) {
		    $ret = -1;
        }else {
            $userinfo = oo::commonOprModel('member')->getUserInfo($uid);//玩家基本信息
            if($userinfo['status']){
            	$ret = oo::commonOprModel('member')->updateUserInfo($uid,array('status'=>0));
            }else{
            	$ret = oo::commonOprModel('member')->updateUserInfo($uid,array('status'=>1));
            }
        }
		return json_encode(array('code' => $ret));
	}

  	public function log($param){
        $start = oo::functions()->uint($param['start']);
        $length = oo::functions()->uint($param['length']);
        $uid = oo::functions()->uint($param['uid']);
        $type = oo::functions()->escape($param['type']);
        $crease = oo::functions()->uint($param['crease']);
        $sort = oo::functions()->escape($param['sort']);
        $stime = oo::functions()->escape($param['stime']);
        $etime = oo::functions()->escape($param['etime']);
        
		
        $tb = otable::Assetslog($uid);
        if($type != 'all'){
            $sql = " SELECT * FROM {$tb} WHERE uid={$uid} AND type='{$type}'";
            $sql2 = " SELECT count(1) as total FROM {$tb} WHERE uid={$uid} AND type='{$type}'";
        }else{
            $sql = "SELECT * FROM {$tb} WHERE uid={$uid}";
            $sql2 = " SELECT count(1) as total FROM {$tb} WHERE uid={$uid}";
        }
        if($crease == 1){
            $sql = $sql." AND crease='+'";
            $sql2 = $sql2." AND crease='+'";
        }else if($crease == 2){
            $sql = $sql." AND crease='-'";
            $sql2 = $sql2." AND crease='-'";
        }
        if(!empty($stime)){
        	$sql = $sql." AND time >= '{$stime}'";
        	$sql2 = $sql2." AND time >= '{$stime}'";
        }
        if(!empty($etime)){
        	$sql = $sql." AND time <= '{$etime}'";
        	$sql2 = $sql2." AND time <= '{$etime}'";
        }
        
        if(!empty($sort)){
        	if($sort == 'DESC'){
        		$sql = $sql." ORDER BY `num` DESC,`time` DESC LIMIT {$start}, {$length}";
        	}else{
        		$sql = $sql." ORDER BY `num` ASC,`time` DESC LIMIT {$start}, {$length}";
        	}
        }else{
        	$sql = $sql." ORDER BY `time` DESC LIMIT {$start}, {$length}";
        }

        $list = oo::commonOprDb('common')->getAll($sql, MYSQLI_ASSOC);
        $list2 = oo::commonOprDb('common')->getOne($sql2, MYSQLI_ASSOC);
        $data['list'] = $list;
        $data['total'] = $list2['total'];
        return json_encode($data);
    }
  
  	 public function getTotalLog($param){
        $uid = oo::functions()->uint($param['uid']);
        $tb = otable::Assetslog($uid);
        $arr = ['money','spins','shield','star'];
        $crease =['+'=>'add','-'=>'low'];
        $out = [];
        foreach ($arr as $row){
            foreach ($crease as $key=>$value){
                $sql =" SELECT SUM(num) as sum FROM {$tb} WHERE uid={$uid} AND type='{$row}' AND crease='{$key}'";
                $ret = oo::commonOprDb('common')->getOne($sql, MYSQLI_ASSOC);
                $out[$row.$value] = $ret['sum'];
            }
        }
        return json_encode($out);
    }
  
   //------------------------------------------------------------------------------------------------------------------
    public function setLevel($param){
        $uid = oo::functions()->uint($param['uid']);
        $levelId = oo::functions()->uint($param['levelId']);
        if(empty($uid) || empty($levelId)){
            return 0;
        }
        $star = -25;
        $info = oo::commonOprModel('member')->getUserAssetsInfo($uid);
        oo::commonOprModel('steal')->outAllQueue($uid,$info['levelId']);
        oo::commonOprModel('attack')->OutAttackQueue($uid,$info['levelId'],2);

        $userlevelTable = otable::userlevel($uid);
        $sql = "DELETE FROM {$userlevelTable} WHERE uid={$uid}";
        oo::commonOprDb('ghgames')->query($sql);
        for ($i=1;$i<=$levelId;$i++){
            $ttime = time();
            if($i<$levelId){
                $str_level = '[{\"id\":1,\"level\":5,\"maxLevel\":5,\"status\":0},{\"id\":2,\"level\":5,\"maxLevel\":5,\"status\":0},{\"id\":3,\"level\":5,\"maxLevel\":5,\"status\":0},{\"id\":4,\"level\":5,\"maxLevel\":5,\"status\":0},{\"id\":5,\"level\":5,\"maxLevel\":5,\"status\":0}]';
            }else if($i==$levelId){
                $str_level = '[{\"id\":1,\"level\":0,\"maxLevel\":0,\"status\":0},{\"id\":2,\"level\":0,\"maxLevel\":0,\"status\":0},{\"id\":3,\"level\":0,\"maxLevel\":0,\"status\":0},{\"id\":4,\"level\":0,\"maxLevel\":0,\"status\":0},{\"id\":5,\"level\":0,\"maxLevel\":0,\"status\":0}]';
            }
            $insertlevelstr = " INSERT INTO {$userlevelTable} (uid, levelId, element,createTime,completionTime) VALUES ({$uid}, {$i},'$str_level',$ttime,NULL) ";
            oo::commonOprDb('common')->query($insertlevelstr);
            $star += 25;
        }
        oo::commonOprModel('member')->updateUserLevel($uid,[
            'levelId' => $levelId,
            'element' => json_decode(stripslashes($str_level),true),
            'is_reward'=> 0,
        ]);//更新用户等级

        $star += mt_rand(1,25);
        $star = $star - $info['star'];
        $res = oo::commonOprModel('member')->optProperty($uid,['star'=>abs($star)],$star>0?'+':'-',999);

//        oo::commonOprModel('gameinfo')->upDateGameInfoSteal($uid,["levelId"=>$levelId,"star"=>$star]);

        oo::commonOprRedis('common')->delete(okeys::UserAssets($uid));
//        oo::commonOprCache('level')->delete(okeys::UserBuildLevel($uid));
        oo::commonOprRedis('common')->delete(okeys::UserBuildLevel($uid));

        if($levelId >= 2){
            $miningInfo = otable::miningInfo();
            $mingTemp = [];
            for ($i=1;$i<$levelId;$i++){
                $mingTemp[$i]=0;
            }
            $mingTemp = json_encode($mingTemp,JSON_NUMERIC_CHECK);
            $sql = "UPDATE {$miningInfo} SET islandLevel='{$mingTemp}' WHERE uid={$uid}";
            oo::commonOprDb('common')->query($sql);
        }
//        ocache::t_userinfo($uid)->delete(okeys::UpLevelLvCache($uid));
        return $res?$res:0;
    }

    function secToTime($sec)
    {
        $sec = round($sec/60);
        if ($sec >= 60){
            $hour = floor($sec/60);
            $min = $sec % 60;
            $res = $hour.' 小时 ';
            $min != 0  &&  $res .= $min.' 分钟';
        }
        else{
            $res = $sec.' 分钟';
        }
        return $res;
    }
  
  	public function abnormalSta($param){
        $stime = oo::functions()->uint($param['stime']);
        $etime = oo::functions()->uint($param['etime']);
        $page = oo::functions()->uint($param['page']);
        $limit = oo::functions()->uint($param['limit']);
        $type = oo::functions()->uint($param['type']);

        if (empty($stime)){
            $stime = strtotime('00:00:00 -1 days');
        }

        if (empty($etime)){
            $etime = strtotime('23:59:59 -1 days');
        }

        $tb = otable::abnormalSta();
        $sql = "SELECT * FROM {$tb} WHERE type={$type} AND time>'{$stime}' AND time<'{$etime}' ORDER BY time DESC LIMIT {$page}, {$limit}";
        $sql2 = "SELECT count(*) as count FROM {$tb} WHERE type={$type} AND time>'{$stime}' AND time<'{$etime}'";
        if(isset($param['uid'])){
            $uid = intval($param['uid']);
            $sql = "SELECT * FROM {$tb} WHERE type={$type} AND uid={$uid}  AND time>'{$stime}' AND time<'{$etime}' ORDER BY time DESC LIMIT {$page}, {$limit}";
            $sql2 = "SELECT count(*) as count FROM {$tb} WHERE type={$type} AND uid={$uid}  AND time>'{$stime}' AND time<'{$etime}'";
        }
        $ret = oo::commonOprDb('common')->getAll($sql,MYSQLI_ASSOC);
        $res = oo::commonOprDb('common')->getOne($sql2,MYSQLI_ASSOC);

        return json_encode(['list'=>$ret,'total'=>$res['count']]);
    }

	public function chatLock($param){
        $uid = oo::functions()->uint($param['uid']);
        $remark = oo::functions()->escape($param['remark']);
        $lock = oo::commonOprRedis('Userinfo')->get(okeys::chatLock($uid));
        $tb = otable::chatLock();
        if($lock){
            oo::commonOprRedis('Userinfo')->delete(okeys::chatLock($uid));
            $sql = "DELETE FROM {$tb} WHERE uid={$uid} LIMIT 1";
            oo::commonOprDb('statistics')->query($sql,false);
        }else{
            oo::commonOprRedis('Userinfo')->set(okeys::chatLock($uid),1);
            $time = time();
            $sql = "INSERT INTO {$tb} VALUES({$uid},'{$time}','{$remark}')";
            oo::commonOprDb('statistics')->query($sql,false);
        }
        return 1;
    }
  
  	public function chatLockList($param){
        $start = ($param['page'] -1)*10;
        $length = $param['page_size'];
        $tb = otable::chatLock();
        $sql = "SELECT * FROM {$tb} ORDER BY time LIMIT {$start},{$length}";
        $ret = oo::commonOprDb('statistics')->getAll($sql,MYSQLI_ASSOC);
        $sql = "SELECT count(uid) as count FROM {$tb} where 1";
        $res = oo::commonOprDb('statistics')->getAll($sql,MYSQLI_ASSOC);
        return json_encode(['data'=>$ret,'count'=>$res['count']]);
    }

    /**
     *	添加道具
     */
    public function actionProps($param){
        $props = $param['props'];
        $uid = oo::functions()->uint($param['uid']);
        if(empty($uid)){
            return json_encode(['code'=>-1]);
        }
        $count = 0;
        if(!empty($props)){
            $props = json_decode($props,1);
            foreach($props['id'] as $key=>$id){
                $num = $props['num'][$key];
                if($num <= 0 || empty($num)){
                    continue;
                }
//                oo::commonOprModel('props')->addUserProps($uid, $id, $num);
                oo::commonOprModel('member')->sendReward($uid,$id,$num,999,'后台修改');
                $count++;
            }
            return json_encode(['code'=>1,'data'=>$props,'count'=>$count]);
        }
        return json_encode(['code'=>-1,'data'=>$props]);
    }
}
