<?php


namespace App\Services;

use App\Constants\StepStatus;
use App\Constants\Util;
use App\Models\Message;
use App\Models\PcIssue;
use App\Models\Rebate;
use App\Models\User;
use App\Models\LhcOrder;
use App\Models\Config;
use App\Models\LhcOrderItem;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;
use App\Jobs\SendTelegramMessageJob;
use App\Jobs\SendTelegramGroupMessageJob;
use Exception;
use Illuminate\Support\Facades\Log;
use Telegram\Bot\Api;
use Telegram\Bot\Exceptions\TelegramSDKException;
use App\Services\ActivityRewardService;

/**
 * 投注
 */
class BetService extends BaseService
{

    /**
     * @param Api $telegram
     * @param $data
     * @param $chatId
     * @param $firstName
     * @param $messageId
     * @param $callbackId
     * @return void
     * @throws TelegramSDKException
     */
    public static function init(Api $telegram, $data, $chatId, $firstName, $messageId, $callbackId): void
    {
        switch ($data) {
            case "todayExchangeRate@@rate":  // 今日汇率
                BetService::todayExchangeRate($chatId);
                break;
            case "betsAlert":// 近期注单弹窗
                Cache::put('message_id_bet_record_' . $chatId, 0, 600);
                $alertText = BetService::recentlyRecord($chatId);
                BetService::alertNotice($callbackId, $alertText);
                break;
            case "promotionalActivityAlert":
                // 删除个人缓存
                Util::delCache($chatId);
                $returnMsg = ActivityRewardService::promotionalActivity($chatId);
                $telegram->sendMessage($returnMsg);
                break;
            default:
                //选择投注记录
                $pattern = "/^betRecordType@@\d+$/";
                if (preg_match($pattern, $data)) {
                    $type = preg_replace('/^betRecordType@@/', '', $data);
                    Cache::put('message_id_bet_record_' . $chatId, intval($type), 600);
                    $telegram->deleteMessage([
                        'chat_id' => $chatId,
                        'message_id' => $messageId,
                    ]);
                    $returnMsg = BetService::record($chatId);
                    $telegram->sendMessage($returnMsg);
                }


                //近期注单，下一页
                $pattern = "/^betRecordNextPage@@\d+$/";
                if (preg_match($pattern, $data)) {
                    $page = preg_replace('/^betRecordNextPage@@/', '', $data);
                    $page = intval($page);
                    $res = BetService::record($chatId, $messageId, $page);
                    $telegram->editMessageText($res);
                }
                break;
        }

    }

    public static function onMessage($chatId, $text, $messageId, $stepStatus): ?array
    {
        switch ($stepStatus) {

            default:
                $res = null;
                break;
        }
        return $res;
    }


    public static $OTHER_BET_1 = [
        '大',
        '小',
        '单',
        '双',
    ];

    public static $OTHER_BET_2 = [
        '大单',
        '大双',
        '小单',
        '小双',
    ];

    /**
     * @description: 模型
     * @return {string}
     */
    public static function model(): string
    {
        return LhcOrder::class;
    }

    /**
     * @description: 枚举
     * @return {*}
     */
    public static function enum(): string
    {
        return '';
    }


    public static function getWhere(array $search = []): array
    {
        $where = [];
        if (isset($search['issue_no']) && !empty($search['issue_no'])) {
            $where[] = ['issue', '=', $search['issue_no']];
        }
        if (isset($search['issue']) && !empty($search['issue'])) {
            $where[] = ['issue', '=', $search['issue']];
        }
        if (isset($search['member_id']) && !empty($search['member_id'])) {
            $where[] = ['member_id', '=', $search['member_id']];
        }
        if (isset($search['keywords']) && !empty($search['keywords'])) {
            $where[] = ['number', '=', $search['keywords']];
        }
        if (isset($search['number']) && !empty($search['number'])) {
            $where[] = ['number', '=', $search['number']];
        }
        if (isset($search['issue_id']) && !empty($search['issue_id'])) {
            $where[] = ['lhc_number_id', '=', $search['issue_id']];
        }
        if (isset($search['id']) && !empty($search['id'])) {
            $where[] = ['id', '=', $search['id']];
        }
        if (isset($search['user_id']) && !empty($search['user_id'])) {
            $where[] = ['user_id', '=', $search['user_id']];
        }


        if (isset($search['start_time']) && !empty($search['start_time'])) {
            $where[] = ['created_at', '>=', "{$search['start_time']} 00:00:00"];
            $where[] = ['created_at', '<=', "{$search['end_time']} 23:59:59"];
        }

        if (isset($search['is_winner']) && $search['is_winner'] != '') {
            $where[] = ['lottery_status', '=', 2];
            if ($search['is_winner'] == 1) {
                $where[] = ['profit_and_loss', '>', 0];
            } else {
                $where[] = ['profit_and_loss', '<=', 0];
            }
        } else {
            if (isset($search['status']) && $search['status'] != '') {
                $where[] = ['lottery_status', '=', $search['status']];
            }
        }
        if (isset($search['lottery_status']) && !empty($search['lottery_status'])) {
            $where[] = ['lottery_status', '=', $search['lottery_status']];
        }
        $where[] = ['type', '>=', 5];
        $where[] = ['type', '<=', 6];
        return $where;
    }

    /**
     * @description: 查询单条数据
     * @param array $search
     * @return \App\Models\Coin|null
     */
    public static function findOne(array $search): ?LhcOrder
    {
        return self::model()::where(self::getWhere($search))->first();
    }

