<?php

defined('IN_WEB') or die('Include Error!');
/**
 * 好友召回活动相关逻辑
 */
class ModelCallback {
    public $rids=[
        ["id"=>1,"ext"=>"偷金币"],
        ["id"=>2,"ext"=>"攻打岛屿"],
        ["id"=>3,"ext"=>"消耗体力数量"],
        ["id"=>4,"ext"=>"签到"],
        ["id"=>5,"ext"=>"分享"],
        ["id"=>6,"ext"=>"fb邀请"],
        ["id"=>7,"ext"=>"召回分享"],
        ["id"=>8,"ext"=>"建造完成"],
        ["id"=>9,"ext"=>"赠送好友体力"],
        ["id"=>10,"ext"=>"赠送好友金币"],
        ["id"=>11,"ext"=>"赠送好友卡牌"],
        ["id"=>31,"ext"=>"好友绑定"],
        ["id"=>32,"ext"=>"好友签到"],
    ];
    const TASK_STEAL     = 1; //偷金币
    const TASK_ATTACK    = 2; //攻打岛屿
    const TASK_SPINS     = 3; //消耗体力数量
    const TASK_DAILYSIGN = 4; //签到
    const TASK_SHARE     = 5; //分享
    const TASK_INVITE    = 6; //fb邀请
    const TASK_CALLBACK  = 7; //召回分享
    const TASK_BUILD     = 8; //建造完成
    const TASK_SENDSPINS = 9; //赠送好友体力
    const TASK_SENDMONEY = 10; //赠送好友金币
    const TASK_SENDCard  = 11; //赠送好友卡牌

    const SCOREKEY = 'callback_score';
    const DEFAULTSCORE = 1;

    public function getTaskTypes() {
        return [
            self::TASK_STEAL,
            self::TASK_ATTACK,
            self::TASK_SPINS,
            self::TASK_DAILYSIGN,
            self::TASK_SHARE,
            self::TASK_INVITE,
            self::TASK_CALLBACK,
            self::TASK_BUILD,
            self::TASK_SENDSPINS,
            self::TASK_SENDMONEY,
            self::TASK_SENDCard,
        ];
    }

    /**
     * 获取当前激活的活动
     * @return array
     */
    public function getCurrentActivity($uid){
        return (array)oo::commonOprModel('activitynew')->getBindActivity($uid,self::SCOREKEY,true);
    }

    /**
     * 检查是否满足活动召回条件
     * @param int $uid
     * @param int $fid
     * @param array $conf
     * @return array
     */
    public function checkCanCallback($uid, $fid, $activity = [],$lastTime=0) {
        if($uid == $fid){ //不能召回自己
            return ['canCallback' => false];
        }
        if(empty($activity)){
            $activity = $this->getCurrentActivity($uid);
        }
        if(empty($activity)){
            return ['canCallback' => false];
        }

        //排序
        $extraData = !empty($activity['extraData'])?(array)json_decode($activity['extraData'],true):[];
        if(empty($extraData)){ //未配数据
            return ['canCallback' => false];
        }

        //玩家当前rfm分组
        $groupId = oo::commonOprModel('config')->getUserGroupIdByCid($fid, 2);
        if(!$lastTime){
            $lastTime = oo::commonOprModel('member')->getUserInfo($fid)['lasttime'];
        }

        $levelId = oo::commonOprModel('member')->getUserLevelId($fid);

        $canCallback = false;
        foreach($extraData as $v){

            //好友分组
            if(!empty($v['gid']) && !in_array(0, $v['gid'])){
                $gids = (array)$v['gid'];
                if(!in_array($groupId, $gids)){
                    continue;
                }
            }

            if(!isset($v['level'], $v['level']['start']) && $levelId < $v['level']['start']){
                continue;
            }
            if(!isset($v['level'], $v['level']['end']) && $levelId > $v['level']['end']){
                continue;
            }

            //不在线时间段
            if(!empty($v['lastDays'])){
                if(time() - $lastTime <24 * 3600 * (int)$v['lastDays']){
                    continue;
                }
            }
            $cid = $v['id'];//好友所在对象类id
            $canCallback = true;
            break;
        }

        return ['canCallback' => $canCallback, 'groupId' => $groupId, 'lasttime' => $lastTime, 'levelId' => $levelId,'cid'=>$cid];
    }

