<?php

/**
 * 活动相关
 */
class ModelActivity
{
    protected $config;//活动配置
    protected $config_new;
    protected $_updateGameVersion_1 = '1.8.1.0';//版本升级活动 --安卓
    protected $_updateGameVersion_2 = '1.8.1.0';//版本升级活动 --IOS
    private $_url_android = 'https://play.google.com/store/apps/details?id=';
    private $_url_ios =  'https://itunes.apple.com/us/app/%E0%B9%84%E0%B8%9E-%E0%B9%80%E0%B8%97-%E0%B8%81%E0%B8%8B-%E0%B8%AA%E0%B8%8B-%E0%B9%80%E0%B8%9B%E0%B8%AD%E0%B8%A3/id1267293867?l=zh&ls=1&mt=8';
    private $_fb_weburl = 'https://www.facebook.com/superpoker.th';
    private $_fb_appurl = 'fb://page/152314908675395';
    private $_activity_title_file = WWWROOT . 'lang/lang.activity.php';//活动标题文件
    private $_activity_bname_file = WWWROOT . 'lang/lang.activity_btnname.php';//活动按钮文件
    private $_activity_img_file = WWWROOT . 'lang/lang.activity_img.php';//活动图片文件
    private $_activity_config_file = [];//活动配置文件

    private $_firstchargeGids = [12, 19, 44, 185, 320];//首冲商品id
    private $_channelSalePercent = 100;//按渠道打折的百分比
    private $_channelSaleList = [1,3,2,4,5,6,7,18,19];//打折的渠道

    private $_playpokerAid = 2;//玩牌得筹码活动ID
    private $_totalpayAid = 17;//累计充值
    private $_playOmahaAid = 9;//奥马哈活动ID
    private $_shakeActAid = 21;//摇一摇活动ID
    private $_channelSaleAid = 12;//买一送一活动
    private $_vipActAid = 19;//vip加送天数活动

    public function __construct(){}



    /**
     * 返回活动title列表
     * @return mixed
     */
    public function getActivityTitleList()
    {
        include_once  $this->_activity_title_file;
        $aConfigLangActivity = $activityLang ?? [];
        return $aConfigLangActivity;
    }

    /**
     * 返回活动t图片列表
     * @return mixed
     */
    public function getActivityImgList()
    {
        include_once  $this->_activity_img_file;
        $aConfigLangActivity = $activityLang ?? [];
        return $aConfigLangActivity;
    }
    /**
     * 返回活动按钮列表
     * @return mixed
     */
    public function getActivityBnameList()
    {
        include_once $this->_activity_bname_file ;
        $aConfigLangActivity = $activityLang ?? [];
        return $aConfigLangActivity;
    }

    /**
     * 设置活动标题的配置文件
     * @param array $titleConfig
     * @return bool
     */
    public function setActivityTitle($titleConfig = [])
    {
        $file = $this->_activity_title_file;
        if(file_exists($file)) {
            include_once  $file;
            $titleList = $activityLang ?? [];
        }else {
            $titleList = [];
        }

        if(empty($titleConfig)) {
            return false;
        }

        if(empty($titleList)) {
            $titleStr = '<?php 
            $activityLang = '.var_export($titleConfig, true).';';
            $num = file_put_contents($file, $titleStr);
        }else {
            foreach ($titleConfig as $k => $v) {
                $titleList[$k] = array_merge($titleList[$k] ?? [], $v);
            }
            $titleStr = '<?php 
            $activityLang = '.var_export($titleList, true).';';
            $num = file_put_contents($file, $titleStr);
        }
        return $num > 0 ? true : false;
    }


    /**
     * 设置活动标题的配置文件
     * @param array $titleConfig
     * @return bool
     */
    public function setActivityImg($imgConfig = [])
    {
        $file = $this->_activity_img_file;
        if(file_exists($file)) {
            include_once  $file;
            $imgList = $activityLang ?? [];
        }else {
            $imgList = [];
        }

        if(empty($imgConfig)) {
            return false;
        }

        if(empty($imgList)) {
            $imgStr = '<?php 
            $activityLang = '.var_export($imgConfig, true).';';
            $num = file_put_contents($file, $imgStr);
        }else {
            foreach ($imgConfig as $k => $v) {
                $imgList[$k] = array_merge($imgList[$k] ?? [], $v);
            }
            $imgStr = '<?php 
            $activityLang = '.var_export($imgList, true).';';
            $num = file_put_contents($file, $imgStr);
        }
        return $num > 0 ? true : false;
    }

    /**
     * 设置活动按钮的配置文件
     * @param array $titleConfig
     * @return bool
     */
    public function setActivityBname($bnameConfig = [])
    {
        $file = $this->_activity_bname_file;
        if(file_exists($file)) {
            include_once  $file;
            $bnameList = $activityLang ?? [];
        }else {
            $bnameList = [];
        }

        if(empty($bnameConfig)) {
            return false;
        }
        if(empty($bnameList)) {
            $bnameStr = '<?php 
            $activityLang = '.var_export($bnameConfig, true).';';
            $num = file_put_contents($file, $bnameStr);
        }else {
            foreach ($bnameConfig as $k => $v) {
                $bnameList[$k] = array_merge($bnameList[$k] ?? [], $v);
            }
            $bnameStr = '<?php 
            $activityLang = '.var_export($bnameList, true).';';
            $num = file_put_contents($file, $bnameStr);
        }
        return $num > 0 ? true : false;
    }

    /**
     * 针对活动做特殊处理
     * @param $config
     */
    private function dealConfig(&$config)
    {
        $id = $config['id'];
        //如果是摇一摇活动，加版本控制
        if($id == 6) {
            $config['version_1'] = '1.1.2.0';//版本判断 android 该版本是否上该活动
            $config['version_2'] = '1.1.1.0';//版本判断 ios 该版本是否上该活动
        }
        //如果是添加邀请码
        if($id == 10) {
            $config['shareonce'] = array('money' => 200);//分享一次
            $config['invitesuc'] = array('money' => 5000);//每成功邀请1个人
        }
        return $config;
    }

    /**
     * 设置活动的配置文件
     * @param array $newConfig
     * @param $flag 1 --新增  其他 --修改
     * @return bool
     */
    public function setActivityConfig($newConfig = [], $flag = 1)
    {
        $file = $this->_activity_config_file;
        if(file_exists($file)) {
            include $file;
            $configList = $config_activity ?? [];
            $max_id = $max_id ?? 0;
        }else {
            $configList = [];
            $max_id = 0;
        }

        if(empty($newConfig)) {
            return false;
        }
        $id = $newConfig['id'] ?? 0;
        if($id < 1) {
            return false;
        }
        $this->dealConfig($newConfig);//针对活动做特殊处理
        if($flag == 1) {//如果是增加活动配置
            if($id <= $max_id) {//max_id 在配置文件配置
                return false;
            }
            array_push($configList, $newConfig);
            $configStr = '<?php 
                $max_id = '.$id.';';
        }else {//如果是修改活动
            if($id > $max_id) {
                return false;
            }
            foreach ($configList as $k => &$v) {
                if($v['id'] === $newConfig['id']) {
                    $v = $newConfig;
                }
            }
            $configStr = '<?php
            $max_id = '.$max_id.';';
        }

        $configStr .= '
        $config_activity = '.var_export($configList, true).';
        return $config_activity;
        ';
        $num = file_put_contents($file, $configStr);

        return $num > 0 ? true : false;
    }

    /**
     * 对某些活动做特殊处理
     * @param $info
     * @return mixed
     */
    private function dealActivityList(&$info, $uid = 0)
    {
        //判断跳转类型是否是，是则添加跳转链接
        $deviceid = $sid=1;
        switch ($info['goto']){
            case 3:
                $info['url'] = $deviceid == 1 ? $this->_url_android : $this->_url_ios;
                break;
            case 15:
                $info['webUrl'] = $this->_fb_weburl;
                $info['appUrl'] = $this->_fb_appurl;
                break;
        }

        //购买商品的活动, 如果payType为官方支付, 则需要根据玩家的设备跳转到不同的官方支付渠道
        if (in_array($info['payType'], [999]) ) {
            $info['payType'] = $deviceid == 1 ? 1 : 3;
        }

        //如果是世界杯活动，版本小于1.6.0，则跳去商店更新。大于则跳到世界杯活动界面
        switch ($info['id']) {
//            case 6://如果是宋干节活动，版本小于1.5.0版，则加上去更新的按钮,否则不显示去更新按钮
//                oo::version()->ge('1.5.0') && $info['actType'] = 0;
//                break;
            case 8://如果是我是冠军活动、奥马哈、邀请码,IOS 小于1.2.2.0版的不显示按钮
            case 10:
            $deviceid == 2 && oo::version()->lt('1.2.2.0') && $info['actType'] = 0;//是否有按钮 1有 0没有
                break;
            case 16://如果是安卓，并且版本小于1.6.0.0，则把跳转链接跳到更新版本
                if(oo::version()->lt('1.6.0.0')) {
                    $info['goto'] = 3;
                    $info['url'] = $deviceid == 1 ? $this->_url_android : $this->_url_ios;
                }
                break;
            case 18://FB点赞
                if($sid == 19 || $sid == 20){
                    if(oo::version()->lt('1.6.4.0')){
                        $info['goto'] = 3;
                        $info['url'] = $this->_fb_weburl;
                    }
                }elseif(oo::version()->lt('1.6.3.0')){
                    $info['goto'] = 3;
                    $info['url'] = $this->_fb_weburl;
                }
                break;
            case $this->_playpokerAid://是玩牌活动
//                $this->dealPlayPoker($info, $uid);
                break;
            case $this->_totalpayAid://累计充值活动
                $this->dealTotalPay($info, $uid);
                break;
            case $this->_playOmahaAid://奥马哈玩牌活动
//                $this->dealOmaha($info, $uid);
                break;
            case $this->_shakeActAid://摇一摇活动
                break;
        }
        return $info;
    }

    /**
     * 獲取盲注對應的快速場
     * @return array
     */
    public function getQuickGameBlindLevel()
    {
        $info = oo::commonOprModel('online')->getGameLevel();
        $texasTableList = oo::commonOprModel('robot')->getTexasTableList();
        $data = [];
        foreach ($info as $level=>$blind){
            if(!in_array($level, $texasTableList)){
                continue;
            }
            $data[$blind] = $level;
        }
        return $data;
    }

    /**
     * 出来玩牌活动
     * @param $info
     * @param $uid
     * @return bool
     */
    public function dealPlayPoker(&$info, $uid)
    {
        if(oo::version()->lt('1.6.2.0')){
            return false;
        }
        $tmpContent = [];
        $tmpContent['contentType'] = 1;
        $tmpContent['title'] = $info['title'];
        $tmpContent['time'] = date('Y.m.d',strtotime($info['stime'])).'-'.date('Y.m.d',strtotime($info['etime']));
        $tmpContent['isChooseDateHour'] = $info['isChooseDateHour'];
        $tmpContent['blind'] = current($info['blindList']);
        $rewardList = [];
        //对应盲注对应的level
        $blindLevelList = $this->getQuickGameBlindLevel();
        $timeNow = date('H:i', time());
        if($info['stimeHour'] == '00:00' && $info['etimeHour'] == '00:00'){
            $online = 1;
        }else{
            $online = ($timeNow >= $info['stimeHour'] && $timeNow <= $info['etimeHour']) ? 1 : 0;
        }

        rsort($info['blindList']);
        foreach ($info['blindList'] as $blind){
            if(is_array($info['reward'][$blind])) {
                foreach ($info['reward'][$blind] as $k => $v){
                    $v['playNum'] = $k;
                    $v['blind'] = $blind;
                    $lang = 'en';
                    if($lang == 'tw' || $lang == 'zh'){
                        $stimeHour = $info['stimeHour'];
                        $etimeHour = $info['etimeHour'];
                        $stimeHourDate = date('Y-m-d').' '.$stimeHour;
                        $etimeHourDate = date('Y-m-d').' '.$etimeHour;
                        $v['time'] = date('H:i', strtotime("+1 hour $stimeHourDate")).'-'.date('H:i', strtotime("+1 hour $etimeHourDate"));
                    }else{
                        $v['time'] = $info['stimeHour'].'-'.$info['etimeHour'];
                    }

                    if($info['stimeHour'] == '00:00' && $info['etimeHour'] == '00:00'){
                        $v['time'] = '00:00-24:00';
                    }

                    $stimeHour = $info['stimeHour'];
                    $etimeHour = $info['etimeHour'];
                    $stimeHourDate = date('Y-m-d').' '.$stimeHour;
                    $etimeHourDate = date('Y-m-d').' '.$etimeHour;
                    $v['startTime'] = strtotime($stimeHourDate);
                    $v['endTime'] = strtotime($etimeHourDate);
                    $v['online'] = $online;
                    $v['gameId'] = 1;
                    $v['gameLevel'] = $blindLevelList[$blind] ?? 0;
                    $rewardList[] = $v;
                }
            }

        }

        $tmpContent['list'] = $rewardList;
        $info['content'] = $tmpContent;
        PRODUCTION_SERVER  && $info['img'] = 'en/5b4f33b651542_415.jpg';
        return true;
    }