    /**
     * @description: 查询所有数据
     * @param array $search
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public static function findAll(array $search = [])
    {
        return self::model()::where(self::getWhere($search))->get();
    }

    /**
     * @description: 分页查询
     * @param array $search
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public static function paginate(array $search = [])
    {
        $limit = isset($search['limit']) ? $search['limit'] : 15;
        $query = self::model()::where(self::getWhere($search))
            ->with(['user']);


        if (isset($search['username']) && !empty($search['username'])) {
            $username = $search['username'];
            $query = $query->whereHas('user', function ($query) use ($username) {
                $query->where('username', $username);
            });
        }
        $query->orderBy('id', 'desc');
        $paginator = $query->paginate($limit);
        return ['total' => $paginator->total(), 'data' => $paginator->items()];
    }

    /**
     * @description: 投注操作
     * @param string $memberId
     * @param string $input
     * @param int $messageId
     * @return array
     */
    public static function bet(string $memberId, string $input, int $messageId = 0): array
    {
        $msg = [];
        $msg['chat_id'] = $memberId;
        // 分解投注的内容
        $betResult = GameplayRuleService::bettingRuleVerify($input);
        $serviceAccount = Config::where('field', 'service_customer')->first()->val;

        $maintenanceSwitch = Config::where('field', 'maintenance_switch')->first()->val;
        if ($maintenanceSwitch != 0) {
            $text = lang("系统维护中") . "\n";
            $text .= lang("任何疑问都可以联系唯一客服") . "：@{$serviceAccount}";
            $msg['text'] = $text;
            if ($messageId) {
                $msg['reply_to_message_id'] = $messageId;
            }
            return $msg;
        }

        //是否封号
        $isBanned = UserService::getIsBanned($memberId);
        if ($isBanned) {
            $text = lang("账号异常") . "\n";
            $text .= lang("任何疑问都可以联系唯一客服") . "：@{$serviceAccount}";
            $msg['text'] = $text;
            if ($messageId) {
                $msg['reply_to_message_id'] = $messageId;
            }
            return $msg;
        }


        if ($betResult == null) {
            $text = lang("消息格式错误！") . "\n";
            $text .= lang("任何疑问都可以联系唯一客服") . "：@{$serviceAccount}";
            $msg['text'] = $text;
            if ($messageId) {
                $msg['reply_to_message_id'] = $messageId;
            }
            return $msg;
        }

        DB::beginTransaction();
        try {
            $text = lang('下注期数') . "：{issue_no}\n";
            $text .= lang("下注内容") . "\n";
            $text .= "--------\n";
            $success = false;
            $sumAmount = 0;
            $errText = $groupText = "";
            foreach ($betResult as $index => $item) {
                $keywords = $item['rule'];
                $amount = $item['amount'];
                $error = $issueNo = "";
                $b = static::singleNote($memberId, $keywords, $amount, $issueNo, $text, $error, $groupText, $index);
                if ($b) {
                    $sumAmount += $amount;
                    $text = str_replace("{issue_no}", $issueNo, $text);
                    $success = true;
                    $text .= "\n";
                } else {
                    $errText .= $error;
                    $errText .= "\n";
                }
            }

            if (!$success) {
                $msg['text'] = $errText;
                if ($messageId) {
                    $msg['reply_to_message_id'] = $messageId;
                }
            } else {
                $sumAmount = number_format($sumAmount, 2);
                $text .= "--------\n";
                $text .= lang("合计金额") . "：{$sumAmount}\n";
                $text .= lang("下注成功");
                $msg['text'] = $text;
                $msg['text'] .= "\n";
                if (!empty($errText)) {
                    $msg['text'] .= "------------------------\n";
                    $msg['text'] .= $errText;
                }
                $groupText .= "\n--------\n";
                self::asyncBettingGroupNotice($groupText, self::getOperateButton());   // 异步群通知
            }
            DB::commit();
        } catch (Exception $e) {
            DB::rollBack();
            Log::error('错误信息', [
                'message' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'trace' => $e->getTraceAsString()
            ]);
            $msg['text'] = "投注失败，请联系管理员";
            if ($messageId) {
                $msg['reply_to_message_id'] = $messageId;
            }
        }
        return $msg;
    }