    /**
     * Notes:获取回归礼包列表
     * User: wsc
     * Time: 2021/3/24 16:57
     * @param $uid
     * @param $aid
     * @return array
     */
    public function getGift($uid,$aid){
        $giftListJson = oo::commonOprRedis('common')->hGetAll(okeys::callbackGift());
        $giftList = funs::getArrFromJsonArr($giftListJson);
        $groupId = oo::commonOprModel('config')->getUserGroupIdByCid($uid, 2);//用户付费分组
        $userBindInfo = oo::commonOprRedis('activity')->hGetAll(okeys::callbackBindUserInfo($aid,$uid));
        foreach ($giftList as $k=>$v){
            $ext=$v['ext'];
            if(!$ext['group']||in_array($groupId,$ext['group'])){//只赛选无分组条件,或 分组条件满足的礼包
                if($ext['isOnlyBack']==1&&!$userBindInfo['fid']){//赛选 设置为召回限制的礼包
                    continue;
                }
                $gift[] = $k;
            }
        }
        return $gift;
    }
    /////////////////////////////////////////////////////
    /////////////////////////////////////////////////////
    //固定积分+额外分组积分+签到分组奖励获取积分,召回者//
    //任务积分（被召回）
    //召回积分和被召回积分
    //回归奖励，分割奖励配置
    /////////////////////////////////////////////////////
    /////////////////////////////////////////////////////


    /**
     * 获取玩家当前可以召回的好友列表
     * @param $uid
     * @return array
     */
    public function getUserCallbackList($uid) {
        $activity = oo::commonOprModel('activitynew')->getBindActivity($uid, self::SCOREKEY, true);
        $friends = oo::commonOprModel('friend')->getUserAllFriend($uid);
        $aid = $activity['id'];
        //成功召回的好友
        $successIds = oo::commonOprRedis('activity')->hGetAll(okeys::activitySuccCallBackList($aid, $uid));
        $list = [];
        if(time()<$activity['reward_time']){//在领奖期之前才有完整列表返回
            foreach($friends as $fid){
                $checkInfo = $this->checkCanCallback($uid, $fid, $activity);
                if(!$checkInfo['canCallback']&&!isset($successIds[$fid])){//不满足被召回条件,且不是被召回的玩家
                    continue;
                }
                $fInfo = oo::commonOprModel('member')->getUserBasic($fid);
                $info = [
                    'uid' => $fInfo['uid'], 'nick' => $fInfo['nick'], 's_picture'=> $fInfo['s_picture'],'star'=>$fInfo['star']
                ];
                if(isset($successIds[$fid])){
                    $info['status'] = $successIds[$fid]; //0:已召回,1可领奖,2:已领奖
                    $info['score'] = oo::commonOprRedis('activity')->hGet(okeys::callbackBindUserCanGetList($aid,$uid),$fid);
                }else{
                    $info['status'] = 0; //可召回
                    $info['score'] = 0;
                }
                $list[] = $info;
            }
        }else{//只返回已找回或已领奖的用户
            if(!empty($successIds)){
                foreach ($successIds as $fid=>$v){
                    $fInfo = oo::commonOprModel('member')->getUserBasic($fid);
                    $info = [
                        'uid' => $fInfo['uid'], 'nick' => $fInfo['nick'], 's_picture'=> $fInfo['s_picture'],'star'=>$fInfo['star']
                    ];
                    $info['status'] = $successIds[$fid];
                    $info['score'] = oo::commonOprRedis('activity')->hGet(okeys::callbackBindUserCanGetList($aid,$uid),$fid);
                    $list[] = $info;
                }
            }
        }
        //活动附加信息-(任务天数,固定积分)
        $extra_reward = oo::commonOprModel('activitynew')->getActReward($activity['id'])['extra_reward'];

        //当前积分情况
        $scoreInfo = oo::commonOprRedis('activity')->hGetAll(okeys::actCallbackScore($aid,$uid));
        $returnTask = null;
        //被召回的人信息
        $userBindInfo = oo::commonOprRedis('activity')->hGetAll(okeys::callbackBindUserInfo($aid,$uid));
        //距离第一次绑定活动已经开始了多少天
        $curDay = !empty($userBindInfo['bindLastTime'])?(strtotime(date('Y-m-d',time()))-strtotime(date('Y-m-d',$userBindInfo['bingBackTime'])))/86400+1:0;

        if(isset($userBindInfo['bindCid'])&&$extra_reward['days']>=$curDay){//玩家是被召回者,且被召回天数小于任务天数时
            $returnTask =[
                'score'  => intval($scoreInfo[2]),
                'totalDay'  => $extra_reward['days'],
                'curDay' => $curDay>$extra_reward['days']?$extra_reward['days']:$curDay,
                'list'   => $this->getTaskList($uid,$activity),//任务列表
                'reward' => $this->getRateReward($uid,$aid,2),
                'fid'    =>intval($userBindInfo['bindFid']),
                'gidList'    =>$this->getGift($uid,$aid),
            ];
        }
        //基础配置
        return [
            //回归数据
            'returnTask' => $returnTask,
            //召回数据
            'recallTask' => [
                'list'       => $list,
                'score'      => intval($scoreInfo[1]),
                'reward' => $this->getRateReward($uid,$aid,1),
                'oneScore' =>$extra_reward['score'],
            ],
        ];
    }