    /**
     * 处理累计充值
     * @param $info
     * @param $uid
     * @return bool
     */
    public function dealTotalPay(&$info, $uid)
    {
        if(oo::version()->lt('1.6.2.0')){
            return false;
        }
        $tmpContent = [];
        $tmpContent['contentType'] = 2;
        $tmpContent['title'] = $info['title'];
        $tmpContent['time'] = date('Y.m.d',strtotime($info['stime'])).'-'.date('Y.m.d',strtotime($info['etime']));
        $tmpContent['curCount'] = $this->getTotalPay($uid, 2);
        $tmpContent['currency'] = 'USD';
        include_once COM_CFG.'config.totalpay.php';
        $tmpContent['list'] = $totalPayConfig ?? [];
        $info['content'] = $tmpContent;
        PRODUCTION_SERVER  && $info['img'] = 'en/5b505176a8896_84.jpg';
        return true;
    }

    /**
     * 获取玩牌活动配置
     * @return array|int
     */
    public function playPokerConfig($blind, $flag=1)
    {
        $data = ['online'=>0, 'rewardArr'=>[], 'dayTime' => '', 'hourTime' => '' ,'countDown'=>0];

        //是否在活动期间
        $checkExpire = $this->checkExpire($this->_playpokerAid);
        if(!$checkExpire || empty($blind)) {
            return $data;
        }
        $info = $this->config[$this->_playpokerAid - 1];
        if(!isset($info['id']) || $info['id'] != $this->_playpokerAid){//是否是玩牌活动
            return $data;
        }

        $now = time();
        if($info['isChooseDateHour'] && ($info['stimeHour'] != '00:00' || $info['etimeHour'] != '00:00')){//说明设置了玩牌时间段，则要判断当前时间是否在该时间段
            $today = date('Y-m-d');
            $stimeHourTmp = $info['stimeHour'];
            $etimeHourTmp = $info['etimeHour'];

            $stimedate = $today.'  '.$stimeHourTmp.':00' ;
            $etimedate = $today.'  '.$etimeHourTmp.':59';

            $stimeTmp = strtotime("$stimedate ");
            $etimeTmp = strtotime("$etimedate ");

            if($now < $stimeTmp || $now > $etimeTmp) {
                return $data;
            }
        }

        //当前盲注是否有该活动
        $blindList = $info['blindList'] ?? [];
        if(!empty($blindList) && !in_array(999, $blindList) && !in_array($blind, $blindList)){//活动盲注不空，且当前盲注不在配置盲注中，则该活动不在线上,且不是针对所有盲注(999表示所有盲注)
            return $data;
        }

        //配置
        $rwdConfig = $info['reward'][$blind] ?? [];
        $data = [];
        if($flag == 2){
            $data = $rwdConfig;
        }else {
            $num = 0;
            foreach ($rwdConfig as $k => $rwd){
                $data[$num]['playNum'] = $k;
                foreach ($rwd as $key=>$val) {
                    $data[$num][$key] = $val;
                }
                $num++;
            }
        }

        $hourTime = '';
        $etimeHour = '23:59';
        if($info['isChooseDateHour']) {//如果按时间段配置
            $hourTime = $info['stimeHour'].'-'.$info['etimeHour'];
            $etimeHour = $info['etimeHour'];
        }

        //获取倒计时
        $endHour = strtotime(date('Y-m-d ', $now).' '.$etimeHour.':59');
        $countDown = $endHour <= $now ? 0 : $endHour - $now;
        $online = $countDown ? 1 : 0;
        return ['online'=> $online, 'rewardArr'=>$data, 'dayTime' => date('Y.m.d', strtotime($info['stime'])).'-'. date('Y.m.d', strtotime($info['etime'])), 'hourTime' =>$hourTime, 'countDown'=>$countDown];
    }

//    /**
//     *	中级场记录打牌
//     */
//    public function recordPlay_midLevel($uid = 0)
//    {
//        foreach ($this->config as $info) {
//            if( $info['online'] == 0 ||  $info['id'] != 5){
//                continue;
//            }
//            $stime = strtotime($info['stime']);
//            $etime = strtotime($info['etime']);
//            $now = time();
//            $key = okeys::actMidLevelRecordPlaying($uid);
//            $expire = strtotime('23:59:59');
//
//            if( $now >= $stime && $now <= $etime ){//必须在活动期间
//                $playIngNum = oo::commonOprRedis('common')->incr($key);
//                oo::commonOprRedis('common')->expireAt($key, $expire);
//
//                //查看是否有大转盘优惠
//                if( isset($info['bigwheel']) ){
//                    $bigwheelNum = array_keys($info['bigwheel']);//大转盘每次加免费次数的局数
//                    $bigwheelNum = reset($bigwheelNum);
//                    $bigwheelTimes = reset($info['bigwheel']);//每次减的次数
//                    if( $playIngNum % $bigwheelNum == 0 ){
//                        $cacheKey = okeys::bigwheel($uid);
//                        $usedTimes = (int)oo::commonOprRedis('userinfo')->get($cacheKey);
//                        if( $usedTimes > 0 ){
//                            --$usedTimes;
//                            oo::commonOprRedis('userinfo')->setex($cacheKey, $usedTimes,7*86400);
//                        }
//                    }
//                }
//
//                $rewardArr = $info['reward'];//奖励
//                $rewardNum = array_keys($rewardArr);
//                if( !in_array($playIngNum, $rewardNum) ){//没有达到预期的牌局数
//                    //oo::logs()->debug3(array('uid' => $uid, 'playIngNum' => $playIngNum, '$rewardNum' => $rewardNum, 'time' => time()), 'Activity_playingReward.log');
//                    continue;
//                }
//
//                $reward = $rewardArr[$playIngNum];
//                if( $reward ){
//                    $msg = oo::getLang('activity_news_1');
//                    $msg = str_replace('@', $playIngNum, $msg);
//                    $msg = str_replace('+', $reward['diamond'], $msg);
//                    $rwd['diamonds'] = $reward['diamond'];
//                    oo::commonOprModel('usernews')->setUserMsg($uid, $msg, 2, 1, $rwd, 1, 2004, 'recordPlayDiamond', [$playIngNum, $reward['diamond']]);
//                    oo::logs()->debug3(array('uid' => $uid, 'playIngNum' => $playIngNum, 'reward' => $reward, 'time' => time()), 'Activity_playingReward.log');
//                    //记录事件
//                    oo::commonOprModel('statistics')->event(array($uid, 1023));
//                }
//            }
//        }
//    }


    /**
     * 按渠道打折活动加钱
     * @param $gchannel
     * @param $baseRwd
     * @param $baseTempRwd
     * @param $uid
     * @param $gid
     * @return bool
     */
    public function channelSaleActivityRwd($gchannel, &$baseRwd, $baseTempRwd, $uid, $gid)
    {
        if(!in_array($gchannel, $this->_channelSaleList)){
            return false;
        }
        $aid = $this->_channelSaleAid;//活动id
        //检查是否在活动期间
        $expire = $this->checkExpire($aid);
        if(!$expire) {
            return false;
        }

        $money = $baseTempRwd['money'] ?? 0;
        $money = $money * $this->_channelSalePercent/100;
        $baseRwd['money'] += $money;
        oo::logs()->debug3(array('uid'=>$uid, 'gid' => $gid, 'extraMoney' => $money, 'totalMoney' => json_encode($baseRwd)),'activityChannelSaleExtraReward.log');
        return true;

    }



    /**
     * 检测是否是折扣商品
     * @param $gid
     */
    public function checkDiscountGoods($gid)
    {
//        if(!in_array($gid, $this->_discountgoodsGids)) {
//            return false;
//        }
        //如果该商品id属于首冲商品，则没有折扣
        if(in_array($gid, $this->_firstchargeGids)) {
            return false;
        }
        //如果是除了筹码外的钻石、道具之类的没有折扣
        $goodsInfo = oo::commonOprModel('goods')->getGoodsInfoByGid($gid);
        $goodsType = intval($goodsInfo['gtype']) ?? 0;
        if($goodsType !== 1) {
            return false;
        }

        return true;
    }

    /**
     * 登录时是否弹窗活动弹窗
     * @return int
     */
//    public function isShowActivity()
//    {
//        //活动弹窗状态
//        $keys = okeys::showactivity();
//        $showActivity = oo::commonOprRedis('common')->get($keys);
//        if($showActivity > 0) {//如果设置活动弹窗弹出,则判断活动列表是否为空
//            $data= $this->getList([]);
//            $list = $data['list'] ?? [];
//            if(empty($list)) {
//                return 0;
//            }else {
//                return 1;
//            }
//        }else {
//            return 0;
//        }
//    }

    /**
     * 统一输出返回json内容
     *
     * @access public
     * @date   2016-08-16
     * @param int    $ret  状态码,0成功
     * @param string $msg  错误信息
     * @param array  $data 返回数据内容
     * @return json;
     */
    public function response($ret = 0, $msg = '', array $data = array())
    {
        $result = [
            'ret'  => $ret,
            'msg'  => $msg,
            'data' => $data,
        ];

        die(json_encode($result));
    }

    /**
     * 概率计算
     * @param $proArr
     * @return int|string
     */
    public   function get_rand($proArr) {
        $result = '';
        //概率数组的总概率精度
        $proSum = array_sum($proArr);
        //概率数组循环
        foreach ($proArr as $key => $proCur) {
            $randNum = mt_rand(1, $proSum);
            if ($randNum <= $proCur) {
                $result = $key;
                break;
            } else {
                $proSum -= $proCur;
            }
        }
        unset ($proArr);
        return $result;
    }


//    /**
//     * 邀请码活动发奖
//     * @param $fatherid
//     */
//    public function inviteCode($fatherid, $uid)
//    {
//        $activity = oo::commonOprModel('activity')->checkExpire(10);
//        if ($activity) {
//            $news = oo::getLang('activity_desc_10');
//            $num = 1;
//            $actRew = ['diamonds'=>$num];
//            oo::commonOprModel('usernews')->setUserMsg($fatherid, $news, 2, 1, $actRew, 1, 2005, 'inviteDiamond', [$num]);
//            //记录事件
//            oo::commonOprModel('statistics')->event(array($uid, 1108));
//        }
//        return true;
//
//    }

    /**
     *   检查活动是否过期,并返回活动配置
     *   @param 活动ID
     */
    public function checkExpire($aid)
    {
        if (!$this->config) {
            return false;
        }

        $activity = array();
        foreach ($this->config as $info) {
            if ($info['id'] == $aid) {
                $activity = $info;
                break;
            }
        }
        if (empty($activity)) {
            return false;
        }

        //判断是否过期
        $online = $activity['online'];
        $stime = strtotime($activity['stime']);
        $etime = strtotime($activity['etime']);
        $now = time();
        if ($now < $stime || $now > $etime || $online != 1) {
            return false;
        }
        //判断该活动是否上线
        if(!$this->checkActivityPackage($aid)) {
            return false;
        }
        return $activity;
    }

    /**
     * 判断该活动是否上线
     * @param $id
     * @return bool
     */
    public function checkActivityPackage($id)
    {
        $key = okeys::activityonlinepackage($id);
        $data = oo::commonOprRedis('common')->get($key);
        $packageList = json_decode($data, 1);
        if(empty($packageList) || !in_array(1, $packageList)) {
            return false;
        }
        return true;
    }

    /**
     * 累计用户充值金额
     * @param $uid
     * @param $price
     * @param $priceThb
     * @param $channel
     * @return int
     */
    public function recordTotalPay($uid, $price, $priceThb, $channel)
    {
//        if(PRODUCTION_SERVER && !in_array($uid, $this->_whiteList)){
//            return false;
//        }
        if(empty($uid) || empty($price) || empty($priceThb) || empty($channel)) {
            return -1;
        }
        //是否在活动期间
        $checkExpire = $this->checkExpire($this->_totalpayAid);
        if(!$checkExpire){//不在活动期间
            return -2;
        }
//        if(!in_array($channel, [1,2,3,4,5,6,7,8])){//渠道
//            return -3;
//        }
        $key = okeys::recordtotalpayact($uid);
        $ret = json_decode(oo::commonOprRedis('common')->get($key), 1);
        $ret['price'] += $price;//美金
        $ret['priceThb'] += $priceThb;//本地
        oo::commonOprRedis('common')->set($key, json_encode($ret));//记录充值累计
        $keyMayRwd = okeys::mayrwdtotalpay();
        oo::commonOprRedis('common')->sAdd($keyMayRwd, $uid);//记录充过值可能领累计充值的用户
        oo::logs()->nodatedebug('uid:'.$uid.' price:'.$price.' priceThb:'.$priceThb.'  channel:'.$channel, 'recordTotalPay.php');
        return 1;
    }