    private static function singleNote($memberId, $keywords, $amount, &$issueNo, &$text, &$errText, &$groupText, $index): bool
    {
        $errText .= "【{$keywords}{$amount}】\n";
        //客服号
        $serviceAccount = Config::where('field', 'service_customer')->first()->val;
        $gameplayRuleInfo = GameplayRuleService::getGameplayRules($keywords);
        if ($gameplayRuleInfo == null) {
            $errText .= lang("玩法未配置！") . "\n";
            $errText .= lang("任何疑问都可以联系唯一财务") . "：@{$serviceAccount}";
            return false;
        }

        if ($gameplayRuleInfo['odds'] <= 0) {
            $errText .= lang("赔率为0 庄家通吃 禁止投注！") . "\n";
            $errText .= lang("任何疑问都可以联系唯一财务") . "：@{$serviceAccount}";
            return false;

        }

        // 期数验证

        $pc28Switch = Config::where('field', 'pc28_switch')->first()->val;
        if ($pc28Switch == 1) {
            $issueInfo = PcIssue::where('status', PcIssue::STATUS_BETTING)->orderBy('id', 'desc')->first();
        } else {
            $issueInfo = IssueService::model()::where('status', IssueService::model()::STATUS_BETTING)->orderBy('id', 'desc')->first();
        }

        if (empty($issueInfo)) {
            if ($pc28Switch == 1) {
                $issueCloseInfo = PcIssue::where('status', PcIssue::STATUS_CLOSE)->orderBy('id', 'desc')->first();
            } else {
                $issueCloseInfo = IssueService::model()::where('status', IssueService::model()::STATUS_CLOSE)->orderBy('id', 'desc')->first();
            }


            if (empty($issueCloseInfo)) {
                $errText .= lang("暂无可下注期数，本次下注无效！");
                return false;
            } else {
                $errText .= lang("封盘中，本次下注无效！");
                return false;
            }
        }


        if (!is_numeric($amount) || $amount <= 0) {
            $errText .= lang("投注金额格式不正确！");
            $errText .= lang("任何疑问都可以联系唯一财务") . "：@{$serviceAccount}";
            return false;
        }

        $now_date = date('Y-m-d H:i:s', time() + 30); // 提前30秒
        if ($issueInfo['end_time'] < $now_date) {
            $errText .= lang("封盘中，本次下注无效！");
            return false;
        }

        // 投注限制校验
        if ($amount < $gameplayRuleInfo['mininum']) {
            $errText .= lang("下注失败，最小金额限制") . "{$gameplayRuleInfo['mininum']}\n";
            return false;
        }

        // 投注限制校验
        if ($amount > $gameplayRuleInfo['maxinum']) {
            $errText .= lang("下注失败，最大金额限制") . "{$gameplayRuleInfo['maxinum']}\n";
            return false;
        }

        // 获取用户余额
        $walletInfo = WalletService::findOne(['member_id' => $memberId]);
        $balance = $walletInfo['available_balance'];

        // 余额计算
        if ($balance < $amount) {
            $errText .= lang("余额不足，本次下注无效！\n");
            return false;
        }

        $userInfo = UserService::findOne(['member_id' => $memberId]);

        $type = $pc28Switch == 1 ? 6 : 5;
        $betInfo = LhcOrder::where(['type' => $type, 'member_id' => $memberId, 'issue' => $issueInfo->issue_no, 'number' => $keywords])->first(); // 相同下注

        if ($betInfo) {
            $betInfo->amount = $betInfo->amount + $amount;
            $bet_id = $betInfo->id;
            $betInfo->save();
        } else {
            $data = [];
            $data['amount'] = $amount; // 分数
            $data['number'] = $keywords;  // 玩法
            $data['member_id'] = $memberId;
            $data['user_id'] = $userInfo->id;
            $data['issue'] = $issueInfo->issue_no;
            $data['lhc_number_id'] = $issueInfo->id;
            $data['odds'] = $gameplayRuleInfo['odds'];
            $data['type'] = $type;
            $newBet = LhcOrder::create($data);

            $bet_id = $newBet->id;
        }


        WalletService::updateBalance($memberId, -$amount);
        BalanceLogService::addLog($memberId, -$amount, $balance, ($balance - $amount), '投注', $bet_id, '');


        //记录投注金额
        $rebate = Rebate::addOrUpdate([
            'member_id' => $memberId,
            'betting_amount' => $amount,
            'first_name' => $userInfo->first_name,
            'username' => $userInfo->username,
        ]);


        $odds = floatval($gameplayRuleInfo['odds']);
        $issueNo = $issueInfo->issue_no;
        $text .= "{$keywords} {$amount}   ({$odds}" . lang('倍率') . ")";
        $lastStr = self::hideMiddleDigits($userInfo->member_id, 4);
        $lang = App::getLocale();
        $group_language = Config::where('field', 'group_language')->first()->val;
        App::setLocale($group_language);
        if ($index === 0) {
            $groupText .= lang("第") . "{$issueNo}" . lang("期") . "\n";
            $groupText .= lang("开奖时间") . "：" . date("H:i:s", strtotime($issueInfo['end_time'])) . "\n";
            $groupText .= lang('投注截止') . "：" . date("H:i:s", (strtotime($issueInfo['end_time'])) - 30) . "\n";;
            $groupText .= lang("成功") . "\n";
            $groupText .= lang('玩家') . "： 【{$lastStr}】 \n";
        }
        $groupText .= "{$keywords} {$amount} ({$odds}" . lang("倍率") . ") \n";
        App::setLocale($lang);
        return true;
    }

    //随机虚拟下注
    public static function randomVirtualBetting($maxPeople = 1): void
    {
        $maxPeople = intval($maxPeople);
        $maxPeople = max($maxPeople, 1);
        $maxPeople = min($maxPeople, 20);
        $num = rand(1, $maxPeople);
        for ($i = 0; $i < $num; $i++) {
            static::fakeBet(4);
        }
    }