    /**
     * 添加召回好友记录
     * @param int $uid
     * @param int $fid
     * @return array
     */
    public function callbackFriend($uid, $fid, $activity) {
        $aid = $activity['id'];
        $key = okeys::activityBeCallBackFriend($aid,$fid);
        if(oo::commonOprRedis('activity')->hGet($key, $uid)){
            return true;
        }
        oo::commonOprModel('callback')->doTask($uid, 7, 1);
//        $aid = $activity['id'];
        $expire = oo::redisRandomExpire($activity['end_time'] + 600);

        $friendInfo = oo::commonOprModel('member')->getUserInfo($fid);
        $lasttime= $friendInfo['lasttime'];
        //添加被召回记录,成功后,让玩家选择是哪个uid召回我的,并记录当时我的最后登录的时间(用于我被好友召回后取绑定对象配置用)
        oo::commonOprRedis('activity')->hSet($key,$uid,$lasttime);
        oo::commonOprRedis('activity')->expireAt($key, $expire);
        oo::commonOprModel('ta')->setEventData($fid,'recalled_user',['recalled_user'=>$uid]);
        return true;
    }

    /**
     * Notes:设置成功绑定信息
     * User: wsc
     * Time: 2021/3/17 10:45
     * @param $uid int 被召回人
     * @param $fid int 召回发起者
     * @param array $activity 活动信息
     * @return bool
     */
    public function setCallbackSuccess($uid, $fid, $activity = []) {
        $aid = $activity['id'];
        $expire = oo::redisRandomExpire($activity['end_time'] - time() + 600);
        $key = okeys::callbackBindUserInfo($aid,$uid);
        $key2 = okeys::activitySuccCallBackList($aid, $fid);
        $keys3 = okeys::callbackBindUserCanGetList($aid,$fid);

        $userBindInfo = oo::commonOprRedis('activity')->hGetAll($key);
        if($userBindInfo['bindFid']){
           return oo::response(errorCode::OVER_RECEIVE_REWARD,[],'已经领过奖');
        }

        $extra_reward = oo::commonOprModel('activitynew')->getActReward($aid)['extra_reward'];
        $cid = $userBindInfo['bindCid'];
        $groupInfo = $this->getUserCallBackGroupInfo($uid,$activity,$cid);

        //给自己绑定召回自己的人
        oo::commonOprRedis('activity')->hSet($key,'bindFid',$fid);

        //给自己发奖
        foreach ($groupInfo['reward'] as $prop){
            $ret = oo::commonOprModel('member')->sendReward($uid,$prop['propsId'],$prop['num'],222,"召回活动:{$aid}:{$cid}",$prop['value']);
        }

        //给邀请发起人绑定信息
        oo::commonOprRedis('activity')->hset($key2, $uid, 1);//领取状态(0:可召回,1:可领奖,2:已领取
        //给邀请发起人发uid的签到任务积分
        $score = 0;
        if($userBindInfo['bindSignDay']){//当uid已完成签到
            $groupInfo  =$this->getUserCallBackGroupInfo($uid,$activity,$userBindInfo['bindCid']);
            $signCfg = array_column($groupInfo['groupInfo']['sign'],null,'day');
            foreach ($signCfg as $day=>$info){
                if($day<=$userBindInfo['bindSignDay']&&$info['score']>0){
//                    $this->addScore($fid,$info['score'],$aid,1,'32',"{$uid}签到{$day}天,给{$fid}补发奖励:{$info['score']}积分");
                    $score += intval($info['score']);
                }
            }
        };
        //给邀请发起人发积分可领状态并记录值
        $score += intval($extra_reward['score']+$groupInfo['groupInfo']['extraScore']);
        oo::commonOprRedis('activity')->hSet($keys3,$uid,$score);//设置可领积分值
        $this->sendInform($fid,$aid,1);//发可领积分通知

        if(oo::commonOprRedis('activity')->hlen($key2) <= 1){
            oo::commonOprRedis('activity')->expire($key2, $expire);
            oo::commonOprRedis('activity')->expire($keys3, $expire);
        }
        return oo::response(errorCode::SUCCESS,$groupInfo['reward']);
    }