    /**
     * 获取累计充值金额
     * @param $uid
     * @param $flag 1泰铢 2美元
     * @return int
     */
    public function getTotalPay($uid, $flag = 1)
    {
        if(empty($uid)) {
            return 0;
        }
        //是否在活动期间
        $checkExpire = $this->checkExpire($this->_totalpayAid);
        if(!$checkExpire){//不在活动期间
            return 0;
        }

        $key = okeys::recordtotalpayact($uid);
        $ret = json_decode(oo::commonOprRedis('common')->get($key), 1);
        if($flag == 2){
            $price = $ret['price'] ?? 0;
        }else {
            $price = $ret['priceThb'] ?? 0;
        }
        return floatval($price);
    }

    /**
     * 累計充值領獎
     * @param $now
     * @return bool
     */
    public function rwdTotalPay($now)
    {
        $info = $this->config[$this->_totalpayAid - 1];
        if(!isset($info['id']) || $info['id'] != $this->_totalpayAid ){
            oo::logs()->debug3('累計充值活動ID不正確', 'rwdTotalPayFail.php');
            return -1;
        }
        //判断该活动是否上线
        if(!$this->checkActivityPackage($this->_totalpayAid)) {
            oo::logs()->debug3('在该包不上线', 'rwdTotalPayFail.php');
            return -3;
        }

        //判断时间是否在活动结束后的第二天
        $etime = $info['etime'];
        $date = date('Y-m-d', strtotime("$etime +1 day"));
        $dateToday = date('Y-m-d', $now);
        if($date != $dateToday){//如果没到领奖时间
            oo::logs()->debug3('累計充值時間還沒到', 'rwdTotalPayFail.php');
            return -2;
        }

        $totalPayConfig = include_once COM_CFG."config.totalpay.php";
        if(!is_array($totalPayConfig)){
            oo::logs()->debug3('配置不正確', 'rwdTotalPayFail.php');
            return -3;
        }
        $rwdConfig = [];
        $rwdChipsList = [];
        foreach ($totalPayConfig as $val){
            $rwdConfig[$val['count']] = $val;
            $rwdChipsList[] = $val['count'];
        }
        rsort($rwdChipsList);//对奖励倒序排列
        if(empty($rwdChipsList) || !is_array($rwdChipsList)){
            oo::logs()->debug3('金額配置不正確', 'rwdTotalPayFail.php');
            return -4;
        }

        //获取可能能领累计充值奖励的用户
        $mayRwdKey = okeys::mayrwdtotalpay();
        $uidList = oo::commonOprRedis('common')->sMembers($mayRwdKey);
        oo::logs()->nodatedebug('可能領累計充值獎勵的uid列表:'.json_encode($uidList), 'rwdTotalPayUid.php');
        foreach ($uidList as $uid) {
            $key = okeys::recordtotalpayact($uid);
            $ret = json_decode(oo::commonOprRedis('common')->get($key), 1);
            $priceThb = intval($ret['price'] ?? 0);
            $checkRwd = $this->checkRwd($priceThb, $rwdChipsList);
            if($checkRwd){//如果能领奖,去发奖。不能则删除
                oo::logs()->nodatedebug('能領獎的uid：'.$uid.' priceThb:'.$priceThb.' checkRwd:'.$checkRwd, 'canRwdTotalPay.php');
                $this->toRwd($uid, $checkRwd, $rwdConfig);
            }else{
                oo::logs()->nodatedebug('不能領獎的uid：'.$uid.' priceThb:'.$priceThb.' checkRwd:'.$checkRwd, 'cannotRwdTotalPay.php');
            }
            oo::commonOprRedis('common')->delete($key);
        }
        oo::commonOprRedis('common')->delete($mayRwdKey);
        return true;
    }


    /**
     * 检测是否能领奖
     * @param $price  --充值的金额
     * @param $rwdChipsList  --按数值倒序
     * @return bool
     */
    public function checkRwd($price, $rwdChipsList)
    {
        foreach ($rwdChipsList as $rwd){
            if($price >= $rwd){
                return $rwd;
            }
        }
        return false;
    }

    /**
     * 累計充值領獎
     * @param $uid
     * @param $price
     * @param $rwdConfig
     * @return bool
     */
    public function toRwd($uid, $price, $rwdConfig)
    {
//        if(PRODUCTION_SERVER && !in_array($uid, $this->_whiteList)){
//            return false;
//        }
        $rwdList = $rwdConfig[$price] ?? [];
        if(empty($rwdList)){
            oo::logs()->nodatedebug('累計充值領獎失敗:配置為空 uid:'.$uid.'  price:'.$price.'  rwdConfig:'.json_encode($rwdConfig), 'totalPayRwdFail.php');
            return false;
        }

        $data = [];
        $replaceList = [$price];
        foreach ($rwdList as $key => $val){
            switch ($key){
                case 'chips':
                    $data['money'] = $val;
                    $replaceList[] = $val;
                    continue;
                case  'diamonds':
                    $data['diamonds'] = $val;
                    $replaceList[] = $val;
                    continue;
                case 'vipType':
                    //如果是vip，先判断用户是否是vip用户。是则加vip用户的VIP等级
                    $vipLevel = oo::commonOprModel('vip')->checkVip($uid);
                    $vipLevel <= 0 &&  $vipLevel = $val;
                    $ret = oo::commonOprModel('vip')->addVip($uid, $vipLevel, $rwdList['days']);
                    $ret = json_decode($ret, 1);
                    if($ret['code'] == 1){//如果加vip成功，则默认发系统消息给用户
                        $msg = '';
                        oo::commonOprModel('usernews')->setUserMsg($uid, $msg, 1, 1, [], 1, '', 'act_totalpay_vip',[ ]);
                    }else {//失败则记录
                        oo::logs()->nodatedebug('加VIP失敗 uid:'.$uid.' viplevel:'.$vipLevel.' days:'.$rwdList['days'], 'totalPayRwdFail.php');
                    }
                    continue;
            }
        }

        if(!empty($data)){//發送領獎消息
            $rwdMsg = '';
            if(count($replaceList) > 2){//如果有鑽石贈送
                $msgRet = oo::commonOprModel('usernews')->setUserMsg($uid, $rwdMsg, 2, 1, $data, 1, 1123, 'activity_totalpay_2', $replaceList);
            }else {
                $msgRet = oo::commonOprModel('usernews')->setUserMsg($uid, $rwdMsg, 2, 1, $data, 1, 1123, 'activity_totalpay_1', $replaceList);
            }
            oo::logs()->nodatedebug('uid:'.$uid.' rwd:'.json_encode($data).' msgId:'.json_encode($msgRet), 'totalPayRwdSuccess.php');
        }
        return true;
    }


    /**
     * 获取打折的百分比
     * @return int
     */
    public function channelSaleInfo($uid=0)
    {
        $checkExpire = $this->checkExpire($this->_channelSaleAid);
        if(!$checkExpire){
            return [];
        }

        $data['percent'] = $this->_channelSalePercent;
        $data['channelList']  = $this->_channelSaleList;
        $data['countdown'] = strtotime($checkExpire['etime']) - time();//倒计时
        return $data;
    }


    public function sendUserMsg($uid)
    {
        if(oo::version()->lt('1.5.0')){
            return false;
        }
        $checkExpire = $this->checkExpire($this->_shakeActAid);
        if(!$checkExpire){
            return false;
        }
        $msg = 'Happy Chinese Valentine\'s day, pick up your  phone and shake it. Click on the gift to surprise you.';
        $ret = oo::commonOprModel('usernews')->setUserMsg($uid, $msg,  1, 1, [], 1, '', 'act_shake_firstIn_msg',  []);
        return true;
    }


    /**
     * vip充值活动
     * @param $uid
     * @param $type
     * @return bool
     */
    public function vipActivity($uid, $type)
    {
        $checkExpire = $this->checkExpire($this->_vipActAid);
        $period = 8;
        if(!$checkExpire){
            return 0;
        }

        $ret = oo::commonOprModel('vip')->addVip($uid, $type, $period);
        oo::logs()->debug3('activity vip: uid:'.$uid.' type:'.$type.' period:'.$period.' ret:'.json_encode($ret), 'vipActivity.php');
        $ret = json_decode($ret, 1);
        if($ret['code'] === 1){
            return $period;
        }
        return 0;
    }

    public function getSymbol($uid){
        if(!$this->activityLock($uid,2,true)){
            return false;
        }
        $temp = oo::commonOprRedis('common')->hGet(okeys::ActivityData(),2);
        $temp = json_decode($temp,true);
        switch (intval($temp['activityType'])){
            case 4:
                $type = 4;
                break;
            default:
                $type = 0;
                break;
        }
        $configKey = okeys::SymbolConfig($type,2);
        $stage = intval(oo::commonOprRedis('common')->hGet(okeys::SymbolStage(),$uid))+1;
        $baseCoins  = 1;
        $rewardType = intval(oo::commonOprRedis('common')->hGet($configKey,$stage."#type"));
        if($rewardType == 1){
            $assetsInfo = oo::commonOprModel('member')->getUserAssetsInfo($uid);
            $baseCoins  = oo::commonOprModel('config')->getActivityCoins($assetsInfo['levelId'],"collect");
        }
        return [
            'stage' =>$stage,
            'num'   =>intval(oo::commonOprRedis('common')->hGet(okeys::SymbolNum(),$uid)),
            'maxNum'=>intval(oo::commonOprRedis('common')->hGet($configKey,$stage)),
            'type'  =>$rewardType,
            'reward'=>intval(oo::commonOprRedis('common')->hGet($configKey,$stage."#reward")) * $baseCoins
        ];
    }

    /**
     * 收集活动
     * @param $uid
     * @param $num
     * @param int $from 1老虎机，2偷，3打
     * @return array
     * created by owen
     * created at 14:13
     */
    public function upSymbol($uid,$num,$from = 0){
        if($this->activityLock($uid,2,true)){
            oo::commonOprRedis('common')->hIncrBy(okeys::SymbolNum(),$uid,$num);
        }
        $ac13 = self::activityLock($uid,13,true);
        if($ac13){
            if(time() < $ac13['reward_time']){
                $model = intval(oo::commonOprModel('readconfig')->getSysCon('activtity13',"model"));
                if($model == 1 && $from == 1){
                    self::UniteAddNumRank($uid,$num);
                }else if($model == 2){
                    self::UniteAddNumRank($uid,$num);
                }else if($model == 3 && ($from == 2 || $from == 3)){
                    self::UniteAddNumRank($uid,$num);
                }
            }
        }
    }

    public function rewardSymbol($uid){
        $symbolData = self::getSymbol($uid);
        if(intval($symbolData['maxNum']) > intval($symbolData['num'])){
            return ['code'=>-1,'msg'=>'进度异常','data'=>['maxNum'=>$symbolData['maxNum'],'num'=>$symbolData['num'],'type'=>$symbolData['type'],'reward'=>$symbolData['reward'],'stage'=>$symbolData['stage']]];
        }else{
            if($symbolData['type'] == 1 || $symbolData['type'] == 2){
                $rewardKey = ($symbolData['type'] == 1)?'money':'spins';
                oo::commonOprModel('member')->optProperty($uid,[$rewardKey=>$symbolData['reward']],'+',204,'活动:金蛋进度：'.$symbolData['stage']);
                oo::commonOprRedis('common')->hIncrBy(okeys::SymbolNum(),$uid,-$symbolData['maxNum']);
                oo::commonOprRedis('common')->hIncrBy(okeys::SymbolStage(),$uid,1);
                return [
                    'code'=>1,'msg'=>'领奖成功',
                    'data'=>[
                        'reward'=>['type'=>$symbolData['type'],'num'=>$symbolData['reward']],
                        'cur'=>self::getSymbol($uid)
                    ]
                ];
            }else if($symbolData['type'] == 3){
                $exclusiveCardInfo = oo::commonOprModel('card')->getExclusiveCardInfoById($symbolData['reward']);
                $flag = false;
                $userCardInfo = oo::commonOprModel('card')->getUserCardInfo($uid);
                $userCardInfo = $userCardInfo['csid']??[];
                if(empty($userCardInfo) || !in_array($symbolData['reward'],$userCardInfo)){
                    $flag = true;
                    oo::commonOprModel('member')->optProperty($uid,array('star'=>$exclusiveCardInfo['ci_star_rank']),'+',32,'获取新卡片星星：限定卡片-'.$symbolData['reward']);
                }
                oo::commonOprModel('card')->rewardExclusiveCard($uid,$symbolData['reward']);
                $cardInfo['receive'][] = [
                    'group'=>$exclusiveCardInfo['cgid'],
                    'card'=>$exclusiveCardInfo['cgposition'],
                    'isNew'=>$flag,
                    'type'=>2,
                ];
                $cardInfo['card']= oo::commonOprModel('card')->getInfo($uid);
                $cardInfo['cardReward'] = ['spins'=>0,'coins'=>0];
                $cardInfo['cardGroupReward'] = ['spins'=>0,'coins'=>0];
                $cardInfo['exclusiveCard'] = oo::commonOprModel('card')->getExclusiveInfo($uid);
                oo::commonOprRedis('common')->hIncrBy(okeys::SymbolNum(),$uid,-$symbolData['maxNum']);
                oo::commonOprRedis('common')->hIncrBy(okeys::SymbolStage(),$uid,1);
                return [
                    'code'=>1,'msg'=>'领奖成功',
                    'data'=>[
                        'reward'=>['type'=>3,'num'=>$symbolData['reward'],'card'=>$cardInfo],
                        'cur'=>self::getSymbol($uid)
                    ]
                ];
            }else{
                return ['code'=>-2, 'msg'=>'领奖失败', 'data'=>['maxNum'=>$symbolData['maxNum'],'num'=>$symbolData['num'],'type'=>$symbolData['type'],'reward'=>$symbolData['reward'],'stage'=>$symbolData['stage']]];
            }
        }
    }

