<?php
defined('IN_WEB') or die( 'Include Error!');

/**
 * 数据落地
 * Class ModelLanding
 * Created by: Owen
 * Created on: 2020/3/26 15:06
 */
class ModelLanding {

    public $expire;
    public $cardKeyJson = [];
    public function __construct(){
        $this->expire      = time() - 3*24*60*60;
        $this->cardKeyJson = ['ciid', 'send_card','sended_card', 'csid', 'cgreward', 'cpreward'];
    }

    /**
     * 统一落地
     * @param bool $uid
     * Created by: Owen
     * Created on: 2020/3/26 19:29
     */
    public function unionLanding($uid = false){
        self::cardNew();
//        self::achieve($uid);
        if($uid){
            self::statistics($uid);
        }
//        self::mining($uid);
        self::props($uid);
        self::building($uid);
//        self::dynamics($uid);
        self::pet($uid);
//        self::coindozer($uid);
        self::userFriend();
    }

    /**
     * Notes:新卡牌落地
     * User: wsc
     * Time: 2023/10/11 18:24
     */
    public function cardNew(){
        $keys = okeys::LandingKeys("CARD");
        foreach($keys as $okey){
            $ret = oo::commonOprRedis('common')->zRangeByScore($okey,0,$this->expire,['withscores'=>true]);
            foreach ($ret as $uid=>$row){
                if(!$uid){
                    oo::commonOprRedis('Usercache')->zDelete($okey,$uid);
                    continue;
                }
                $nkey = "USER_CARD_LIST:{$uid}";
                $list = oo::commonOprRedis('common')->hGetAll($nkey);
                if(!empty($list)){
                    $userCardList = json_encode($list);
                    $tb = otable::usercard_config($uid);
                    $sql= "UPDATE {$tb} SET ciid='".$userCardList."' WHERE uid={$uid} LIMIT 1";
                    $ret = oo::commonOprDb('common')->query($sql);
                    if($ret){
                        oo::commonOprRedis('common')->zDelete(okeys::Landing("CARD", $uid),$uid);
                        oo::commonOprRedis('common')->expire($nkey,oo::redisRandomExpire(7*24*60*60));
                    }
                }
            }
        }
    }
    /**
     * 卡片落地
     * @param bool $uid
     * @param bool $recursive 递归
     * @return bool
     * Created by: Owen
     * Created on: 2020/3/26 19:34
     */
    public function card($uid = false,$recursive = false){
        if($uid != false){
            if(!$recursive){
                if(!oo::commonOprRedis('common')->zScore(okeys::Landing("CARD", $uid),$uid)){
                    return false;
                }
            }
            $userCardInfo = oo::commonOprModel('card')->getUserCardInfo($uid);
            $tb = otable::usercard_config($uid);
            $sql= "UPDATE {$tb} SET ";
            foreach ($userCardInfo as $key=>$row){
                if($key == "id" || $key == "uid"){
                    continue;
                }
                if(in_array($key,$this->cardKeyJson)){
                    $temp = json_encode($row);
                    $sql .= "`$key`='$temp',";
                }else{
                    $sql .= "`$key`='$row',";
                }
            }
            $sql = trim($sql,',');
            $sql.= " WHERE uid={$uid} LIMIT 1";
            $ret = oo::commonOprDb('common')->query($sql);
            if($ret){
                oo::commonOprRedis('common')->zDelete(okeys::Landing("CARD", $uid),$uid);
                oo::commonOprRedis('common')->setex(okeys::UserCardInfo($uid),json_encode($userCardInfo),oo::redisRandomExpire(7*24*60*60));
            }
        }else{
            $keys = okeys::LandingKeys("CARD");
            foreach($keys as $okey){
                $ret = oo::commonOprRedis('common')->zRangeByScore($okey,0,$this->expire,['withscores'=>true]);
                foreach ($ret as $key=>$row){
                    if(!$key){
                        oo::commonOprRedis('Usercache')->zDelete($okey,$key);
                        continue;
                    }
                    self::card($key,true);
                }
            }
        }
    }

