123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847 |
- <?php
- namespace app\common\service;
- use app\common\library\Redis;
- use app\common\model\CampaignMatch;
- use app\main\constants\PayConstants;
- use app\main\constants\CampaignConstants;
- use app\main\service\FinancialService;
- use app\main\service\UserDdFlushService;
- use app\main\service\UserService;
- use app\common\model\CampaignUserMatch;
- use app\main\service\MyScene;
- use think\Collection;
- use think\Config;
- use think\Cookie;
- use think\Log;
- use think\Request;
- use think\Db;
- use think\Cache;
- /**
- * Class CampaignService
- * @package app\common\service
- * wudd
- * 消耗活动 作废 迁移到 recharge
- * 20191029
- */
- class CampaignService
- {
- public static $self;
- /**
- * @return CampaignService
- */
- public static function instance()
- {
- if(self::$self == NULL){
- self::$self = new self();
- }
- return self::$self;
- }
- public function getCampaignReadModel()
- {
- return model('CampaignRead');
- }
- public function getCampaignMatchModel()
- {
- return model('CampaignMatch');
- }
- public function getUserMatchModel( $userId ){
- return model('CampaignUserMatch')->setConnect($userId);
- }
- public function getCampaignConsumeModel( $userId ){
- return model('CampaignConsume')->setConnect($userId);
- }
- /**
- * 记录当天打卡人数
- * @param $kandian
- */
- public function setSignNumToday( $matchId ){
- $rediskey = CampaignConstants::getMatchSignNumToday($matchId);
- $num = Redis::instance()->incr($rediskey);
- if ($num == 1){
- Redis::instance()->expire($rediskey, 3600*24);
- }
- return $num;
- }
- /**
- * 获取一个场次
- * wud
- */
- public function getMatchByTime( $matchDate, $kandian=50 ){
- $redisKey = CampaignConstants::getCampaignMatchRedisKey($matchDate,$kandian);
- $campaign = Redis::instance()->hGetAll($redisKey);//'active_id'=>$active
- if ( $campaign==false ){
- $campaign = $this->getCampaignMatchModel()
- ->where(['match_date'=>$matchDate,'kandian'=>$kandian])
- ->find();
- if ( !empty($campaign) ){
- $campaign = is_array($campaign) ? $campaign : $campaign->toArray();
- Redis::instance()->hmSet($redisKey, $campaign );
- Redis::instance()->expire($redisKey,3600*24);
- }
- }
- return $campaign;
- }
- /**
- * wudd
- * 报名成功更新活动场次表人数
- */
- public function updateMatchById( $matchId, $matchDate, $kandian=50 ){
- $redisKey = CampaignConstants::getCampaignMatchRedisKey($matchDate,$kandian);
- $update = [
- 'participator_num'=>['exp','participator_num+1'],
- ];
- $res = $this->getCampaignMatchModel()
- ->where(['id'=>$matchId])
- ->update($update);
- if ( $res && Redis::instance()->exists($redisKey) ){
- Redis::instance()->HINCRBY( $redisKey, 'participator_num', 1 );
- }
- return $res;
- }
- /**
- * 获取用户打卡记录
- */
- public function getUserMatch( $userId, $toDb=false ){
- $redisKey = CampaignConstants::getUserMatchKey($userId);
- if ( !$toDb ){
- $userMatch = Redis::instance()->hGetAll( $redisKey );
- if ( empty($userMatch) ){
- $toDb = true;
- }
- }
- if ( $toDb ){
- $userMatch = $this->getUserMatchModel($userId)
- ->where(['user_id'=>$userId])
- ->order('id desc')
- ->find();
- if (empty($userMatch)){
- $userMatch['noSign'] = 1;
- }else{
- $userMatch = $userMatch->toArray();
- }
- Redis::instance()->hmSet( $redisKey,$userMatch);
- Redis::instance()->expire($redisKey,3600*24);
- }
- if ( count($userMatch) < 2 ){
- $userMatch = [];
- }
- return $userMatch;
- }
- /**
- * @param $userId
- * @param $id
- * @param $status
- */
- public function updateUserMatch( $userId, $id, $status ){
- $this->getUserMatchModel($userId)->where(['id'=>$id])
- ->update(['status'=>$status,'updatetime'=>time()] );
- Redis::instance()->del(CampaignConstants::getUserMatchKey($userId));
- }
- /**
- * test
- */
- public function updateUserMatchTest( $args ){
- $update = [];
- if ( $args['status'] ){
- $update['status'] = $args['status'];
- }
- if ( $args['num'] ){
- $update['num'] = $args['num'];
- }
- if ( $args['is_again'] ){
- $update['is_again'] = $args['is_again'];
- }
- if ( $args['match_date'] ){
- $update['match_date'] = $args['match_date'];
- $update['updatetime'] = strtotime($args['match_date']);
- }
- if ( $args['match_id'] ){
- $update['match_id'] = $args['match_id'];
- }
- if ( $args['kandian'] ){
- $update['kandian'] = $args['kandian'];
- }
- $res = $this->getUserMatchModel($args['user_id'])->where(['id'=>$args['id']])
- ->update($update);
- Redis::instance()->del(CampaignConstants::getUserMatchKey($args['user_id']));
- Redis::instance()->del(CampaignConstants::getCampaignMatchRedisKey($args['match_date'],$args['kandian']));
- return $res;
- }
- /**
- *充值完成后自动报名
- */
- public function autoCheckIn( $userInfo, $matchInfo ){
- if ( !empty($matchInfo['campaign']) ){
- $args['nickname'] = $userInfo['nickname'];
- $args['avatar'] = $userInfo['avatar'];
- $args['openid'] = $userInfo['openid'];
- $args['channel_id'] = $userInfo['channel_id'];
- $args['kandian'] = $matchInfo['campaign']['kandian'];
- $args['matchDate'] = $matchInfo['campaign']['match_date'];
- try{
- $res = $this->checkIn( $userInfo['id'], $args );
- if ( $res['code'] != 200 ){
- LogService::info('autoCheckInError002'.json_encode($res));
- }else{
- Redis::instance()->set(CampaignConstants::getUserMatchFirstLogin($userInfo['id']),1,3600*4);//进入报名页弹窗标识
- LogService::info('autoCheckInSuccess');
- }
- }catch ( \Throwable $th ){
- LogService::info( 'autoCheckInError001'.$th->getMessage());
- }
- }else{
- LogService::info('autoCheckInError003'.json_encode($matchInfo).json_encode($userInfo));
- }
- return;
- }
- /**
- * @param $userId
- * @param $args
- * @return array
- * 报名 wud
- */
- public function checkIn( $userId, $args ){
- $res = ['code'=>201,'msg'=>'报名失败','return'=>[]];
- $match = $this->getMatchByTime($args['matchDate'], $args['kandian']);
- if ( !empty($match) && $match['match_date'] == date('Ymd',time() )){
- $userMatch = $this->getUserMatch( $userId );
- $active = $this->getCampaignById($match['campaign_id']);
- if ( empty($userMatch) || $userMatch['match_date'] != $match['match_date'] ){
- // 报名前刷新remainkandian
- LogService::info('autoCheckIn1'.json_encode($userMatch));
- UserDdFlushService::instance()->checkUserFlushState($userId);
- $insert = [
- 'active_id'=>$match['campaign_id'],
- 'user_id'=>$userId,
- 'match_id'=> $match['id'],
- 'match_date'=>$match['match_date'],
- 'period'=>$match['period'],
- 'kandian'=>$match['kandian'],
- 'openid'=>$args['openid'],
- 'channel_id'=>$args['channel_id'],
- 'endtime'=>time()+3600*24*10,
- 'num'=>0,
- 'status'=>1,
- 'updatetime'=>time(),
- 'createtime'=>time()
- ];
- //扣除书币
- $match['realKandian'] = $match['kandian'];
- $match['activeName'] = $active['name'];
- $isPay = FinancialService::instance()->reduceKandianCampaign( $userId, $match);
- if ( $isPay->code == 0 ){
- //更新场次人数
- $this->updateMatchById( $match['id'],$args['matchDate'], $args['kandian'] );
- //新增用户报名记录
- $isInsert = $this->getUserMatchModel($userId)->insert($insert);
- //插入报名弹幕 集合
- $this->insertBarrage($args['nickname'],$args['avatar'],$args['kandian']);
- //新增失败返回书币
- if ( !$isInsert ){
- //退回书币
- FinancialService::instance()->modifyUserKandian( $userId, 1, 3,$match['kandian']);
- return $res;
- }
- //删除 用户报名信息的缓存
- Redis::instance()->del(CampaignConstants::getUserMatchKey($userId));
- $res=['code'=>200, 'msg'=>'报名成功','return'=>[
- 'kandian'=>$args['kandian'],
- 'matchDate'=>$args['matchDate'],
- 'readNumber'=>$active['read_number'],
- ]];
- return $res;
- }
- LogService::info('activeMatcherror'.json_encode($isPay));
- $res['return'] = json_encode($isPay);
- return $res;
- }else{
- LogService::info('autoCheckIn'.json_encode($userMatch));
- $res['msg'] = '您已经报名成功,请刷新页面';
- }
- }
- return $res;
- }
- /**
- * wud 领奖
- * @param $userId
- * @param $matchId
- * @return array
- * @throws \think\Exception
- * @throws \think\exception\PDOException
- */
- public function getReward( $userId, $args ){
- $res = ['code'=>201,'msg'=>'奖励未发放,请稍后'];
- $match = $this->getMatchByTime($args['matchDate'], $args['kandian']);
- if ( !empty($match) ){
- //查看挑战是否完成
- $data = $this->getUserMatch( $userId );
- if ( !empty($data) && $data['match_date']==$match['match_date'] && $data['status'] == 3 ){
- $days = intval( ( time()-strtotime($data['match_date']) )/(3600*24) );
- if ( $days == 0 ){
- $res['msg'] = '奖励明日发放';
- return $res;
- }
- if ( $days-$match['period'] > CampaignConstants::CAMPAIGN_PERIOD_DAY){// 领奖超时 为失败
- $res['msg'] = '超过领奖时间';
- $this->updateUserMatch($userId,$data['id'],5);
- return $res;
- }
- //查看奖励是否发放 打卡完成后的2天 0点1分 计算 ,计算规则 $this->getAward
- if ( $match['award'] == false ){
- $res['msg'] = '系统正在计算,请稍后';
- return $res;
- }
- //计算奖励
- //$reward = $match['success_num'] ? ( $match['participator_num'] * $match['kandian'] + $match['subsidy_need'] )/$match['success_num'] : 0;
- //更新 场次表和打卡日志表
- $this->getCampaignMatchModel()->where(['id'=>$match['id']])->update(['award_amount'=>['exp','award_amount+'.$match['award']]]);
- $success = $this->getUserMatchModel($userId)
- ->where(['id'=>$data['id']])
- ->update(['status'=>4, 'reward'=>$match['award'],'updatetime'=>time()] );
- //删除用户打卡日志缓存 更新场次缓存
- Redis::instance()->del(CampaignConstants::getUserMatchKey($userId));
- $this->updateMatchById( $match['id'], $args['matchDate'], $args['kandian'] );
- if ( $success ){
- //增加书币
- FinancialService::instance()->modifyUserKandian( $userId, 1, 1,0,$match['award'],'活动赠送书币',2);
- $res['code'] = 200;
- $res['data'] = $match['award'];
- $res['msg'] = '领取成功';
- return $res;
- }
- }
- $res['msg'] = '操作异常';
- return $res;
- }
- return $res;
- }
- /**
- * @return mixed
- * 用户第一次进入页面 标记 n
- */
- public function setUserMatchFirstLogin($userId){
- $key = CampaignConstants::getUserMatchFirstLogin($userId);
- if( Redis::instance()->setnx($key,1) ){
- Redis::instance()->expire($key,3600);
- return true;
- }
- return false;
- }
- /**
- * 我的挑战记录
- */
- public function getUserRecharge( $userId ){
- // $data = Cache::get('LIST'.$userId);
- // if( $data == false ){
- $data = $this->getUserMatchModel($userId)->where(['user_id'=>$userId])->order(['id desc'])->select();
- Cache::set('LIST'.$userId,$data,60);
- // }
- return $data;
- }
- /**
- * 活动信息
- * wudd
- */
- public function getActivityById( $activeId, $toDb=false ){
- $redisKey = CampaignConstants::getCampaignRedisKey($activeId);
- if ( !$toDb ){
- $activiy = Redis::instance()->hGetAll($redisKey);
- $toDb = empty($activiy) ? true : false;
- }
- if ( $toDb ){
- $activiy = $this->getCampaignReadModel()
- ->where([
- 'id'=>$activeId
- ])
- ->find();
- $activiy = is_array($activiy) ? $activiy : $activiy->toArray();
- redis::instance()->hmSet($redisKey, $activiy);
- Redis::instance()->expire($redisKey,3600*24);
- }
- return $activiy;
- }
- /**
- * wudd
- * 批量获取场次数据
- */
- public function getMatchBatch( $matchLevel, $dates ){
- $campaignRedis = [];
- foreach ($matchLevel as $kandian) {
- foreach ( $dates as $date ){
- $campaignRedis[] = $this->getMatchByTime($date, $kandian);
- }
- }
- return $campaignRedis;
- // $campaign = $pipe->exec();
- // $isExists = [];
- // $campaignRedis = [];
- // if( !empty($campaign) )foreach ($campaign as $k =>$v){
- // if (!empty($v)){
- // $isExists[] = $v['id'];
- // $campaignRedis[] = $v;
- // }
- // }
- // if ( count($isExists) < count($matchLevel) ){
- // $isExists[] = -1;
- // $campaignDb = $this->getCampaignMatchModel()
- // ->where(['id'=>['not in', $isExists], 'match_date'=>['in', $dates]])
- // ->select();
- // if ( $campaignDb ){
- // $pipe = Redis::instance()->multi(\Redis::PIPELINE);
- // foreach ($campaignDb as $vv) {
- // if ( is_object($vv) ){
- // $vv = $vv->toArray();
- // }
- // $campaignRedis[] = $vv;
- // $pipe->hMSet(CampaignConstants::getCampaignMatchRedisKey( $vv['match_date'],$vv['kandian'] ), $vv);
- // $pipe->expire(CampaignConstants::getCampaignMatchRedisKey( $vv['match_date'],$vv['kandian'] ), 3600*24);
- // }
- // $pipe->exec();
- // }
- // }
- // unset($campaignDb);
- // unset($campaign);
- // return $campaignRedis;
- }
- /**
- * 计算奖励
- */
- public function awardInit( $date = 0 ){
- $awardDay = CampaignConstants::CAMPAIGN_PERIOD_DAY;
- if ( !$date ){
- $date = date( 'Ymd', time()-3600*24*(7+$awardDay) );
- }
- $data = $this->getCampaignMatchModel()->where([
- 'match_date' => $date,
- ])->select();
- if ( !empty($data) ){
- $activeId = $data[0]->campaign_id;
- $active = $this->getActivityById($activeId);
- //每个场次的基数
- $baseNum =$active['elementary_num']*$active['elementary_need']+$active['intermediate_num']*$active['intermediate_need']+$active['advanced_num']*$active['advanced_need'];
- //实际报名和成功的人数
- $signNum = 0;
- $successNum = 0;
- foreach ($data as $k =>$v){
- $signNum += $v['kandian']*$v['participator_num'];
- $successNum += $v['kandian']*$v['success_num'];
- }
- //官方补贴+基数+实际报名人数
- $signNum += $baseNum+$active['subsidy_need'];
- //基数+实际成功的人数
- $successNum += $baseNum;
- //升值倍数
- $awardPercent = !empty($successNum) ?round($signNum/$successNum,2) : 1;
- foreach ($data as $k=>$v) {
- $update[$k]['id'] = $v['id'];
- $update[$k]['award'] = intval($v['kandian']*$awardPercent);
- }
- $this->getCampaignMatchModel()->isUpdate()->saveAll($update);
- }
- return;
- }
- /**
- * 弹幕
- * @param $matchLevel
- * @return array
- */
- public function getBarrage10( $matchLevel ){
- $key = CampaignConstants::MATCH_SIGN_USER_INFO;
- $data = Cache::get($key);
- if ( $data == false ){
- $data = [
- 'name'=>[],
- 'avatar'=>[]
- ];
- $nameInit = ['果果吧','我本善良','Bear.zheng','书友','幸福','可乐要加冰块','金芳','有些梦,忘了追','杨洪旭'];
- $len = Redis::instance()->sCard(CampaignConstants::MATCH_SIGN_USER_INFO);
- if ( $len >= 20 ){
- $res = Redis::instance()->spop($key, 10);
- }else{
- $res = Redis::instance()->SRANDMEMBER($key, 10);
- }
- if ( !empty($res) ){
- foreach ( $res as $k=>$v ){
- $res[$k] = json_decode( $v );
- }
- $data['name'] = array_column($res, 'name');
- $data['avatar'] = array_column( $res, 'avatar');
- }
- unset($res);
- //不够十个填充
- $diff = 10 - count($data['name']);
- while ( $diff ){
- $data['name'][] = array_pop($nameInit).'参加了'.$matchLevel[rand(0,2)].'看点挑战赛';
- $data['avatar'][] ="/assets/img/frontend/campaign/default_people.png";
- $diff--;
- }
- Cache::set( $key, $data, 6 );
- }
- return $data;
- }
- /**
- * @param $nickname
- * @param $avatar
- * @param $kandian
- * 插入弹幕 集合
- */
- private function insertBarrage( $nickname, $avatar, $kandian ){
- $data['name'] = $nickname.' 报名了'.$kandian.'书币挑战赛';
- $data['avatar'] = $avatar;
- if ( Redis::instance()->scard(CampaignConstants::MATCH_SIGN_USER_INFO) < 20 ){
- Redis::instance()->sadd(CampaignConstants::MATCH_SIGN_USER_INFO, json_encode( $data ) );
- }
- return;
- }
- /**
- * @param $userId
- * @return array
- */
- public function getActiveByUser( $userId ){
- //检查活动是否开启
- $isOpen = $this->checkCampaignOpen();
- if ($isOpen != 1){
- return [];
- }
- $userMatch = $this->getUserMatch( $userId );
- $res = [];
- if ( !empty ($userMatch) && isset($userMatch['active_id']) ){
- $res = $this->getActivityById( $userMatch['active_id'] );
- }
- return $res;
- }
- /**
- * 计算本期的报名人数 总奖池 和预期奖励
- * 奖励=奖励系数*报名书币
- * 奖励系数=官方补贴+初级报名人数*初级书币+中级报名人数*中级书币+高级报名人数*高级书币/(初级完成人数*初级书币+中级完成人数*中级书币+高级完成人数*高级书币)
- */
- public function getAward( $dateMatch, $active){
- //报名人数基数
- $signNum = $active['base_number'];
- //基础奖励
- $awardNum =$active['elementary_num']*$active['elementary_need']+$active['intermediate_num']*$active['intermediate_need']+$active['advanced_num']*$active['advanced_need'];
- foreach ($dateMatch as $k =>$v){
- $signNum+=$v['participator_num'];
- $awardNum +=$v['kandian']*$v['participator_num'];
- }
- $totalAward = $awardNum+$active['subsidy_need'];
- $awardPercent = !empty($awardNum) ?round($totalAward/$awardNum,2) : 1;
- $res = [
- 'signNum'=>$signNum,
- 'totalAward'=>$totalAward,
- 'awardPercent'=>$awardPercent
- ];
- return $res;
- }
- /**
- * 获取最近一次结束得场次
- */
- public function lastTimeMatch()
- {
- $key = CampaignConstants::getLastAwardMatch();
- $res = Redis::instance()->hGetAll($key);
- if ( empty($res) ){
- $data = $this->getCampaignMatchModel()->where('award','>', 0)->order('id desc')->limit(3)->select();
- if ( empty($data) ){
- $res['nodata'] = 1;
- }else{
- foreach($data as $k =>$v ){
- $res[$v['kandian']] = $v['award'];
- }
- }
- Redis::instance()->hMSet($key, $res);
- Redis::instance()->expire($key, 3600*23);
- }
- if ( isset($res['nodata']) ){
- $res = [];
- }
- return $res;
- }
- /**
- * 充值后 如果没有参加活动 发推送
- */
- public function checkActive($userId){
- //检查活动是否开启
- $isOpen = $this->checkCampaignOpen();
- if ($isOpen != 1){
- return 0;
- }
- $res = $this->getUserMatch($userId);
- if ( empty($res) ){
- $res = $this->getLatestReadInfo();
- if ( !empty($res) ){
- return $res['id'];//有进行得活动进行推送
- }
- }
- return 0;
- }
- /**
- * 查看消耗活动是否开启 :1 开启 2 是关闭
- * @return int
- */
- public function checkCampaignOpen()
- {
- $redisKey = CampaignConstants::CAMPAIGN_IS_OPEN;
- $isOpen = Redis::instance()->get($redisKey);
- if ( !$isOpen ){
- $lastDate = model('CampaignMatch')->field('match_date,period')->order('id desc')->limit(1)->find();
- if ( !empty($lastDate) && isset($lastDate->match_date) ){
- //判断最后一个场次 是不是已经结束
- $day = ( time()-date($lastDate->match_date) )/(3600*24);
- $day-=$lastDate->period;
- if( ($day-$lastDate->match_date) > 4 ){
- $lastDate = [];
- }
- }
- $isOpen = empty($lastDate) ? 2 : 1;
- Redis::instance()->set($redisKey,$isOpen,3600*24);
- }
- return (int)$isOpen;
- }
- /**
- * 维护活动场次数据
- * @param $campaign_id
- * @param $campaign_data
- */
- public function maintainMacth($campaign_id, $campaign_data)
- {
- $start_time = strtotime($campaign_data['start_time']);
- $end_time = strtotime($campaign_data['end_time']);
- if($end_time >= $start_time) {
- for ($i = 0; ($start_time + $i * 86400) <= $end_time; $i++) {
- $match_date = date('Ymd', $start_time + $i * 86400);
- $mdata_elementary = [
- 'campaign_id' => $campaign_id,
- 'subsidy_need' => $campaign_data['subsidy_need'],
- 'match_date' => $match_date,
- 'period' => $campaign_data['period'],
- 'kandian' => $campaign_data['elementary_need'],
- 'goods_id' => $campaign_data['elementary_goods_id'],
- 'level'=> 0,
- 'createtime' => time(),
- 'updatetime' => time()
- ];
- $mdata_intermediate = [
- 'campaign_id' => $campaign_id,
- 'subsidy_need' => $campaign_data['subsidy_need'],
- 'match_date' => $match_date,
- 'period' => $campaign_data['period'],
- 'kandian' => $campaign_data['intermediate_need'],
- 'goods_id' => $campaign_data['intermediate_goods_id'],
- 'level'=> 1,
- 'createtime' => time(),
- 'updatetime' => time()
- ];
- $mdata_advanced = [
- 'campaign_id' => $campaign_id,
- 'subsidy_need' => $campaign_data['subsidy_need'],
- 'match_date' => $match_date,
- 'period' => $campaign_data['period'],
- 'kandian' => $campaign_data['advanced_need'],
- 'goods_id' => $campaign_data['advanced_goods_id'],
- 'level'=> 2,
- 'createtime' => time(),
- 'updatetime' => time()
- ];
- $this->getCampaignMatchModel()->insert($mdata_elementary);
- $this->getCampaignMatchModel()->insert($mdata_intermediate);
- $this->getCampaignMatchModel()->insert($mdata_advanced);
- }
- }
- }
- /**
- * 根据活动ID,删除Match表中数据
- * @param $campaign_id
- */
- public function delMatch($campaign_id)
- {
- $rst = $this->getCampaignMatchModel()->where('campaign_id', $campaign_id)->select();
- if ($rst) {
- $pipe = Redis::instance()->multi(\Redis::PIPELINE);
- foreach ($rst as $k=>$v){
- $redis_key = CampaignConstants::USER_MATCH_KEY_PREFIX.$v->match_date.$v->kandian;
- $pipe->del($redis_key);
- }
- $pipe->exec();
- }
- $this->getCampaignMatchModel()->where('campaign_id', $campaign_id)->delete();
- }
- /**
- * 获取最新有效活动(有Banner 或者 弹窗图 或者 智能推送图)
- * @param $channel_id
- * @param $user_id
- * @return array
- */
- public function getLatestCampaign($userInfo)
- {
- //检查是不是新用户
- $user_id = $userInfo->id;
- $channel_id = $userInfo->channel_id;
- $createDate = date('Ymd',$userInfo->createtime);
- if ($createDate == date('Ymd',time())) {//新用户不弹出
- return [];
- }
- //检查活动是否开启
- $isOpen = $this->checkCampaignOpen();
- if ($isOpen != 1){
- return [];
- }
- // 获取用户参与活动的信息
- $userMatchInfo = $this->getUserMatch($user_id);
- $registration_time = $userMatchInfo['createtime'] ?? 0;
- //$active_end_time = $registration_time + ($userMatchInfo['period'] + CampaignConstants::CAMPAIGN_PERIOD_DAY) * 86400;
- $arward_flag = true;
- if ($userMatchInfo) {
- $diff_day = (time() - $registration_time) / 86400 - $userMatchInfo['num'];
- $arward_flag = (in_array($userMatchInfo['status'], ['1', '2']) && $diff_day <= 2) || ($userMatchInfo['status'] == 3 && $diff_day <= 3);
- }
- if ($userMatchInfo && $userMatchInfo['active_id'] && $arward_flag) {
- $data = $this->getCampaignById($userMatchInfo['active_id']);
- } else {
- //黑名单改为白名单
- //$forbidden_channels = explode(',', str_replace(',', ',', Config::get('site.campaign_forbidden_channels')));
- $isWrite = model('ChannelSpecialManage')->isWhite('campaign', $channel_id);
- if(!$isWrite){
- $data = [];
- }else{
- $data = $this->getLatestReadInfo();
- if ($data && $data['end_time'] < time()) {
- $data = [];
- }
- }
- }
- return $data;
- }
- /**
- * 按时间取出最新的一条挑战赛活动信息
- */
- public function getLatestReadInfo()
- {
- $redisKey = CampaignConstants::CAMPAIGN_READ_LAST_KEY;
- $rst_arr = Redis::instance()->hGetAll($redisKey);
- if (empty($rst_arr)) {
- $rst = $this->getCampaignReadModel()
- ->where('status', 'eq', 'normal')
- ->where('start_time', '<=', time())
- ->where('end_time', '>=', time())
- ->where(function ($query) {
- $query->where('banner_img', 'neq', '')
- ->whereor('popup_img', 'neq', '');
- })
- ->order('id', 'desc')
- ->find();
- $ttl = strtotime(date('Y-m-d 23:59:59', time())) - time();
- if ($rst) {
- $rst_arr = $rst->toArray();
- $rst_arr['banner_img'] = !empty($rst_arr['banner_img']) ? cdnurl($rst_arr['banner_img']) : '';
- $rst_arr['popup_img'] = !empty($rst_arr['popup_img']) ? cdnurl($rst_arr['popup_img']) : '';
- } else {
- $rst_arr = [
- 'id' => 0,
- 'end_time' => 0
- ];
- }
- Redis::instance()->hMSet($redisKey, $rst_arr);
- Redis::instance()->expire($redisKey, $ttl);
- }
- return $rst_arr;
- }
- /**
- * 通过ID获取信息
- * @param $id
- * @return array
- */
- public function getCampaignById($id)
- {
- $redisKey = CampaignConstants::CAMPAIGN_READ_KEY . $id;
- if (Redis::instance()->hGetAll($redisKey)) {
- return Redis::instance()->hGetAll($redisKey);
- } else {
- $rst = $this->getCampaignReadModel()
- ->where('id', '=', $id)
- ->find();
- $ttl = strtotime(date('Y-m-d 23:59:59', time())) - time();
- if ($rst) {
- $rst_arr = $rst->toArray();
- $rst_arr['banner_img'] = !empty($rst_arr['banner_img']) ? cdnurl($rst_arr['banner_img']) : '';
- $rst_arr['popup_img'] = !empty($rst_arr['popup_img']) ? cdnurl($rst_arr['popup_img']) : '';
- } else {
- $rst_arr = [];
- }
- Redis::instance()->hMSet($redisKey, $rst_arr);
- Redis::instance()->expire($redisKey, $ttl);
- return $rst_arr;
- }
- }
- /**
- * 删除Redis中最新的活动信息
- */
- public function delLatestCampaignRedis()
- {
- Redis::instance()->del(CampaignConstants::CAMPAIGN_READ_LAST_KEY);
- }
- /**
- * 删除活动缓存
- * @param $activeId
- */
- public function delReadRedisById($activeId)
- {
- $redisKey = CampaignConstants::getCampaignRedisKey($activeId);
- Redis::instance()->del($redisKey);
- }
- /**
- * 获取消费活动商品
- */
- public function getCampaignGoods()
- {
- $list = model('Goods')->getGoodsList(PayConstants::BUSINESS_WECHAT,PayConstants::GOODS_CATEGORY_CAMPAIGN,PayConstants::GOODS_TYPE_KD);
- return $list;
- }
- }
|