    /**
     * Notes:写回归记录
     * User: wsc
     * Time: 2021/3/19 11:58
     * @param $uid
     * @param $lastTime
     * @param $version
     */
    public function callBackLog($uid,$lastTime,$version){
        if(oo::compareVersion($version,'1.8.4')){
            $activity = $this->getCurrentActivity($uid);
            if(!empty($activity)&&$lastTime<$activity['reward_time']){
                $key = okeys::callbackBindUserInfo($activity['id'],$uid);
                $check = $this->checkCanCallback(1,$uid,$activity,$lastTime);
                if(intval($check['cid'])<1){
                    return false;
                }
                $bindInfo = ['bindCid'=>$check['cid'],'bindLastTime'=>$lastTime,'bingBackTime'=>time()];
                oo::commonOprRedis('activity')->hMset($key,$bindInfo);
                $expire = oo::redisRandomExpire($activity['end_time'] - time());
                oo::commonOprRedis('activity')->expire($key,$expire);
                return $activity['id'];
            }
        }
        return false;
    }
    /**
     * Notes:被召回者获取召回对象组信息
     * User: wsc
     * Time: 2021/3/17 10:00
     * @param $uid
     * @param $activity
     * @param int $cid 被召回者所在对象组
     * @return array
     */
    public function getUserCallBackGroupInfo($uid,$activity,$cid=1){
        $data = $props = [];
        $rewardInfo =json_decode($activity['reward_pro'],true);
        $rewardInfo = array_column($rewardInfo,null,'stage');
        $reward =$rewardInfo[1];
        $lv = oo::commonOprModel('member')->getUserLevel($uid)['levelId'];
        $bet =oo::commonOprModel('activitynew')->getCoinRewardByTypeAndLevel('collect',$lv);
        foreach ($reward['prize'] as $prize){
            $props[] = oo::commonOprModel('activitynew')->getFormattingProps($uid,$activity['id'],$prize,$bet);
        }
        $data['reward'] = $props;//对象组对应的奖励信息

        $gScoreInfo = json_decode($activity['extraData'],true);
        $gScoreInfo = array_column($gScoreInfo,null,'id');
        $data['groupInfo'] =$gScoreInfo[$cid]?$gScoreInfo[$cid]:$gScoreInfo[1];//对象组配置信息
        return $data;
    }

    /**
     * Notes:获取任务列表
     * User: wsc
     * Time: 2021/3/17 20:54
     * @param $uid
     * @param $activity
     * @return array
     */
    public function getTaskList($uid,$activity){
        $data =[];
        $tmp = isset($activity['reward_conf']) ? array_values((array)json_decode($activity['reward_conf'],true)) : [];
        $userTaskInfo = oo::commonOprRedis('activity')->hGetAll(okeys::callbackUserTaskInfo($activity['id'],$uid));
        $overList = !empty($userTaskInfo['overReceive'])?json_decode($userTaskInfo['overReceive'],true):[];
        foreach ($tmp as $k=>$v){
            $data[$k]['id'] = $v['id'];
            $data[$k]['type'] = $v['type'];
            $data[$k]['score'] = $v['score'];
            $data[$k]['maxLimit'] = $v['num'];
            $data[$k]['limit'] = intval($userTaskInfo[$v['type']]);
            $data[$k]['status'] = in_array($v['type'],$overList)?2:(isset($userTaskInfo["score_{$v['type']}"])?1:0);
        }
        $data = array_values($data);
        return $data;
    }

