BetService.php 44 KB

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