    /**
     * 获得活动信息
     * @param $activityId
     * @return mixed
     * Created by: Owen
     * Created on: 2019/9/2 14:57
     * Description:
     */
    public function getActivity($activityId){
        $Activity = oo::commonOprRedis('common')->hGetAll(okeys::Activity());
        foreach ($Activity as $key=>$row){
            $temp = explode('#',$key);
            if($activityId == $temp[0]){
                $ac = json_decode($row,true);
                $ac['start']  = $temp[1];
                $ac['end']    = $temp[2];
                $ac['openLv'] = $temp[3];
                return $ac;
            }
        }
        return false;
    }


    public $activityLock = [];

    /**
     * 活动开关
     * @param $uid
     * @param $activityId
     * @param $flag--根据该参数确定新旧版本
     * @return bool
     * Created by: Owen
     * Created on: 2019/9/2 14:57
     * Description:
     */
    public function activityLock($uid,$activityId,$flag = false){
        if($activityId == 8){
            $cache = oo::commonOprRedis('activity')->get(okeys::ActivityTemp($uid,8));
            if($cache){
                return json_decode($cache,true);
            }
        }
        $Activity = oo::commonOprRedis('common')->hGetAll(okeys::Activity());
        if(empty($Activity)){
            return false;
        }

        $time = time();
        foreach ($Activity as $key=>$row){
            $temp = explode('#',$key);
            if($temp[0] == $activityId){
                if($temp[2]>$time){
                    if($temp[1]<$time){
                        $userInfo = oo::commonOprModel('member')->getUserAssetsInfo($uid);
                        if($userInfo['levelId'] >= $temp[3]){
                            $ac = json_decode($row,true);
                            $ac['start']  = $temp[1];
                            $ac['end']    = $temp[2];
                            $ac['openLv'] = $temp[3];
                            if(!in_array($activityId,[5,12])){
                                oo::commonOprRedis('Activity')->setnx(okeys::ActivityOnLinePush($activityId),1) && self::activityChangeStatus(['actId'=>$activityId,'status'=>1,'startTime'=>$ac['start']]);
                            }
                            return $ac;
                        }
                    }
                }else{
                    self::outLine($activityId);
                }
            }
        }
        return false;
    }

    /**
     * 支付等级
     * @param $uid
     * @return int
     * Created by: Owen
     * Created on: 2019/8/14 15:32
     * Description:
     */
    private function PayLevel($uid){
        $tb = otable::payment($uid);
        $sql = "SELECT SUM(push) AS sum FROM {$tb} WHERE uid={$uid} AND status=2";
        $ret = oo::commonOprDb('payment')->getOne($sql,MYSQLI_ASSOC);
        $sum = $ret['sum'];
        $level = 1;

        $tb = otable::payLevel();
        $sql = "SELECT * FROM {$tb} WHERE 1";
        $ret = oo::commonOprDb('config')->getAll($sql,MYSQLI_ASSOC);

        foreach ($ret as $row){
            if(is_numeric($row['num'])){
                if($sum >= $row['num']){
                    $level = $row['level'];
                }else{
                    return $level;
                }
            }else{
                return $row['level'];
            }
        }
    }

    /**
     * 关卡等级
     * @param $uid
     * @return int
     * Created by: Owen
     * Created on: 2019/8/14 14:29
     * Description:
     */
    private function levelLevel($uid){
        $userInfo = oo::commonOprModel('member')->getUserAssetsInfo($uid);
        $userLevel = intval($userInfo['levelId']);
        $beginGuide = oo::commonOprRedis('common')->hGet(okeys::beginGuide(),$uid);
        if($beginGuide != false){
            return 0;
        }
        $level = 1;
        $tb = otable::activityLevel();
        $sql = "SELECT * FROM {$tb} WHERE 1";
        $ret = oo::commonOprDb('config')->getAll($sql,MYSQLI_ASSOC);

        foreach ($ret as $row){
            if($userLevel >= $row['num']){
                $level = $row['level'];
            }else{
                return $level;
            }
        }
    }

  	public function refreshActivity($id,$del = true){

        if($id == 2){
            $activity = [];
            $keys = oo::commonOprRedis('common')->hGetAll(okeys::SymbolStage());
            if(!empty($keys)){
                foreach ($keys as $uid=>$row){
                    $activity[$uid] = $row;
                }
                $tb  = otable::activitySta();
                $date= date('Ymd H:i');
                $data= json_encode($activity);
                $sql = "INSERT INTO {$tb} VALUES({$id},'{$date}','{$data}') ";
                oo::commonOprDb('statistics')->query($sql,false);
                $del && oo::commonOprRedis('common')->delete([okeys::SymbolStage(),okeys::SymbolNum()]);
            }
        }

        if($id == 3){
            $activity = oo::commonOprRedis('common')->hGetAll(okeys::BalloonCount());
            if(!empty($activity)){
                $tb  = otable::activitySta();
                $date= date('Ymd H:i');
                $data= json_encode($activity);
                $sql = "INSERT INTO {$tb} VALUES({$id},'{$date}','{$data}') ";
                oo::commonOprDb('statistics')->query($sql,false);
                $del && oo::commonOprRedis('common')->delete(okeys::BalloonCount());
            }
        }

        if($id == 6){
            $stageKey = okeys::StealAttackStage();
            $numKey   = okeys::StealAttackNum();

            //偷打活动统计
            $activity = [];
            $keys = oo::commonOprRedis('common')->hGetAll($numKey);
            if(!empty($keys)) {
                foreach ($keys as $uid => $row) {
                    $activity[$uid] = $row;
                }
                $tb = otable::activitySta();
                $date = date('Ymd H:i');
                $data = json_encode($activity);
                $sql = "INSERT INTO {$tb} VALUES({$id},'{$date}','{$data}') ";
                oo::commonOprDb('statistics')->query($sql, false);
                $del && oo::commonOprRedis('common')->delete([$stageKey, $numKey]);
            }
        }

        if($id == 7){
            $stageKey = okeys::HolidayCollectStage();
            $numKey   = okeys::HolidayCollectNum();
            oo::commonOprRedis('common')->delete([$stageKey,$numKey]);
        }

        if($id == 8){
            oo::commonOprRedis('common')->delete(okeys::BuildMaster());
        }

        if($id == 11){
            oo::commonOprRedis('common')->set(okeys::JackPotPool(),5000000);
            oo::commonOprRedis('common')->delete(okeys::LastJackPot("reward"));
            oo::commonOprRedis('common')->delete(okeys::LastJackPot("push"));
            oo::commonOprRedis('common')->delete(okeys::LastJackPot("systemAdd"));
        }

        if($id == 13) {
            $roomId   = self::getRankCurMaxRoomId();
            $activity = ['number'=>[],'rank'=>[],'progress'=>[]];//排行榜活动统计
            for ($i=1;$i<=$roomId;$i++){
                $result = oo::commonOprRedis('common')->zRange(okeys::ActivityRank($i),0,-1,true);
                foreach ($result as $uid => $num){
                    $activity['number'][$uid] = $num;
                    $activity['rank'][$i][$uid] = self::getCurUserRank($uid);
                    $activity['progress'][$uid] = self::getRankProgressId($uid);
                }
                $del && oo::commonOprRedis('Activity')->delete([okeys::AcRankRoomIdUsers($i),okeys::ActivityRank($i)]);
            }
            $del && oo::commonOprRedis('Activity')->delete(okeys::AcRankCurMaxRoomId());
            $del && oo::commonOprRedis('common')->delete([
                okeys::AcUserRankRoomId(),
                okeys::ActivityRankProgress("NUM"),
                okeys::ActivityRankProgress("ID"),
                okeys::ActivityRankProgress("LASTREWARD"),
                okeys::ActivityRankProgress("DAY"),
                okeys::ActivityRankProgress("BARID"),
                okeys::ActivityRankProgress("BARNUM"),
                okeys::ActivityRankProgress("CARD"),
                okeys::RewardedAcRank(),
                okeys::RewardedAcRankProgress(),
                okeys::ActivityRankPush(),
                okeys::ActivityRankPushLock("PUSH"),
                okeys::ActivityRankPushLock("PUSHED")
            ]);

            //排行榜活动统计
            $activityStaTb  = otable::activitySta();
            $date= date('Ymd H:i');
            $data= json_encode($activity);
            $sql = "INSERT INTO {$activityStaTb} VALUES({$id},'{$date}','{$data}') ";
            oo::commonOprDb('statistics')->query($sql,false);
        }

        if($id == 15) {
            oo::commonOprRedis('User')->delete(okeys::SerialPackTimer());
        }

        if($id == 16) {
            oo::commonOprRedis('Activity')->delete([
                okeys::TreasureTaskCard(),
                okeys::TreasureTaskId(),
                okeys::TreasureTaskNum(),
                okeys::TreasureCurTaskType(),
                okeys::treasureQuestGiftLog()
            ]);
        }
        return true;
    }

    public function cycleActivity($id){
        $activity = oo::commonOprRedis('common')->hGet(okeys::ActivityData(),$id);
        if(empty($activity)){
            return false;
        }

        $activityLock = oo::commonOprRedis('common')->hGetAll(okeys::Activity());
        if(!empty($activityLock)){
            foreach ($activityLock as $key=>$row){
                $temp = explode('#',$key);
                if($temp[0] == $id){
                    return false;
                }
            }
        }
        $time = time();
        $activity = json_decode($activity,true);
        if($activity['end_time']<=$time){
            oo::commonOprRedis('common')->hDel(okeys::ActivityData(),$id);
        }

        $lastTime = $activity['last_time'];
        $times    = $activity['lock_time']*60*60;
        if($lastTime+$times>$time){
            return false;
        }

        $temp = [
            'name'    =>$activity['name'],
            'name_en' =>$activity['name_en'],
            'package' =>$activity['package'],
            'sort'    =>$activity['sort'],
            'actType' =>$activity['actType'],
            'bname'   =>$activity['bname'],
            'bname_en'=>$activity['bname_en'],
        ];

        if($id == 2){
            $temp['dialogImg'] = $activity['dialogImg'];
            $temp['slotImg']   = $activity['slotImg'];
            $temp['buttonImg'] = $activity['buttonImg'];
            $temp['activityType']  = $activity['activityType'];
            $temp['activityName']  = $activity['activityName'];
            $temp['textColor'] = $activity['textColor'];
        }else if($id == 6 || $id == 3 || $id == 7){
            $temp['activityType']  = $activity['activityType'];
            $temp['activityName']  = $activity['activityName'];
        }

        $lastTime = $activity['last_time'] + $activity['lock_time']*60*60 + $activity['action_time']*60*60;
        if($lastTime>$activity['end_time']){
            $lastTime = $activity['end_time'];
        }

        oo::commonOprRedis('common')->hSet(okeys::Activity(),$id."#".$activity['start_time']."#".$lastTime."#".$activity['openlv'],json_encode($temp));
        $activity['last_time'] = $lastTime;
        oo::commonOprRedis('common')->hSet(okeys::ActivityData(),$id,json_encode($activity));
        $tb = otable::activity();
        $sql = "UPDATE {$tb} SET is_online=1 WHERE id = {$id} LIMIT 1";
        oo::commonOprDb('activity')->query($sql,false);
        $this->refreshActivity($id);
        return true;
    }