    // 模拟下注
    private static function fakeBet($betNumber = 1): void
    {
        $noRule = ['0操', '27操'];
        // 防止一开就虚拟投注
        $cache = Cache::get('new_issue_no');
        if ($cache) {
            echo "防止一开就虚拟投注\n";
            return;
        }

        //系统维护
        $maintenanceSwitch = Config::where('field', 'maintenance_switch')->first()->val;
        if ($maintenanceSwitch != 0) {
            echo "系统维护中\n";
            return;
        }
        //后台是否开启虚拟投注
        $betFake = Config::where('field', 'bet_fake')->first()->val;
        if ($betFake != 1) {
            echo "未开启虚拟投注\n";
            return;
        }


        // 期数验证
        $pc28Switch = Config::where('field', 'pc28_switch')->first()->val;
        if ($pc28Switch == 1) {
            $issueInfo = PcIssue::where('status', PcIssue::STATUS_BETTING)->orderBy('id', 'desc')->first();
        } else {
            $issueInfo = IssueService::model()::where('status', IssueService::model()::STATUS_BETTING)->orderBy('id', 'desc')->first();
        }

        if ($issueInfo) {
            $betFakeRandAmount = Config::where('field', 'bet_fake_rand_amount')->first()->val;
            $betFakeRandAmount = explode(',', $betFakeRandAmount);
            $betMini = $betFakeRandAmount[0] ?? 10;
            $betMax = $betFakeRandAmount[1] ?? 10000;

            $now_date = date('Y-m-d H:i:s', time() + 38); // 提前45秒
            if ($issueInfo['end_time'] > $now_date) {
                $fake_bet_list = Cache::get('fake_bet_' . $issueInfo->issue_no, []);
                $gameplayRuleList = GameplayRuleService::model()::where('odds', '>', 0)->get();
                $gameplayRuleList = $gameplayRuleList->toArray();
                $member_id = self::generateRandomNumber(10);
                $betTimes = rand(1, $betNumber); // 每次下注次数
                Cache::add("封盘后下注单数_{$issueInfo->issue_no}", rand(3, 5), 4);


                $lastStr = self::hideMiddleDigits($member_id, 4);
                $lang = App::getLocale();
                $group_language = Config::where('field', 'group_language')->first()->val;
                $first_name = self::generateRandomString(6);
                App::setLocale($group_language);
                $groupText = lang("第") . "{$issueInfo->issue_no}" . lang("期") . "\n";
                $groupText .= lang("开奖时间") . "：" . date("H:i:s", strtotime($issueInfo['end_time'])) . "\n";
                $groupText .= lang('投注截止') . "：" . date("H:i:s", (strtotime($issueInfo['end_time'])) - 30) . "\n";;
                $groupText .= lang("成功") . "\n";
                $groupText .= lang('玩家') . "： 【{$lastStr}】 \n";
                App::setLocale($lang);
                $haveBet = false;
                for ($i = 0; $i < $betTimes; $i++) {
                    if (strtotime($issueInfo['end_time']) - time() < IssueService::COUNTDOWN_TO_CLOSING_THE_MARKET) {
                        $fake_bet_count = Cache::get("fake_bet_count_{$issueInfo->issue_no}", 0);
                        $cc = Cache::get("封盘后下注单数_{$issueInfo->issue_no}");
                        if ($fake_bet_count >= $cc) return;
                    }


                    $randKey = array_rand($gameplayRuleList, 1);
                    $gameplayRuleInfo = $gameplayRuleList[$randKey] ?? [];
                    if ($gameplayRuleInfo) {
                        if (in_array($gameplayRuleInfo['keywords'], $noRule)) {
                            return;

                        }
                        if ($gameplayRuleInfo['maxinum'] < $betMax) {
                            $betMax = $gameplayRuleInfo['maxinum'];
                        }
                        if ($gameplayRuleInfo['mininum'] > $betMini) {
                            $betMini = $gameplayRuleInfo['mininum'];
                        }

                        $amount = rand($betMini, $betMax);
                        $amount = floor($amount / 10) * 10;
                        $input = $gameplayRuleInfo['keywords'] . ' ' . $amount;
                        // $amount = number_format($amount,2);
                        $item = [];
                        $item['keywords'] = $gameplayRuleInfo['keywords'];
                        $item['odds'] = floatval($gameplayRuleInfo['odds']);
                        $item['amount'] = $amount;
                        $item['first_name'] = $first_name;
                        $item['member_id'] = $member_id;
                        $item['profit'] = 0;
                        // $input = $item['keywords'] . $item['amount'];

                        $fake_bet_list[] = $item;
                        $lang = App::getLocale();
                        $group_language = Config::where('field', 'group_language')->first()->val;
                        $first_name = self::generateRandomString(6);
                        App::setLocale($group_language);
                        $groupText .= "{$input} (" . $item['odds'] . lang("倍率") . ") \n";
                        $haveBet = true;
                        App::setLocale($lang);

                        if (strtotime($issueInfo['end_time']) - strtotime($now_date) < 22) {
                            $fake_bet_count = Cache::get("fake_bet_count_{$issueInfo->issue_no}", 0);
                            Cache::put("fake_bet_count_{$issueInfo->issue_no}", $fake_bet_count + 1, 500);
                        }
                    }
                }
                if ($haveBet) {
                    $groupText .= "\n-------- \n";
                    $inlineButton = self::getOperateButton();
                    // 群通知  暂停2秒再发送，避免同时发送多个消息而超过 Telegram 的频率限制
                    self::asyncBettingGroupNotice($groupText, $inlineButton);   // 异步群通知
                    sleep(2);
                }

                Cache::put('fake_bet_' . $issueInfo->issue_no, $fake_bet_list, 500);
            }


        }

    }

    /**
     * @description: 当期下注
     * @param {*} $memberId
     * @return {*}
     */
    public static function currentBet($memberId)
    {
        $msg['chat_id'] = $memberId;
        // 期数验证
        $issueInfo = IssueService::model()::where('status', IssueService::model()::STATUS_BETTING)->orderBy('id', 'desc')->first();
        $issue_no = '';
        if (!empty($issueInfo)) {
            $issue_no = $issueInfo->issue_no;
        } else {
            $issueCloseInfo = IssueService::model()::where('status', IssueService::model()::STATUS_CLOSE)->orderBy('id', 'desc')->first();
            if (empty($issueCloseInfo)) {
                $issue_no = $issueCloseInfo->issue_no;
            }
        }

        if ($issue_no) {
            $text = lang("期数") . " {$issue_no} \n";
            // $text .= "\n";
            // $text .= "----------\n";
            $list = self::findAll(['member_id' => $memberId, 'issue' => $issue_no]);
            $list = $list->toArray();
            if (empty($list)) {
                $text .= lang("本期暂未下注") . "！ \n";
            } else {
                $keywords = implode(',', array_column($list, 'number'));
                $amounts = implode(',', array_column($list, 'amount'));


                $text .= lang("下注类型") . "：[" . $keywords . "] \n";
                $text .= lang("下注金额") . "：" . $amounts . " \n";
                $text .= lang("下注总额") . "：" . array_sum(array_column($list, 'amount')) . " \n";
                $text .= lang("开奖状态") . "：" . lang("等待开奖") . " \n";
            }
            // foreach ($list->toArray() as $k => $v) {
            //     $text .= "{$v['keywords']}{$v['amount']} \n";
            // }

            // $text .= "\n";
            // $text .= "----------\n";
            $msg['text'] = $text;
        } else {
            $msg['text'] = lang("当前没有开放的投注期数") . "！ \n";
        }

        return $msg;
    }