    /**
     * 成就落地
     * @param bool $uid
     * @param bool $recursive
     * @return bool
     * Created by: Owen
     * Created on: 2020/4/7 19:15
     */
    public function achieve($uid = false,$recursive = false){
        if($uid != false){
            if(!$recursive){
                if(!oo::commonOprRedis('common')->zScore(okeys::Landing("ACHIEVE", $uid),$uid)){
                    return false;
                }
            }
            $userAchieve = oo::commonOprModel('achievement')->getUserAchieve($uid);
            $tb = otable::achievement($uid);
            $achieveSize   = count($userAchieve);
            $noLandingSize = 0;
            foreach ($userAchieve as $achieve){
                if(isset($achieve['isLanding']) && $achieve['isLanding'] == 1){
                    $sql= "UPDATE {$tb} SET ";
                    foreach ($achieve as $key=>$row){
                        if($key == "aid" || $key == "uid" || $key == "isLanding"){
                            continue;
                        }
                        $sql .= "`$key`='$row',";
                    }
                    $sql = trim($sql,',');
                    $sql.= " WHERE uid={$uid} AND aid={$achieve['aid']} LIMIT 1";
                    $ret = oo::commonOprDb('common')->query($sql);
                }else{
                    $noLandingSize++;
                }
            }
            if($ret || $achieveSize == $noLandingSize){
                oo::commonOprRedis('common')->zDelete(okeys::Landing("ACHIEVE", $uid),$uid);
                oo::commonOprRedis('common')->expire(okeys::UserAchieve($uid),oo::redisRandomExpire(3*24*60*60));
            }
        }else{
            $keys = okeys::LandingKeys("ACHIEVE");
            foreach($keys as $okey){
                $ret = oo::commonOprRedis('common')->zRangeByScore($okey,0,$this->expire,['withscores'=>true]);
                foreach ($ret as $key=>$row){
                    if(!$key){
                        oo::commonOprRedis('Usercache')->zDelete($okey,$key);
                        continue;
                    }
                    self::achieve($key,true);
                }
            }
        }
    }

    /**
     * 个人统计
     * @param bool $uid
     * @param bool $recursive
     * @return bool
     * Created by: Owen
     * Created on: 2020/4/10 16:16
     */
    public function statistics($uid = false,$recursive = false){
        if($uid != false){
            if(!$recursive){
                if(!oo::commonOprRedis('Usercache')->zScore(okeys::Landing("STATISTICS", $uid),$uid)){
                    return false;
                }
            }
            $userStatistics = oo::commonOprModel('member')->getUserBasicsStatistics($uid);
            $inData= [];
            $tb = otable::statistics($uid);
            $sql= "UPDATE {$tb} SET ";
            foreach ($userStatistics as $key=>$row){
                if($key == "id" || $key == "uid"){
                    continue;
                }
                $inData[$key]=$row;
                $sql .= "`$key`='$row',";
            }
            $sql = trim($sql,',');
            $sql.= " WHERE uid={$uid} LIMIT 1";
            $ret = oo::commonOprDb('common')->query($sql);
            if(!$ret){
                $inData['uid'] = $uid;
                $sql2 = funs::db_insertSQL($tb,$inData);
                $ret =oo::commonOprDb('common')->query($sql2);
            }
            if($ret){
                oo::commonOprRedis('Usercache')->zDelete(okeys::Landing("STATISTICS", $uid),$uid);
                oo::commonOprRedis('userinfo')->expire(okeys::userBasicsStatistics($uid),86400*7);
            }
        }else{
            $keys = okeys::LandingKeys("STATISTICS");
            foreach($keys as $okey){
                $ret = oo::commonOprRedis('Usercache')->zRangeByScore($okey,0,$this->expire,['withscores'=>true]);
                foreach ($ret as $key=>$row){
                    if(!$key){
                        oo::commonOprRedis('Usercache')->zDelete($okey,$key);
                        continue;
                    }
                    self::statistics($key,true);
                }
            }
        }
    }


