Flip.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. <?php
  2. namespace app\admin\controller\card;
  3. use app\common\controller\Backend;
  4. use app\common\library\Redis;
  5. use app\common\service\CardFlipService;
  6. use app\main\constants\ActivityConstants;
  7. use app\common\model\CardFlip;
  8. use think\Config;
  9. use think\Controller;
  10. use think\Model;
  11. use think\Request;
  12. /**
  13. * 翻牌活动
  14. *
  15. * @icon fa fa-circle-o
  16. */
  17. class Flip extends Backend
  18. {
  19. /**
  20. * CardFlip模型对象
  21. */
  22. protected $model = null;
  23. protected $noNeedRight = ['index', 'edit', 'add','relateusergroup','ajaxlapse','initcache'];
  24. public function _initialize()
  25. {
  26. parent::_initialize();
  27. $this->model = model('CardFlip');
  28. $this->view->assign("stateList", $this->model->getStateList());
  29. }
  30. /**
  31. * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个方法
  32. * 因此在当前控制器中可不用编写增删改查的代码,如果需要自己控制这部分逻辑
  33. * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
  34. */
  35. /**
  36. * 查看
  37. */
  38. public function index()
  39. {
  40. //设置过滤方法
  41. $this->request->filter(['strip_tags']);
  42. if ($this->request->isAjax())
  43. {
  44. //如果发送的来源是Selectpage,则转发到Selectpage
  45. if ($this->request->request('pkey_name'))
  46. {
  47. return $this->selectpage();
  48. }
  49. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  50. $total = $this->model
  51. ->where($where)
  52. ->order($sort, $order)
  53. ->count();
  54. $list = $this->model
  55. ->where($where)
  56. ->order($sort, $order)
  57. ->limit($offset, $limit)
  58. ->select();
  59. $result = array("total" => $total, "rows" => $list);
  60. return json($result);
  61. }
  62. $camAuth = CardFlipService::instance()->getAuth($this->group,$this->auth->id);
  63. $this->assign('camAuth',$camAuth);
  64. return $this->view->fetch();
  65. }
  66. /**
  67. * 添加
  68. */
  69. public function add()
  70. {
  71. if ($this->request->isPost())
  72. {
  73. $params = $this->request->post("row/a");
  74. if ($params)
  75. {
  76. /*
  77. * 已经弃用,如果为了兼容老版可取消注释
  78. foreach ($params as $k => &$v)
  79. {
  80. $v = is_array($v) ? implode(',', $v) : $v;
  81. }
  82. */
  83. if ($this->dataLimit)
  84. {
  85. $params[$this->dataLimitField] = $this->auth->id;
  86. }
  87. $this->checkAwardParams($params['list']);
  88. try
  89. {
  90. //是否采用模型验证
  91. if ($this->modelValidate)
  92. {
  93. $name = basename(str_replace('\\', '/', get_class($this->model)));
  94. $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
  95. $this->model->validate($validate);
  96. }
  97. $list = $params['list'];
  98. unset($params['list']);
  99. $result = $this->model->allowField(true)->save($params);
  100. if ($result !== false)
  101. {
  102. $id = $this->model->getLastInsID();
  103. $this->addAwardList($list,$id);
  104. $this->success();
  105. }
  106. else
  107. {
  108. $this->error($this->model->getError());
  109. }
  110. }
  111. catch (\think\exception\PDOException $e)
  112. {
  113. $this->error($e->getMessage());
  114. }
  115. }
  116. $this->error(__('Parameter %s can not be empty', ''));
  117. }
  118. $awardList = $this->getAwards();
  119. $cam = CardFlipService::instance()->getAuth($this->group,$this->auth);
  120. $this->view->assign('cam',$cam);
  121. $this->view->assign('awardList',$awardList);
  122. return $this->view->fetch();
  123. }
  124. /**
  125. * 编辑
  126. */
  127. public function edit($ids = NULL)
  128. {
  129. $row = $this->model->get($ids);
  130. if (!$row)
  131. $this->error(__('No Results were found'));
  132. $adminIds = $this->getDataLimitAdminIds();
  133. if (is_array($adminIds))
  134. {
  135. if (!in_array($row[$this->dataLimitField], $adminIds))
  136. {
  137. $this->error(__('You have no permission'));
  138. }
  139. }
  140. if ($this->request->isPost())
  141. {
  142. $params = $this->request->post("row/a");
  143. if ($params)
  144. {
  145. /*
  146. * 已经弃用,如果为了兼容老版可取消注释
  147. foreach ($params as $k => &$v)
  148. {
  149. $v = is_array($v) ? implode(',', $v) : $v;
  150. }
  151. */
  152. try
  153. {
  154. $this->checkAwardParams($params['list']);
  155. $list = $params['list'];
  156. unset($params['list']);
  157. //是否采用模型验证
  158. if ($this->modelValidate)
  159. {
  160. $name = basename(str_replace('\\', '/', get_class($this->model)));
  161. $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
  162. $row->validate($validate);
  163. }
  164. $result = $row->allowField(true)->save($params);
  165. if ($result !== false)
  166. {
  167. $this->addAwardList($list,$ids);
  168. $this->success();
  169. }
  170. else
  171. {
  172. $this->error($row->getError());
  173. }
  174. }
  175. catch (\think\exception\PDOException $e)
  176. {
  177. $this->error($e->getMessage());
  178. }
  179. }
  180. $this->error(__('Parameter %s can not be empty', ''));
  181. }
  182. $awardList = $this->getAwards($ids);
  183. $this->view->assign('awardList',$awardList);
  184. $this->view->assign("row", $row);
  185. return $this->view->fetch();
  186. }
  187. /**
  188. * 获取 活动关联的奖品列表
  189. * @param int $id
  190. * @return array
  191. */
  192. private function getAwards($id = 0)
  193. {
  194. $awardList = [];
  195. if ($id){
  196. $lists = Model('CardAwards')->where('c_id',$id)->select();
  197. if (!empty($lists)){
  198. $aIds = array_column($lists,'a_id');
  199. $names = Model('AwardLists')->whereIn('id',$aIds)->select();
  200. $names = array_column($names,null,'id');
  201. foreach($lists as $k =>$v){
  202. $temp = [
  203. 'num'=>$k+1,
  204. 'a_id'=>$v['a_id'],
  205. 'id'=>$v['id'],
  206. 'show_name'=>$v['show_name'],
  207. 'percent'=>$v['percent'],
  208. 'name'=>$names[$v['a_id']]['name'] ?? '',
  209. ];
  210. $awardList[] = $temp;
  211. }
  212. }
  213. }
  214. $beginNum = count($awardList)+1;
  215. for ($i=$beginNum;$i<=6;$i++){
  216. $temp = [
  217. 'num'=>$i,
  218. 'id'=>0,
  219. 'a_id'=>0,
  220. 'show_name'=>'',
  221. 'percent'=>0,
  222. 'name'=>'',
  223. ];
  224. $awardList[] = $temp;
  225. }
  226. return $awardList;
  227. }
  228. /**
  229. * 检查活动添加的奖品
  230. * @param $list
  231. * @return bool
  232. */
  233. public function checkAwardParams($list)
  234. {
  235. $award = Model('AwardLists')->where('state',2)->field('id')->select();
  236. $ids = [];
  237. if (!empty($award)){
  238. $ids = array_column($award,'id');
  239. unset($award);
  240. }
  241. $percent = 0;
  242. for ($i=1;$i<=6;$i++){
  243. if( !isset($list['a_id'.$i]) || !$list['a_id'.$i]){
  244. $this->error('请添加6个奖品');
  245. }
  246. if (in_array($list['a_id'.$i],$ids)){
  247. $this->error('奖品失效,请添加其他奖品-'.$list['show_name'.$i]);
  248. }
  249. if (!$list['percent'.$i]){
  250. $this->error('请为奖品添写中奖概率');
  251. }
  252. $percent += $list['percent'.$i];
  253. }
  254. if ($percent != 100){
  255. $this->error('中奖概率和必须等于100');
  256. }
  257. return true;
  258. }
  259. /**
  260. * 添加或更新活动的奖品
  261. * @param $list
  262. * @param $cId
  263. * @return bool
  264. */
  265. public function addAwardList($list,$cId)
  266. {
  267. for ($i=1;$i<=6;$i++) {
  268. $insert = [
  269. 'show_name' => $list['show_name' . $i],
  270. 'a_id' => $list['a_id' . $i],
  271. 'c_id' => $cId,
  272. 'percent' => $list['percent' . $i],
  273. 'updatetime' => time(),
  274. ];
  275. if ($list['ac_id' . $i]) {
  276. model('CardAwards')->update($insert, ['id' => $list['ac_id' . $i]]);
  277. } else {
  278. model('CardAwards')->insert($insert);
  279. }
  280. }
  281. return true;
  282. }
  283. /**
  284. * 关联用户组
  285. */
  286. public function relateusergroup()
  287. {
  288. $id = $this->request->post('id');
  289. $groupId = $this->request->post('group_id');
  290. $this->model->update(['group_id'=>$groupId],['id'=>$id]);
  291. $this->success('关联成功');
  292. }
  293. /**
  294. * 状态操作
  295. */
  296. public function ajaxlapse()
  297. {
  298. $id = $this->request->param('id',0);
  299. $state = $this->request->param('state',0);
  300. if ( !$id || !$state ){
  301. $this->error('操作失败');
  302. }
  303. $state = $state == 2 ? 1 : 2;
  304. $obj = $this->model->find($id);
  305. $obj->state=$state;
  306. $obj->save();
  307. $this->success('操作成功');
  308. }
  309. /**
  310. * 初始化活动数据到redis
  311. * @throws \think\Exception
  312. */
  313. public function initCache()
  314. {
  315. $id = $this->request->param('id',0);
  316. if (!$id){
  317. $this->error('操作失败');
  318. }
  319. $cardInfo = model('CardFlip')->where(['id'=>$id,'state'=>1])->where('end_time','>',time())->find();
  320. if (!$cardInfo){
  321. $this->delCache($id);
  322. $this->error('操作成功');
  323. }
  324. $cardInfo = is_object($cardInfo) ? $cardInfo->toArray() : $cardInfo;
  325. $ttl = $cardInfo['end_time'] - time();
  326. $this->initCardInfo($cardInfo,$ttl);
  327. $this->initCodes($cardInfo['id'],$ttl);
  328. $this->initAwardList($cardInfo['id'],$ttl);
  329. $this->initActList();
  330. $this->success('操作成功');
  331. }
  332. /**
  333. * 初始化 中奖名单
  334. * @param $cId
  335. * @return bool
  336. */
  337. public function initAwardList($cId,$ttl)
  338. {
  339. $redisKey = ActivityConstants::CARD_AWARD_WIN_LIST.$cId;
  340. $awardList =CardFlipService::instance()->getCardAwardList($cId);
  341. $awardName = [];
  342. foreach ($awardList as $k=>$v){
  343. if (in_array($v['type'],[2,3,4])){
  344. $awardName[] = $v['show_name'];
  345. }
  346. }
  347. if ($awardName == false){
  348. $this->error('请先生成奖品缓存');
  349. }
  350. unset($awardList);
  351. $redislist = [];
  352. for ($i=0;$i<10;$i++){
  353. $t = [];
  354. $t['id'] = rand(100,999).'****'.rand(1000,9999);
  355. $t['name'] = $awardName[array_rand($awardName)];
  356. $res[] = $t;
  357. $redislist[] = json_encode($t);
  358. }
  359. Redis::instance()->del($redisKey);
  360. Redis::instance()->rpush($redisKey,...$redislist);
  361. Redis::instance()->expire($redisKey,$ttl);
  362. return true;
  363. }
  364. /**
  365. * 活动失效 清除缓存
  366. * @param $cId
  367. */
  368. private function delCache($cId)
  369. {
  370. $actKey = ActivityConstants::CARD_FLIP_INFO.$cId;//活动详情
  371. Redis::instance()->del($actKey);
  372. }
  373. /**
  374. * 初始化活动数据
  375. * @param $cardInfo
  376. */
  377. private function initCardInfo($cardInfo,$ttl)
  378. {
  379. $actKey = ActivityConstants::CARD_FLIP_INFO.$cardInfo['id'];//活动详情
  380. Redis::instance()->hmset($actKey,$cardInfo);
  381. Redis::instance()->expire($actKey,$ttl);
  382. return ;
  383. }
  384. /**
  385. * 初始化活动的中奖缓存,和活动关联的奖品缓存
  386. * @param $cId
  387. */
  388. private function initCodes($cId,$ttl)
  389. {
  390. $redisKey = ActivityConstants::CARD_FLIP_AWARD_LIST.$cId;
  391. $codeRedisKey = ActivityConstants::CARD_AWARD_CODES.$cId;
  392. $dbList = model('CardAwards')->where(['c_id'=>$cId])->select();
  393. $rdList = [];
  394. if ($dbList && $ttl){
  395. $codes = [];
  396. $percent = 0;
  397. foreach ($dbList as $k=>$v){
  398. $percent += $v['percent'];
  399. $codes[$percent] =$v['id'];
  400. $rdList[] = json_encode($v);
  401. }
  402. //生成奖品种子
  403. Redis::instance()->del($codeRedisKey);
  404. Redis::instance()->hmset($codeRedisKey,$codes);
  405. Redis::instance()->expire($codeRedisKey,$ttl);
  406. //将活动关联的奖品更新值缓存
  407. Redis::instance()->del($redisKey);
  408. Redis::instance()->sAddArray($redisKey,$rdList);
  409. Redis::instance()->expire($redisKey,$ttl);
  410. }
  411. return;
  412. }
  413. /**
  414. * 初始化 开始中,有banner的 活动集合
  415. * @return bool
  416. */
  417. private function initActList()
  418. {
  419. $data = model('CardFlip')
  420. ->where(['state'=>1])
  421. ->where('begin_time','<',time())
  422. ->where('end_time','>',time())
  423. ->select();
  424. $redisKey = ActivityConstants::CARD_FLIP_LISTS;
  425. if (!$data){
  426. Redis::instance()->del($redisKey);
  427. return true;
  428. }
  429. $rdSet = [];
  430. foreach ($data as $key =>$val){
  431. $t = [
  432. 'id'=>$val['id'],
  433. 'end_time'=>$val['end_time'],
  434. 'banner_img'=>$val['banner_img'],
  435. 'group_id'=>$val['group_id'],
  436. ];
  437. $rdSet[] = json_encode($t);
  438. }
  439. Redis::instance()->sAddArray($redisKey,$rdSet);
  440. return true;
  441. }
  442. }