    /**
     * @description: 近期投注
     * @param {*} $memberId
     * @return {*}
     */
    public static function recentlyRecord($memberId, $page = 1, $limit = 5)
    {
        $list = self::model()::where('type', 'in', [5,6])->where('member_id', $memberId)->orderBy('id', 'desc')->forPage($page, $limit)->get();

        // $text = "```\n";
        $text = "";
        $text .= "期数--内容--盈亏 \n";
        foreach ($list->toArray() as $k => $v) {
            $profit = $v['win_amount'] - $v['amount'];
            // $text .= $v['issue_no']." ".$v['keywords']." ".$v['amount']." ".$v['profit']."\n";
            $item = $v['issue'] . "==" . $v['number'] . rtrim(rtrim(number_format($v['amount'], 2, '.', ''), '0'), '.') . "==" . rtrim(rtrim(number_format($profit, 2, '.', ''), '0'), '.') . "\n";
            $text .= $item;
        }
        // $text .= "```\n";

        return $text;
    }


    /**
     * @description: 投注记录
     * @param {*} $memberId
     * @param {*} $page
     * @param {*} $limit
     * @return {*}
     */
    public static function record($memberId, $messageId = null, $page = 1, $limit = 5)
    {
        $type = Cache::get('message_id_bet_record_' . $memberId, 0);
        if ($type == 0) {
            $type = '';
        }

        $msg['chat_id'] = $memberId;
        $list = self::model()::where('type', 'in', [5,6])->where('member_id', $memberId)->orderBy('id', 'desc')->forPage($page, $limit)->get();
        $count = self::model()::where('type', 'in', [5,6])->where('member_id', $memberId)->count();

        $keyboard = [];


        $total_amount = BalanceLogService::model()::where('member_id', $memberId)->where('change_type', '中奖')->sum('amount');
        $total_amount = number_format($total_amount, 2);
        $text = lang("历史注单") . " \n";
        $text .= lang("中奖总派彩") . "：{$total_amount} \n";
        foreach ($list as $k => $v) {
            if ($v->lottery_status == self::model()::STATUS_WIN || $v->lottery_status == self::model()::STATUS_LOSS) {
                $phase = $v->win_amount - $v->amount;
            } else {
                $phase = lang('待开奖');
            }

            $text .= "-------------------------------------\n";
            $text .= lang("期数") . "：{$v->issue} \n";
            $text .= lang("内容") . "：{$v->number} \n";
            $text .= lang("金额") . "：{$v->amount} \n";
            $text .= lang("盈亏") . "：{$phase} \n";
        }

        $msg['text'] = $text;

        $keyboard[] = [
            ['text' => lang("全部"), 'callback_data' => "betRecordType@@0"],
            ['text' => lang("盈利"), 'callback_data' => "betRecordType@@1"],
            ['text' => lang("亏损"), 'callback_data' => "betRecordType@@2"]
        ];

        if ($page > 1) {
            $keyboard[] = [
                ['text' => "👆" . lang("上一页"), 'callback_data' => "betRecordNextPage@@" . ($page - 1)]
            ];
        }
        $allPage = ceil($count / $limit);
        if ($allPage > $page) {
            if ($page > 1) {
                $keyboard[count($keyboard) - 1][] = ['text' => "👇" . lang("下一页"), 'callback_data' => "betRecordNextPage@@" . ($page + 1)];
            } else {
                $keyboard[] = [
                    ['text' => "👇" . lang("下一页"), 'callback_data' => "betRecordNextPage@@" . ($page + 1)]
                ];
            }
        }
        if ($messageId) {
            $msg['message_id'] = $messageId;
        }
        if ($keyboard) {
            $msg['reply_markup'] = json_encode(['inline_keyboard' => $keyboard]);
        }
        return $msg;
    }


    /**
     * @description: 开奖失败退回投注的
     * @param {*} $issue_no
     * @return {*}
     */
    public static function betFail($issue_no)
    {
        $list = self::findAll(['issue' => $issue_no, 'lottery_status' => self::model()::STATUS_STAY]);
        foreach ($list->toArray() as $k => $v) {
            $profit = $v['amount'];
            WalletService::updateBalance($v['member_id'], $profit);

            $walletInfo = WalletService::findOne(['member_id' => $v['member_id']]);
            $balance = $walletInfo['available_balance'];

            BalanceLogService::addLog($v['member_id'], $profit, ($balance - $profit), $balance, '投注退分', $v['id'], '');

            $text = $issue_no . "期开奖失败 \n";
            $text .= "投注类型:{$v['number']} \n";
            $text .= "投注金额:{$v['amount']} \n";
            $text .= "投注的资金已退回您的钱包 \n";

            self::asyncSendMessage($v['member_id'], $text);
            $item = [];
            $item['lottery_status'] = self::model()::STATUS_LOSS;
            self::model()::where('id', $v['id'])->update($item);

            //下注项状态更新为未中奖
            LhcOrderItem::where('ordernum', $v['ordernum'])->update(['lottery_status' => self::model()::STATUS_LOSS]);
        }

    }

