123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477 |
- <?php
- namespace app\admin\controller\card;
- use app\common\controller\Backend;
- use app\common\library\Redis;
- use app\common\service\CardFlipService;
- use app\main\constants\ActivityConstants;
- use app\common\model\CardFlip;
- use think\Config;
- use think\Controller;
- use think\Model;
- use think\Request;
- /**
- * 翻牌活动
- *
- * @icon fa fa-circle-o
- */
- class Flip extends Backend
- {
-
- /**
- * CardFlip模型对象
- */
- protected $model = null;
- protected $noNeedRight = ['index', 'edit', 'add','relateusergroup','ajaxlapse','initcache'];
- public function _initialize()
- {
- parent::_initialize();
- $this->model = model('CardFlip');
- $this->view->assign("stateList", $this->model->getStateList());
- }
-
- /**
- * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个方法
- * 因此在当前控制器中可不用编写增删改查的代码,如果需要自己控制这部分逻辑
- * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
- */
- /**
- * 查看
- */
- public function index()
- {
- //设置过滤方法
- $this->request->filter(['strip_tags']);
- if ($this->request->isAjax())
- {
- //如果发送的来源是Selectpage,则转发到Selectpage
- if ($this->request->request('pkey_name'))
- {
- return $this->selectpage();
- }
- list($where, $sort, $order, $offset, $limit) = $this->buildparams();
- $total = $this->model
- ->where($where)
- ->order($sort, $order)
- ->count();
- $list = $this->model
- ->where($where)
- ->order($sort, $order)
- ->limit($offset, $limit)
- ->select();
- $result = array("total" => $total, "rows" => $list);
- return json($result);
- }
- $camAuth = CardFlipService::instance()->getAuth($this->group,$this->auth->id);
- $this->assign('camAuth',$camAuth);
- return $this->view->fetch();
- }
- /**
- * 添加
- */
- public function add()
- {
- if ($this->request->isPost())
- {
- $params = $this->request->post("row/a");
- if ($params)
- {
- /*
- * 已经弃用,如果为了兼容老版可取消注释
- foreach ($params as $k => &$v)
- {
- $v = is_array($v) ? implode(',', $v) : $v;
- }
- */
- if ($this->dataLimit)
- {
- $params[$this->dataLimitField] = $this->auth->id;
- }
- $this->checkAwardParams($params['list']);
- try
- {
- //是否采用模型验证
- if ($this->modelValidate)
- {
- $name = basename(str_replace('\\', '/', get_class($this->model)));
- $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
- $this->model->validate($validate);
- }
- $list = $params['list'];
- unset($params['list']);
- $result = $this->model->allowField(true)->save($params);
- if ($result !== false)
- {
- $id = $this->model->getLastInsID();
- $this->addAwardList($list,$id);
- $this->success();
- }
- else
- {
- $this->error($this->model->getError());
- }
- }
- catch (\think\exception\PDOException $e)
- {
- $this->error($e->getMessage());
- }
- }
- $this->error(__('Parameter %s can not be empty', ''));
- }
- $awardList = $this->getAwards();
- $cam = CardFlipService::instance()->getAuth($this->group,$this->auth);
- $this->view->assign('cam',$cam);
- $this->view->assign('awardList',$awardList);
- return $this->view->fetch();
- }
- /**
- * 编辑
- */
- public function edit($ids = NULL)
- {
- $row = $this->model->get($ids);
- if (!$row)
- $this->error(__('No Results were found'));
- $adminIds = $this->getDataLimitAdminIds();
- if (is_array($adminIds))
- {
- if (!in_array($row[$this->dataLimitField], $adminIds))
- {
- $this->error(__('You have no permission'));
- }
- }
- if ($this->request->isPost())
- {
- $params = $this->request->post("row/a");
- if ($params)
- {
- /*
- * 已经弃用,如果为了兼容老版可取消注释
- foreach ($params as $k => &$v)
- {
- $v = is_array($v) ? implode(',', $v) : $v;
- }
- */
- try
- {
- $this->checkAwardParams($params['list']);
- $list = $params['list'];
- unset($params['list']);
- //是否采用模型验证
- if ($this->modelValidate)
- {
- $name = basename(str_replace('\\', '/', get_class($this->model)));
- $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
- $row->validate($validate);
- }
- $result = $row->allowField(true)->save($params);
- if ($result !== false)
- {
- $this->addAwardList($list,$ids);
- $this->success();
- }
- else
- {
- $this->error($row->getError());
- }
- }
- catch (\think\exception\PDOException $e)
- {
- $this->error($e->getMessage());
- }
- }
- $this->error(__('Parameter %s can not be empty', ''));
- }
- $awardList = $this->getAwards($ids);
- $this->view->assign('awardList',$awardList);
- $this->view->assign("row", $row);
- return $this->view->fetch();
- }
- /**
- * 获取 活动关联的奖品列表
- * @param int $id
- * @return array
- */
- private function getAwards($id = 0)
- {
- $awardList = [];
- if ($id){
- $lists = Model('CardAwards')->where('c_id',$id)->select();
- if (!empty($lists)){
- $aIds = array_column($lists,'a_id');
- $names = Model('AwardLists')->whereIn('id',$aIds)->select();
- $names = array_column($names,null,'id');
- foreach($lists as $k =>$v){
- $temp = [
- 'num'=>$k+1,
- 'a_id'=>$v['a_id'],
- 'id'=>$v['id'],
- 'show_name'=>$v['show_name'],
- 'percent'=>$v['percent'],
- 'name'=>$names[$v['a_id']]['name'] ?? '',
- ];
- $awardList[] = $temp;
- }
- }
- }
- $beginNum = count($awardList)+1;
- for ($i=$beginNum;$i<=6;$i++){
- $temp = [
- 'num'=>$i,
- 'id'=>0,
- 'a_id'=>0,
- 'show_name'=>'',
- 'percent'=>0,
- 'name'=>'',
- ];
- $awardList[] = $temp;
- }
- return $awardList;
- }
- /**
- * 检查活动添加的奖品
- * @param $list
- * @return bool
- */
- public function checkAwardParams($list)
- {
- $award = Model('AwardLists')->where('state',2)->field('id')->select();
- $ids = [];
- if (!empty($award)){
- $ids = array_column($award,'id');
- unset($award);
- }
- $percent = 0;
- for ($i=1;$i<=6;$i++){
- if( !isset($list['a_id'.$i]) || !$list['a_id'.$i]){
- $this->error('请添加6个奖品');
- }
- if (in_array($list['a_id'.$i],$ids)){
- $this->error('奖品失效,请添加其他奖品-'.$list['show_name'.$i]);
- }
- if (!$list['percent'.$i]){
- $this->error('请为奖品添写中奖概率');
- }
- $percent += $list['percent'.$i];
- }
- if ($percent != 100){
- $this->error('中奖概率和必须等于100');
- }
- return true;
- }
- /**
- * 添加或更新活动的奖品
- * @param $list
- * @param $cId
- * @return bool
- */
- public function addAwardList($list,$cId)
- {
- for ($i=1;$i<=6;$i++) {
- $insert = [
- 'show_name' => $list['show_name' . $i],
- 'a_id' => $list['a_id' . $i],
- 'c_id' => $cId,
- 'percent' => $list['percent' . $i],
- 'updatetime' => time(),
- ];
- if ($list['ac_id' . $i]) {
- model('CardAwards')->update($insert, ['id' => $list['ac_id' . $i]]);
- } else {
- model('CardAwards')->insert($insert);
- }
- }
- return true;
- }
- /**
- * 关联用户组
- */
- public function relateusergroup()
- {
- $id = $this->request->post('id');
- $groupId = $this->request->post('group_id');
- $this->model->update(['group_id'=>$groupId],['id'=>$id]);
- $this->success('关联成功');
- }
- /**
- * 状态操作
- */
- public function ajaxlapse()
- {
- $id = $this->request->param('id',0);
- $state = $this->request->param('state',0);
- if ( !$id || !$state ){
- $this->error('操作失败');
- }
- $state = $state == 2 ? 1 : 2;
- $obj = $this->model->find($id);
- $obj->state=$state;
- $obj->save();
- $this->success('操作成功');
- }
- /**
- * 初始化活动数据到redis
- * @throws \think\Exception
- */
- public function initCache()
- {
- $id = $this->request->param('id',0);
- if (!$id){
- $this->error('操作失败');
- }
- $cardInfo = model('CardFlip')->where(['id'=>$id,'state'=>1])->where('end_time','>',time())->find();
- if (!$cardInfo){
- $this->delCache($id);
- $this->error('操作成功');
- }
- $cardInfo = is_object($cardInfo) ? $cardInfo->toArray() : $cardInfo;
- $ttl = $cardInfo['end_time'] - time();
- $this->initCardInfo($cardInfo,$ttl);
- $this->initCodes($cardInfo['id'],$ttl);
- $this->initAwardList($cardInfo['id'],$ttl);
- $this->initActList();
- $this->success('操作成功');
- }
- /**
- * 初始化 中奖名单
- * @param $cId
- * @return bool
- */
- public function initAwardList($cId,$ttl)
- {
- $redisKey = ActivityConstants::CARD_AWARD_WIN_LIST.$cId;
- $awardList =CardFlipService::instance()->getCardAwardList($cId);
- $awardName = [];
- foreach ($awardList as $k=>$v){
- if (in_array($v['type'],[2,3,4])){
- $awardName[] = $v['show_name'];
- }
- }
- if ($awardName == false){
- $this->error('请先生成奖品缓存');
- }
- unset($awardList);
- $redislist = [];
- for ($i=0;$i<10;$i++){
- $t = [];
- $t['id'] = rand(100,999).'****'.rand(1000,9999);
- $t['name'] = $awardName[array_rand($awardName)];
- $res[] = $t;
- $redislist[] = json_encode($t);
- }
- Redis::instance()->del($redisKey);
- Redis::instance()->rpush($redisKey,...$redislist);
- Redis::instance()->expire($redisKey,$ttl);
- return true;
- }
- /**
- * 活动失效 清除缓存
- * @param $cId
- */
- private function delCache($cId)
- {
- $actKey = ActivityConstants::CARD_FLIP_INFO.$cId;//活动详情
- Redis::instance()->del($actKey);
- }
- /**
- * 初始化活动数据
- * @param $cardInfo
- */
- private function initCardInfo($cardInfo,$ttl)
- {
- $actKey = ActivityConstants::CARD_FLIP_INFO.$cardInfo['id'];//活动详情
- Redis::instance()->hmset($actKey,$cardInfo);
- Redis::instance()->expire($actKey,$ttl);
- return ;
- }
- /**
- * 初始化活动的中奖缓存,和活动关联的奖品缓存
- * @param $cId
- */
- private function initCodes($cId,$ttl)
- {
- $redisKey = ActivityConstants::CARD_FLIP_AWARD_LIST.$cId;
- $codeRedisKey = ActivityConstants::CARD_AWARD_CODES.$cId;
- $dbList = model('CardAwards')->where(['c_id'=>$cId])->select();
- $rdList = [];
- if ($dbList && $ttl){
- $codes = [];
- $percent = 0;
- foreach ($dbList as $k=>$v){
- $percent += $v['percent'];
- $codes[$percent] =$v['id'];
- $rdList[] = json_encode($v);
- }
- //生成奖品种子
- Redis::instance()->del($codeRedisKey);
- Redis::instance()->hmset($codeRedisKey,$codes);
- Redis::instance()->expire($codeRedisKey,$ttl);
- //将活动关联的奖品更新值缓存
- Redis::instance()->del($redisKey);
- Redis::instance()->sAddArray($redisKey,$rdList);
- Redis::instance()->expire($redisKey,$ttl);
- }
- return;
- }
- /**
- * 初始化 开始中,有banner的 活动集合
- * @return bool
- */
- private function initActList()
- {
- $data = model('CardFlip')
- ->where(['state'=>1])
- ->where('begin_time','<',time())
- ->where('end_time','>',time())
- ->select();
- $redisKey = ActivityConstants::CARD_FLIP_LISTS;
- if (!$data){
- Redis::instance()->del($redisKey);
- return true;
- }
- $rdSet = [];
- foreach ($data as $key =>$val){
- $t = [
- 'id'=>$val['id'],
- 'end_time'=>$val['end_time'],
- 'banner_img'=>$val['banner_img'],
- 'group_id'=>$val['group_id'],
- ];
- $rdSet[] = json_encode($t);
- }
- Redis::instance()->sAddArray($redisKey,$rdSet);
- return true;
- }
- }
|