    /**
     * 更新偷打活动数据
     * @param $uid
     * @param int $num
     * @param int $from
     * @return array|bool
     * Created by: Owen
     * Created on: 2019/12/4 19:49
     */
    public function updateStealAttack($uid,$num = 0,$from = 0){
        $activityData = self::activityLock($uid,6,true);
        if(!$activityData){
            return false;
        }
        if($from == 1 || $from == 2){
            if($activityData['activityType'] != $from){
                return false;
            }
        }
        $stageKey = okeys::StealAttackStage();
        $stage  = intval(oo::commonOprRedis('common')->hGet($stageKey,$uid)) + 1;
        $config = oo::commonOprModel('config')->getStealAttackConfig($stage,2);
        $baseCoins  = 1;
        if($config['type'] == 1){
            $assetsInfo = oo::commonOprModel('member')->getUserAssetsInfo($uid);
            if($activityData['activityType'] == 1){
                $baseCoins  = oo::commonOprModel('config')->getActivityCoins($assetsInfo['levelId'],"steal");
            }else{
                $baseCoins  = oo::commonOprModel('config')->getActivityCoins($assetsInfo['levelId'],"attack");
            }
        }
        $numKey   = okeys::StealAttackNum();
        $data = [
            'stage' => intval(oo::commonOprRedis('common')->hGet($stageKey,$uid)) + 1,
            'num'   => intval(oo::commonOprRedis('common')->hGet($numKey,$uid)),
            'maxNum'=> $config['max'],
            'type'  => $config['type'],
            'reward'=> $config['num'] * $baseCoins
        ];
        if($num == 0){
            return $data;
        }
        oo::commonOprRedis('common')->hIncrBy($numKey,$uid,$num);
        $data['num'] = $data['num']+$num;
        return $data;
    }

    /**
     * 偷打活动领奖
     * @param $uid
     * @return mixed
     * Created by: Owen
     * Created on: 2019/12/4 17:56
     */
    public function rewardStealAttack($uid){
        $data = self::updateStealAttack($uid);
        $stageKey = okeys::StealAttackStage();
        $numKey   = okeys::StealAttackNum();
        if($data){
            if($data['maxNum']<=$data['num']){
                oo::commonOprRedis('common')->hIncrBy($numKey,$uid,-$data['maxNum']);
                oo::commonOprRedis('common')->hIncrBy($stageKey,$uid,1);
                if($data['type'] == 1){
                    $type = 'money';
                }else if($data['type'] == 2){
                    $type = 'spins';
                }
                oo::commonOprModel('member')->optProperty($uid,[$type=>$data['reward']],'+',211,'偷打活动:'.$data['stage']);
                return oo::response(1,[
                    'reward'=>['type' => $data['type'], 'num'=> $data['reward']],
                    'cur'   =>self::updateStealAttack($uid)
                ],'',true);
            }else{
                return oo::response(-2,$data,'阶段未达标');
            }
        }
    }

    /**
     * 更新节日收集进度
     * @param $uid
     * @param int $num
     * @return array|bool
     * Created by: Owen
     * Created on: 2019/12/10 17:05
     */
    public function updateHolidayCollect($uid,$num = 0){
        if(!self::activityLock($uid,7,true)){
            return false;
        }
        $stageKey = okeys::HolidayCollectStage();
        $numKey   = okeys::HolidayCollectNum();
        $stage = oo::commonOprRedis('common')->hGet($stageKey,$uid);
        $stage = empty($stage)?[]:json_decode($stage,true);
        $data = [
            'stage' => $stage,
            'num'   => intval(oo::commonOprRedis('common')->hGet($numKey,$uid)),
        ];
        if($num == 0){
            return $data;
        }
        $data['num'] += $num;
        oo::commonOprRedis('common')->hIncrBy($numKey,$uid,$num);
        return $data;
    }

    /**
     * 节日收集进度奖励
     * @param $uid
     * @param $stage
     * @return string
     * Created by: Owen
     * Created on: 2019/12/10 17:06
     */
    public function rewardHolidayCollect($uid,$stage){
        $stageKey = okeys::HolidayCollectStage();
        $userStage = oo::commonOprRedis('common')->hGet($stageKey,$uid);
        $userStage = empty($userStage)?[]:json_decode($userStage,true);
        $data = [
            'stage' => $userStage,
        ];
        if(in_array($stage,$data['stage'])){
            return oo::response(-2,[],'已领取过');
        }
        $numKey   = okeys::HolidayCollectNum();
        $data['num'] = intval(oo::commonOprRedis('common')->hGet($numKey,$uid));
        $config = oo::commonOprModel('config')->getHolidayCollectConfig($stage);
        if($config['max']>$data['num']){
            return oo::response(-3,[],'阶段未达标');
        }
        $data['stage'][] = $stage;
        oo::commonOprRedis('common')->hSet($stageKey,$uid,json_encode($data['stage']));
        $coins =  oo::commonOprModel('goods')->getGoodCoins($uid,'coins01');
        $reward = [
            'spins' => $config['spins'],
            'money' => $coins*$config['money'],
        ];
        oo::commonOprModel('member')->optProperty($uid,$reward,'+',202,'节日收集活动:'.$stage);
        $chest = json_decode($config['chest'],true);
        oo::commonOprModel('props')->addUserProps($uid,$chest['id'],$chest['num']);
        $reward['card']  = [];
        $reward['coins'] = $reward['money'];
        return oo::response(1,$reward,'',true);
    }

    /**
     * 建筑大师
     * @param $uid
     * @return string
     * Created by: Owen
     * Created on: 2019/12/17 16:11
     */
    public function rewardBuildMaster($uid){
        $key = okeys::BuildMaster();
        $userData = oo::commonOprRedis('common')->hGet($key,$uid);
        if(empty($userData)){
            return oo::response(-2);
        }else{
            $userData = json_decode($userData,true);
            $min = 0;
            $dataKey = 0;
            foreach ($userData as $k=>$row){
                if($min>$row || $min==0){
                    $min = $row;
                    $dataKey = $k;
                }
            }
            if($min == 0){
                oo::commonOprRedis('common')->hDel($key,$uid);
                return oo::response(-2);
            }
            unset($userData[$dataKey]);
            $userData = array_filter(array_unique($userData));
            sort($userData);
            if(empty($userData)){
                oo::commonOprRedis('common')->hDel($key,$uid);
            }else{
                oo::commonOprRedis('common')->hSet($key,$uid,json_encode($userData));
            }
            $config = oo::commonOprModel('config')->getBuildMasterConfig($min);
            $reward = [
                'money' => oo::commonOprModel('goods')->getGoodCoinsByLevelId($min,$config['money']) / 2,
                'spins' => $config['spins'],
            ];
            oo::commonOprModel('member')->optProperty($uid,$reward,'+',203,'建筑大师:'.$min);
            $chest = json_decode($config['chest'],true);
            oo::commonOprModel('props')->addUserProps($uid,$chest['id'],$chest['num']);
            $reward['card'] = [];
            return oo::response(1,$reward,'',true);
        }
    }

    /**
     * jackPot 获取当前奖池金额
     * @return int
     * created by owen
     * created at 11:53
     */
    public function getJackPotPool(){
        self::systemAddJackPotPool();
        return intval(oo::commonOprRedis('common')->get(okeys::JackPotPool()));
    }

    /**
     * jackPot 追加奖池
     * @param $uid
     * @param $money
     * @return bool
     * created by owen
     * created at 11:44
     */
    public function slotAddJackPotPool($uid,$money){
        oo::commonOprRedis('common')->incrBy(okeys::JackPotPool(),$money);
        if(!funs::concurrentLock(1,'slotAddJackPotPool',10)){
            return true;
        }
        oo::commonOprModel('Workerman')->pushAll(ocmd::$send['JackPotPool'],['curPoolNum'=>self::getJackPotPool()]);
    }

    /**
     * jackPot 中奖
     * @param $uid
     * @return mixed
     * created by owen
     * created at 12:46
     */
    public function rewardJackPot($uid){
        $curPoolNum = self::getJackPotPool();
        oo::commonOprRedis('common')->set(okeys::JackPotPool(),0);
        $protectedTime = 300;
        oo::commonOprModel('member')->setUserStealProtect($uid,$protectedTime);
        oo::commonOprModel('Workerman')->push($uid,ocmd::$send['stealProtected'],[ 'expireTime' => time() + $protectedTime]);
        oo::commonOprModel('member')->optProperty($uid,['money'=>$curPoolNum],'+',212,'JackPot活动');
        $userinfo = oo::commonOprModel('member')->getUserInfo($uid);//玩家基本信息
        $pushData = [
            'curPoolNum'=> $curPoolNum,
            'uid'       => $uid,
            'nick'      => oo::commonOprModel('member')->getUserFirstName($userinfo['nick']),
            's_picture' => $userinfo['s_picture'],
            'vip'       => $userinfo['vip'],
            'vipLv'     => $userinfo['vipLv'],
            'avatar'    => $userinfo['avatar'],
        ];
        oo::commonOprModel('Workerman')->pushAll(ocmd::$send['JackPotReward'],$pushData);
        oo::commonOprRedis('common')->setex(okeys::LastJackPot("reward"),time(),24*60*60);
        return $pushData;
    }

    public function systemAddJackPotPool(){
        $curPoolNum = intval(oo::commonOprRedis('common')->get(okeys::JackPotPool()));
        if($curPoolNum < 5000000){
            $lastSystemAddTime = oo::commonOprRedis('common')->get(okeys::LastJackPot("systemAdd"));
            if(!$lastSystemAddTime){
                oo::commonOprRedis('common')->setex(okeys::LastJackPot("systemAdd"),time(),20);
                return false;
            }
            $addNum = ceil((time() - $lastSystemAddTime)/2);
            oo::commonOprRedis('common')->incrBy(okeys::JackPotPool(),$addNum*random_int(2750,3250));
            oo::commonOprRedis('common')->setex(okeys::LastJackPot("systemAdd"),time(),20);
        }
    }

    /**
     * 机器人领奖
     * created by owen
     * created at 12:53
     */
    public function robotRewardJackPot(){
        if(!self::isOnLine(11)){
            return -1;
        }
        $curPoolNum = self::getJackPotPool();
        $lastRewardTime = oo::commonOprRedis('common')->get(okeys::LastJackPot("reward"));
        if(!$lastRewardTime){
            oo::commonOprRedis('common')->setex(okeys::LastJackPot("reward"),time(),24*60*60);
        }
        $time = intval(oo::commonOprModel('readconfig')->getCon('basic',"jackRobotTime")); //限制
        $limit= intval(oo::commonOprModel('readconfig')->getCon('basic',"jackRobotLimit")); //限制
        if(($lastRewardTime + $time*60) < time() || ($curPoolNum > $limit && ($lastRewardTime + 60 < time()))){
            $robot = oo::commonOprModel('robot')->getAllRobot();
            $robotUid = $robot[array_rand($robot,1)];
            oo::commonOprRedis('common')->getSet(okeys::JackPotPool(),0);
            $userinfo = oo::commonOprModel('member')->getUserInfo($robotUid);//玩家基本信息
            $pushData = [
                'curPoolNum'=> $curPoolNum,
                'uid'       => $robotUid,
                'nick'      => $userinfo['nick'],
                's_picture' => $userinfo['s_picture'],
                'vip'       => $userinfo['vip'],
                'vipLv'     => $userinfo['vipLv'],
                'avatar'    => $userinfo['avatar'],
            ];
            oo::commonOprModel('Workerman')->pushAll(ocmd::$send['JackPotReward'],$pushData);
            oo::commonOprRedis('common')->setex(okeys::LastJackPot("reward"),time(),24*60*60);
        }
    }

    /**
     * 排行榜活动当前最大房间号
     * @return mixed
     * created by owen
     * created at 22:02
     */
    public function getRankCurMaxRoomId(){
        $key   = okeys::AcRankCurMaxRoomId();
        $cache = oo::commonOprRedis('Activity')->get($key);
        if(!empty($cache)){
            return $cache;
        }
        $roomId = 1;
        oo::commonOprRedis('Activity')->set($key,$roomId);
        return $roomId;
    }

    /**
     * 房间号真实用户
     * @return array
     * created by owen
     * created at 22:02
     */
    public function getRankCurRoomUsers(){
        $key   = okeys::AcRankRoomIdUsers(self::getRankCurMaxRoomId());
        $cache = oo::commonOprRedis('Activity')->sMembers($key);
        if(!empty($cache)){
            return $cache;
        }
        return [];
    }

    /**
     * 获取房间用户
     * @param $roomId
     * @return array
     * Created by: Owen
     * Created on: 2020/7/4 15:03
     */
    public function getRankRoomUsers($roomId){
        $cache = oo::commonOprRedis('Activity')->sMembers(okeys::AcRankRoomIdUsers($roomId));
        if(!empty($cache)){
            return $cache;
        }
        return [];
    }

