BetService.php 44 KB

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