jxg/jinxiangguo-master/app/Http/Controllers/LotteryController.php

126 lines
3.5 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?php
namespace App\Http\Controllers;
use App\Models\Lottery;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Carbon\Carbon;
class LotteryController extends Controller
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
private static $list = [
[
'id' => 1,
'amount' => 115,
'weight' => 50, // 随便写正整数,越大随机到的概率越大,并且会挤占其他选项的概率
],
[
'id' => 2,
'amount' => 90,
'weight' => 100
],
[
'id' => 3,
'amount' => 120,
'weight' => 40
],
[
'id' => 4,
'amount' => 110,
'weight' => 60
],
[
'id' => 5,
'amount' => 666,
'weight' => 1 // 大奖填1概率最小
],
[
'id' => 6,
'amount' => 66,
'weight' => 50, // 亏钱的,也不要给太高权重,否则都不玩了~
],
[
'id' => 7,
'amount' => 99,
'weight' => 100
],
[
'id' => 8,
'amount' => 150,
'weight' => 20,
],
[
'id' => 9,
'amount' => 200,
'weight' => 10
]
];
private static $price = 100; // 抽奖价格
/**
* 抽奖
*/
public function golottery(Request $request)
{
$user = $request->user();
$islottery = Lottery::whereBetween('created_at', [Carbon::today()->startOfDay(), Carbon::today()->endOfDay()])->where('user_id', $user->id)->first();
// return $this->success($user);
if ($islottery && $user->amount < $this::$price) return $this->error('像果余额不足');
$arr = [];
foreach ($this::$list as $item) {
for ($i = 0; $i < $item['weight']; $i++) {
$arr[] = $item;
}
}
$resObj = $arr[array_rand($arr)]; // 随机选一个
try {
DB::beginTransaction();
$cur_price = $islottery ? $this::$price : 0;
Lottery::query()->create([
'user_id' => $user->id,
'amount' => $cur_price,
'reward_amount' => $resObj['amount']
]);
$user->amount += ($resObj['amount'] - $cur_price); // 加奖励,减花费
$user->save();
DB::commit();
} catch (\Exception $e) {
DB::rollBack();
Log::error(__METHOD__, $e->getTrace());
}
unset($resObj['weight']);
return $this->success($resObj);
}
/**
* 获取奖品列表
*/
public function get(Request $request)
{
$user = $request->user()->toArray();
// return $this->success($user);
$islottery = Lottery::whereBetween('created_at', [Carbon::today()->startOfDay(), Carbon::today()->endOfDay()])->where('user_id', $user['id'])->first();
array_walk($this::$list, function (&$item) {
unset($item['weight']);
$item['check'] = false;
}); // 隐藏权重选项
return $this->success([
'price' => $this::$price,
'free' => !$islottery, // 是否免费
'list' => $this::$list
]);
}
}