    /**
     * 加入房间
     * @param $uid
     * @return string
     * created by owen
     * created at 14:06
     */
    public function addToRankRoom($uid){
        if(self::getUserRankRoomId($uid)){
            return oo::response(-3,[],"已加入房间",true);
        }
        $curRoomUsers = self::getRankCurRoomUsers();
        $score = oo::commonOprRedis('Activity')->hGet(okeys::ActivityRankProgress("NUM"),$uid);
        if($score < 5){
            return oo::response(-2,[],"未达标开始");
        }
        $roomId = self::getRankCurMaxRoomId();
        if(count($curRoomUsers) >= 50){
            $roomId += 1;
            oo::commonOprRedis('Activity')->zAdd(okeys::ActivityRank($roomId),$score,$uid);
            oo::commonOprRedis('Activity')->sAdd(okeys::AcRankRoomIdUsers($roomId),$uid);
            oo::commonOprRedis('Activity')->incr(okeys::AcRankCurMaxRoomId());
        }else{
            oo::commonOprRedis('Activity')->zAdd(okeys::ActivityRank($roomId),$score,$uid);
            oo::commonOprRedis('Activity')->sAdd(okeys::AcRankRoomIdUsers($roomId),$uid);
        }
        oo::commonOprRedis('Activity')->hSet(okeys::AcUserRankRoomId(),$uid,$roomId);
        //判断进度奖励是否有卡片
        $config = oo::commonOprModel('config')->getActivityRankProgressConfig();
        $configTemp = end($config);
        $cardData = null;
        if(!empty($configTemp['props'])) {
            $configTemp['props'] = json_decode($configTemp['props'], 1);
            foreach ($configTemp['props'] as $key => $row) {
                if ($row['propsId'] == -1) {
                    $cardData = self::getRankCard($uid);
                    oo::commonOprRedis('Activity')->hSet(okeys::ActivityRankProgress("CARD"), $uid, json_encode($cardData));
                    break;
                }
            }
        }
        return oo::response(1,['selfData'=>self::getUserRankData($uid),'rankData'=>self::getAllUserRankByUid($uid),'cardData'=>$cardData],"",true);
    }

    /**
     * 获取用户排行榜数据
     * @param $uid
     * @return mixed
     * created by owen
     * created at 13:54
     */
    public function getUserRankData($uid){
        if(!self::activityLock($uid,13,true)){
            return false;
        }
        $roomId = self::getUserRankRoomId($uid);
        if(empty($roomId)){
            return [
                'roomId'     => 0,
                'curRankId'  => 0,
                'curRankNum' => 0,
                'isRankReward' => intval(oo::commonOprRedis('Activity')->hGet(okeys::RewardedAcRank(),$uid)),
                'curRankProgressNum' => self::getRankProgress($uid),
                'curRankProgressId'  => 0,
                'cardData' => null,
            ];
        }
        //卡片
        $cardData = oo::commonOprRedis('Activity')->hGet(okeys::ActivityRankProgress("CARD"),$uid);
        if(empty($cardData)){
            //判断进度奖励是否有卡片
            $config = oo::commonOprModel('config')->getActivityRankProgressConfig();
            $configTemp = end($config);
            if(!empty($configTemp['props'])) {
                $configTemp['props'] = json_decode($configTemp['props'], 1);
                foreach ($configTemp['props'] as $key => $row) {
                    if ($row['propsId'] == -1) {
                        $cardData = self::getRankCard($uid);
                        oo::commonOprRedis('Activity')->hSet(okeys::ActivityRankProgress("CARD"), $uid, json_encode($cardData));
                        break;
                    }
                }
            }
        }else{
            $cardData = json_decode($cardData,1);
        }
        return [
            'roomId'     => $roomId,
            'curRankId'  => self::getCurUserRank($uid) + 1,
            'curRankNum' => self::getNumRank($uid),
            'isRankReward' => intval(oo::commonOprRedis('Activity')->hGet(okeys::RewardedAcRank(),$uid)),
            'curRankProgressNum' => self::getRankProgress($uid,true),
            'curRankProgressId'  => self::getRankProgressId($uid),
            'cardData' => $cardData,
        ];
    }

    /**
     * 获取用户房间号
     * @param $uid
     * @return int
     * created by owen
     * created at 15:55
     */
    public function getUserRankRoomId($uid){
        $key   = okeys::AcUserRankRoomId();
        $cache = oo::commonOprRedis('Activity')->hGet($key,$uid);
        if(!empty($cache)){
            return $cache;
        }
        return 0;
    }


    /**
     * 获取房间排行榜 -- 房间号
     * @param int $roomId
     * @param int $star
     * @param int $end
     * @return mixed
     * created by owen
     * created at 18:06
     */
    public function getAllUserRankByRoomId($roomId,$star = 0,$end = 50){
        if(empty($roomId)){
            return [];
        }
        return oo::commonOprRedis('Activity')->zRevRange(okeys::ActivityRank($roomId),$star,$end,true);
    }

    /**
     * 获取房间排行榜 -- 用户号
     * @param int $uid
     * @param int $star
     * @param int $end
     * @return mixed
     * created by owen
     * created at 18:06
     */
    public function getAllUserRankByUid($uid,$star = 0,$end = 50){
        $users = self::getAllUserRankByRoomId(self::getUserRankRoomId($uid),$star,$end);
        if(empty($users)){
            return [];
        }
        $data = [];
        $i = 0;
        foreach ($users as $key=>$row){
            $userinfo = oo::commonOprModel('member')->getUserInfo($key);
            $data[] = [
                'rankId' => $i+1,
                'uid'       => $key,
                'nick'      => oo::commonOprModel('member')->getUserFirstName($userinfo['nick']),
                's_picture' => $userinfo['s_picture'],
                'vip'       => $userinfo['vip'],
                'vipLv'     => $userinfo['vipLv'],
                'vipExpire' => $userinfo['vip_expire'],
                'avatar'    => $userinfo['avatar'],
                'curRankNum'=> $row,
            ];
            $i++;
        }
        return $data;
    }


    /**
     * 获取当前用户排行
     * @param $uid
     * @return mixed
     * created by owen
     * created at 18:07
     */
    public function getCurUserRank($uid){
        return oo::commonOprRedis('Activity')->zRevRank(okeys::ActivityRank(self::getUserRankRoomId($uid)),$uid);
    }

    /**
     * 获取当前用户排行值
     * @param $uid
     * @return int
     * created by owen
     * created at 9:43
     */
    public function getNumRank($uid){
        return intval(oo::commonOprRedis('Activity')->zScore(okeys::ActivityRank(self::getUserRankRoomId($uid)),$uid));
    }
    /**
     * 追加排行榜活动进度
     * @param $uid
     * @param $num
     * @return int
     * created by owen
     * created at 16:15
     */
    public function addNumRank($uid,$num){
        $roomID = self::getUserRankRoomId($uid);
        if(!$roomID){
            return 0;
        }
        return intval(oo::commonOprRedis('Activity')->zIncrBy(okeys::ActivityRank($roomID),$num,$uid));
    }

    /**
     * 排行榜活动奖励
     * @param $uid
     * @return string
     * created by owen
     * created at 13:53
     */
    public function rewardRank($uid){
        $key = okeys::RewardedAcRank();
        $cache = oo::commonOprRedis('Activity')->hGet($key,$uid);
        if(!empty($cache)){
            return oo::response(-2,[],"奖励已领取过");
        }
        $roomId  = self::getUserRankRoomId($uid);
        $isSet = true;
        $curRank = oo::commonOprRedis('Activity')->zRevRank(okeys::ActivityRank($roomId),$uid);
        if($curRank !== false){
            $curRank += 1;
            $config = oo::commonOprModel('config')->getActivityRankConfig($curRank);
            oo::commonOprRedis('Activity')->setex(okeys::ActivityRankPushLock("PUSH"),1,3*24*60*60);
        }else{
            $randId = oo::commonOprRedis('Activity')->hGet(okeys::ActivityRankPushData(),$uid);
            $isSet  = false;
            if(!$randId){
                return oo::response(-4,[],"活动结束领奖标识异常");
            }
            $config = oo::commonOprModel('config')->getActivityRankConfig($randId);
        }
        $add = [
            'money' => $config['coins'],
            'spins' => $config['spins']
        ];
        oo::commonOprModel('member')->optProperty($uid, $add, '+',208,'排行榜活动');
        $props = json_decode($config['props'],true);
        if(!empty($props)){
            oo::commonOprModel('props')->addUserProps($uid,$props['propsId'],$props['num']);
        }
        $isSet && oo::commonOprRedis('Activity')->hSet($key,$uid,1);
        oo::commonOprRedis('Activity')->hDel(okeys::ActivityRankPushData(),$uid);
        return oo::response(1);
    }



    /**
     * 当前获取进度
     * @param $uid
     * @param $addBar
     * @return int
     * created by owen
     * created at 17:44
     */
    public function getRankProgress($uid,$addBar = false){
        $barNum = 0;
        if($addBar){
            $barNum = oo::commonOprRedis('Activity')->hGet(okeys::ActivityRankProgress("BARNUM"),$uid);
        }
        return $barNum + intval(oo::commonOprRedis('Activity')->hGet(okeys::ActivityRankProgress("NUM"),$uid));
    }

    /**
     * 获取当前阶段进度值
     * @param $uid
     * @return int
     * created by owen
     * created at 13:53
     */
    public function getRankProgressId($uid){
        return intval(oo::commonOprRedis('Activity')->hGet(okeys::ActivityRankProgress("ID"),$uid));
    }

    /**
     * 追加进度值
     * @param $uid
     * @param $num
     * @return int
     * created by owen
     * created at 13:52
     */
    public function addNumRankProgress($uid,$num){
        return intval(oo::commonOprRedis('Activity')->hIncrBy(okeys::ActivityRankProgress("NUM"),$uid,$num));
    }

    /**
     * 统一增加
     * @param $uid
     * @param $num
     * @return array
     * created by owen
     * created at 13:52
     */
    public function UniteAddNumRank($uid,$num){
        return [
            'rank'     => self::addNumRank($uid,$num),
            'progress' => self::addNumRankProgress($uid,$num),
        ];
    }

    /**
     * 阶段奖励
     * @param $uid
     * @return string
     * created by owen
     * created at 13:52
     */
    public function rewardRankProgress($uid){
        $key = okeys::RewardedAcRankProgress();
        $cache = oo::commonOprRedis('Activity')->hGet($key,$uid);
        $id  = self::getRankProgressId($uid) + 1;
        if(intval($cache) >= $id && $id != 0){
            return oo::response(-2,[],"奖励已领取");
        }
        $assetsInfo = oo::commonOprModel('member')->getUserAssetsInfo($uid);
        $config = oo::commonOprModel('config')->getActivityRankProgressConfig($id,'1.6.1',$assetsInfo['levelId']);
        if(empty($config)){
            return oo::response(-3,[],"奖励不存在");
        }
        $curNum = self::getRankProgress($uid);
        if($config['max'] <= $curNum){
            oo::commonOprRedis('Activity')->hSet(okeys::ActivityRankProgress("LASTREWARD"),$uid,time());
            oo::commonOprRedis('Activity')->hIncrBy(okeys::ActivityRankProgress("DAY"),$uid,1);
            oo::commonOprRedis('Activity')->hIncrBy(okeys::ActivityRankProgress("ID"),$uid,1);
            oo::commonOprRedis('Activity')->hIncrBy(okeys::ActivityRankProgress("NUM"),$uid,-$config['max']);
            $barId = oo::commonOprRedis('Activity')->hGet(okeys::ActivityRankProgress("BARID"),$uid);
            if($barId == false){
                $barId = 1;
            }
            $nextConfig = oo::commonOprModel('config')->getActivityRankProgressConfig($id + 1);
            if(intval($barId) == $nextConfig['progressBarId']){
                oo::commonOprRedis('Activity')->hIncrBy(okeys::ActivityRankProgress("BARNUM"),$uid,$config['max']);
            }else{
                oo::commonOprRedis('Activity')->hSet(okeys::ActivityRankProgress("BARID"),$uid,$nextConfig['progressBarId']);
                oo::commonOprRedis('Activity')->hSet(okeys::ActivityRankProgress("BARNUM"),$uid,0);
            }
            $limitTimeReward = oo::commonOprRedis('Activity')->hGet(okeys::AcRankLimitReward(),$uid);
            if($limitTimeReward){
                $limitTimeReward = json_decode($cache,true);
                if($limitTimeReward['isReward'] == 0 && $limitTimeReward['lastTime'] < time()){
                    $config['coins'] = ceil($config['coins'] + $config['coins']*$limitTimeReward['percent']);
                    $config['spins'] = ceil($config['spins'] + $config['spins']*$limitTimeReward['percent']);
                    $limitTimeReward['isReward'] = 1;
                    oo::commonOprRedis('Activity')->hSet(okeys::AcRankLimitReward(),$uid,json_encode($limitTimeReward));
                }
            }
            oo::commonOprModel('member')->optProperty($uid, ['money'=>$config['coins'],'spins'=>$config['spins']], '+',209,'排行榜活动阶段奖励:'.$config['id']);
            $props = json_decode($config['props'],true);
            if(!empty($props)){
                if(count($props) == count($props, 1)){
                    //旧版本
                    oo::commonOprModel('props')->addUserProps($uid, $props['propsId'], $props['num']);
                }else{
                    //1.6.1+
                    foreach($props as $key => $row){
                        if(!empty($row['propsId']) && !empty($row['num'])){
                            if($row['propsId'] == -1){
                                //卡片
                                $card = oo::commonOprRedis('Activity')->hGet(okeys::ActivityRankProgress("CARD"),$uid);
                                $card = json_decode($card,1);
                                if(!empty($card['id'])){
                                    oo::commonOprModel('card')->getCardByType($uid,7,0,[$card['id']]);
                                }
                            }else{
                                oo::commonOprModel('props')->addUserProps($uid, $row['propsId'], $row['num']);
                            }
                        }

                    }
                }
            }

            oo::commonOprRedis('Activity')->hSet($key,$uid,$id);
            return oo::response(1,['selfData'=>self::getUserRankData($uid)]);
        }else{
            return oo::response(-4,[],"非达标");
        }
    }

