BetService.php 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110
  1. <?php
  2. namespace App\Services;
  3. use App\Models\Message;
  4. use App\Models\PcIssue;
  5. use App\Models\Rebate;
  6. use App\Models\User;
  7. use App\Models\Bet;
  8. use App\Models\Config;
  9. use Illuminate\Support\Facades\App;
  10. use Illuminate\Support\Facades\DB;
  11. use Illuminate\Support\Facades\Cache;
  12. use App\Jobs\SendTelegramMessageJob;
  13. use App\Jobs\SendTelegramGroupMessageJob;
  14. use Exception;
  15. use Illuminate\Support\Facades\Log;
  16. /**
  17. * 投注
  18. */
  19. class BetService extends BaseService
  20. {
  21. public static $OTHER_BET_1 = [
  22. '大',
  23. '小',
  24. '单',
  25. '双',
  26. ];
  27. public static $OTHER_BET_2 = [
  28. '大单',
  29. '大双',
  30. '小单',
  31. '小双',
  32. ];
  33. /**
  34. * @description: 模型
  35. * @return {string}
  36. */
  37. public static function model(): string
  38. {
  39. return Bet::class;
  40. }
  41. /**
  42. * @description: 枚举
  43. * @return {*}
  44. */
  45. public static function enum(): string
  46. {
  47. return '';
  48. }
  49. /**
  50. * @description: 获取查询条件
  51. * @param {array} $search 查询内容
  52. * @return {array}
  53. */
  54. public static function getWhere(array $search = []): array
  55. {
  56. $where = [];
  57. if (isset($search['issue_no']) && !empty($search['issue_no'])) {
  58. $where[] = ['issue_no', '=', $search['issue_no']];
  59. }
  60. if (isset($search['member_id']) && !empty($search['member_id'])) {
  61. $where[] = ['member_id', '=', $search['member_id']];
  62. }
  63. if (isset($search['keywords']) && !empty($search['keywords'])) {
  64. $where[] = ['keywords', '=', $search['keywords']];
  65. }
  66. if (isset($search['issue_id']) && !empty($search['issue_id'])) {
  67. $where[] = ['issue_id', '=', $search['issue_id']];
  68. }
  69. if (isset($search['id']) && !empty($search['id'])) {
  70. $where[] = ['id', '=', $search['id']];
  71. }
  72. if (isset($search['user_id']) && !empty($search['user_id'])) {
  73. $where[] = ['user_id', '=', $search['user_id']];
  74. }
  75. if (isset($search['start_time']) && !empty($search['start_time'])) {
  76. $where[] = ['created_at', '>=', "{$search['start_time']} 00:00:00"];
  77. $where[] = ['created_at', '<=', "{$search['end_time']} 23:59:59"];
  78. }
  79. if (isset($search['is_winner']) && $search['is_winner'] != '') {
  80. $where[] = ['status', '=', 2];
  81. if ($search['is_winner'] == 1) {
  82. $where[] = ['profit', '>', 0];
  83. } else {
  84. $where[] = ['profit', '<=', 0];
  85. }
  86. } else {
  87. if (isset($search['status']) && !empty($search['status'])) {
  88. $where[] = ['status', '=', $search['status']];
  89. }
  90. }
  91. return $where;
  92. }
  93. /**
  94. * @description: 查询单条数据
  95. * @param array $search
  96. * @return \App\Models\Coin|null
  97. */
  98. public static function findOne(array $search): ?Bet
  99. {
  100. return self::model()::where(self::getWhere($search))->first();
  101. }
  102. /**
  103. * @description: 查询所有数据
  104. * @param array $search
  105. * @return \Illuminate\Database\Eloquent\Collection
  106. */
  107. public static function findAll(array $search = [])
  108. {
  109. return self::model()::where(self::getWhere($search))->get();
  110. }
  111. /**
  112. * @description: 分页查询
  113. * @param array $search
  114. * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
  115. */
  116. public static function paginate(array $search = [])
  117. {
  118. $limit = isset($search['limit']) ? $search['limit'] : 15;
  119. $query = self::model()::where(self::getWhere($search))
  120. ->with(['user']);
  121. if (isset($search['username']) && !empty($search['username'])) {
  122. $username = $search['username'];
  123. $query = $query->whereHas('user', function ($query) use ($username) {
  124. $query->where('username', $username);
  125. });
  126. }
  127. $query->orderBy('id', 'desc');
  128. $paginator = $query->paginate($limit);
  129. return ['total' => $paginator->total(), 'data' => $paginator->items()];
  130. }
  131. /**
  132. * @description: 投注操作
  133. * @param string $memberId
  134. * @param string $input
  135. * @param int $messageId
  136. * @return array
  137. */
  138. public static function bet(string $memberId, string $input, int $messageId = 0): array
  139. {
  140. $msg = [];
  141. $msg['chat_id'] = $memberId;
  142. // 分解投注的内容
  143. $betResult = GameplayRuleService::bettingRuleVerify($input);
  144. $serviceAccount = Config::where('field', 'service_customer')->first()->val;
  145. $maintenanceSwitch = Config::where('field', 'maintenance_switch')->first()->val;
  146. if ($maintenanceSwitch != 0) {
  147. $text = lang("系统维护中") . "\n";
  148. $text .= lang("任何疑问都可以联系唯一客服") . ":@{$serviceAccount}";
  149. $msg['text'] = $text;
  150. if ($messageId) {
  151. $msg['reply_to_message_id'] = $messageId;
  152. }
  153. return $msg;
  154. }
  155. if ($betResult == null) {
  156. $text = lang("消息格式错误!") . "\n";
  157. $text .= lang("任何疑问都可以联系唯一客服") . ":@{$serviceAccount}";
  158. $msg['text'] = $text;
  159. if ($messageId) {
  160. $msg['reply_to_message_id'] = $messageId;
  161. }
  162. return $msg;
  163. }
  164. DB::beginTransaction();
  165. try {
  166. $text = lang('下注期数') . ":{issue_no}\n";
  167. $text .= lang("下注内容") . "\n";
  168. $text .= "--------\n";
  169. $success = false;
  170. $sumAmount = 0;
  171. $errText = $groupText = "";
  172. foreach ($betResult as $index => $item) {
  173. $keywords = $item['rule'];
  174. $amount = $item['amount'];
  175. $error = $issueNo = "";
  176. $b = static::singleNote($memberId, $keywords, $amount, $issueNo, $text, $error, $groupText, $index);
  177. if ($b) {
  178. $sumAmount += $amount;
  179. $text = str_replace("{issue_no}", $issueNo, $text);
  180. $success = true;
  181. $text .= "\n";
  182. } else {
  183. $errText .= $error;
  184. $errText .= "\n";
  185. }
  186. }
  187. if (!$success) {
  188. $msg['text'] = $errText;
  189. if ($messageId) {
  190. $msg['reply_to_message_id'] = $messageId;
  191. }
  192. } else {
  193. $sumAmount = number_format($sumAmount, 2);
  194. $text .= "--------\n";
  195. $text .= lang("合计金额") . ":{$sumAmount}\n";
  196. $text .= lang("下注成功");
  197. $msg['text'] = $text;
  198. $msg['text'] .= "\n";
  199. if (!empty($errText)) {
  200. $msg['text'] .= "------------------------\n";
  201. $msg['text'] .= $errText;
  202. }
  203. $groupText .= "\n--------\n";
  204. self::asyncBettingGroupNotice($groupText, self::getOperateButton()); // 异步群通知
  205. }
  206. DB::commit();
  207. } catch (Exception $e) {
  208. DB::rollBack();
  209. Log::error('错误信息', [
  210. 'message' => $e->getMessage(),
  211. 'file' => $e->getFile(),
  212. 'line' => $e->getLine(),
  213. 'trace' => $e->getTraceAsString()
  214. ]);
  215. $msg['text'] = "投注失败,请联系管理员";
  216. if ($messageId) {
  217. $msg['reply_to_message_id'] = $messageId;
  218. }
  219. }
  220. return $msg;
  221. }
  222. private static function singleNote($memberId, $keywords, $amount, &$issueNo, &$text, &$errText, &$groupText, $index): bool
  223. {
  224. $errText .= "【{$keywords}{$amount}】\n";
  225. //客服号
  226. $serviceAccount = Config::where('field', 'service_customer')->first()->val;
  227. $gameplayRuleInfo = GameplayRuleService::getGameplayRules($keywords);
  228. if ($gameplayRuleInfo == null) {
  229. $errText .= lang("玩法未配置!") . "\n";
  230. $errText .= lang("任何疑问都可以联系唯一财务") . ":@{$serviceAccount}";
  231. return false;
  232. }
  233. if ($gameplayRuleInfo['odds'] <= 0) {
  234. $errText .= lang("赔率为0 庄家通吃 禁止投注!") . "\n";
  235. $errText .= lang("任何疑问都可以联系唯一财务") . ":@{$serviceAccount}";
  236. return false;
  237. }
  238. // 期数验证
  239. $pc28Switch = Config::where('field', 'pc28_switch')->first()->val;
  240. if ($pc28Switch == 1) {
  241. $issueInfo = PcIssue::where('status', PcIssue::STATUS_BETTING)->orderBy('id', 'desc')->first();
  242. } else {
  243. $issueInfo = IssueService::model()::where('status', IssueService::model()::STATUS_BETTING)->orderBy('id', 'desc')->first();
  244. }
  245. if (empty($issueInfo)) {
  246. if ($pc28Switch == 1) {
  247. $issueCloseInfo = PcIssue::where('status', PcIssue::STATUS_CLOSE)->orderBy('id', 'desc')->first();
  248. } else {
  249. $issueCloseInfo = IssueService::model()::where('status', IssueService::model()::STATUS_CLOSE)->orderBy('id', 'desc')->first();
  250. }
  251. if (empty($issueCloseInfo)) {
  252. $errText .= lang("暂无可下注期数,本次下注无效!");
  253. return false;
  254. } else {
  255. $errText .= lang("封盘中,本次下注无效!");
  256. return false;
  257. }
  258. }
  259. if (!is_numeric($amount) || $amount <= 0) {
  260. $errText .= lang("投注金额格式不正确!");
  261. $errText .= lang("任何疑问都可以联系唯一财务") . ":@{$serviceAccount}";
  262. return false;
  263. }
  264. $now_date = date('Y-m-d H:i:s', time() + 30); // 提前30秒
  265. if ($issueInfo['end_time'] < $now_date) {
  266. $errText .= lang("封盘中,本次下注无效!");
  267. return false;
  268. }
  269. // 投注限制校验
  270. if ($amount < $gameplayRuleInfo['mininum']) {
  271. $errText .= lang("下注失败,最小金额限制") . "{$gameplayRuleInfo['mininum']}\n";
  272. return false;
  273. }
  274. // 投注限制校验
  275. if ($amount > $gameplayRuleInfo['maxinum']) {
  276. $errText .= lang("下注失败,最大金额限制") . "{$gameplayRuleInfo['maxinum']}\n";
  277. return false;
  278. }
  279. // 获取用户余额
  280. $walletInfo = WalletService::findOne(['member_id' => $memberId]);
  281. $balance = $walletInfo['available_balance'];
  282. // 余额计算
  283. if ($balance < $amount) {
  284. $errText .= lang("余额不足,本次下注无效!\n");
  285. return false;
  286. }
  287. $userInfo = UserService::findOne(['member_id' => $memberId]);
  288. $betInfo = self::findOne(['member_id' => $memberId, 'issue_no' => $issueInfo->issue_no, 'keywords' => $keywords]); // 相同下注
  289. if ($betInfo) {
  290. $betInfo->amount = $betInfo->amount + $amount;
  291. $bet_id = $betInfo->id;
  292. $betInfo->save();
  293. } else {
  294. $data = [];
  295. $data['amount'] = $amount; // 分数
  296. $data['keywords'] = $keywords; // 玩法
  297. $data['member_id'] = $memberId;
  298. $data['user_id'] = $userInfo->id;
  299. $data['issue_no'] = $issueInfo->issue_no;
  300. $data['issue_id'] = $issueInfo->id;
  301. $data['odds'] = $gameplayRuleInfo['odds'];
  302. $newBet = self::model()::create($data);
  303. $bet_id = $newBet->id;
  304. }
  305. WalletService::updateBalance($memberId, -$amount);
  306. BalanceLogService::addLog($memberId, -$amount, $balance, ($balance - $amount), '投注', $bet_id, '');
  307. //记录反水
  308. $rebate = Rebate::addOrUpdate([
  309. 'member_id' => $memberId,
  310. 'betting_amount' => $amount,
  311. 'first_name' => $userInfo->first_name,
  312. 'username' => $userInfo->username,
  313. ]);
  314. if (!RebateService::BibiReturn($rebate, $amount)) {
  315. $errText .= lang("笔笔返失败");
  316. return false;
  317. }
  318. $odds = floatval($gameplayRuleInfo['odds']);
  319. $issueNo = $issueInfo->issue_no;
  320. $text .= "{$keywords} {$amount} ({$odds}" . lang('倍率') . ")";
  321. $lastStr = self::hideMiddleDigits($userInfo->member_id, 4);
  322. $lang = App::getLocale();
  323. $group_language = Config::where('field', 'group_language')->first()->val;
  324. App::setLocale($group_language);
  325. if ($index === 0) {
  326. $groupText .= lang("第") . "{$issueNo}" . lang("期") . "\n";
  327. $groupText .= lang("开奖时间") . ":" . date("H:i:s", strtotime($issueInfo['end_time'])) . "\n";
  328. $groupText .= lang('投注截止') . ":" . date("H:i:s", (strtotime($issueInfo['end_time'])) - 30) . "\n";;
  329. $groupText .= lang("成功") . "\n";
  330. $groupText .= lang('玩家') . ": 【{$lastStr}】 \n";
  331. }
  332. $groupText .= "{$keywords} {$amount} ({$odds}" . lang("倍率") . ") \n";
  333. App::setLocale($lang);
  334. return true;
  335. }
  336. //随机虚拟下注
  337. public static function randomVirtualBetting($maxPeople = 1): void
  338. {
  339. $maxPeople = intval($maxPeople);
  340. $maxPeople = max($maxPeople, 1);
  341. $maxPeople = min($maxPeople, 20);
  342. $num = rand(1, $maxPeople);
  343. for ($i = 0; $i < $num; $i++) {
  344. static::fakeBet(4);
  345. }
  346. }
  347. // 模拟下注
  348. private static function fakeBet($betNumber = 1): void
  349. {
  350. $noRule = ['0操', '27操'];
  351. // 防止一开就虚拟投注
  352. $cache = Cache::get('new_issue_no');
  353. if ($cache) {
  354. return;
  355. }
  356. $maintenanceSwitch = Config::where('field', 'maintenance_switch')->first()->val;
  357. if ($maintenanceSwitch != 0) {
  358. return;
  359. }
  360. $betFake = Config::where('field', 'bet_fake')->first()->val;
  361. if ($betFake) {
  362. // 期数验证
  363. $pc28Switch = Config::where('field', 'pc28_switch')->first()->val;
  364. if ($pc28Switch == 1) {
  365. $issueInfo = PcIssue::where('status', PcIssue::STATUS_BETTING)->orderBy('id', 'desc')->first();
  366. } else {
  367. $issueInfo = IssueService::model()::where('status', IssueService::model()::STATUS_BETTING)->orderBy('id', 'desc')->first();
  368. }
  369. if ($issueInfo) {
  370. $betFakeRandAmount = Config::where('field', 'bet_fake_rand_amount')->first()->val;
  371. $betFakeRandAmount = explode(',', $betFakeRandAmount);
  372. $betMini = $betFakeRandAmount[0] ?? 10;
  373. $betMax = $betFakeRandAmount[1] ?? 10000;
  374. $now_date = date('Y-m-d H:i:s', time() + 38); // 提前45秒
  375. if ($issueInfo['end_time'] > $now_date) {
  376. $fake_bet_list = Cache::get('fake_bet_' . $issueInfo->issue_no, []);
  377. $gameplayRuleList = GameplayRuleService::model()::where('odds', '>', 0)->get();
  378. $gameplayRuleList = $gameplayRuleList->toArray();
  379. $member_id = self::generateRandomNumber(10);
  380. $betTimes = rand(1, $betNumber); // 每次下注次数
  381. Cache::add("封盘后下注单数_{$issueInfo->issue_no}", rand(3, 5), 4);
  382. $lastStr = self::hideMiddleDigits($member_id, 4);
  383. $lang = App::getLocale();
  384. $group_language = Config::where('field', 'group_language')->first()->val;
  385. $first_name = self::generateRandomString(6);
  386. App::setLocale($group_language);
  387. $groupText = lang("第") . "{$issueInfo->issue_no}" . lang("期") . "\n";
  388. $groupText .= lang("开奖时间") . ":" . date("H:i:s", strtotime($issueInfo['end_time'])) . "\n";
  389. $groupText .= lang('投注截止') . ":" . date("H:i:s", (strtotime($issueInfo['end_time'])) - 30) . "\n";;
  390. $groupText .= lang("成功") . "\n";
  391. $groupText .= lang('玩家') . ": 【{$lastStr}】 \n";
  392. App::setLocale($lang);
  393. $haveBet = false;
  394. for ($i = 0; $i < $betTimes; $i++) {
  395. if (strtotime($issueInfo['end_time']) - time() < IssueService::COUNTDOWN_TO_CLOSING_THE_MARKET) {
  396. $fake_bet_count = Cache::get("fake_bet_count_{$issueInfo->issue_no}", 0);
  397. $cc = Cache::get("封盘后下注单数_{$issueInfo->issue_no}");
  398. if ($fake_bet_count >= $cc) return;
  399. }
  400. $randKey = array_rand($gameplayRuleList, 1);
  401. $gameplayRuleInfo = $gameplayRuleList[$randKey] ?? [];
  402. if ($gameplayRuleInfo) {
  403. if (in_array($gameplayRuleInfo['keywords'], $noRule)) {
  404. return;
  405. }
  406. if ($gameplayRuleInfo['maxinum'] < $betMax) {
  407. $betMax = $gameplayRuleInfo['maxinum'];
  408. }
  409. if ($gameplayRuleInfo['mininum'] > $betMini) {
  410. $betMini = $gameplayRuleInfo['mininum'];
  411. }
  412. $amount = rand($betMini, $betMax);
  413. $amount = floor($amount / 10) * 10;
  414. $input = $gameplayRuleInfo['keywords'] . ' ' . $amount;
  415. // $amount = number_format($amount,2);
  416. $item = [];
  417. $item['keywords'] = $gameplayRuleInfo['keywords'];
  418. $item['odds'] = floatval($gameplayRuleInfo['odds']);
  419. $item['amount'] = $amount;
  420. $item['first_name'] = $first_name;
  421. $item['member_id'] = $member_id;
  422. $item['profit'] = 0;
  423. // $input = $item['keywords'] . $item['amount'];
  424. $fake_bet_list[] = $item;
  425. $lang = App::getLocale();
  426. $group_language = Config::where('field', 'group_language')->first()->val;
  427. $first_name = self::generateRandomString(6);
  428. App::setLocale($group_language);
  429. $groupText .= "{$input} (" . $item['odds'] . lang("倍率") . ") \n";
  430. $haveBet = true;
  431. App::setLocale($lang);
  432. if (strtotime($issueInfo['end_time']) - strtotime($now_date) < 22) {
  433. $fake_bet_count = Cache::get("fake_bet_count_{$issueInfo->issue_no}", 0);
  434. Cache::put("fake_bet_count_{$issueInfo->issue_no}", $fake_bet_count + 1, 500);
  435. }
  436. }
  437. }
  438. if ($haveBet) {
  439. $groupText .= "\n-------- \n";
  440. $inlineButton = self::getOperateButton();
  441. // 群通知 暂停2秒再发送,避免同时发送多个消息而超过 Telegram 的频率限制
  442. self::asyncBettingGroupNotice($groupText, $inlineButton); // 异步群通知
  443. sleep(2);
  444. }
  445. Cache::put('fake_bet_' . $issueInfo->issue_no, $fake_bet_list, 500);
  446. }
  447. }
  448. }
  449. }
  450. /**
  451. * @description: 当期下注
  452. * @param {*} $memberId
  453. * @return {*}
  454. */
  455. public static function currentBet($memberId)
  456. {
  457. $msg['chat_id'] = $memberId;
  458. // 期数验证
  459. $issueInfo = IssueService::model()::where('status', IssueService::model()::STATUS_BETTING)->orderBy('id', 'desc')->first();
  460. $issue_no = '';
  461. if (!empty($issueInfo)) {
  462. $issue_no = $issueInfo->issue_no;
  463. } else {
  464. $issueCloseInfo = IssueService::model()::where('status', IssueService::model()::STATUS_CLOSE)->orderBy('id', 'desc')->first();
  465. if (empty($issueCloseInfo)) {
  466. $issue_no = $issueCloseInfo->issue_no;
  467. }
  468. }
  469. if ($issue_no) {
  470. $text = lang("期数") . " {$issue_no} \n";
  471. // $text .= "\n";
  472. // $text .= "----------\n";
  473. $list = self::findAll(['member_id' => $memberId, 'issue_no' => $issue_no]);
  474. $list = $list->toArray();
  475. if (empty($list)) {
  476. $text .= lang("本期暂未下注") . "! \n";
  477. } else {
  478. $keywords = implode(',', array_column($list, 'keywords'));
  479. $amounts = implode(',', array_column($list, 'amount'));
  480. $text .= lang("下注类型") . ":[" . $keywords . "] \n";
  481. $text .= lang("下注金额") . ":" . $amounts . " \n";
  482. $text .= lang("下注总额") . ":" . array_sum(array_column($list, 'amount')) . " \n";
  483. $text .= lang("开奖状态") . ":" . lang("等待开奖") . " \n";
  484. }
  485. // foreach ($list->toArray() as $k => $v) {
  486. // $text .= "{$v['keywords']}{$v['amount']} \n";
  487. // }
  488. // $text .= "\n";
  489. // $text .= "----------\n";
  490. $msg['text'] = $text;
  491. } else {
  492. $msg['text'] = lang("当前没有开放的投注期数") . "! \n";
  493. }
  494. return $msg;
  495. }
  496. /**
  497. * @description: 近期投注
  498. * @param {*} $memberId
  499. * @return {*}
  500. */
  501. public static function recentlyRecord($memberId, $page = 1, $limit = 5)
  502. {
  503. $list = self::model()::where('member_id', $memberId)->whereIn('status', [self::model()::STATUS_STAY, self::model()::STATUS_SETTLED])->orderBy('id', 'desc')->forPage($page, $limit)->get();
  504. // $text = "```\n";
  505. $text = "";
  506. $text .= "期数--内容--盈亏 \n";
  507. foreach ($list->toArray() as $k => $v) {
  508. $profit = $v['profit'] - $v['amount'];
  509. // $text .= $v['issue_no']." ".$v['keywords']." ".$v['amount']." ".$v['profit']."\n";
  510. $item = $v['issue_no'] . "==" . $v['keywords'] . rtrim(rtrim(number_format($v['amount'], 2, '.', ''), '0'), '.') . "==" . rtrim(rtrim(number_format($profit, 2, '.', ''), '0'), '.') . "\n";
  511. $text .= $item;
  512. }
  513. // $text .= "```\n";
  514. return $text;
  515. }
  516. /**
  517. * @description: 投注记录
  518. * @param {*} $memberId
  519. * @param {*} $page
  520. * @param {*} $limit
  521. * @return {*}
  522. */
  523. public static function record($memberId, $messageId = null, $page = 1, $limit = 5)
  524. {
  525. $type = Cache::get('message_id_bet_record_' . $memberId, 0);
  526. if ($type == 0) {
  527. $type = '';
  528. }
  529. $msg['chat_id'] = $memberId;
  530. $list = self::model()::where('member_id', $memberId)->whereIn('status', [self::model()::STATUS_STAY, self::model()::STATUS_SETTLED])->where(self::getWhere(['is_winner' => $type]))->orderBy('id', 'desc')->forPage($page, $limit)->get();
  531. $count = self::model()::where('member_id', $memberId)->whereIn('status', [self::model()::STATUS_STAY, self::model()::STATUS_SETTLED])->where(self::getWhere(['is_winner' => $type]))->count();
  532. $keyboard = [];
  533. $total_amount = BalanceLogService::model()::where('member_id', $memberId)->where('change_type', '中奖')->sum('amount');
  534. $total_amount = number_format($total_amount, 2);
  535. $text = lang("历史注单") . " \n";
  536. $text .= lang("中奖总派彩") . ":{$total_amount} \n";
  537. foreach ($list as $k => $v) {
  538. if ($v->status == self::model()::STATUS_SETTLED) {
  539. $phase = $v->profit - $v->amount;
  540. } else {
  541. $phase = lang('待开奖');
  542. }
  543. $text .= "-------------------------------------\n";
  544. $text .= lang("期数") . ":{$v->issue_no} \n";
  545. $text .= lang("内容") . ":{$v->keywords} \n";
  546. $text .= lang("金额") . ":{$v->amount} \n";
  547. $text .= lang("盈亏") . ":{$phase} \n";
  548. }
  549. $msg['text'] = $text;
  550. $keyboard[] = [
  551. ['text' => lang("全部"), 'callback_data' => "betRecordType@@0"],
  552. ['text' => lang("盈利"), 'callback_data' => "betRecordType@@1"],
  553. ['text' => lang("亏损"), 'callback_data' => "betRecordType@@2"]
  554. ];
  555. if ($page > 1) {
  556. $keyboard[] = [
  557. ['text' => "👆" . lang("上一页"), 'callback_data' => "betRecordNextPage@@" . ($page - 1)]
  558. ];
  559. }
  560. $allPage = ceil($count / $limit);
  561. if ($allPage > $page) {
  562. if ($page > 1) {
  563. $keyboard[count($keyboard) - 1][] = ['text' => "👇" . lang("下一页"), 'callback_data' => "betRecordNextPage@@" . ($page + 1)];
  564. } else {
  565. $keyboard[] = [
  566. ['text' => "👇" . lang("下一页"), 'callback_data' => "betRecordNextPage@@" . ($page + 1)]
  567. ];
  568. }
  569. }
  570. if ($messageId) {
  571. $msg['message_id'] = $messageId;
  572. }
  573. if ($keyboard) {
  574. $msg['reply_markup'] = json_encode(['inline_keyboard' => $keyboard]);
  575. }
  576. return $msg;
  577. }
  578. /**
  579. * @description: 开奖失败退回投注的
  580. * @param {*} $issue_no
  581. * @return {*}
  582. */
  583. public static function betFail($issue_no)
  584. {
  585. $list = self::findAll(['issue_no' => $issue_no, 'status' => self::model()::STATUS_STAY]);
  586. foreach ($list->toArray() as $k => $v) {
  587. $profit = $v['amount'];
  588. WalletService::updateBalance($v['member_id'], $profit);
  589. $walletInfo = WalletService::findOne(['member_id' => $v['member_id']]);
  590. $balance = $walletInfo['available_balance'];
  591. BalanceLogService::addLog($v['member_id'], $profit, $balance, ($balance + $profit), '中奖', $v['id'], '');
  592. $text = $issue_no . "期开奖失败 \n";
  593. $text .= "投注类型:{$v['keywords']} \n";
  594. $text .= "投注金额:{$v['amount']} \n";
  595. $text .= "投注的资金已退回您的钱包 \n";
  596. self::asyncSendMessage($v['member_id'], $text);
  597. $item = [];
  598. $iem['status'] = self::model()::STATUS_SETTLED;
  599. self::model()::where('id', $v['id'])->update($item);
  600. }
  601. }
  602. /**
  603. * @description: 中奖结算
  604. * @param {*} $issue_no
  605. * @param {*} $awards
  606. * @return {*}
  607. */
  608. public static function betSettled($issue_no, $awards)
  609. {
  610. $list = self::findAll(['issue_no' => $issue_no, 'status' => self::model()::STATUS_STAY]);
  611. // 大小单双的
  612. $otherSum = self::model()::where('issue_no', $issue_no)->where('status', self::model()::STATUS_STAY)->whereIn('keywords', ['大', '小', '单', '双'])->sum('amount');
  613. $fakeOpenData = self::fakeLotteryDraw($issue_no, $awards, 0);
  614. $keywordsList = $fakeOpenData['keywordsList'];
  615. $fakeOtherSum = $fakeOpenData['sum'];
  616. $sum = $otherSum + $fakeOtherSum;
  617. $betNoticeNum = Config::where('field', 'bet_notice_num')->first()->val;
  618. $betNoticeNum = explode(',', $betNoticeNum);
  619. $betNoticeMini = $betNoticeNum[0] ?? 26;
  620. $betNoticeMax = $betNoticeNum[1] ?? 38;
  621. $noticeNum = rand($betNoticeMini, $betNoticeMax);
  622. $realNoticeNum = ceil($noticeNum / 2);
  623. $openList = [];
  624. $memberList = [];
  625. $bet_num = 0;
  626. foreach ($list->toArray() as $k => $v) {
  627. if (isset($keywordsList[$v['keywords']])) {
  628. $keywordsList[$v['keywords']] += $v['amount'];
  629. } else {
  630. $keywordsList[$v['keywords']] = $v['amount'];
  631. }
  632. // $userInfo = UserService::findAll(['member_id' => $v['member_id']]);
  633. // $lastStr = self::getLastChar($userInfo->first_name, 1);
  634. $lastStr = self::hideMiddleDigits($v['member_id'], 4);
  635. $item = [];
  636. $item['id'] = $v['id'];
  637. $item['status'] = self::model()::STATUS_SETTLED;
  638. if (in_array($v['keywords'], $awards)) {
  639. // $profit = $v['amount'] * $v['odds'];
  640. $amount = $v['amount'];
  641. // $amount = rtrim($amount, '0'); // 去掉右侧的 0
  642. // $amount = rtrim($amount, '.'); // 如果末尾是 . 就去掉
  643. $odds = $v['odds'];
  644. // 玩 大单 小单 大双 小双 :如果开出13和14 总注小于10000 1.5赔率含本,大于等于10000退本金。
  645. if (in_array('13操', $awards) || in_array('14操', $awards)) {
  646. // 13 14特殊处理倍率
  647. if (in_array($v['keywords'], self::$OTHER_BET_2)) {
  648. if ($sum < 10000) {
  649. $odds = 1.5;
  650. } else {
  651. $odds = 1;
  652. }
  653. }
  654. // if (in_array($v['keywords'], self::$OTHER_BET_2)) {
  655. // $odds = 1;
  656. // }
  657. }
  658. $profit = bcmul($amount, $odds, 2); // 保留两位小数
  659. if ($profit > 1000000) {
  660. $profit = 1000000; // 单注最高奖金1000000
  661. }
  662. $item['profit'] = $profit;
  663. // $yl = $profit - $amount;
  664. $yl = bcsub($profit, $amount, 2); // 盈利
  665. if (!in_array('13操', $awards) && !in_array('14操', $awards)) {
  666. Rebate::updateProfit([
  667. 'member_id' => $v['member_id'],
  668. 'profit' => $yl,
  669. ]);
  670. }
  671. $memberList[$v['member_id']][] = [
  672. 'member_id' => $v['member_id'],
  673. 'keywords' => $v['keywords'],
  674. 'amount' => $v['amount'],
  675. 'profit' => $profit,
  676. 'yl' => $yl,
  677. ];
  678. // 结算
  679. WalletService::updateBalance($v['member_id'], $profit);
  680. $walletInfo = WalletService::findOne(['member_id' => $v['member_id']]);
  681. $balance = $walletInfo['available_balance'];
  682. BalanceLogService::addLog($v['member_id'], $profit, $balance, ($balance + $profit), '中奖', $v['id'], '');
  683. if (isset($openList[$v['member_id']])) {
  684. $openList[$v['member_id']]['member_id'] = $v['member_id'];
  685. $openList[$v['member_id']]['amount'] += $v['amount'];
  686. $openList[$v['member_id']]['profit'] += $profit;
  687. $openList[$v['member_id']]['lastStr'] = $lastStr;
  688. $openList[$v['member_id']]['openKeywords'][] = $v['keywords'] . "({$odds}" . lang("倍率") . ")";
  689. $openList[$v['member_id']]['keywords'][] = $v['keywords'];
  690. $openList[$v['member_id']]['win_amount'] += $v['amount'];
  691. } else {
  692. $openList[$v['member_id']]['member_id'] = $v['member_id'];
  693. $openList[$v['member_id']]['amount'] = $v['amount'];
  694. $openList[$v['member_id']]['profit'] = $profit;
  695. $openList[$v['member_id']]['lastStr'] = $lastStr;
  696. $openList[$v['member_id']]['openKeywords'] = [];
  697. $openList[$v['member_id']]['keywords'] = [];
  698. $openList[$v['member_id']]['openKeywords'][] = $v['keywords'] . "({$odds}" . lang("倍率") . ")";
  699. $openList[$v['member_id']]['keywords'][] = $v['keywords'];
  700. $openList[$v['member_id']]['win_amount'] = $v['amount'];
  701. $openList[$v['member_id']]['is_send'] = true;
  702. }
  703. } else {
  704. if (!in_array('13操', $awards) && !in_array('14操', $awards)) {
  705. Rebate::updateProfit([
  706. 'member_id' => $v['member_id'],
  707. 'profit' => ($v['amount'] * -1),
  708. ]);
  709. }
  710. $profit = 0;
  711. if (in_array('13操', $awards) || in_array('14操', $awards)) {
  712. $amount = $v['amount'];
  713. $odds = 0;
  714. // 13 14特殊处理倍率
  715. if (in_array($v['keywords'], self::$OTHER_BET_1)) {
  716. if ($sum < 10000) {
  717. $odds = 1.5;
  718. } else {
  719. $odds = 1;
  720. }
  721. }
  722. if (in_array($v['keywords'], self::$OTHER_BET_2)) {
  723. $odds = 1;
  724. }
  725. $profit = bcmul($amount, $odds, 2); // 保留两位小数
  726. if ($profit > 1000000) {
  727. $profit = 1000000; // 单注最高奖金1000000
  728. }
  729. $item['profit'] = $profit;
  730. $yl = bcsub($profit, $amount, 2); // 盈利
  731. WalletService::updateBalance($v['member_id'], $profit);
  732. $walletInfo = WalletService::findOne(['member_id' => $v['member_id']]);
  733. $balance = $walletInfo['available_balance'];
  734. BalanceLogService::addLog($v['member_id'], $profit, $balance, ($balance + $profit), '中奖', $v['id'], '');
  735. }
  736. if (isset($openList[$v['member_id']])) {
  737. $openList[$v['member_id']]['member_id'] = $v['member_id'];
  738. $openList[$v['member_id']]['amount'] += $v['amount'];
  739. $openList[$v['member_id']]['profit'] += $profit;
  740. $openList[$v['member_id']]['lastStr'] = $lastStr;
  741. $openList[$v['member_id']]['keywords'][] = $v['keywords'];
  742. } else {
  743. $openList[$v['member_id']]['member_id'] = $v['member_id'];
  744. $openList[$v['member_id']]['amount'] = $v['amount'];
  745. $openList[$v['member_id']]['profit'] = $profit;
  746. $openList[$v['member_id']]['lastStr'] = $lastStr;
  747. $openList[$v['member_id']]['openKeywords'] = [];
  748. $openList[$v['member_id']]['keywords'] = [];
  749. $openList[$v['member_id']]['keywords'][] = $v['keywords'];
  750. $openList[$v['member_id']]['win_amount'] = 0;
  751. $openList[$v['member_id']]['is_send'] = true;
  752. }
  753. }
  754. self::model()::where('id', $v['id'])->update($item);
  755. }
  756. $openList = array_merge($openList, $fakeOpenData['list']);
  757. self::lotteryNotice($openList, $issue_no, $keywordsList);
  758. }
  759. // 虚拟开奖
  760. public static function fakeLotteryDraw($issue_no, $awards, $rand_num = 30)
  761. {
  762. $fake_bet_list = Cache::get('fake_bet_' . $issue_no, []);
  763. $text = "";
  764. $keywordsList = [];
  765. $fakeOtherSum = 0;
  766. $openList = [];
  767. foreach ($fake_bet_list as $k => $v) {
  768. if (in_array($v['keywords'], ['大', '小', '单', '双'])) {
  769. $fakeOtherSum += $v['amount'];
  770. }
  771. if (isset($keywordsList[$v['keywords']])) {
  772. $keywordsList[$v['keywords']] += $v['amount'];
  773. } else {
  774. $keywordsList[$v['keywords']] = $v['amount'];
  775. }
  776. // $lastStr = self::getLastChar($v['first_name'], 1);
  777. $lastStr = self::hideMiddleDigits($v['member_id'], 4);
  778. if (in_array($v['keywords'], $awards)) {
  779. $amount = $v['amount'];
  780. $odds = $v['odds'];
  781. $profit = bcmul($amount, $odds, 2); // 保留两位小数
  782. if ($profit > 880000) {
  783. $profit = 880000; // 单注最高奖金880000
  784. }
  785. $item['profit'] = $profit;
  786. // $v['amount'] = number_format($amount,2);
  787. if (isset($openList[$v['member_id']])) {
  788. $openList[$v['member_id']]['member_id'] = $v['member_id'];
  789. $openList[$v['member_id']]['amount'] += $v['amount'];
  790. $openList[$v['member_id']]['profit'] += $profit;
  791. $openList[$v['member_id']]['lastStr'] = $lastStr;
  792. $openList[$v['member_id']]['openKeywords'][] = $v['keywords'] . "({$odds}" . lang("倍率") . ")";
  793. $openList[$v['member_id']]['keywords'][] = $v['keywords'];
  794. $openList[$v['member_id']]['win_amount'] += $v['amount'];
  795. } else {
  796. $openList[$v['member_id']]['member_id'] = $v['member_id'];
  797. $openList[$v['member_id']]['amount'] = $v['amount'];
  798. $openList[$v['member_id']]['profit'] = $profit;
  799. $openList[$v['member_id']]['lastStr'] = $lastStr;
  800. $openList[$v['member_id']]['openKeywords'] = [];
  801. $openList[$v['member_id']]['keywords'] = [];
  802. $openList[$v['member_id']]['openKeywords'][] = $v['keywords'] . "({$odds}" . lang("倍率") . ")";
  803. $openList[$v['member_id']]['keywords'][] = $v['keywords'];
  804. $openList[$v['member_id']]['win_amount'] = $v['amount'];
  805. $openList[$v['member_id']]['is_send'] = false;
  806. }
  807. } else {
  808. if (isset($openList[$v['member_id']])) {
  809. $openList[$v['member_id']]['member_id'] = $v['member_id'];
  810. $openList[$v['member_id']]['amount'] += $v['amount'];
  811. $openList[$v['member_id']]['lastStr'] = $lastStr;
  812. $openList[$v['member_id']]['keywords'][] = $v['keywords'];
  813. } else {
  814. $openList[$v['member_id']]['member_id'] = $v['member_id'];
  815. $openList[$v['member_id']]['amount'] = $v['amount'];
  816. $openList[$v['member_id']]['profit'] = 0;
  817. $openList[$v['member_id']]['lastStr'] = $lastStr;
  818. $openList[$v['member_id']]['openKeywords'] = [];
  819. $openList[$v['member_id']]['keywords'] = [];
  820. $openList[$v['member_id']]['keywords'][] = $v['keywords'];
  821. $openList[$v['member_id']]['win_amount'] = 0;
  822. $openList[$v['member_id']]['is_send'] = false;
  823. }
  824. }
  825. }
  826. return ['sum' => $fakeOtherSum, 'list' => $openList, 'keywordsList' => $keywordsList];
  827. }
  828. // 开奖通知
  829. public static function lotteryNotice($openList, $issue_no, $keywordsList = [])
  830. {
  831. $betNoticeNum = Config::where('field', 'bet_notice_num')->first()->val;
  832. $betNoticeNum = explode(',', $betNoticeNum);
  833. $betNoticeMini = $betNoticeNum[0] ?? 26;
  834. $betNoticeMax = $betNoticeNum[1] ?? 38;
  835. $noticeNum = rand($betNoticeMini, $betNoticeMax);
  836. // shuffle($openList);
  837. // Log::error('lotteryNotice openList', $openList);
  838. $lang = App::getLocale();
  839. $group_language = Config::where('field', 'group_language')->first()->val;
  840. App::setLocale($group_language);
  841. $text = "{$issue_no} " . lang("期开奖结果");
  842. $text .= "\n-----" . lang("本期开奖账单") . "----- \n";
  843. App::setLocale($lang);
  844. foreach ($openList as $k => $v) {
  845. $amount = number_format($v['amount'], 2);
  846. $v['win_amount'] = number_format($v['win_amount'], 2);
  847. $profit = number_format($v['profit'], 2);
  848. $yl = bcsub($v['profit'], $v['amount'], 2); // 盈利
  849. if (empty($v['openKeywords'])) {
  850. $openKeyword = '-';
  851. } else {
  852. $openKeyword = implode(',', $v['openKeywords']);
  853. }
  854. if (($k + 1) <= $noticeNum) {
  855. $lang = App::getLocale();
  856. $group_language = Config::where('field', 'group_language')->first()->val;
  857. App::setLocale($group_language);
  858. $text .= lang("用户ID") . ":{$v['lastStr']} \n";
  859. $text .= lang("下注类型") . ":[" . implode(',', $v['keywords']) . "] \n";
  860. $text .= lang('中奖类型') . ":[" . $openKeyword . "] \n";
  861. $text .= lang('投注金额') . ":{$amount} \n";
  862. $text .= lang('中奖金额') . ":{$v['win_amount']} \n";
  863. $text .= lang('派彩金额') . ":{$profit} \n";
  864. $text .= lang("盈亏金额") . ":{$yl} \n";
  865. $text .= "-------------------------------- \n";
  866. App::setLocale($lang);
  867. }
  868. if ($v['is_send']) {
  869. $language = User::where('member_id', $v['member_id'])->first()->language;
  870. $wallet = WalletService::findOne(['member_id' => $v['member_id']]);
  871. App::setLocale($language);
  872. $text2 = lang("{issue_no}期开奖结果");
  873. $text2 = str_replace("{issue_no}", $issue_no, $text2);
  874. $text2 .= "\n";
  875. $text2 .= lang('下注类型') . ":[" . implode(',', $v['keywords']) . "] \n";
  876. $text2 .= lang('中奖类型') . ":[" . $openKeyword . "] \n";
  877. $text2 .= lang('投注金额') . ":{$amount} \n";
  878. $text2 .= lang('中奖金额') . ":{$v['win_amount']} \n";
  879. $text2 .= lang('派彩金额') . ":{$profit} \n";
  880. $text2 .= lang("盈亏金额") . ":{$yl} \n";
  881. $balance = floatval($wallet->available_balance);
  882. $text2 .= "----------------\n";
  883. $text2 .= "当前余额:{$balance} \n";
  884. $keyboard = [];
  885. $keyboard[] = [
  886. ['text' => lang("开奖历史"), 'callback_data' => "showLotteryHistory@@" . $issue_no]
  887. ];
  888. // self::sendMessage($v['member_id'],$text2,$keyboard);
  889. SendTelegramMessageJob::dispatch($v['member_id'], $text2, $keyboard);
  890. }
  891. }
  892. $inlineButton = self::getOperateButton();
  893. // 群通知
  894. $pc28Switch = Config::where('field', 'pc28_switch')->first()->val;
  895. if (($pc28Switch == 0 && is_numeric($issue_no)) || $pc28Switch == 1 && !is_numeric($issue_no)) {
  896. SendTelegramGroupMessageJob::dispatch($text, $inlineButton, '', false, '--------------------------------');
  897. }
  898. }
  899. /**
  900. * @description: 统计投注情况通知
  901. * @param {*} $issue_no
  902. * @return {*}
  903. */
  904. public static function statNotice($issue_no)
  905. {
  906. $keywordsList = [];
  907. // 虚拟投注情况
  908. $fake_bet_list = Cache::get('fake_bet_' . $issue_no, []);
  909. foreach ($fake_bet_list as $k => $v) {
  910. if (isset($keywordsList[$v['keywords']])) {
  911. $keywordsList[$v['keywords']] += $v['amount'];
  912. } else {
  913. $keywordsList[$v['keywords']] = $v['amount'];
  914. }
  915. }
  916. // 真实投注
  917. $list = self::findAll(['issue_no' => $issue_no, 'status' => self::model()::STATUS_STAY]);
  918. foreach ($list->toArray() as $k => $v) {
  919. if (isset($keywordsList[$v['keywords']])) {
  920. $keywordsList[$v['keywords']] += $v['amount'];
  921. } else {
  922. $keywordsList[$v['keywords']] = $v['amount'];
  923. }
  924. }
  925. $lang = App::getLocale();
  926. $group_language = Config::where('field', 'group_language')->first()->val;
  927. App::setLocale($group_language);
  928. $text3 = "📝 {$issue_no}" . lang('期投注统计') . " \n";
  929. $text3 .= lang("玩法") . " " . lang("总投") . " \n";
  930. App::setLocale($lang);
  931. if ($keywordsList) {
  932. uksort($keywordsList, 'custom_sort');
  933. // ksort($keywordsList);
  934. foreach ($keywordsList as $k => $v) {
  935. $text3 .= "{$k} {$v} \n";
  936. }
  937. }
  938. $inlineButton = self::getOperateButton();
  939. // 投注统计的消息不发了
  940. // SendTelegramGroupMessageJob::dispatch($text3, $inlineButton, '');
  941. }
  942. public static function todayExchangeRate($chatId)
  943. {
  944. $exchangeRate = Config::where('field', 'exchange_rate_rmb')->first()->val;
  945. $text = lang("今日汇率") . ":1USDT = {$exchangeRate} RMB \n";
  946. // $botMsg = [
  947. // 'chat_id' => "@{$chatId}",
  948. // 'text' => $text
  949. // ];
  950. self::sendMessage($chatId, $text);
  951. // return $botMsg;
  952. }
  953. }