    /**
     * 矿工落地
     * @param bool $uid
     * @param bool $recursive
     * @return bool
     * Created by: Owen
     * Created on: 2020/4/10 16:16
     */
    public function mining($uid = false,$recursive = false){
        if($uid != false){
            if(!$recursive){
                if(!oo::commonOprRedis('common')->zScore(okeys::Landing("MINING", $uid),$uid)){
                    return false;
                }
            }
            $userMiningInfo = oo::commonOprModel('mining')->getUserMiningInfo($uid);
            $tb  = otable::miningInfo();
            $islandLevel = addslashes(json_encode($userMiningInfo['islandLevel']));
            $ret = oo::commonOprDb('common')->query("UPDATE {$tb} SET `islandLevel`='{$islandLevel}' WHERE uid={$uid} LIMIT 1");
            if($ret){
                oo::commonOprRedis('common')->zDelete(okeys::Landing("MINING", $uid),$uid);
                oo::commonOprRedis('common')->setex(okeys::UserMining($uid),json_encode($userMiningInfo),oo::redisRandomExpire(7*24*60*60));
            }
        }else{
            $keys = okeys::LandingKeys("MINING");
            foreach($keys as $okey){
                $ret = oo::commonOprRedis('common')->zRangeByScore($okey,0,$this->expire,['withscores'=>true]);
                foreach ($ret as $key=>$row){
                    if(!$key){
                        oo::commonOprRedis('Usercache')->zDelete($okey,$key);
                        continue;
                    }
                    self::mining($key,true);
                }
            }
        }
    }

    /**
     * 道具落地
     * @param bool $uid
     * @param bool $recursive
     * @return bool
     * Created by: Owen
     * Created on: 2020/5/7 20:31
     */
    public function props($uid = false,$recursive = false){
        if($uid != false){
            if(!$recursive){
                if(!oo::commonOprRedis('common')->zScore(okeys::Landing("PROPS", $uid),$uid)){
                    return false;
                }
            }
            $propsInfo = oo::commonOprModel('props')->getUserPropsData($uid);
            $tb  = otable::userprops($uid);
            $cacheKey = okeys::UserProps($uid);
            foreach ($propsInfo as $row){
                if(isset($row['isLanding']) && $row['isLanding'] == 1){
                    if($row['count'] <= 0){
                        $ret = oo::commonOprDb('common')->query("DELETE FROM {$tb}  WHERE uid = {$uid} AND id = {$row['id']} LIMIT 1");
                        oo::commonOprRedis('common')->hDel($cacheKey,$row['id']);
                    }else{
                        $ret = oo::commonOprDb('common')->query("UPDATE {$tb} SET `count`='{$row['count']}' WHERE uid = {$uid} AND id = {$row['id']} LIMIT 1");
                        $temp = $row;
                        unset($temp['isLanding']);
                        oo::commonOprRedis('common')->hSet($cacheKey,$row['id'],json_encode($temp));
                    }
                }
            }
            if($ret){
                oo::commonOprRedis('common')->zDelete(okeys::Landing("PROPS", $uid),$uid);
                oo::commonOprRedis('common')->expire($cacheKey,oo::redisRandomExpire(7*24*60*60));
            }
        }else{
            $keys = okeys::LandingKeys("PROPS");
            foreach($keys as $okey){
                $ret = oo::commonOprRedis('common')->zRangeByScore($okey,0,$this->expire,['withscores'=>true]);
                foreach ($ret as $key=>$row){
                    if(!$key){
                        oo::commonOprRedis('Usercache')->zDelete($okey,$key);
                        continue;
                    }
                    self::props($key,true);
                }
            }
        }
    }

