123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437 |
- <?php
- namespace app\api\controller;
- use app\common\controller\Api;
- use app\common\Service\Lottery\LotteryService;
- use app\common\Service\Lottery\LotteryChanceService;
- use app\common\Service\Lottery\LotteryRecordService;
- use app\common\Service\Lottery\LotteryActivityService;
- use app\common\model\lottery\LotteryActivity;
- use app\common\model\lottery\LotteryPrize;
- use app\common\model\lottery\LotteryWinRecord;
- use app\common\library\Auth;
- use app\api\validate\Lottery as LotteryValidate;
- use app\common\Enum\ActivityEnum;
- use app\common\Enum\LotteryEnum;
- use app\common\exception\BusinessException;
- use app\common\Enum\ErrorCodeEnum;
- use think\Exception;
- use app\common\Service\OrderService;
- /**
- * 抽奖API控制器
- */
- class Lottery extends Api
- {
- protected $noNeedLogin = ['activityList', 'activityDetail', 'getPrizes'];
- protected $noNeedRight = ['*'];
- /**
- * 获取抽奖活动列表
- */
- public function getActivityList()
- {
- // 验证参数
- $validate = new LotteryValidate();
- $params = $this->request->param();
- if (!$validate->scene('activityList')->check($params)) {
- $this->error($validate->getError());
- }
- $page = $params['page'] ?? 1;
- $limit = $params['pageSize'] ?? 10;
- $status = $params['status'] ?? ActivityEnum::ACTIVITY_STATUS_ONGOING; // 默认只返回进行中的活动
- $where = [];
- if ($status !== '') {
- $where['status'] = $status;
- }
- // 只返回进行中且在时间范围内的活动
- $now = time();
- $where['start_time'] = ['<=', $now];
- $where['end_time'] = ['>=', $now];
- $activities = LotteryActivity::where($where)
- ->field('id,name,description,cover_image,type,status,start_time,end_time,lottery_type,guide_image,guide_text,intro_content')
- ->order('createtime desc')
- ->page($page, $limit)
- ->select();
- $list = [];
- foreach ($activities as $activity) {
- $item = $activity->toArray();
-
- // 获取奖品信息
- $prizes = LotteryPrize::where('activity_id', $activity->id)
- ->where('status', 1)
- ->where('type', '>', 1) // 排除未中奖类型
- ->field('id,name,type,image,probability')
- ->order('sort_order asc')
- ->select();
- $item['prizes'] = $prizes;
-
- // 统计信息
- $item['total_participants'] = LotteryChanceService::getActivityParticipants($activity->id);
-
- $list[] = $item;
- }
- $this->success('获取成功', [
- 'list' => $list,
- 'total' => LotteryActivity::where($where)->count()
- ]);
- }
- /**
- * 获取活动详情
- */
- public function getActivityDetail()
- {
- // 验证参数
- $validate = new LotteryValidate();
- if (!$validate->scene('activityDetail')->check($this->request->param())) {
- $this->error($validate->getError());
- }
- $activityId = $this->request->param('lottery_id/d');
- $activity = LotteryActivity::find($activityId);
- if (!$activity) {
- throw new BusinessException('活动不存在', ErrorCodeEnum::USER_ACTIVITY_NOT_FOUND);
- }
- $detail = $activity->toArray();
- // 获取奖品列表
- $prizes = LotteryPrize::where('activity_id', $activityId)
- ->where('status', 1)
- ->field('id,name,type,image,description,probability,total_stock,remain_stock,win_prompt,sort_order,unlock_people_num')
- ->order('sort_order asc')
- ->select();
-
- // 检查奖品是否已解锁(如果开启按人数解锁)
- if ($activity->unlock_by_people) {
- $currentPeopleCount = LotteryChanceService::getActivityParticipants($activityId);
- foreach ($prizes as &$prize) {
- $prize['is_unlocked'] = $prize->isUnlocked($currentPeopleCount);
- }
- } else {
- foreach ($prizes as &$prize) {
- $prize['is_unlocked'] = true;
- }
- }
- $detail['prizes'] = $prizes;
- // 统计信息
- $detail['total_participants'] = LotteryChanceService::getActivityParticipants($activityId);
- // 如果用户已登录,返回用户相关信息
- if (Auth::instance()->isLogin()) {
- $userId = Auth::instance()->id;
- $detail['user_chances'] = LotteryService::getUserChances($activityId, $userId);
- $detail['user_draw_count'] = LotteryRecordService::getUserDrawCount($activityId, $userId);
- $detail['user_win_count'] = LotteryRecordService::getUserWinCount($activityId, $userId);
- }
- $this->success('获取成功', $detail);
- }
- /**
- * 执行抽奖
- */
- public function draw()
- {
- // 验证参数
- $validate = new LotteryValidate();
- if (!$validate->scene('draw')->check($this->request->param())) {
- $this->error($validate->getError());
- }
- $activityId = $this->request->post('lottery_id/d');
- $userId = $this->auth->id;
- $result = LotteryService::drawLottery($activityId, $userId);
- $this->success('抽奖成功', $result);
- }
- /**
- * 获取用户抽奖机会
- */
- public function getUserChances()
- {
- // 验证参数
- $validate = new LotteryValidate();
- if (!$validate->scene('getUserChances')->check($this->request->param())) {
- $this->error($validate->getError());
- }
- $activityId = $this->request->post('lottery_id/d');
- $userId = $this->auth->id;
- $chances = LotteryChanceService::getUserChanceDetail($activityId, $userId);
- $this->success('获取成功', $chances);
- }
- /**
- * 获取用户抽奖记录
- */
- public function getDrawRecords()
- {
- // 验证参数(activity_id可选)
- $params = $this->request->param();
- $validate = new LotteryValidate();
-
- // 如果有activity_id参数,则把它映射为activity_id_optional进行验证
- $validateParams = $params;
- if (isset($params['lottery_id'])) {
- $validateParams['activity_id_optional'] = $params['lottery_id'];
- unset($validateParams['lottery_id']);
- }
- if (isset($params['status'])) {
- $validateParams['record_status'] = $params['status'];
- unset($validateParams['status']);
- }
- if (!$validate->scene('getDrawRecords')->check($validateParams)) {
- $this->error($validate->getError());
- }
- $activityId = $this->request->post('lottery_id/d');
- $page = $this->request->param('page/d', 1);
- $pageSize = $this->request->param('pageSize/d', 10);
- $status = $params['status'] ?? 1;
- $userId = $this->auth->id;
-
- $records = LotteryRecordService::getUserDrawRecords($userId, $activityId, $status, $page, $pageSize);
- $this->success('获取成功', $records);
- }
- /**
- * 获取抽奖记录详情
- */
- public function getDrawRecordDetail()
- {
- $drawRecordId = $this->request->get('draw_record_id/d');
- $validate = new LotteryValidate();
- if (!$validate->scene('getDrawRecordDetail')->check(['draw_record_id' => $drawRecordId])) {
- $this->error($validate->getError());
- }
- $userId = $this->auth->id;
- $drawRecord = LotteryRecordService::getDrawRecordDetail($drawRecordId, $userId);
- $this->success('获取成功', $drawRecord);
- }
- /**
- * 获取用户中奖记录
- */
- public function getWinRecords()
- {
- // 验证参数
- $validate = new LotteryValidate();
- if (!$validate->scene('getWinRecords')->check($this->request->param())) {
- $this->error($validate->getError());
- }
- $page = $this->request->param('page/d', 1);
- $pageSize = $this->request->param('pageSize/d', 20);
- $userId = $this->auth->id;
- $records = LotteryRecordService::getUserWinRecords($userId, $page, $pageSize);
- $list = [];
- foreach ($records as $record) {
- $item = [
- 'id' => $record->id,
- 'activity_id' => $record->activity_id,
- 'activity_name' => $record->activity->name ?? '',
- 'prize_id' => $record->prize_id,
- 'prize_name' => $record->prize_name,
- 'prize_type' => $record->prize_type,
- 'deliver_status' => $record->deliver_status,
- 'deliver_status_text' => $record->deliver_status_text,
- 'deliver_time' => $record->deliver_time,
- 'exchange_code' => $record->exchange_code,
- 'createtime' => $record->createtime
- ];
- // 根据奖品类型返回特定信息
- $prizeValue = $record->prize_value_data;
- switch ($record->prize_type) {
- case LotteryEnum::PRIZE_TYPE_REDPACK:
- $item['amount'] = $prizeValue['amount'] ?? 0;
- break;
- case LotteryEnum::PRIZE_TYPE_COUPON:
- $item['coupon_id'] = $prizeValue['coupon_id'] ?? 0;
- break;
- case LotteryEnum::PRIZE_TYPE_GOODS:
- $item['goods_id'] = $prizeValue['goods_id'] ?? 0;
- $item['goods_sku_id'] = $prizeValue['goods_sku_id'] ?? 0;
- break;
- }
- // 奖品图片
- $item['prize_image'] = cdnurl($item['prize_image']);
- $list[] = $item;
- }
- $this->success('获取成功', [
- 'list' => $list,
- 'total' => LotteryRecordService::getUserWinRecords($userId, 1, 1)->count()
- ]);
- }
- /**
- * 设置中奖记录收货地址
- */
- public function setWinRecordAddress()
- {
- // 验证参数
- $validate = new LotteryValidate();
- if (!$validate->scene('setWinRecordAddress')->check($this->request->param())) {
- $this->error($validate->getError());
- }
- $winRecordId = $this->request->param('win_record_id/d');
- $receiverName = $this->request->param('receiver_name');
- $receiverMobile = $this->request->param('receiver_mobile');
- $receiverAddress = $this->request->param('receiver_address');
- $userId = $this->auth->id;
- $winRecord = LotteryWinRecord::where('id', $winRecordId)
- ->where('user_id', $userId)
- ->find();
- if (!$winRecord) {
- $this->error('中奖记录不存在');
- }
- if ($winRecord->deliver_status != LotteryEnum::DELIVER_STATUS_PENDING) {
- $this->error('该奖品已处理,无法修改地址');
- }
- try {
- $winRecord->setDeliveryAddress($receiverName, $receiverMobile, $receiverAddress);
- $this->success('设置成功');
- } catch (Exception $e) {
- $this->error('设置失败:' . $e->getMessage());
- }
- }
- /**
- * 获取活动排行榜(中奖次数)
- */
- public function getRanking()
- {
- // 验证参数
- $validate = new LotteryValidate();
- if (!$validate->scene('getRanking')->check($this->request->param())) {
- $this->error($validate->getError());
- }
- $activityId = $this->request->param('activity_id/d');
- $page = $this->request->param('page/d', 1);
- $limit = $this->request->param('limit/d', 50);
- // 统计用户中奖次数
- $ranking = LotteryRecordService::getActivityDrawRanking($activityId, $limit);
- $list = [];
- $rank = ($page - 1) * $limit + 1;
- foreach ($ranking as $item) {
- $list[] = [
- 'rank' => $rank++,
- 'user_id' => $item->user_id,
- 'nickname' => $item->user->nickname ?? '匿名用户',
- 'avatar' => $item->user->avatar ?? '',
- 'win_count' => $item->win_count ?? 0
- ];
- }
- $this->success('获取成功', $list);
- }
- /**
- * 获取奖品列表
- */
- public function getPrizes()
- {
- // 验证参数
- $validate = new LotteryValidate();
- $params = $this->request->param();
- if (!$validate->scene('getPrizes')->check($params)) {
- $this->error($validate->getError());
- }
- $activityId = $params['lottery_id'] ?? 0;
- $page = $params['page'] ?? 1;
- $pageSize = $params['pageSize'] ?? 10;
- $type = $params['type'] ?? null; // 奖品类型筛选,支持逗号分隔字符串
- // 调用服务层方法
- $paginate = LotteryActivityService::getPrizes($activityId, $page, $pageSize, $type);
-
- // 处理图片 地址
- foreach ($paginate as $item) {
- $item['image'] = $item['image'] ? cdnurl($item['image']) : '';
- }
- $this->success('获取成功', $paginate);
- }
- // 订单完成后 分发抽奖机会
- public function getLotteryChanceByOrder()
- {
- $orderId = $this->request->post('order_id/d');
- // 验证器
- $validate = new LotteryValidate();
- if (!$validate->scene('getLotteryChanceByOrder')->check(['order_id' => $orderId])) {
- $this->error($validate->getError());
- }
- $userId = $this->auth->id;
- $orderInfo = OrderService::getDetail($orderId, $userId);
- if(!$orderInfo){
- $this->error('订单不存在');
- }
- // 是否是已支付
- if(!$orderInfo->isPayStatus()){
- $this->error('订单未支付');
- }
- // 构造数据
- $goodsList = $orderInfo->orderGoods;
- $goodsList = collection($goodsList)->toArray();
- $goodsList = array_map(function($item){
- return [
- 'goods_id' => $item['goods_id'],
- ];
- }, $goodsList);
- $orderInfo = [
- 'id' => $orderInfo->id,
- 'total_amount' => $orderInfo->amount,
- 'goods' => $goodsList
- ];
- // 获取当前正在进行的单个抽奖活动
- $activity = LotteryActivityService::getCurrentRunningActivity();
-
- // 如果没有正在进行的活动,返回null
- if (!$activity) {
- $this->success('获取成功', null);
- }
- // 用户 订单 是否已经分发过 抽奖机会
- $isGranted = LotteryChanceService::isGrantedChanceForOrder($orderInfo, $userId);
- if($isGranted){
- // 直接返回 所剩 机会
- $userChance = LotteryChanceService::getUserChance($activity->id, $userId);
- $arrReturn = [
- 'lottery_id' => $activity->id,
- 'lottery_type' => $activity->lottery_type,
- 'lottery_name' => $activity->name,
- 'chances' => $userChance->total_chances,
- ];
- $this->success('获取成功', $arrReturn);
- }
- $grantedChances = LotteryChanceService::checkAndGrantChanceForOrderOne($activity, $orderInfo, $userId);
- $this->success('获取成功', $grantedChances);
- }
- }
|