__('购买商品'), '2' => __('订单消费'), '3' => __('充值'), '4' => __('累计消费'), '5' => __('管理员发放'), '6' => __('签到奖励'), '7' => __('邀请奖励'), '8' => __('活动奖励') ]; } /** * 状态列表 */ public function getStatusList() { return [ '0' => __('已失效'), '1' => __('有效') ]; } // 获取器 public function getSourceTypeTextAttr($value, $data) { $value = $value ? $value : (isset($data['source_type']) ? $data['source_type'] : ''); $list = $this->getSourceTypeList(); return isset($list[$value]) ? $list[$value] : ''; } public function getStatusTextAttr($value, $data) { $value = $value ? $value : (isset($data['status']) ? $data['status'] : ''); $list = $this->getStatusList(); return isset($list[$value]) ? $list[$value] : ''; } public function getExpireTimeTextAttr($value, $data) { $value = $value ? $value : (isset($data['expire_time']) ? $data['expire_time'] : ''); if ($value && is_numeric($value)) { return date("Y-m-d H:i:s", $value); } return $value ?: '永不过期'; } public function getRemainCountAttr($value, $data) { $chance_count = isset($data['chance_count']) ? $data['chance_count'] : 0; $used_count = isset($data['used_count']) ? $data['used_count'] : 0; return max(0, $chance_count - $used_count); } // 修改器 protected function setExpireTimeAttr($value) { return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value); } // 关联关系 public function activity() { return $this->belongsTo('Activity', 'activity_id', 'id'); } public function user() { return $this->belongsTo('app\\common\\model\\User', 'user_id', 'id'); } /** * 检查机会是否有效 */ public function isValid() { // 检查状态 if ($this->status != 1) { return false; } // 检查是否过期 if ($this->expire_time && $this->expire_time < time()) { return false; } // 检查是否还有剩余次数 if ($this->chance_count <= $this->used_count) { return false; } return true; } /** * 使用抽奖机会 */ public function useChance() { if (!$this->isValid()) { return false; } $this->used_count += 1; return $this->save(); } /** * 获取用户在指定活动的有效抽奖机会 */ public static function getUserValidChances($user_id, $activity_id) { return self::where([ 'user_id' => $user_id, 'activity_id' => $activity_id, 'status' => 1 ])->where(function($query) { $query->where('expire_time', 0) ->whereOr('expire_time', '>', time()); })->where('chance_count', '>', 'used_count')->sum('chance_count - used_count'); } /** * 获取用户总的剩余抽奖次数 */ public static function getUserRemainCount($user_id, $activity_id) { $list = self::where([ 'user_id' => $user_id, 'activity_id' => $activity_id, 'status' => 1 ])->where(function($query) { $query->where('expire_time', 0) ->whereOr('expire_time', '>', time()); })->select(); $total = 0; foreach ($list as $item) { $remain = $item->chance_count - $item->used_count; if ($remain > 0) { $total += $remain; } } return $total; } }