    /**
     * @description: 中奖结算
     * @param {*} $issue_no
     * @param {*} $awards
     * @return {*}
     */
    public static function betSettled($issue_no, $awards)
    {
        $list = self::findAll(['issue' => $issue_no, 'lottery_status' => self::model()::STATUS_STAY]);
        // 大小单双的
        $otherSum = self::model()::leftJoin('lhc_order_item', 'lhc_order_item.ordernum', '=', 'lhc_order.ordernum')
                    ->whereIn('lhc_order.type', [5, 6])
                    ->where('lhc_order.issue', $issue_no)
                    ->where('lhc_order.lottery_status', self::model()::STATUS_STAY)
                    ->whereIn('lhc_order_item.number', ['大', '小', '单', '双'])
                    ->sum('lhc_order.total_amount');

        $fakeOpenData = self::fakeLotteryDraw($issue_no, $awards, 0);
        $keywordsList = $fakeOpenData['keywordsList'];
        $fakeOtherSum = $fakeOpenData['sum'];
        $sum = $otherSum + $fakeOtherSum;
        $betNoticeNum = Config::where('field', 'bet_notice_num')->first()->val;
        $betNoticeNum = explode(',', $betNoticeNum);
        $betNoticeMini = max(1, (int)($betNoticeNum[0] ?? 26));
        $betNoticeMax = max($betNoticeMini, (int)($betNoticeNum[1] ?? 38));
        $noticeNum = rand($betNoticeMini, $betNoticeMax);
        $openList = [];
        $memberList = [];
        
        foreach ($list->toArray() as $k => $v) {

            $order_item = LhcOrderItem::where('ordernum', $v['ordernum'])->get()->toArray();
            $total_amount = 0;
            foreach($order_item as $value) {
                $number = $value['number'];

                if (isset($keywordsList[$number])) {
                    $keywordsList[$number] += $v['amount'];
                } else {
                    $keywordsList[$number] = $v['amount'];
                }
                $lastStr = self::hideMiddleDigits($v['member_id'], 4);
                $item = [];
                $item['id'] = $value['id'];
                $item['lottery_status'] = self::model()::STATUS_LOSS;//未中奖
                $item['profit_and_loss'] = -$v['amount'];

                if (in_array($number, $awards)) {
                    $amount = $v['amount'];
                    $odds = $v['odds'];

                    //玩 大单 小单 大双 小双 ：如果开出13和14 总注小于10000 1.5赔率含本，大于等于10000退本金。
                    if (in_array('13操', $awards) || in_array('14操', $awards)) {
                        // 13 14特殊处理倍率
                        if (in_array($number, self::$OTHER_BET_2)) {
                            if ($sum < 10000) {
                                $odds = 1.5;
                            } else {
                                $odds = 1;
                            }
                        }
                    }

                    $profit = bcmul($amount, $odds, 2); // 保留两位小数

                    if ($profit > 1000000) {
                        $profit = 1000000; // 单注最高奖金1000000
                    }

                    $item['lottery_status'] = self::model()::STATUS_WIN;//中奖
                    $item['win_amount'] = $profit;
                    $total_amount += $profit;

                    $yl = bcsub($profit, $amount, 2); // 盈利
                    $item['profit_and_loss'] = $yl;
                    $rebate = Rebate::updateProfit([
                        'member_id' => $v['member_id'],
                        'profit' => $yl,
                    ]);

                    if (!in_array('13操', $awards) && !in_array('14操', $awards)) {
                        RebateService::updateEffectiveBettingAmount($rebate, $v['amount']);
                        ActivityUserService::updateBettingAmount($v['member_id'],$v['amount']);
                    }

                    $memberList[$v['member_id']][] = [
                        'member_id' => $v['member_id'],
                        'keywords' => $number,
                        'amount' => $v['amount'],
                        'profit' => $profit,
                        'yl' => $yl,
                    ];

                    $walletInfo = WalletService::findOne(['member_id' => $v['member_id']]);
                    $balance = $walletInfo['available_balance'];
                    WalletService::updateBalance($v['member_id'], $profit);
                    BalanceLogService::addLog($v['member_id'], $profit, $balance, ($balance + $profit), '中奖', $v['id'], "盈利:{$yl}");

                    if (isset($openList[$v['member_id']])) {
                        $openList[$v['member_id']]['member_id'] = $v['member_id'];
                        $openList[$v['member_id']]['amount'] += $v['amount'];
                        $openList[$v['member_id']]['profit'] += $profit;
                        $openList[$v['member_id']]['lastStr'] = $lastStr;
                        $openList[$v['member_id']]['openKeywords'][] = $number . "({$odds}" . lang("倍率") . ")";
                        $openList[$v['member_id']]['keywords'][] = $number;
                        $openList[$v['member_id']]['win_amount'] += $v['amount'];
                    } else {
                        $openList[$v['member_id']]['member_id'] = $v['member_id'];
                        $openList[$v['member_id']]['amount'] = $v['amount'];
                        $openList[$v['member_id']]['profit'] = $profit;
                        $openList[$v['member_id']]['lastStr'] = $lastStr;
                        $openList[$v['member_id']]['openKeywords'] = [];
                        $openList[$v['member_id']]['keywords'] = [];
                        $openList[$v['member_id']]['openKeywords'][] = $number . "({$odds}" . lang("倍率") . ")";
                        $openList[$v['member_id']]['keywords'][] = $number;
                        $openList[$v['member_id']]['win_amount'] = $v['amount'];
                        $openList[$v['member_id']]['is_send'] = true;
                    }
                } else {
                    $rebate = Rebate::updateProfit([
                        'member_id' => $v['member_id'],
                        'profit' => ($v['amount'] * -1),
                    ]);

                    if (!in_array('13操', $awards) && !in_array('14操', $awards)) {
                        RebateService::updateEffectiveBettingAmount($rebate, $v['amount']);
                        ActivityUserService::updateBettingAmount($v['member_id'],$v['amount']);
                    }
                    // 未命中的组合不应用 13/14 特殊赔率。
                    $profit = 0;

                    if (isset($openList[$v['member_id']])) {
                        $openList[$v['member_id']]['member_id'] = $v['member_id'];
                        $openList[$v['member_id']]['amount'] += $v['amount'];
                        $openList[$v['member_id']]['profit'] += $profit;
                        $openList[$v['member_id']]['lastStr'] = $lastStr;
                        $openList[$v['member_id']]['keywords'][] = $number;
                    } else {
                        $openList[$v['member_id']]['member_id'] = $v['member_id'];
                        $openList[$v['member_id']]['amount'] = $v['amount'];
                        $openList[$v['member_id']]['profit'] = $profit;
                        $openList[$v['member_id']]['lastStr'] = $lastStr;
                        $openList[$v['member_id']]['openKeywords'] = [];
                        $openList[$v['member_id']]['keywords'] = [];
                        $openList[$v['member_id']]['keywords'][] = $number;
                        $openList[$v['member_id']]['win_amount'] = 0;
                        $openList[$v['member_id']]['is_send'] = true;
                    }
                }

                LhcOrderItem::where('id', $value['id'])->update($item);
            }

            if ($total_amount > 0) {
                LhcOrder::where("id", $v['id'])->update(['lottery_status' => '2', 'win_amount' => $total_amount]);
            } else {
                LhcOrder::where("id", $v['id'])->update(['lottery_status' => '1', 'win_amount' => 0]);
            }
        }
        $openList = array_merge($openList, $fakeOpenData['list']);

        self::lotteryNotice($openList, $issue_no, $keywordsList);
    }