    /**
     * Notes:添加积分
     * User: wsc
     * Time: 2021/3/17 11:16
     * @param $uid
     * @param $score int 积分
     * @param $aid int 活动id
     * @param int $type 积分类型 1作为召回者积分 2作为被召回者积分
     * @return int
     */
    public function addScore($uid,$score,$aid,$type=1,$rid='',$ext=''){
        $score = abs(intval($score));
        $key = okeys::actCallbackScore($aid, $uid);
        $count = oo::commonOprRedis('activity')->hIncrBy($key,$type,$score);
        //活动积分流水
        $stype =$type==1?'call_score':'be_call_score';
        oo::commonOprModel('currency')->actlog($aid,$uid,$stype,'+',$score,$count,$rid,$ext);
        return $count;
    }

    /**
     * Notes:积分领取通知
     * User: wsc
     * Time: 2021/3/19 15:00
     * @param $uid
     * @param $aid
     * @param $type
     */
    public function sendInform($uid,$aid,$type){
        //是否满足领取积分通知
        $data =[
            "actId"  =>oo::commonOprModel('activitynew')->act_type['callback_score']['rcid'],
            "aid"    =>$aid,
            "type"   =>$type,
        ];
        oo::commonOprModel('Workerman')->push($uid,ocmd::$send['ActivityFlush'],$data); //推送可领积分
    }
    /**
     * Notes:领取好友绑定积分
     * User: wsc
     * Time: 2021/3/17 11:35
     * @param $uid
     * @param $fid
     * @return string
     */
    public function receiveBindScore($uid,$fid){
        $aid = oo::commonOprModel('activitynew')->activityLock($uid,'callback_score');
        if(!$aid){
            return oo::response(errorCode::NOT_FOUND_ACTIVITY,[],'活动不存在');
        }
        $key = okeys::callbackBindUserCanGetList($aid,$uid);
        $key2 = okeys::activitySuccCallBackList($aid, $uid);
        $score = intval(oo::commonOprRedis('activity')->hGet($key,$fid));
        if($score<1){
            return oo::response(errorCode::NONE_REWARD,[],'没有可领取的积分');
        }
        if(intval(oo::commonOprRedis('activity')->hGet($key2,$fid))==2){
            return oo::response(errorCode::OVER_RECEIVE_REWARD,[],'已经领取过领取的积分');
        }
        oo::commonOprRedis('activity')->hset($key2, $fid, 2);//标记好友奖励积分已领取
        oo::commonOprRedis('activity')->hSet($key,$fid,0);//清空可领积分
        $count = $this->addScore($uid,$score,$aid,1,31,"好友{$fid}绑定奖励");
        return oo::response(1,["score"=>$count]);
    }

    /**
     * Notes:领取任务积分
     * User: wsc
     * Time: 2021/3/17 17:33
     * @param $uid
     * @param $tid
     * @return string
     */
    public function receiveTaskScore($uid,$id){
        $actInfo= $this->getCurrentActivity($uid);
        $aid =$actInfo['id'];
        if(!$aid){
            return oo::response(errorCode::NOT_FOUND_ACTIVITY,[],'活动不存在');
        }
        $reward_conf = json_decode($actInfo['reward_conf'],1);
        $taskCfg = array_column($reward_conf,null,'id');
        $tid = $taskCfg[$id]['type'];;
        $key = okeys::callbackUserTaskInfo($aid,$uid);
        $score = oo::commonOprRedis('activity')->hGet($key,"score_{$tid}");
        if($score<1){
            return oo::response(errorCode::NONE_REWARD,[],'没有积分可领取');
        }
        $overReceiveJSon = oo::commonOprRedis('activity')->hGet($key,'overReceive');
        $overReceiveList = $overReceiveJSon?json_decode($overReceiveJSon,1):[];
        if(in_array($tid,$overReceiveList)){//已经领取过
            return oo::response(errorCode::OVER_RECEIVE_REWARD,[],'已经领取');
        }
        //发放积分
        $count = $this->addScore($uid,$score,$aid,2,$tid,"任务:{$tid}");
        //写领取记录
        array_push($overReceiveList,$tid);
        oo::commonOprRedis('activity')->hSet($key,'overReceive',json_encode($overReceiveList));
        return oo::response(1,["score"=>$count]);
    }