    /**
     * 建筑落地
     * @param bool $uid
     * @param bool $recursive
     * @return bool
     * Created by: Owen
     * Created on: 2020/5/7 20:31
     */
    public function building($uid = false,$recursive = false){
        if($uid != false){
            if(!$recursive){
                if(!oo::commonOprRedis('common')->zScore(okeys::Landing("BUILDING", $uid),$uid)){
                    return false;
                }
            }
            $userBuildInfo = oo::commonOprModel('member')->getUserLevel($uid);
            if(isset($userBuildInfo['isLanding']) && $userBuildInfo['isLanding'] == 1){
                $tb = otable::userlevel($uid);
                $level     = $userBuildInfo['levelId'];
                $element   = addslashes(json_encode($userBuildInfo['element']));
                $is_reward = intval($userBuildInfo['is_reward']);
                $ret       = oo::commonOprDb('common')->getOne("SELECT max(levelId) as levelId FROM {$tb} WHERE uid={$uid} LIMIT 1",MYSQLI_ASSOC);
                if(empty($ret) || $ret['levelId'] == 0){
                    $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}]';
                    $tb = otable::userlevel($uid);
                    $time = time();
                    oo::commonOprDb('common')->query("INSERT INTO {$tb} (`uid`,`levelId`,`element`,`createTime`) VALUES ({$uid},1, '$str_level','{$time}')");
                    $ret['levelId'] = 1;
                }
                oo::commonOprDb('common')->query("UPDATE {$tb} SET `levelId`={$level},`element`='{$element}',is_reward='{$is_reward}' WHERE uid = {$uid} AND levelId={$ret['levelId']} LIMIT 1");
            }
            oo::commonOprRedis('common')->zDelete(okeys::Landing("BUILDING", $uid),$uid);
            oo::commonOprRedis('common')->expire(okeys::UserBuildLevel($uid),oo::redisRandomExpire(7*24*60*60));
        }else{
            $keys = okeys::LandingKeys("BUILDING");
            foreach($keys as $okey){
                $ret = oo::commonOprRedis('common')->zRangeByScore($okey,0,$this->expire,['withscores'=>true]);
                foreach ($ret as $key=>$row){
                    if(!$key){
                        oo::commonOprRedis('Usercache')->zDelete($okey,$key);
                        continue;
                    }
                    self::building($key,true);
                }
            }
        }
    }

    /**
     * Notes:用户重要信息落地
     * User: wsc
     * Time: 2020/6/30 18:43
     * @param bool $uid
     * @param bool $recursive
     * @return bool
     */
    public function gameinfo($uid=false,$recursive=false){
        if($uid != false){
            if(!$recursive){
                if(!oo::commonOprRedis('Usercache')->zScore(okeys::Landing("GAMEINFO", $uid),$uid)){
                    return false;
                }
            }
            $userinfo = oo::commonOprModel('member')->getUserAssetsInfo($uid);
            $tb = otable::gh_gameserver($uid);
            $sql= "UPDATE {$tb} SET ";
            foreach ($userinfo as $key=>$row){
                if($key == "id" || $key == "uid"){
                    continue;
                }
                $sql .= "`$key`='$row',";
            }
            $sql = trim($sql,',');
            $sql.= " WHERE mid={$uid} LIMIT 1";
            $ret = oo::commonOprDb('ghgames')->query($sql);
            if($ret){
                oo::commonOprRedis('Usercache')->zDelete(okeys::Landing("GAMEINFO", $uid),$uid);
                oo::commonOprRedis('user')->persist(okeys::userAttr($uid));
//                oo::commonOprRedis('user')->expire(okeys::userAttr($uid),oo::redisRandomExpire(86400*7*24));
            }
        }else{
            $t = time() - 60;
            $keys = okeys::LandingKeys("GAMEINFO");
            foreach($keys as $okey){
                $ret = oo::commonOprRedis('Usercache')->zRangeByScore($okey,0,$t,['withscores'=>true]);
                foreach ($ret as $key=>$row){
                    if(!$key){
                        oo::commonOprRedis('Usercache')->zDelete($okey, $key);
                        continue;
                    }
                    self::gameinfo($key,true);
                }
            }
        }
    }


    /**
     * 用户动态数据
     * @param bool $uid
     * @param bool $recursive
     * @return bool
     * Created by: Owen
     * Created on: 2020/4/10 16:16
     */
    public function dynamics($uid = false,$recursive = false){
        return;
        if($uid != false){
            if(!$recursive){
                if(!oo::commonOprRedis('Usercache')->zScore(okeys::Landing("DYNAMICS", $uid),$uid)){
                    return false;
                }
            }
            $userDynamicsData = oo::commonOprModel('member')->getUserDynamicsData($uid);
            if(!isset($userDynamicsData['isLanding']) || $userDynamicsData['isLanding'] != 1){
                oo::commonOprRedis('Usercache')->zDelete(okeys::Landing("DYNAMICS", $uid),$uid);
                return false;
            }
//            $tb = otable::UserDynamicsData();
//            $sql= "UPDATE {$tb} SET ";
//            foreach ($userDynamicsData as $key=>$row){
//                if($key == "isLanding" || $key == "uid"){
//                    continue;
//                }
//                if($key == "userCache"){
//                    $row = json_encode((array)$row);
//                    $temp = addslashes($row);
//                    $sql .= "`$key`='$temp',";
//                }else{
//                    $sql .= "`$key`='$row',";
//                }
//            }
//            $sql = trim($sql,',');
//            $sql.= " WHERE uid={$uid} LIMIT 1";
//            $ret = oo::commonOprDb('common')->query($sql);
//            if($ret){
                oo::commonOprRedis('Usercache')->zDelete(okeys::Landing("DYNAMICS", $uid),$uid);
                oo::commonOprRedis('userinfo')->expire(okeys::UserDynamicsData($uid),oo::redisRandomExpire(86400*7));
//            }
        }else{
            $keys = okeys::LandingKeys("DYNAMICS");
            foreach($keys as $okey){
                $ret = oo::commonOprRedis('Usercache')->zRangeByScore($okey,0,$this->expire,['withscores'=>true]);
                foreach ($ret as $key=>$row){
                    if(!$key){
                        oo::commonOprRedis('Usercache')->zDelete($okey,$key);
                        continue;
                    }
                    self::dynamics($key,true);
                }
            }
        }
    }

    /**
     * 用户宠物数据
     * @param bool $uid
     * @param bool $recursive
     * @return bool
     * Created by: Owen
     * Created on: 2020/4/10 16:16
     */
    public function pet($uid = false,$recursive = false){
        if($uid != false){
            if(!$recursive){
                if(!oo::commonOprRedis('Usercache')->zScore(okeys::Landing("PET", $uid),$uid)){
                    return false;
                }
            }
            $userPetArr = oo::commonOprModel('pet')->getUserPet($uid,0,true);
            $tb = otable::UserPet($uid);
            $deleteFlag = false;
            foreach ($userPetArr as $row){
                if($row['isLanding'] == 1){
                    $sql= "UPDATE {$tb} SET ";
                    foreach ($row as $key=>$value){
                        if($key == "isLanding" || $key == "uid" || $key == "petId"){
                            continue;
                        }
                        $sql .= "`$key`='$value',";
                    }
                    $petId = $row['petId'];
                    $sql = trim($sql,',');
                    if(empty($petId)){
                        $deleteFlag = true;
                        continue;
                    }
                    $sql.= " WHERE uid={$uid} AND petId={$petId} LIMIT 1";
                    oo::commonOprDb('common')->query($sql);
                }
            }
            if($deleteFlag){
                oo::commonOprRedis('User')->delete(okeys::UserPet2($uid));
                oo::commonOprModel('pet')->getUserPet($uid);
            }
            oo::commonOprRedis('Usercache')->zDelete(okeys::Landing("PET", $uid),$uid);
            oo::commonOprRedis('userinfo')->expire(okeys::UserPet2($uid),oo::redisRandomExpire(86400*7));
        }else{
            $keys = okeys::LandingKeys("PET");
            foreach($keys as $okey){
                $ret = oo::commonOprRedis('Usercache')->zRangeByScore($okey,0,$this->expire,['withscores'=>true]);
                foreach ($ret as $key=>$row){
                    if(!$key){
                        oo::commonOprRedis('Usercache')->zDelete($okey,$key);
                        continue;
                    }
                    self::pet($key,true);
                }
            }
        }
    }

    /**
     * Notes:推金币用户游戏数据落地
     * User: wsc
     * Time: 2020/11/26 12:20
     * @param bool $uid
     * @param bool $recursive
     * @return bool
     */
    public function coindozer($uid = false,$recursive = false){
        if($uid != false){
            if(!$recursive){
                if(!oo::commonOprRedis('common')->zScore(okeys::Landing("COINDOZER_GAMEDATA"),$uid)){
                    return false;
                }
            }
            $key1 = okeys::userGameInfoCoinDozer($uid);
            $userGameInfo = oo::commonOprModel('coindozer')->getUserGameInfo($uid)['info'];
            $tb  = otable::usercoindozer();
            $data = $userGameInfo;
            $data['up_ts'] =time();
            unset($data['uid'],$data['create_ts']);
            $sql = funs::db_updateSQL($tb,$data," uid={$uid}");
            $ret = oo::commonOprDb('common')->query($sql);
            if($ret){
//                oo::commonOprRedis('usercache')->hMset($key1,$userGameInfo);
                oo::commonOprRedis('Usercache')->zDelete(okeys::Landing("COINDOZER_GAMEDATA"),$uid);
                oo::commonOprRedis('usercache')->expire($key1,oo::redisRandomExpire(86400*7));
            }
        }else{
            $ret = oo::commonOprRedis('Usercache')->zRangeByScore(okeys::Landing("COINDOZER_GAMEDATA"),0,$this->expire,['withscores'=>true]);
            foreach ($ret as $key=>$row){
                if(!$key){
                    oo::commonOprRedis('Usercache')->zDelete(okeys::Landing("COINDOZER_GAMEDATA"),$key);
                    continue;
                }
                self::coindozer($key,true);
            }
        }
    }
    /**
     * Notes:推金币用户游戏数据落地
     * User: wsc
     * Time: 2020/11/26 12:20
     * @param bool $uid
     * @param bool $recursive
     * @return bool
     */
    public function userStatistics($uid = false,$recursive = false){
        if($uid != false){
            if(!$recursive){
                if(!oo::commonOprRedis('common')->zScore(okeys::Landing("USERSTATISTICS"),$uid)){
                    return false;
                }
            }
            $userStatisticsInfo = oo::commonOprModel('statistics')->getUserStatistics($uid);
            $tb = otable::UserStatistics($uid);
            unset($userStatisticsInfo['uid']);
            oo::commonOprDb('common')->query(funs::db_updateSQL($tb,$userStatisticsInfo," uid={$uid}"));
            oo::commonOprRedis('Usercache')->zDelete(okeys::Landing("USERSTATISTICS"),$uid);
        }else{
            $ret = oo::commonOprRedis('Usercache')->zRangeByScore(okeys::Landing("USERSTATISTICS"),0,$this->expire,['withscores'=>true]);
            foreach ($ret as $key=>$row){
                if(!$key){
                    oo::commonOprRedis('Usercache')->zDelete(okeys::Landing("USERSTATISTICS"),$key);
                    continue;
                }
                self::userStatistics($key,true);
            }
        }
    }

    /**
     * Notes:好友数据落地
     * User: wsc
     * Time: 2022/2/25 21:14
     * @param bool $uid
     * @param bool $recursive
     * @return bool
     */
    public function userFriend($uid =false,$recursive=false){
        if($uid != false){
            if(!$recursive){
                if(!oo::commonOprRedis('Usercache')->zScore(okeys::Landing("USERFRIENDS", $uid),$uid)){
                    return false;
                }
            }
            $data =[];
            $fields = ["poker"=>"fb","nopoker"=>"nopoker","game_list"=>"game"];
            foreach ($fields as $k=>$type){
                $friendsStr = oo::commonOprRedis('userinfo')->get(okeys::userfriends($uid,$type));
                if(!$friendsStr){
                    continue;
                }
                $friendsList = json_decode($friendsStr,true);
                $data[$k] = is_array($friendsList)?implode(',',$friendsList):'';
            }
            $data['updatetime']=time();
            $w =" uid={$uid}";
            $sql = funs::db_updateSQL(otable::userfriends($uid),$data,$w);
            $ret = oo::commonOprDb('common')->query($sql);
            if($ret){
                oo::commonOprRedis('Usercache')->zDelete(okeys::Landing("USERFRIENDS", $uid),$uid);
                oo::commonOprRedis('user')->expire(okeys::userfriends($uid,$type),oo::redisRandomExpire(86400*7));
            }
        }else{
            $t = time() - 60;
            $keys = okeys::LandingKeys("USERFRIENDS");
            foreach($keys as $okey){
                $ret = oo::commonOprRedis('Usercache')->zRangeByScore($okey,0,$t,['withscores'=>true]);
                foreach ($ret as $key=>$row){
                    if(!$key){
                        oo::commonOprRedis('Usercache')->zDelete($okey, $key);
                        continue;
                    }
                    self::userFriend($key,true);
                }
            }
        }
    }
}