    // 虚拟开奖
    public static function fakeLotteryDraw($issue_no, $awards, $rand_num = 30)
    {

        $fake_bet_list = Cache::get('fake_bet_' . $issue_no, []);
        $text = "";

        $keywordsList = [];

        $fakeOtherSum = 0;
        $openList = [];

        foreach ($fake_bet_list as $k => $v) {
            if (in_array($v['keywords'], ['大', '小', '单', '双'])) {
                $fakeOtherSum += $v['amount'];
            }

            if (isset($keywordsList[$v['keywords']])) {
                $keywordsList[$v['keywords']] += $v['amount'];
            } else {
                $keywordsList[$v['keywords']] = $v['amount'];
            }

            // $lastStr = self::getLastChar($v['first_name'], 1);
            $lastStr = self::hideMiddleDigits($v['member_id'], 4);
            if (in_array($v['keywords'], $awards)) {
                $amount = $v['amount'];

                $odds = $v['odds'];
                $profit = bcmul($amount, $odds, 2); // 保留两位小数
                if ($profit > 880000) {
                    $profit = 880000; // 单注最高奖金880000
                }
                $item['profit'] = $profit;
                // $v['amount'] = number_format($amount,2);

                if (isset($openList[$v['member_id']])) {
                    $openList[$v['member_id']]['member_id'] = $v['member_id'];
                    $openList[$v['member_id']]['amount'] += $v['amount'];
                    $openList[$v['member_id']]['profit'] += $profit;
                    $openList[$v['member_id']]['lastStr'] = $lastStr;
                    $openList[$v['member_id']]['openKeywords'][] = $v['keywords'] . "({$odds}" . lang("倍率") . ")";
                    $openList[$v['member_id']]['keywords'][] = $v['keywords'];
                    $openList[$v['member_id']]['win_amount'] += $v['amount'];

                } else {
                    $openList[$v['member_id']]['member_id'] = $v['member_id'];
                    $openList[$v['member_id']]['amount'] = $v['amount'];
                    $openList[$v['member_id']]['profit'] = $profit;
                    $openList[$v['member_id']]['lastStr'] = $lastStr;
                    $openList[$v['member_id']]['openKeywords'] = [];
                    $openList[$v['member_id']]['keywords'] = [];
                    $openList[$v['member_id']]['openKeywords'][] = $v['keywords'] . "({$odds}" . lang("倍率") . ")";
                    $openList[$v['member_id']]['keywords'][] = $v['keywords'];
                    $openList[$v['member_id']]['win_amount'] = $v['amount'];
                    $openList[$v['member_id']]['is_send'] = false;

                }
            } else {

                if (isset($openList[$v['member_id']])) {
                    $openList[$v['member_id']]['member_id'] = $v['member_id'];
                    $openList[$v['member_id']]['amount'] += $v['amount'];
                    $openList[$v['member_id']]['lastStr'] = $lastStr;
                    $openList[$v['member_id']]['keywords'][] = $v['keywords'];
                } else {
                    $openList[$v['member_id']]['member_id'] = $v['member_id'];
                    $openList[$v['member_id']]['amount'] = $v['amount'];
                    $openList[$v['member_id']]['profit'] = 0;
                    $openList[$v['member_id']]['lastStr'] = $lastStr;
                    $openList[$v['member_id']]['openKeywords'] = [];
                    $openList[$v['member_id']]['keywords'] = [];
                    $openList[$v['member_id']]['keywords'][] = $v['keywords'];
                    $openList[$v['member_id']]['win_amount'] = 0;
                    $openList[$v['member_id']]['is_send'] = false;
                }

            }

        }

        return ['sum' => $fakeOtherSum, 'list' => $openList, 'keywordsList' => $keywordsList];
    }