    /**
     * Notes:做任务
     * User: wsc
     * Time: 2021/3/17 15:23
     * @param $uid
     * @param $tid
     * @return bool
     */
    public function doTask($uid,$tid,$num=1){
        $aid = oo::commonOprModel('activitynew')->activityLock($uid,'callback_score');
        if(!$aid){
            return false;
        }
        if(oo::commonOprRedis('activity')->hGet(okeys::callbackUserTaskInfo($aid,$uid),"score_{$tid}")){//该任务存在可领取的积分
            return false;
        }

        $key = okeys::callbackBindUserInfo($aid,$uid);
        $userBindInfo = oo::commonOprRedis('activity')->hGetAll($key);
        if(!isset($userBindInfo['bindCid'])){//作为判断回归条件
            return false;
        }
        $actInfo =  oo::commonOprModel('activitynew')->getActivity($aid);

        $extra_reward = oo::commonOprModel('activitynew')->getActReward($aid)['extra_reward'];
        $thisDay = !empty($userBindInfo['bindLastTime'])?(strtotime(date('Y-m-d',time()))-strtotime(date('Y-m-d',$userBindInfo['bingBackTime'])))/86400+1:0;
        if($thisDay>$extra_reward['days']){//已用完可以任务的天数

            return false;
        }

        if($tid==4){//给邀请者发签到积分
            $day = intval($userBindInfo['bindSignDay'])+1;
            oo::commonOprRedis('activity')->hSet($key,'bindSignDay',$day);//设置签到累计日期
            $fid = $userBindInfo['bindFid'];
            $groupInfo  =$this->getUserCallBackGroupInfo($uid,$actInfo,$userBindInfo['bindCid']);
            $signCfg = array_column($groupInfo['groupInfo']['sign'],null,'day');
            if(isset($signCfg[$day])&&$signCfg[$day]['score']>0&&$fid){//配置日有签到奖励积分,则发起人加可积分可领
//                $this->addScore($fid,$signCfg[$day]['score'],$aid,1,'32',"{$uid}签到{$day}天,给{$fid}奖励:{$signCfg[$day]['score']}积分");
                oo::commonOprRedis('activity')->hIncrBy(okeys::callbackBindUserCanGetList($aid,$fid),$uid,$signCfg[$day]['score']);
                oo::commonOprRedis('activity')->hset(okeys::activitySuccCallBackList($aid, $fid), $uid, 1);//设置为可领取状态
                $this->sendInform($fid,$aid,1);//发可领积分通知
            }
        }

        $key2 = okeys::callbackUserTaskInfo($aid,$uid);
        $reward_conf = json_decode($actInfo['reward_conf'],1);
        $taskCfg = array_column($reward_conf,null,'type');
        if($num>$taskCfg[$tid]['num']){
            $num = $taskCfg[$tid]['num'];
        }
        $count = oo::commonOprRedis('activity')->hIncrBy($key2,$tid,$num);//累计完成次数
        if($count>=$taskCfg[$tid]['num']){//达到领取积分条件
            oo::commonOprRedis('activity')->hSet($key2,"score_{$tid}",$taskCfg[$tid]['score']);//写任务积分可领缓存
            $this->sendInform($uid,$aid,2);//发可领积分通知
        }
        if(oo::commonOprRedis('activity')->ttl($key2)<0){//未设置过期则设置到凌晨过期
            oo::commonOprRedis('activity')->expire($key2,oo::todayDeadline());
        }
        return true;
    }


    /**
     * Notes:获取阶段进度奖励
     * User: wsc
     * Time: 2021/3/17 15:55
     * @param $uid
     * @param $aid
     * @param int $utype
     * @return array
     */
    public function getRateReward($uid,$aid,$utype=1){
        $datas =[];
        $type = 'callback_score';
        $rewardInfo =oo::commonOprModel('activitynew')->getActReward($aid)['reward'];
        $overNum =oo::commonOprRedis('activity')->hGetAll(okeys::actCallbackScore($aid, $uid))[$utype];
        $lv = oo::commonOprModel('member')->getUserLevel($uid)['levelId'];
        $bet =oo::commonOprModel('activitynew')->getCoinRewardByTypeAndLevel($type,$lv);
        if($utype==2){
            $reward = $rewardInfo['becallback'];
            $key2 = okeys::actBeCallbackReward($aid,$uid);
        }else{
            $reward = $rewardInfo['callback'];
            $key2 = okeys::actCallbackReward($aid,$uid);
        }
        foreach ($reward as $k=>$v){
            $data['stage'] =$v['stage'];
            $data['stepnum'] = intval($v['stepnum']);
            $data['props'] = [];
            foreach ($v['prize'] as $val){
                $data['props'][] = oo::commonOprModel('activitynew')->getFormattingProps($uid,$aid,$val,$bet);
            }
            $data['status'] =0;
            if($overNum>=$data['stepnum']){
                $data['status'] =1;
            }
            $stage_status = intval(oo::commonOprRedis('activity')->hGet($key2,$data['stage']));
            if($stage_status>0){
                $data['status'] =2;
            }
            $datas[] = $data;
        }
        return $datas;
    }