    public function triggerRankLimitReward($uid){
        $cache = oo::commonOprRedis('Activity')->hGet(okeys::AcRankLimitReward(),$uid);
        if($cache){
            return json_decode($cache,true);
        }

        $lastReward = intval(oo::commonOprRedis('Activity')->hGet(okeys::ActivityRankProgress("LASTREWARD"),$uid));
        $dayNum = intval(oo::commonOprRedis('Activity')->hGet(okeys::ActivityRankProgress("DAY"),$uid));
        if($lastReward + 24*60*60 < time() || $dayNum>=3){
            $lastTime = time() + 5*60 + 5;
            $percent  = 0.8;
            oo::commonOprModel('Workerman')->push($uid,ocmd::$send['AcRankLimitTimeReward'],[
                'lastTime' => $lastTime - 5,
                'percent'  => $percent,
            ]);
            $data = [
                'lastTime' => $lastTime,
                'percent'  => $percent,
                'isReward' => 0
            ];
            oo::commonOprRedis('Activity')->hSet(okeys::AcRankLimitReward(),$uid,json_encode($data));
            return $data;
        }else{
            return false;
        }
    }

    public function doubleSpins($uid,$maxBet = 0,$autoSpins = 0){
        $cacheKey = okeys::SpeedUpSpins($uid);
        $cache    = oo::commonOprRedis('common')->get($cacheKey);
        if($cache){
            return intval($cache);
        }
        if(!self::activityLock($uid,14,true)){
            return false;
        }
        $config = oo::commonOprModel('config')->getSpeedUpSpins();
        $action      = false;
        $configBet   = 0;
        $configEffecteTime = 0;
        foreach ($config as $row){
            $id = $row['id'];
            if($id == 1 && $maxBet){
                $count = intval(oo::commonOprRedis('common')->get(okeys::SpeedUpSpins($uid,$id)));
                if($count < $row['max']){
                    $action = true;
                }
            }else if($id == 2 && $autoSpins){
                $count = intval(oo::commonOprRedis('common')->get(okeys::SpeedUpSpins($uid,$id)));
                if($count < $row['max']){
                    $action = true;
                }
            }else if($id == 3){
                $count = intval(oo::commonOprRedis('common')->get(okeys::SpeedUpSpins($uid,$id)));
                $advertisementCount = intval(oo::commonOprRedis('common')->hGet(okeys::advertisementRemainCount(),$uid));
                if($advertisementCount >=3 &&  $count < $row['max']){
                    $action = true;
                }
            }else if($id == 4){
                $cache = oo::commonOprRedis('common')->get(okeys::TodayBuyGoods($uid,1));
                $count = intval(oo::commonOprRedis('common')->get(okeys::SpeedUpSpins($uid,$id)));
                if($count < $row['max'] && $cache){
                    $action = true;
                }
            }
            if($action){
                $configBet   = $row['bet'];
                $configEffecteTime = $row['effecteTime'];
                oo::commonOprRedis('common')->setex(okeys::SpeedUpSpins($uid,$id),$count+1,oo::todayDeadline());
                break;
            }
        }
        if($action){
            oo::commonOprRedis('common')->setex($cacheKey,$configBet,$configEffecteTime);
            $lastTime = time() + $configEffecteTime;
            oo::commonOprModel('Workerman')->push($uid,ocmd::$send['Activity_doubleSpins'],[
                'bet'     =>$configBet,
                'lastTime'=>$configEffecteTime,
            ]);
            $keys = okeys::userRestoreTime($uid);
            $spinsKey = oo::commonOprRedis('common')->get($keys);
            if($spinsKey){
                $spinsCache = explode("*",$spinsKey);
                if(count($spinsCache) > 2){
                    $spinsCache[2] = time() + $configEffecteTime;
                    $spinsCache[3] = $configBet;
                    oo::commonOprRedis('common')->set($keys,implode("*",$spinsCache));
                }else{
                    oo::commonOprRedis('common')->set($keys,$spinsKey."*{$lastTime}*{$configBet}");
                }
            }
            return $configBet;
        }
        return false;
    }

    /**
     * 活动下线
     * @param $id
     * @return bool
     * Created by: Owen
     * Created on: 2020/7/3 16:32
     */
    public function outLine($id){
        $Activity = oo::commonOprRedis('common')->hGetAll(okeys::Activity());
        foreach ($Activity as $key=>$row){
            $temp = explode('#',$key);
            if($temp[0] == $id){
                oo::commonOprRedis('common')->hDel(okeys::Activity(),$key);
                $tb = otable::activity();
                oo::commonOprDb('activity')->query("UPDATE {$tb} SET is_online=0 WHERE id = {$id} LIMIT 1");
                oo::commonOprRedis('Activity')->delete(okeys::ActivityOnLinePush($id));
            }
        }
        return true;
    }

    /**
     * 判断是否在线
     * @param $id
     * @return bool
     * Created by: Owen
     * Created on: 2020/7/18 18:02
     */
    public function isOnLine($id){
        $Activity = oo::commonOprRedis('common')->hGetAll(okeys::Activity());
        foreach ($Activity as $key=>$row){
            $temp = explode('#',$key);
            if($temp[0] == $id){
                return true;
            }
        }
        return false;
    }

    /**
     * 排行榜活动动态奖励卡片
     * 2.卡片为金卡；
     * 3.玩家未获得的卡片；（如果玩家已获得符合条件所有金卡，则取获得数量最少的卡片）
     * 4.解锁等级最高的卡片；（如果解锁等级相同，则取卡片ID排前的卡片）
     * 20200922修改为解锁等级最低的卡片
     * @return array
     * Created by: Hss
     * Created on: 2020/7/15 14:59
     */
    public function getRankCard($uid){
        //grade 2 金卡
        //$unlockCard = oo::commonOprModel('card')->getUnlockCard($uid);
        $assetsInfo  = oo::commonOprModel('member')->getUserAssetsInfo($uid);
        $unlockCard = oo::commonOprModel('card')->getUnlockCardByLevelId($assetsInfo['levelId']);
        //krsort($unlockCard);//20200922修改为解锁等级最低的卡片
        $userCardInfo = oo::commonOprModel('card')->getUserCardInfo($uid);
        $userCardTemp = array_keys($userCardInfo['ciid']);

        $level = oo::commonOprModel('member')->getUserLevel($uid);
        $levelId = intval($level['levelId']);

        $reward = [];
        $isNew = true;
        foreach($unlockCard as $key => $row){
            if($row['grade'] == 2 && $row['ci_lockRank'] <= $levelId && !in_array($row['ciid'],$userCardTemp)){
                $reward = $row;
                break;
            }
        }
        if(empty($reward)){
            $gradeCardTemp = [];
            $unlockCardTemp = [];
            foreach ($unlockCard as $key => $val){
                $unlockCardTemp[$val['ciid']] = $val;
            }
            foreach ($userCardTemp as $ciid){
                if($unlockCardTemp[$ciid]['grade'] == 2){
                    $gradeCardTemp[$ciid] = $userCardInfo['ciid'][$ciid];
                }
            }
            asort($gradeCardTemp);
            $minCiid = array_slice($gradeCardTemp,0,1,true);
            $reward = $unlockCardTemp[key($minCiid)];
            $isNew = false;
        }
        return ['id'=>$reward['ciid'],'isNew'=>$isNew];
    }


    /**
     * 推送状态
     * @param $data
     * @return bool
     * Created by: Owen
     * Created on: 2020/7/20 15:11
     */
    public function activityChangeStatus($data){
        $actId = self::activityToFrontId($data['actId']);
        if(empty($actId)){
            return false;
        }
        $data['actId'] = $actId;
        if($data['status'] == 0){
            oo::commonOprModel('Workerman')->pushAll(ocmd::$send['ActivityChangeStatus'],$data);
        }else{
            //消息队列推送到不同服务器节点
            oo::commonOprModel('workerman')->pushFun('activitynew', 'activityCircleChangeStatus', [$data]);
        }
        return true;
    }

    /**
     * 通知当前节点推送
     */
    public function activityCircleChangeStatus($data){
        $online = oo::commonOprModel('Workerman')->getCurAllUidList();
        $i = 0;
        foreach ($online as $uid){
            $i++;
            oo::commonOprModel('Workerman')->push($uid,ocmd::$send['ActivityChangeStatus'],$data);
            if($i == 100){
                $data['startTime'] += 5;
                $i = 0;
            }
        }
    }

    /**
     * 后端活动ID映射前端
     * @param $id
     * @return mixed
     * Created by: Owen
     * Created on: 2020/7/20 15:10
     */
    public function activityToFrontId($id){
        $idArr = [
            2=>5,     //收集
            3=>6,     //气球
            6=>8,     //偷打活动
            7=>10,    //节日收集活动
            8=>12,    //建筑大师
            9=>13,    //倍率活动
            10=>14,   //卡片活动
            11=>15,   //JackPot
            12=>16,   //卡片交换
            13=>17,   //排行榜活动
            14=>18,   //体力加速恢复
            15=>19,   //连环礼包
            16=>20,   //宝藏活动
        ];
        return $idArr[$id];
    }

    /**
     * 宝藏活动用户信息
     * @param $uid
     * @param $origData
     * @return array
     * Created by: Owen
     * Created on: 2020/7/27 18:55
     */
    public function getUserTreasureData($uid,$origData = false){
        $userAssetsInfo = oo::commonOprModel('member')->getUserAssetsInfo($uid);
        $levelId = $userAssetsInfo['levelId'];
        $treasureCollect = oo::commonOprModel('config')->getActivityCoins($levelId,"treasureCollect");
        $treasureReward  = oo::commonOprModel('config')->getActivityCoins($levelId,"treasureReward");
        $treasureBet     = oo::commonOprModel('config')->getActivityCoins($levelId,"treasureBet");
        $version = oo::commonOprModel('user')->getUserVersion($uid);
        if(oo::compareVersion($version,'1.7.0')){
            $config  = oo::commonOprModel('config')->getTreasureConfig(0,true);
        }else{
            $config  = oo::commonOprModel('config')->getTreasureConfig(0,false);
        }
        foreach ($config as $key=>$row){
            if($row['taskType'] != 1){
                $config[$key]['target'] *= $treasureCollect;
            }
            $config[$key]['coins'] *= $treasureReward;
            $temp = $row['bet'];
            foreach ($temp as $b=>$bet){
                $temp[$b] = $bet * $treasureBet;
            }
            $config[$key]['bet'] = $temp;
            if($row['special'] == 1){
                $card = self::getTreasureTaskCard($uid,$row['id']);
                if(empty($card['id'])){
                    $config[$key]['special'] = 0;
                }else{
                    $config[$key]['card'] = $card;
                }

            }
            foreach($row['props'] as $propsKey => $propsTemp){
                if($propsTemp['propsId'] == 13 && isset($propsTemp['type'])){
                    if($propsTemp['type'] == 1){
                        $card = self::getTreasureTaskCard($uid,$row['id']);
                        if(empty($card['id'])){
                            $config[$key]['props'][$propsKey]['value'] = null;
                        }else{
                            $config[$key]['props'][$propsKey]['value'][] = $card;
                        }
                    }else{
                        $config[$key]['props'][$propsKey]['value'] = null;
                    }

                }
            }
        }
        if($origData){
            foreach ($config as $key=>$row){
                $config[$key]['props'][] = ['propsId'=>14,'num'=>$row['coins'],'value'=>$row['coins']];
                $config[$key]['props'][] = ['propsId'=>15,'num'=>$row['spins'],'value'=>$row['spins']];
                unset($config[$key]['coins']);
                unset($config[$key]['spins']);
                $temp = $config[$key]['props'];
                array_multisort(array_column($temp,'propsId'),SORT_DESC,$temp);
                $config[$key]['props'] = $temp;
            }

        }
        $betConfig  = oo::commonOprModel('config')->getTreasureProConfig($levelId);
        $reward     = $betConfig['pro'];
        foreach ($reward as $key=>$row){
            $temp = $row;
            unset($temp['pro']);
            $reward[$key] = $temp;
        }
        $bet = array_column($betConfig['superBet'],'bet');
        rsort($bet);
        return [
            'config' => $config,
            'bet'    => $bet,
            'reward' => $reward,
        ];
    }

