<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Customer extends MY_Controller{
    public function __construct()
    {
        parent::__construct();
    }
    function souchUserAccount($uid = '', $mac = ''){
        $data =[];
        $tb = otable::userinfo();
        $mac = urldecode($mac);
        $data['uid'] = $uid;
        $data['mac'] = $mac;
        $where = ' where 1 ';

        if($uid)$where .= ' and uid='.intval($uid);
        if($mac)$where .= "  and mac='{$mac}' ";
        if($uid || $mac){
            $sql = "Select * from {$tb} {$where}";
            $data["list"] = oo::commonOprDb('slavedb')->getAll($sql,1);
        }
        $this->load->view('customer/userAccount', $data);
    }
    //===========好友操作==============
    public function souchFriend($uid = 0){
        $data =[];
        if($uid>0){
            $data['uid'] =$uid;
            $arr = ["game"=>"游戏内好友","fb"=>"fb好友","nopoker_new"=>"fb已解除好友关系(游戏内不展示)"];
            foreach ($arr as $k=>$item){
                $flistArr = oo::commonOprModel('friend')->getUserAllFriend($uid,$k);
                $list[$item]  = json_encode($flistArr,32);
            }
            $data['list'] = $list;
        }
        $this->load->view('customer/souchFriend', $data);
    }
    public function addFriendApi(){
        $postData = $this->input->post();
        if(!$postData['uid']||!$postData['toUid']||$postData['toUid']==$postData['uid']){
            return $this->response(0, '参数不合法');
        }
        $this->addFriend($postData['uid'],$postData['toUid']);
        $this->addFriend($postData['toUid'],$postData['uid']);


        return $this->response(0, '添加成功',["uid"=>$postData["uid"]]);
    }
    public function addFriend($uid,$toUid){
        //建立好友关系缓存
        $key = okeys::userfriends($uid,"game");
        $gameFriendList =oo::commonOprModel('friend')->getUserAllFriend($uid,"game");
        array_push($gameFriendList,$toUid);
        $gameFriendList =is_array($gameFriendList)?$gameFriendList:[];
        $gameFriendList = array_unique($gameFriendList);
        $gamsFriendStr = json_encode($gameFriendList,32);
        oo::commonOprRedis('games')->setex($key,$gamsFriendStr,86400*7);
        //清理过滤好友关系
        $key2 = okeys::userfriends($uid,"nopoker_new");
        $dFriendList =oo::commonOprModel('friend')->getUserAllFriend($uid,"nopoker_new");
        if(in_array($toUid,$dFriendList)){
            if(array_search($toUid,$dFriendList)!==false){
                unset($dFriendList[array_search($toUid,$dFriendList)]);
            }
            $dFriendList=array_values($dFriendList);
            $dFriendStr = json_encode($dFriendList,32);
            oo::commonOprRedis('games')->setex($key2,$dFriendStr,86400*7);
        }
        //设置落地标识
        $key3 =okeys::Landing("USERFRIENDS",$uid);
        oo::commonOprRedis('games')->zAdd($key3,time(),$uid);
    }
    public function delFriendApi(){
        $postData = $this->input->post();
        if(!$postData['uid']||!$postData['toUid']||$postData['toUid']==$postData['uid']){
            return $this->response(0, '参数不合法');
        }
        $this->delFriend($postData['uid'],$postData['toUid']);
        $this->delFriend($postData['toUid'],$postData['uid']);


        return $this->response(0, '添加成功',["uid"=>$postData["uid"]]);
    }
    public function delFriend($uid,$toUid){
        //解除好友关系
        foreach (["game","fb"] as $type){
            $key2 = okeys::userfriends($uid,$type);
            $dFriendList =oo::commonOprModel('friend')->getUserAllFriend($uid,$type);
            if(in_array($toUid,$dFriendList)){
                if(array_search($toUid,$dFriendList)!==false){
                    unset($dFriendList[array_search($toUid,$dFriendList)]);
                }
                $dFriendList=array_values($dFriendList);
                $dFriendStr = json_encode($dFriendList,32);
                oo::commonOprRedis('games')->setex($key2,$dFriendStr,86400*7);
                if($type=="fb"){
                    $key = okeys::userfriends($uid,"nopoker_new");
//                    $gflist = oo::commonOprRedis('games')->get($key);
                    $gameFriendList =oo::commonOprModel('friend')->getUserAllFriend($uid,"nopoker_new");
                    $gameFriendList =is_array($gameFriendList)?$gameFriendList:[];
                    array_push($gameFriendList,$toUid);
                    $gameFriendList = array_unique($gameFriendList);
                    $gamsFriendStr = json_encode($gameFriendList,32);
                    oo::commonOprRedis('games')->setex($key,$gamsFriendStr,86400*7);
                }
            }
        }

        //设置落地标识
        $key3 =okeys::Landing("USERFRIENDS",$uid);
        oo::commonOprRedis('games')->zAdd($key3,time(),$uid);
    }
    //==========活动查询===========
    //锦标赛信息
    public function userActRank($uid=0){
        $data =[];
        if($uid>0){
            $data['uid'] =$uid;
            $aid = oo::commonOprRedis('games')->get(okeys::userBindActivity("rank",$uid));
            if($aid>0){
                $data['userActInfo'] = [
                    "aid"=>$aid,
                    "group"=>oo::commonOprRedis('games')->get(okeys::userBindStageGroup($aid,$uid)),
                    "attrInfo"=>json_encode(oo::commonOprRedis('games')->hGetAll(okeys::activityBindUserAttr($uid,$aid))),
                    "stageInfo"=>json_encode(oo::commonOprRedis('games')->hGetAll(okeys::userActStageRate($uid,$aid)))
                ];
            }
            $now = time();
            $tb = otable::activityConf();
            $sql = "SELECT * FROM {$tb} where type='rank' AND end_time>$now and start_time<=$now limit 6";
            $actList = oo::commonOprDb('slavedb')->getAll($sql,1);
            foreach ($actList as $item){

                $roomId = oo::commonOprRedis('games')->hGet(okeys::userRankRoomIdList($item['id']),$uid);//房间
                $key = okeys::activityUserRankList($aid,$roomId);
                $ranking  = intval(oo::commonOprRedis('games')->zRevRank($key,$uid))+1;//排名
                $score=  intval(oo::commonOprRedis('games')->zScore($key,$uid));//分数
                $wrlist = oo::commonOprRedis('games')->hGetAll(okeys::awardRankEndReward($uid,"rank"));//待领取记录
                $one =[
                    "uid"=>$uid,
                    "aid"=>$item['id'],
                    "ranking"=>$roomId?$ranking:0,
                    "rankNum"=>$score,
                    "isreward"=>in_array($item['id'],array_keys($wrlist))?"待领取":($roomId?"可能已领取":"尚未获得积分"),
                    "etime"=>0,
                    "stage"=>1,
                ];
                if(in_array($item['id'],array_keys($wrlist))){
                    $one["etime"] = $wrlist[$item['id']];
                }
                $data['list'][] = $one;
            }

        }
        $this->load->view('customer/actRank', $data);
    }
    //体力大师信息
    public function userActSpinsMaster($uid=0){
        $data =[];
        if($uid>0) {
            $data['uid'] = $uid;
            $aid = oo::commonOprRedis('games')->get(okeys::userBindActivity("spins_master", $uid));
            if ($aid > 0) {
                $data['userActInfo'] = [
                    "aid" => $aid,
                    "group" => oo::commonOprRedis('games')->get(okeys::userBindStageGroup($aid, $uid)),
                    "attrInfo" => json_encode(oo::commonOprRedis('games')->hGetAll(okeys::activityBindUserAttr($uid, $aid))),
                    "score" => json_encode(oo::commonOprRedis('games')->get(okeys::userSpinsMasterScore($aid,$uid)))
                ];
                $data["list"] = oo::commonOprRedis('games')->hGetAll(okeys::userSpinsMasterReceiveLog($aid,$uid));//领取记录
            }
        }
        $this->load->view('customer/actSpinsMaster', $data);
    }
    //收集信息
    public function userActSuperCollect($uid=0){
        $data =[];
        if($uid>0) {
            $data['uid'] = $uid;
            $aid = oo::commonOprRedis('games')->get(okeys::userBindActivity("super_collect", $uid));
            if ($aid > 0) {
                $data['userActInfo'] = [
                    "aid" => $aid,
                    "group" => oo::commonOprRedis('games')->get(okeys::userBindStageGroup($aid, $uid)),
                    "attrInfo" => json_encode(oo::commonOprRedis('games')->hGetAll(okeys::activityBindUserAttr($uid, $aid))),
                    "stageInfo" => json_encode(oo::commonOprRedis('games')->hGetAll(okeys::userActStageRate($uid, $aid)))
                ];
            }
        }
        $this->load->view('customer/actCollect', $data);
    }
    //俱乐部锦标赛信息
    public function userActClubRank(){
        echo "<h1>敬请期待</h1>";
    }
    //通行证信息
    public function userActGamePass($uid = 0)
    {
        $data = [];
        if ($uid > 0) {
            $data['uid'] = $uid;
            $aid = oo::commonOprRedis('games')->get(okeys::userBindActivity(TRAFFIC_PERMIT, $uid));
            if ($aid > 0) {
                $data['userActInfo'] = oo::commonOprRedis('games')->hGetAll(okeys::GamePassInfo($aid, $uid));
            }
            $passInfo = $this->findPassRewardConfByLvRange($uid, $aid) ?? [];
            if ($passInfo) {
                $levelConf = $passInfo['levels'] ?? [];

                $list = array_column($levelConf, "max", "levelId");

                $userExp = $data['userActInfo']["exp"];
                $maxLv = max(array_keys($list));
                $maxExp = $list[$maxLv];

                $thisLv = 0;
                $thisLvExp = 0;

                // 超过配置的最大经验值
                if ($userExp > $maxExp) {
                    $thisLv = $maxLv + floor(($userExp - $maxExp) / $passInfo['basic']['maxLevelExpGap']);
                    $thisLvExp = ($userExp - $maxExp) % $passInfo['basic']['maxLevelExpGap'];
                } else {
                    foreach ($levelConf as $row) {
                        if ($row['max'] > $userExp) {
                            break;
                        }
                        $thisLv = $row['levelId'];
                        $thisLvExp = $userExp - $row['max'];
                    }
                }

                $data['userActInfo']['thisLv'] = $thisLv;
                $data['userActInfo']['thisLvExp'] = $thisLvExp;
            }
        }
        $this->load->view('customer/actGamePass', $data);
    }

    // 通过等级范围获取通行证奖励
    public function findPassRewardConfByLvRange($uid, $aid)
    {
        $stage = oo::commonOprRedis('games')->get(okeys::activityUserStageKey($uid, $aid));
        $reward_conf = oo::commonOprRedis('games')->hget(okeys::activityInfo($aid), 'reward_pro');
        $reward_conf = json_decode($reward_conf ?: "[]", true);
        return $reward_conf[$stage] ?? [];
    }
    //=========奖励邮件发放============
    // 获取历史发送记录
    public function sendUserGameMailIndex($page = 0){
//        var_dump(get_cookie('username'));
//        var_dump($_COOKIE);

        $data = [];
        $data['page'] = $page;
        $limitStr = " limit $page, 20";
        $tb2 = otable::gmSendUserMsgLog();
        $sql= "Select * from {$tb2} order by id desc {$limitStr}";
        $data['list'] = oo::commonOprDb('statistics')->getAll($sql,1);

        //获取总数
        $totalSql = " SELECT COUNT(*) AS t FROM {$tb2}";
        $totalRet = oo::commonOprDb('slavedb')->getOne($totalSql, MYSQLI_ASSOC);
        $data['total'] = (int)$totalRet['t'];


        //分页
        $pageConfig = $this->pageConfig;
        $pageConfig['base_url'] = base_url('#Customer/sendUserGameMailIndex');
        $pageConfig['total_rows'] = $data['total'];
        $pageConfig['per_page'] = $this->page;
        $this->pagination->initialize($pageConfig);
        $pageurl = $this->pagination->create_links();
        $data['pageurl'] = $pageurl;

        $this->load->view('customer/userMsg', $data);
    }
    //发放奖励
    public function sendGameMailReward(){
        $postData = $this->input->post();
        $uids = explode(',',$postData['uids']);
        $msgId = $postData['mid'];
        $rewards = $postData['rewards'];
        if(empty($uids)||!is_array($uids)){
            return $this->response(1, '添加失败,uid 异常',$postData);
        }
        if(empty($msgId)){
            return $this->response(1, '添加失败,模板id不为空',$postData);
        }
        if(empty($rewards)||!is_array($rewards)){
            return $this->response(1, '添加失败,奖励异常异常',['reward'=>$rewards]);
        }
        foreach ($uids as $uid){
            $tb = otable::userSysMail($uid);
            $key = okeys::sysMsgGet($uid);
            $rewardNew = [];
            foreach ($rewards as $k=>$v){
                //go fox 结构体
                $one = [
                    "propsId"=>$v['propsId'],
                    "num"=>$v['num'],
                    "jokerCardExpireTime"=>0,
                    "cards"=>null,
                    "chestProps"=>null,
                    "skinResourceId"=>0,
                    "skin"=>intval($v['skin']),
                ];
                if($v["propsId"]==19){
                    $one["skin"] = $v['skin'];
                    //通过skin 获取皮肤资源id
                    $conf = oo::commonOprModel('config')->getChestSkinConfig($v['skin']);
                    $one["skinResourceId"] = $conf['skinResourceId']>0?$conf['skinResourceId']:$one["skin"];
                }
                array_push($rewardNew,$one);
            }
            $data = [
                "uid"=>$uid,
                "msgid"=>$msgId,
                "got"=>0,
                "rewards"=>json_encode($rewardNew),
                "expire"=>time()+86400*3,
                "create_time"=>time(),
            ];
            $sql = funs::db_insertSQL($tb,$data);
            $ret = oo::commonOprDb('games')->query($sql,1);
            if($ret){
                $eid = oo::commonOprDb('games')->insertID();
                $data['id'] = $eid;
                $data['rewards'] = json_decode($data['rewards'],true);
                $field = "{$msgId}_{$eid}";
                oo::commonOprRedis('games')->hSet($key,$field,json_encode($data));
                oo::commonOprRedis('games')->expire($key,time()+86400*16);
            }else{
                return $this->response(0, '添加失败',["ret"=>$ret]);
            }
        }
        $insertLog = [
            "uids"=>$postData['uids'],
            "mid"=>$msgId,
            "rewards"=>json_encode($rewards,32),
            "optuser"=>get_cookie('username'),
            "creat_ts"=>time()
        ];
        $tb2 = otable::gmSendUserMsgLog();
        $sql2 = funs::db_insertSQL($tb2,$insertLog);
        oo::commonOprDb('statistics')->query($sql2,1);

        return $this->response(1, '添加成功',["uid"=>$postData["uid"]]);
    }
    //========宠物激活===========
    public function getUserPet($uid,$petId = 0,$orig = false){
        $cacheKey = okeys::UserPet2($uid);
        $userPetArr = oo::commonOprRedis('games')->hGetAll($cacheKey);
        if(empty($userPetArr)){
            $tb         = otable::UserPet($uid);
            $userPetArr = oo::commonOprDb('games')->getAll("SELECT * FROM {$tb} WHERE uid={$uid}", MYSQLI_ASSOC);
            if(!empty($userPetArr)){
                oo::commonOprRedis('games')->expire($cacheKey,oo::redisRandomExpire(7*24*60*60));
            }
        }else{
            $userPetArr = array_values($userPetArr);
            foreach ($userPetArr as $key=>$row){
                $userPetArr[$key] = json_decode($row,true);
                if($petId&&$petId==$row['petId']){
                    $petId2 = $userPetArr[$key];
                }
            }
        }
        if($petId2){
            $userPetArr = $petId2;
        }else if($petId){
            $userPetArr = [];
        }
//        echo "<pre>";
//        print_r($userPetArr);
        return $userPetArr;
    }

    public function showUserPet($uid=0){
        $data =[];
        $data['pet'] = ["1"=>"偷宠物","2"=>"盾牌宠物(游戏内位置3)","3"=>"攻击宠物(游戏内位置2)"];
        if($uid>0){
            $data['list'] =[];
            $data['uid'] = $uid;
            $list = $this->getUserPet($uid);
            $arr =  array_column($list,null,'petId');
            foreach ($data['pet'] as $pid=>$item){
                $one = [
                    "status"=>isset($arr[$pid])?1:0,
                    "showName"=>$item,
                    "petId"=>$pid,
                    "lv"=>isset($arr[$pid])?$arr[$pid]["lv"]:0
                ];
                array_push($data['list'],$one);
            }
        }
//        var_dump($data);
        $this->load->view('customer/petShow', $data);
    }
    public function openUserPet(){
        $postData = $this->input->post();
        $uid = $postData['uid'];
        $petId = intval($postData['pid']);
        if($uid<1||!in_array($petId,[1,2,3])){
            return $this->response(-1, '激活失败，uid 或宠物id 异常');
        }
//        return $this->response(1, '激活成功',$postData);
        $petInfo = $this->getUserPet($uid,$petId);
        if($petInfo){
            return oo::response(-1,[],"已经激活过:{$petId}");
        }
        $tb  = otable::UserPet($uid);
        $time = time();
        oo::commonOprDb('games')->query("INSERT INTO {$tb} (uid,petId,nick,getTime,star) VALUES ('{$uid}','{$petId}','pet','{$time}',-1)", false);
        $userPet = oo::commonOprDb('games')->getOne("SELECT * FROM {$tb} WHERE uid={$uid} AND petId={$petId} LIMIT 1", MYSQLI_ASSOC);
        oo::commonOprRedis('games')->hSet(okeys::UserPet2($uid),$petId,json_encode($userPet));

        return $this->response(0, '激活成功',$postData);
    }

}