    /**
     * Notes:领取进度阶段奖励
     * User: wsc
     * Time: 2021/3/17 15:55
     * @param $uid
     * @param $aid
     * @param $type
     * @param $stage
     * @param int $utype
     * @return string
     */
    public function receiveRateReward($uid,$stage,$utype=1){
        $type = 'callback_score';
        $data = [];
        $aid = oo::commonOprModel('activitynew')->activityLock($uid,$type);
        if(!$aid){
            return oo::response(errorCode::NOT_FOUND_ACTIVITY,$data,"活动不存在");
        }

        $rewardInfo = $this->getRateReward($uid,$aid,$utype);
        $reward = array_column($rewardInfo,null,'stage');
        if(empty($reward[$stage])){
            return oo::response(errorCode::CONDITION_NOT_RNOUGH,$data,"没有可领取的奖励");
        }
        if($reward[$stage]['status']==2){
            return oo::response(errorCode::OVER_RECEIVE_REWARD,$data,"已领过该阶段奖励");
        }
        if($reward[$stage]['status']!=1){
            return oo::response(errorCode::CONDITION_NOT_RNOUGH,$data,"未达领奖条件");
        }

        if($utype==2){
            $key = okeys::actBeCallbackReward($aid,$uid);
            $rid = 224;
        }else{
            $key = okeys::actCallbackReward($aid,$uid);
            $rid = 223;
        }

        foreach ($reward[$stage]['props'] as $k=>$v){
            $result = oo::commonOprModel('member')->sendReward($uid,$v['propsId'],$v['num'],$rid,"活动:{$type}:{$aid}：".$stage,$v['value'],$v);
            $reward[$stage]['props'][$k]['value'] = $result;
        }
        oo::commonOprRedis('activity')->hSet($key,$stage,time());
        $data = $reward[$stage]['props'];
        return oo::response(errorCode::SUCCESS,$data);
    }

    public function clearUserCache($uid,$aid,$doFid=0){

        $key[0] = okeys::activitySuccCallBackList($aid, $uid);//uid成功召回的用户列表情况0已找回2领奖
        $key[1] = okeys::callbackBindUserCanGetList($aid,$uid);//被uid召回的fid列表及待领取积分
        $key[]  = okeys::actCallbackReward($aid,$uid);//uid领取阶段奖励记录

        $key[]  = okeys::actBeCallbackReward($aid,$uid);//uid作为fid领取阶段奖励记录
        $key[]  = okeys::actCallbackScore($aid, $uid);//uid的积分情况 1作为uid的积分 2作为fid的积分

        $key[] = okeys::activityBeCallBackFriend($aid,$uid);
        $key[] = okeys::callbackBindUserInfo($aid,$uid);
        $key[] =  okeys::callbackUserTaskInfo($aid,$uid);

        if($doFid){
            $fids = oo::commonOprRedis('activity')->hGetAll($key[1]);//被uid召回的所有fid 及状态
            foreach ($fids as $fid=>$status){
                $key[] = okeys::activityBeCallBackFriend($aid,$fid);//fid绑定的 召回fid的uid列表 及fid的最后登录时间
                $key[] = okeys::callbackBindUserInfo($aid,$fid);//fid绑定的uid及自己所在对象组id信息

                $key[] = okeys::callbackUserTaskInfo($aid,$fid);//fid的任务详情
                $key[] = okeys::actBeCallbackReward($aid,$fid);//fid的阶段奖励领取记录
                $key[] = okeys::actCallbackScore($aid, $fid);//fid的积分情况,1作为uid的积分 2作为fid的积分
            }
        }
        oo::commonOprRedis('activity')->delete($key);
    }
}