    // 开奖通知
    public static function lotteryNotice($openList, $issue_no, $keywordsList = [])
    {
        $betNoticeNum = Config::where('field', 'bet_notice_num')->first()->val;
        $betNoticeNum = explode(',', $betNoticeNum);
        $betNoticeMini = max(1, (int)($betNoticeNum[0] ?? 26));
        $betNoticeMax = max($betNoticeMini, (int)($betNoticeNum[1] ?? 38));
        $noticeNum = rand($betNoticeMini, $betNoticeMax);
        // shuffle($openList);
        // Log::error('lotteryNotice openList', $openList);

        $lang = App::getLocale();
        $group_language = Config::where('field', 'group_language')->first()->val;
        App::setLocale($group_language);
        $text = "{$issue_no} " . lang("期开奖结果");
        $text .= "\n-----" . lang("本期开奖账单") . "----- \n";
        App::setLocale($lang);
        $noticeIndex = 0;
        $noticeRows = 0;
        foreach ($openList as $v) {
            $noticeIndex++;


            $amount = number_format($v['amount'], 2);
            $v['win_amount'] = number_format($v['win_amount'], 2);
            $profit = number_format($v['profit'], 2);
            $yl = bcsub($v['profit'], $v['amount'], 2); // 盈利
            if (empty($v['openKeywords'])) {
                $openKeyword = '-';

            } else {
                $openKeyword = implode(',', $v['openKeywords']);
            }

            if ($noticeIndex <= $noticeNum) {
                $noticeRows++;
                $lang = App::getLocale();
                $group_language = Config::where('field', 'group_language')->first()->val;
                App::setLocale($group_language);
                $text .= lang("用户ID") . "：{$v['lastStr']} \n";
                $text .= lang("下注类型") . "：[" . implode(',', $v['keywords']) . "] \n";
                $text .= lang('中奖类型') . "：[" . $openKeyword . "] \n";
                $text .= lang('投注金额') . "：{$amount} \n";
                $text .= lang('中奖金额') . "：{$v['win_amount']} \n";
                $text .= lang('派彩金额') . "：{$profit} \n";
                $text .= lang("盈亏金额") . "：{$yl} \n";
                $text .= "-------------------------------- \n";
                App::setLocale($lang);
            }

            //根据环境变量配置是否发送电报
            if ($v['is_send'] && env('SEND_TELEGRAM')) {
                $language = User::where('member_id', $v['member_id'])->first()->language;
                $wallet = WalletService::findOne(['member_id' => $v['member_id']]);
                App::setLocale($language);
                $text2 = lang("{issue_no}期开奖结果");
                $text2 = str_replace("{issue_no}", $issue_no, $text2);
                $text2 .= "\n";
                $text2 .= lang('下注类型') . "：[" . implode(',', $v['keywords']) . "] \n";
                $text2 .= lang('中奖类型') . "：[" . $openKeyword . "] \n";
                $text2 .= lang('投注金额') . "：{$amount} \n";
                $text2 .= lang('中奖金额') . "：{$v['win_amount']} \n";
                $text2 .= lang('派彩金额') . "：{$profit} \n";
                $text2 .= lang("盈亏金额") . "：{$yl} \n";
                $balance = floatval($wallet->available_balance);
                $text2 .= "----------------\n";
                $text2 .= "当前余额：{$balance} \n";
                $keyboard = [];
                $keyboard[] = [
                    ['text' => lang("开奖历史"), 'callback_data' => "showLotteryHistory@@" . $issue_no]
                ];
                // self::sendMessage($v['member_id'],$text2,$keyboard);
                SendTelegramMessageJob::dispatch($v['member_id'], $text2, $keyboard)->afterCommit();
            }

        }

        $inlineButton = self::getOperateButton();
        
        //根据环境变量配置是否发送电报
        if (env('SEND_TELEGRAM')) {
            // 群通知
            $pc28Switch = Config::where('field', 'pc28_switch')->first()->val;
            if (($pc28Switch == 0 && is_numeric($issue_no)) || $pc28Switch == 1 && !is_numeric($issue_no)) {
                Log::channel('issue')->info('结算列表群通知入队', [
                    'issue_no' => $issue_no,
                    'pc28_switch' => $pc28Switch,
                    'text_length' => strlen($text),
                    'open_list_count' => count($openList),
                    'notice_num' => $noticeNum,
                    'notice_rows' => $noticeRows,
                ]);
                SendTelegramGroupMessageJob::dispatch($text, $inlineButton, '', false, '--------------------------------', [
                    'message_type' => 'settlement_list',
                    'issue_no' => $issue_no,
                    'open_list_count' => count($openList),
                    'notice_rows' => $noticeRows,
                ])->afterCommit();
            } else {
                Log::channel('issue')->info('结算列表群通知跳过', [
                    'issue_no' => $issue_no,
                    'pc28_switch' => $pc28Switch,
                    'reason' => 'pc28_switch_not_match_issue_type',
                ]);
            }
        } else {
            Log::channel('issue')->info('结算列表群通知跳过', [
                'issue_no' => $issue_no,
                'reason' => 'send_telegram_disabled',
            ]);
        }


    }

    /**
     * @description: 统计投注情况通知
     * @param {*} $issue_no
     * @return {*}
     */
    public static function statNotice($issue_no)
    {
        $keywordsList = [];
        // 虚拟投注情况
        $fake_bet_list = Cache::get('fake_bet_' . $issue_no, []);
        foreach ($fake_bet_list as $k => $v) {
            if (isset($keywordsList[$v['keywords']])) {
                $keywordsList[$v['keywords']] += $v['amount'];
            } else {
                $keywordsList[$v['keywords']] = $v['amount'];
            }
        }

        // 真实投注
        $list = self::findAll(['issue_no' => $issue_no]);
        foreach ($list->toArray() as $k => $v) {
            if (isset($keywordsList[$v['keywords']])) {
                $keywordsList[$v['keywords']] += $v['amount'];
            } else {
                $keywordsList[$v['keywords']] = $v['amount'];
            }
        }
        $lang = App::getLocale();
        $group_language = Config::where('field', 'group_language')->first()->val;
        App::setLocale($group_language);
        $text3 = "📝 {$issue_no}" . lang('期投注统计') . " \n";
        $text3 .= lang("玩法") . "    " . lang("总投") . " \n";
        App::setLocale($lang);
        if ($keywordsList) {
            uksort($keywordsList, 'custom_sort');
//            ksort($keywordsList);
            foreach ($keywordsList as $k => $v) {
                $text3 .= "{$k}    {$v} \n";
            }
        }

        $inlineButton = self::getOperateButton();

//        投注统计的消息不发了
//        SendTelegramGroupMessageJob::dispatch($text3, $inlineButton, '');
    }


    public static function todayExchangeRate($chatId)
    {
        $exchangeRate = Config::where('field', 'exchange_rate_rmb')->first()->val;
        $text = lang("今日汇率") . "：1USDT = {$exchangeRate} RMB \n";
        // $botMsg = [
        //     'chat_id' => "@{$chatId}",
        //     'text' => $text
        // ];
        self::sendMessage($chatId, $text);
        // return $botMsg;
    }


}