    /**
     * 更新宝藏活动任务数量
     * @param $uid
     * @param $num
     * @param $from
     * @return mixed
     * Created by: Owen
     * Created on: 2020/7/27 20:04
     */
    public function updateTreasureTaskNum($uid,$num,$from){
        $taskType = self::getUserTreasureCurTaskType($uid);
        if($taskType == 1){
            $newNum = oo::commonOprRedis('User')->hIncrBy(okeys::TreasureTaskNum(),$uid,1);
        }else {
            if ($taskType == 2) {
                $newNum = oo::commonOprRedis('User')->hIncrBy(okeys::TreasureTaskNum(), $uid, $num);
            }else if ($taskType == 3 && $from == 1) {
                $newNum = oo::commonOprRedis('User')->hIncrBy(okeys::TreasureTaskNum(), $uid, $num);
            }else{
                $newNum = intval(oo::commonOprRedis('User')->hGet(okeys::TreasureTaskNum(),$uid));
            }
        }
        return [
            'taskId' => max(oo::commonOprRedis('User')->hGet(okeys::TreasureTaskId(),$uid),1),
            'taskNum'=> $newNum,
        ];
    }

    /**
     * 领取宝藏奖励
     * @param $uid
     * @return string
     * Created by: Owen
     * Created on: 2020/7/27 20:15
     */
    public function getTreasureTaskReward($uid){
        $userTreasureData = self::getUserTreasureData($uid);
        $taskId = max(oo::commonOprRedis('User')->hGet(okeys::TreasureTaskId(),$uid),1);
        $taskNum= intval(oo::commonOprRedis('User')->hGet(okeys::TreasureTaskNum(),$uid));
        $rewardConfig = array_column($userTreasureData['config'],NULL,'id');
        $reward = $rewardConfig[$taskId];
        if($reward['target'] > $taskNum){
            return oo::response(-2,[],'目标未达标');
        }
        oo::commonOprRedis('Activity')->hDel(okeys::TreasureTaskNum(),$uid);
        $newId = oo::commonOprRedis('User')->hIncrBy(okeys::TreasureTaskId(),$uid,$taskId==1?2:1);
        $actionReward = [];
        if(!empty($reward['coins'])){
            $actionReward['money'] = $reward['coins'];
        }
        if(!empty($reward['spins'])){
            $actionReward['spins'] = $reward['spins'];
        }
        $ret = !empty($actionReward) && oo::commonOprModel('member')->optProperty($uid,$actionReward,'+',213,"宝藏活动-{$taskId}");
        $cardData = [];
        if($ret && !empty($reward['props'])){
            foreach ($reward['props'] as $row){
                if($row['propsId'] == 13){
                    if(isset($row['type']) && $row['type'] == 1){
                        foreach($row['value'] as $valueTemp){
                            $userCardInfo = oo::commonOprModel('card')->getUserCardInfo($uid);
                            $userCurCard  = $userCardInfo['ciid'];
                            $userCurCard[$valueTemp['id']] += 1;
                            $ret2 = oo::commonOprModel('card')->updateUserCardInfo($uid,['ciid'=>$userCurCard]);
                            if($ret2 && $valueTemp['isNew']){
                                $cardsInfo = array_column(oo::commonOprModel('card')->getCardInfo(),NULL,'ciid');
                                $cardInfo  = $cardsInfo[$valueTemp['id']];
                                oo::commonOprModel('member')->optProperty($uid,['star'=>$cardInfo['ci_star_rank']],'+',213,"宝藏活动-{$taskId}");
                            }
                            oo::commonOprModel('statistics')->treasureRewardSta(13,$taskId,1);//宝藏探索产出消耗统计
                        }
                        $cardData = $row['value'];
                    }else if(isset($row['type']) && $row['type'] == 0){
                        $cardData[] = oo::commonOprModel('member')->sendReward($uid,$row['propsId'],1,213,"宝藏探索-随机金卡",0);
                    }
                    oo::logs()->debug3(["msg"=>"金卡发放,随机金卡","cardData"=>$cardData,'res'=>$row],'sendRankReward.txt');
                }else{
                    oo::commonOprModel('props')->addUserProps($uid,$row['propsId'],$row['num']);
                }
                oo::commonOprModel('statistics')->treasureRewardSta($row['propsId'],$taskId,$row['num']);//宝藏探索产出消耗统计
            }
        }
        if($ret && $reward['special'] == 1 && !empty($reward['card']['id'])){
            $userCardInfo = oo::commonOprModel('card')->getUserCardInfo($uid);
            $userCurCard  = $userCardInfo['ciid'];
            $userCurCard[$reward['card']['id']] += 1;
            $ret = oo::commonOprModel('card')->updateUserCardInfo($uid,['ciid'=>$userCurCard]);
            if($ret && $reward['card']['isNew']){
                $cardsInfo = array_column(oo::commonOprModel('card')->getCardInfo(),NULL,'ciid');
                $cardInfo  = $cardsInfo[$reward['card']['id']];
                oo::commonOprModel('member')->optProperty($uid,['star'=>$cardInfo['ci_star_rank']],'+',213,"宝藏活动-{$taskId}");
            }
            oo::commonOprModel('statistics')->treasureRewardSta(13,$taskId,1);//宝藏探索产出消耗统计
        }
        oo::commonOprRedis('Activity')->hDel(okeys::TreasureCurTaskType(),$uid);
        $data['curData'] = [
            'taskId' => $newId,
            'taskNum'=> 0,
            'cardData'=>$cardData,
        ];
        return oo::response(1,$data);
    }

    /**
     * 宝藏活动金卡
     * @param $uid
     * @param $id
     * @return array|mixed
     * Created by: Owen
     * Created on: 2020/7/27 20:21
     */
    public function getTreasureTaskCard($uid,$id){
        $cardData = oo::commonOprRedis('Activity')->hGet(okeys::TreasureTaskCard(),$uid."-".$id);
        if($cardData){
            $cardData = json_decode($cardData,true);
        }else{
            $cardData = self::getRankCard($uid);
            oo::commonOprRedis('Activity')->hSet(okeys::TreasureTaskCard(),$uid."-".$id,json_encode($cardData));
        }
        return $cardData;
    }

    /**
     * 领取宝藏活动转盘奖励
     * @param $uid
     * @param $id
     * @param $coins
     * @return string
     * Created by: Owen
     * Created on: 2020/7/28 14:56
     */
    public function getTreasureSlotReward($uid,$id,$coins){
        $cacheKey = okeys::TreasureCacheResult(0,$uid,"SLOT");
        $reward   = oo::commonOprRedis('Activity')->hGet($cacheKey,$id);
        if(empty($reward)){
            return oo::response(-2,['id'=>$id],'奖励已领取');
        }
        $assetsInfo = oo::commonOprModel('member')->getUserAssetsInfo($uid);
        if($coins > $assetsInfo['money']){
            return oo::response(-2,['id'=>$id],'金币不足');
        }
        $temp = explode('-',$reward);
        $rid  = $temp[0];
        $getCoins    = $temp[1] * $coins;
        $actionCoins = $getCoins - $coins;
        $actionType  = $actionCoins >= 0 ? "+" : "-";
        oo::commonOprModel('member')->optProperty($uid,['money'=>abs($actionCoins)],$actionType,214,"宝藏活动:(花费{$coins}),奖励倍率{$temp[1]},摇奖ID:{$rid}");
        oo::commonOprRedis('Activity')->hDel($cacheKey,$id);
        $proteEndTs = oo::commonOprModel('activitynew')->getEndproteTime($uid, date("Ymd",time()));
        $ttl = $proteEndTs-time();
        if($ttl < 100 && $actionCoins >= 0 ){
            oo::commonOprModel('member')->setUserStealProtect($uid,300);
            $proteEndTs = time()+298;
        }
        $newData = self::updateTreasureTaskNum($uid,$getCoins,$temp[0] == 1 ? 1 : 2);
        $data['curData']  = $newData;
        $data['id']       = $id;

        oo::commonOprModel('currency')->log($uid,"money","-",$coins,0,1003,$newData['taskId']);//发放消耗统计
        oo::commonOprModel('currency')->log($uid,"money","+",$getCoins,0,1010+$temp[0],$newData['taskId']);//宝藏统计
        $data['proteEndTs'] = $proteEndTs;//保护截至时间戳

        oo::commonOprModel('currency')->participation($uid, 'treasure', 0); //宝藏活动参与率

        return oo::response(1,$data);
    }

    /**
     * 宝藏活动结果
     * @param $uid
     * @param $id
     * @return array
     * Created by: Owen
     * Created on: 2020/7/28 14:43
     */
    public function getUserTreasureSlotResult($uid,$id = 0){
        $cacheKey = okeys::TreasureCacheResult(0,$uid,"SLOT");
        if($id){
            oo::commonOprRedis('Activity')->delete($cacheKey);
        }
        $len      = oo::commonOprRedis('Activity')->hLen($cacheKey);
        if($len <= 2){
            $userAssetsInfo = oo::commonOprModel('member')->getUserAssetsInfo($uid);
            $betConfig      = oo::commonOprModel('config')->getTreasureProConfig($userAssetsInfo['levelId'] ?? 1);
            $superBet       = array_column($betConfig['superBet'],'pro');
            $pro            = array_column($betConfig['pro'],'pro');
            $proReward      = array_column($betConfig['pro'],null,'id');
            $superReward    = array_column($betConfig['superBet'],null,'id');
            for ($i=0;$i<10-$len;$i++){
                $rid = oo::commonOprModel('slot')->get_rand($pro,true);
                $rid = $id ? $id : $rid+1;
                $temp = $proReward[$rid];
                if($temp['bet'] == -1){
                    $superRid  = oo::commonOprModel('slot')->get_rand($superBet,true);
                    $superRid  += 1;
                    $superTemp = $superReward[$superRid];
                    $temp['bet'] = $superTemp['bet'];
                }
                oo::commonOprRedis('Activity')->hSet($cacheKey,time().$i,$rid."-".$temp['bet']);
            }
            oo::commonOprRedis('Activity')->expire($cacheKey,2*3600);
        }
        $ridArr = oo::commonOprRedis('Activity')->hGetAll($cacheKey);
        $out    = [];
        foreach ($ridArr as $key=>$row){
            $temp = explode('-',$row);
            $out[] = [
                'id'    => $key,
                'rid'  => $temp[0],
                'bet'  => $temp[1],
            ];
        }
        return $out;
    }

    /**
     * 入门奖励
     * @param $uid
     * @param bool $get
     * @return string
     * Created by: Owen
     * Created on: 2020/7/28 16:50
     */
    public function getTreasureGift($uid,$get = false){
        if(!$get){
            if(oo::commonOprRedis('Activity')->hGet(okeys::TreasureTaskGift(),$uid)){
                return oo::response(-2,"奖励已领取");
            }
        }
        $userTreasureData = self::getUserTreasureData($uid);
        $rewardConfig = array_column($userTreasureData['config'],NULL,'id');
        $reward = $rewardConfig[1];
        if($get){
            return $reward['bet'][0];
        }
        oo::commonOprModel('member')->setUserStealProtect($uid,300);
        oo::commonOprModel('member')->optProperty($uid,['money'=>$reward['bet'][0]],"+",215,"宝藏活动-入门奖励");
        oo::commonOprRedis('Activity')->hSet(okeys::TreasureTaskGift(),$uid,1);
        return oo::response(1,["proteEndTs"=>time()+299]);
    }

    /**
     * 获取宝藏活动用户当前任务
     * @param $uid
     * @return mixed
     * Created by: Owen
     * Created on: 2020/7/31 10:36
     */
    public function getUserTreasureCurTaskType($uid){
        $cacheKey = okeys::TreasureCurTaskType();
        $cache    = oo::commonOprRedis('Activity')->hGet($cacheKey,$uid);
        if(empty($cache)){
            $userTreasureData = self::getUserTreasureData($uid);
            $taskId = max(oo::commonOprRedis('User')->hGet(okeys::TreasureTaskId(),$uid),1);
            $rewardConfig = array_column($userTreasureData['config'],NULL,'id');
            $reward = $rewardConfig[$taskId];
            oo::commonOprRedis('Activity')->hSet($cacheKey,$uid,$reward['taskType']);
            $cache = $reward['taskType'];
        }
        return $cache;
    }
}
