彭俊 6 жил өмнө
parent
commit
ef44363815

+ 223 - 188
app/Lib/Settlement/SettlementOrder.php

@@ -20,18 +20,27 @@ use App\Models\SettlementMiddleDetail as SettlementMiddleDetailModel;
  */
 class SettlementOrder extends SettlementBase
 {
-    private $orderId = '';   //订单ID
+
     private $orderType = 1; //订单类型  1单式  2串式;
     private $BuyDatasMainModel = [];  //订单豪华版  单式一条   串式可能多条
     private $BuyDatas = [];  //订单豪华版  单式一条   串式可能多条
     private $match_id = 0;
     private $game_code = '';
     private $SN = 0;    //结算批次号
-    private $hissettlementDetail = [];
     private $set_type = 0;
     private $change_status = 1;
 
-    private $SettlementBaseObj = '' ;
+    private $SettlementBaseObj = '';
+
+
+    private $sqlArray = [];   //最终生成的执行sql
+    private $Money_buy_Orders_Array = [];    //订单主表映射
+    private $Money_buy_Orders_batch_Array = [];    //订单按批次号表映射
+    private $Money_buy_Match_array = [];      //单式订单表的映射
+    private $account_map_array = [];            //用户账号映射
+    private $account_indentity_map_array = [];  //用户账号indenty映射
+    private $settlement_middle_detail_array = [];  //已结算过的数据映射,按订单号及[单串式]
+    private $money_prize_map = [];                  //中奖记录数据
 
 
     //返回数据
@@ -71,13 +80,14 @@ class SettlementOrder extends SettlementBase
         $this->set_type = $settype;
 
         if (empty($order_ids)) {
-            $needs_matchs = DB::table('money_buy_match')->where(['game_code' => $game_code, 'match_id' => $match_id])->get();
-            if (count($needs_matchs) <= 0) {
+            $needs_matchs = DB::table('money_buy_match')->where(['game_code' => $game_code, 'match_id' => $match_id])->count();
+            if ($needs_matchs <= 0) {
                 $this->cgStatus($game_code, $match_id, $this->change_status);
                 return self::makeData();
             } else {
                 return self::makeData(5, '订单号不能为空');
             }
+            unset($needs_matchs);
         }
 
 
@@ -90,17 +100,16 @@ class SettlementOrder extends SettlementBase
         $this->match_id = $match_id;
         $this->game_code = $game_code;
 
-
-
+        if (!$this->DataPre($order_ids, $bettype, $settype, $game_code, $match_id, $change_status)) {
+            return self::makeData(-1, 'false', '没找到订单信息');
+        }
 
         try {
             DB::beginTransaction();
 
-            $this->UndoSettlement($this->game_code, $this->match_id, $order_ids, $bettype);
-
+            $this->UndoSettlement();
             foreach ($order_ids as $order_id) {
-                $this->BuyDatasMainModel = $this->orderTypeGet($order_id, $bettype);
-
+                $this->BuyDatasMainModel = $this->Money_buy_Orders_Array[$order_id];
                 if ($this->BuyDatasMainModel->settle_status == 2 && $settype == 1) {
                     continue;
                 }
@@ -111,14 +120,14 @@ class SettlementOrder extends SettlementBase
                     $this->ChuanOrder($order_id);
                 }
             }
-
             $this->cgStatus($game_code, $match_id, $this->change_status);
 
+            $this->RunSql();
 
             DB::commit();
         } catch (\Exception $e) {
             DB::rollBack();
-            return self::makeData(-2, $e->getMessage());
+            return self::makeData(-2, $e->getMessage() . ' Line:' . $e->getLine());
         }
         return self::makeData();
 
@@ -145,27 +154,27 @@ class SettlementOrder extends SettlementBase
      * 单式注单结算
      * @param mixed $order_id 注单ID
      */
-    public function singOrder($order_id)
+    private function singOrder($order_id)
     {
         // 查询订单下所有的单式注单
         $simplexData = $this->BuyDatasMainModel;
 
-        $matchData = DB:: table('money_buy_match')->where(['bet_type' => 1, 'batch_id' => $simplexData->batch_id, 'match_id' => $simplexData->match_id])->get();
+        $matchData = $this->Money_buy_Match_array[$simplexData->batch_id];
         if (count($matchData) <= 0) {
             throw new  \Exception("没有数据的错误!");
         }
+
         foreach ($matchData as $val) {
             if (!in_array($val->result, [-1, 1, 2, 3, 4])) {
                 throw  new  \Exception('match 比赛结果异常或还没有输赢结果->' . $val->id);
             }
         }
 
-
         // 计算总回款
-        if (empty($this->SettlementBaseObj)){
+        if (empty($this->SettlementBaseObj)) {
             $settlementBase = new \App\Lib\Settlement\SettlementBase();
-        }else{
-            $settlementBase  = $this->SettlementBaseObj;
+        } else {
+            $settlementBase = $this->SettlementBaseObj;
         }
         $returnMoney = 0;
         $oddsResult = [];
@@ -182,9 +191,8 @@ class SettlementOrder extends SettlementBase
         // 判断盈亏  1 赢  2 输  3 平
         $game_status = $returnMoney > $simplexData->money ? 1 : ($returnMoney == $simplexData->money ? 3 : 2);
         // 修改投注表状态及盈亏
-        DB:: table('money_buy_simplex')
-            ->where(['order_id' => $order_id])
-            ->update(['settle_status' => 2, 'game_status' => $game_status, 'gain_money' => $returnMoney, 'settlementTime' => date('Y-m-d H:i:s')]);
+        $this->sqlArray[] = "update money_buy_simplex set settle_status=2, game_status=$game_status,gain_money=$returnMoney  where order_id='$order_id' ";
+
         $this->WriteOrAddSettlement($this->game_code, $this->match_id, $this->orderType, $order_id, $this->BuyDatasMainModel->account_identity, $returnMoney);
         $this->insertData(
             $order_id,
@@ -199,100 +207,15 @@ class SettlementOrder extends SettlementBase
 
     }
 
-    /**
-     * 结算数据填入
-     * @param mixed $order_id 注单ID
-     * @param mixed $returnMoney 返现金额
-     * @param mixed $account_identity 用户ID
-     * @param mixed $type 1单式 2串式
-     * @param mixed $game_name 游戏名(zq,lq)
-     * @param mixed $buy_identity 游戏投注id
-     * @param mixed $money 投注金额
-     * @param mixed $match_id 赛场ID
-     */
-    public function insertData($order_id, $returnMoney, $account_identity, $type, $game_name, $buy_identity, $money, $match_id = 0)
-    {
-        // 查询用户当前剩余金额
-        $accountInfo = DB:: table('account_detailed')
-            ->join('account', 'account_detailed.account_identity', 'account.identity')
-            ->select(['available_cash', 'cash', 'account', 'account_identity'])
-            ->where(['account_identity' => $account_identity])
-            ->first();
-        // 计算用户回账后余额
-        $available_cash = $accountInfo->available_cash + $returnMoney;
-        $cash = $accountInfo->cash + $returnMoney;
-        // 添加流水记录
-        $info_identity = UUID();
-        $money_time = date('Y-m-d H:i:s', time());
-        $trade_desc = $type == 1 ? '单式投注订单回款' : '串式投注订单回款';
-        $reason = $type == 1 ? '单式投注订单回款' : '串式投注订单回款';
-        DB:: table('money_details')->insert([
-            'info_identity' => $info_identity,
-            'trade_id' => $order_id,
-            'account_name' => $accountInfo->account,
-            'account_identity' => $accountInfo->account_identity,
-            'money' => $returnMoney,
-            'money_time' => $money_time,
-            'money_type' => 1,
-            'money_cash' => $available_cash,
-            'trade_type' => 4,
-            'trade_desc' => $trade_desc,
-            'reason' => $reason,
-            'sysetem_user' => '系统',
-            'status' => '1',
-        ]);
-
-        // 修改用余额
-        DB:: table('account_detailed')
-            ->where(['account_identity' => $account_identity])
-            ->update(['available_cash' => $available_cash, 'cash' => $cash]);
-        // 新增用户中奖信息
-        $content = $type == 1 ? '您的单式投注订单' . $order_id . '于' . $money_time . '成功回款' . $returnMoney . '该次投注流程结束,如有疑问请联系客服'
-            : '您的串式投注订单' . $order_id . '于' . $money_time . '成功回款' . $returnMoney . '该次投注流程结束,如有疑问请联系客服';
-        DB:: table('account_news')->insert([
-            'identity' => $info_identity,
-            'account_identity' => $account_identity,
-            'title' => '投注订单回款通知',
-            'content' => $content,
-            'details' => $content,
-            'write_time' => $money_time,
-            'read_status' => -1,
-            'type' => 1,
-        ]);
-        // 新增中奖记录表
-        $old = DB:: table('money_prize')->where(['buy_identity' => $buy_identity])->orWhere(['order_id' => $order_id])->first();
-        if (count($old)) {
-            DB:: table('money_prize')->where(['buy_identity' => $buy_identity])->orWhere(['order_id' => $order_id])->update(['money' => $money, 'prize_money' => $returnMoney, 'get_money' => $returnMoney - $money]);
-        } else {
-            DB:: table('money_prize')->insert([
-                'info_identity' => $info_identity,
-                'order_id' => $order_id,
-                'account_identity' => $account_identity,
-                'account_name' => $accountInfo->account,
-                'game_name' => $game_name,
-                'buy_identity' => $buy_identity,
-                'money' => $money,
-                'money_time' => $money_time,
-                'status' => 1,
-                'prize_money' => $returnMoney,
-                'get_money' => $returnMoney - $money,
-            ]);
-        }
-
-    }
-
-
-    //单个串式订单的处理
-    public function ChuanOrder($order_id)
+    private function ChuanOrder($order_id)
     {
 
         $batch_id = $this->BuyDatasMainModel->batch_id;
-        $matchModels = DB::table('money_buy_match')->where(['batch_id' => $batch_id, 'bet_type' => 2])->get();
-        if ($matchModels->count() <= 0) {
+        $matchModels = $this->Money_buy_Match_array[$batch_id];
+        if (count($matchModels) <= 0) {
             throw  new  \Exception('match 数据异常');
         }
 
-
         $newTime = date('Y-m-d H:i:s');
         if ($this->BuyDatasMainModel->status == 1) {
             $in_array = [];
@@ -302,10 +225,9 @@ class SettlementOrder extends SettlementBase
                 }
 
                 if ($val->result == -1) {
-                    DB::table('money_buy_str')->where('batch_id', $batch_id)->update(['wait_match_num' => 0, 'prize_note' => 0, 'game_status' => 3, 'settle_status' => 2, 'gain_money' => 0, 'settlementTime' => date('Y-m-d H:i:s')]);
+                    $this->sqlArray[] = "update  money_buy_str set wait_match_num=0, prize_note=0, game_status=3, settle_status=2, gain_money=0,settlementTime='" . date('Y-m-d H:i:s') . "' where batch_id='$batch_id' ";
                     return true;
                 }
-
                 $in_array[] = ['odds' => $val->odds, 'winOrLose' => $val->result];
             }
 
@@ -317,131 +239,244 @@ class SettlementOrder extends SettlementBase
             $money = $this->BuyDatasMainModel->money;
         }
 
-        $ret = DB::update('update money_buy_str  set settle_status=2 , game_status=1 , "settlementTime"=? , gain_money=?  where order_id = ?', [$newTime, $money, $order_id]);
-        if (!($ret || $ret === 0)) {
-            throw  new \Exception('更新数据出错3!');
-        }
+        $this->sqlArray[] = " update money_buy_str  set settle_status=2 , game_status=1 , settlementTime='$newTime' , gain_money=$money  where order_id = '$order_id'";
 
         $this->WriteOrAddSettlement($this->game_code, $this->match_id, $this->orderType, $order_id, $this->BuyDatasMainModel->account_identity, $money);
         $this->insertData($order_id, $money, $this->BuyDatasMainModel->account_identity, 2, $val->game_code, $this->BuyDatasMainModel->info_identity, $this->BuyDatasMainModel->money, $this->match_id);
 
         return true;
-
     }
 
-    //校验是否同一场比赛的订单处理
-    private function Match_check($idsArray, $betType)
+    //重结算时,要先扣掉先前发的钱
+    private function UndoSettlement()
     {
-        array_walk($idsArray, function (&$item, $key) {
-            $item = "'" . $item . "'";
-        });
-
-        $idString = implode(",", $idsArray);
-
-        $table = "money_buy_simplex";
-        $sql = "select game_code,match_id   from  $table  where  status=1 and  order_id in ($idString)  group by  game_code,match_id ";
+        if (empty($this->settlement_middle_detail_array)) {
+            return true;
+        }
 
-        $ret = DB::select($sql);
+        $nowArray = $this->settlement_middle_detail_array[$this->orderType];
+        foreach ($nowArray as $order => $val) {
+            $money = abs(floatval($val->money));
+            $acc = $val->account_identity;
+            $sql = "update account_detailed  set  cash=cash-$money where identity='$acc' ";
+            $this->sqlArray[] = $sql;
+            $ids[] = $order;
+        }
 
-        return $ret;
+        $ids = array_map(function($i){return "'.$i.'";},$ids);
+        $ids_array = implode(",", $ids);
+        $sql = "update settlement_middle_detail  set  money=0 where order_id in($ids_array) and bet_type=$this->orderType  ";
+        $this->sqlArray[] = $sql;
 
+        return true;
     }
 
-    //取消某个赛事订单的结算数据
-    public function UndoSettlement($game_code, $match_id, $order_ids, $bettype)
+
+    //数据预批量获取
+    private function DataPre($order_ids, $bettype = 2, $settype = 1, $game_code = 0, $match_id = 0, $change_status = 1)
     {
 
-        if ($this->set_type == 1) {
-            return;
+        if ($bettype == 1) {
+            $moneytable = 'money_buy_simplex';
+            $ret = DB::table('money_buy_simplex')->where(['game_code' => $game_code, 'match_id' => $match_id])->whereIn('order_id', $order_ids)->get();
+        } else {
+            $moneytable = 'money_buy_str';
+            $ret = DB::table('money_buy_str')->where(['game_code' => $game_code])->whereIn('order_id', $order_ids)->get();
+        }
+        if (empty($ret)) {
+            return false;
         }
 
-        $modelSMD = new SettlementMiddleDetailModel();
-        $hisData = $modelSMD->getSettledatas($game_code, $match_id, $bettype, $order_ids);
-
-        if (count($hisData) <= 0) {
-            goto DONEXT;
+        $tmpbatchid = [];
+        $userindentys = [];
+        $orderarr = [];
+        foreach ($ret as $val) {
+            $this->Money_buy_Orders_Array[$val->order_id] = $val;
+            $orderarr[] = $val->order_id;
+            $this->Money_buy_Orders_batch_Array[$val->batch_id][] = $val;
+            $tmpbatchid[] = $val->batch_id;
+            $userindentys[] = $val->account_identity;
         }
 
-        $this->hissettlementDetail = $hisData;
-        $orderList = [];
+        $tmpbatchid = array_unique($tmpbatchid);
+        $userindentys = array_unique($userindentys);
 
         if ($bettype == 1) {
-            $order_list = DB::table('money_buy_simplex')->where(['game_code' => $game_code, 'match_id' => $match_id, 'status' => 1])->whereIn('order_id', $order_ids)->get();
-
-            foreach ($order_list as $val) {
-                $orderList[$val->order_id] = $val;
-            }
-
+            $ret = DB::table('money_buy_match')->where(['game_code' => $game_code, 'match_id' => $match_id])->whereIn('batch_id', $tmpbatchid)->get();
         } else {
-            $order_list = DB::table('money_buy_str')->where(['status' => 1])->whereIn('order_id', $order_ids)->get();
+            $ret = DB::table('money_buy_match')->where(['game_code' => $game_code])->whereIn('batch_id', $tmpbatchid)->get();
+        }
+        foreach ($ret as $val) {
+            $this->Money_buy_Match_array[$val->batch_id][] = $val;
+        }
 
-            foreach ($order_list as $val) {
-                $orderList[$val->order_id] = $val;
-            }
+        $ret = DB::table('account_detailed')->whereIn('account_identity', $userindentys)->get();
+        foreach ($ret as $val) {
+            $this->account_indentity_map_array[$val->account_identity] = $val;
         }
 
+        $ret = DB::table('account')->whereIn('identity', $userindentys)->get();
+        foreach ($ret as $val) {
+            $this->account_map_array[$val->identity] = $val;
+        }
 
-        foreach ($hisData as $oid => $val) {
-            if (!isset($orderList[$val->order_id])) {
-                throw  new  \Exception("订单数据缺失异常!($game_code,$match_id,$oid)");
+        if ($settype == 2) {
+            $ret = DB::table('settlement_middle_detail')->where(['game_code' => $game_code, 'match_id' => $match_id])->whereIn('order_id', $order_ids)->get();
+            if ($ret) {
+                foreach ($ret as $val) {
+                    $this->settlement_middle_detail_array[$val->bet_type][$val->order_id] = $val;
+                }
             }
-            $money = $val->money * (-1);
-            if (intval($money) * 100 == 0) {
-                continue;
+
+            $maparr = array_map(function ($i) {
+                return "'" . $i . "'";
+            }, $orderarr);
+            $order_str = implode(",", $maparr);
+            if ($change_status) {
+                if ($bettype == 1) {
+                    $this->sqlArray[] = "update $moneytable set  settle_status=1, gain_money=0, game_status=0 where  game_code='$game_code' and match_id=$match_id and  status=1 and order_id in ($order_str)  ";
+                } else {
+                    $this->sqlArray[] = "update $moneytable set  settle_status=1, gain_money=0  where order_id in ($order_str)  ";
+                }
             }
-            $this->insertData($oid, $money, $val->account_identity, $bettype, $game_code, $orderList[$oid]->info_identity, $money, $this->match_id);
-        }
-        DONEXT:
-        $table = $bettype == 1 ? 'money_buy_simplex' : 'money_buy_str';
-        if ($bettype == 1) {
-            $ret1 = DB::table($table)->where(['game_code' => $game_code, 'match_id' => $match_id, 'status' => 1])->whereIn('order_id', $order_ids)->update(['settle_status' => 1, 'gain_money' => 0, 'game_status' => 0]);
-        } else {
-            $ret1 = DB::table($table)->where(['status' => 1])->whereIn('order_id', $order_ids)->update(['settle_status' => 1, 'gain_money' => 0]);
         }
 
-        DB::table('settlement_middle_detail')->where(['game_code' => $game_code, 'match_id' => $match_id, 'bet_type' => $bettype])->whereIn('order_id', $order_ids)->update(['money' => 0]);
-
-        if ($ret1) {
-            return true;
-        } else {
-            throw new \Exception("取消结算更新数据状态出错操作中止($ret1)!");
+        $ret = DB::table('money_prize')->whereIn('order_id', $order_ids)->get();
+        if ($ret) {
+            foreach ($ret as $val) {
+                $this->money_prize_map[$val->order_id] = $val;
+            }
         }
 
+        return true;
     }
 
+
     private function WriteOrAddSettlement($game_code, $match_id, $bet_type, $order_id, $account_ident, $money)
     {
         if (intval($money * 100) == 0) {
             return;
         }
 
-        if (isset($this->hissettlementDetail[$order_id])) {
-            $ret = DB::table('settlement_middle_detail')
-                ->where(['game_code' => $game_code, 'bet_type' => $bet_type, 'order_id' => $order_id])
-                ->update(['money' => $money]);
+        if ($this->set_type == 2 && isset($this->settlement_middle_detail_array[$bet_type][$order_id])) {
+            $this->sqlArray[] = "update  settlement_middle_detail  set  money=$money  where game_code='$game_code' and bet_type=$bet_type and order_id='$order_id' ";
+        } else {
+            $this->sqlArray[] = "insert into settlement_middle_detail(game_code,match_id,account_identity,bet_type,order_id,money) values('$game_code','$match_id','$account_ident',$bet_type,'$order_id',$money)";
+        }
+        return true;
+    }
+
+    /**
+     * 结算数据填入
+     * @param mixed $order_id 注单ID
+     * @param mixed $returnMoney 返现金额
+     * @param mixed $account_identity 用户ID
+     * @param mixed $type 1单式 2串式
+     * @param mixed $game_name 游戏名(zq,lq)
+     * @param mixed $buy_identity 游戏投注id
+     * @param mixed $money 投注金额
+     * @param mixed $match_id 赛场ID
+     */
+    private function insertData($order_id, $returnMoney, $account_identity, $type, $game_name, $buy_identity, $money, $match_id = 0)
+    {
+        // 查询用户当前剩余金额
+        $accountInfo = $this->account_indentity_map_array[$account_identity];
+        // 计算用户回账后余额
+        $this->account_indentity_map_array[$account_identity]->available_cash = $available_cash = $accountInfo->available_cash + $returnMoney;
+        $this->account_indentity_map_array[$account_identity]->cash = $cash = $accountInfo->cash + $returnMoney;
+        // 添加流水记录
+        $info_identity = UUID();
+        $money_time = date('Y-m-d H:i:s', time());
+        $trade_desc = $type == 1 ? '单式投注订单回款' : '串式投注订单回款';
+        $reason = $type == 1 ? '单式投注订单回款' : '串式投注订单回款';
+
+        $accountInfobase = $this->account_map_array[$account_identity];
+        $sql = "insert into money_details(info_identity,trade_id,account_name,account_identity,money,money_time,money_type,money_cash,trade_type,trade_desc,reason,sysetem_user,status)  values(";
+        $sql .= "'$info_identity','$order_id','$accountInfobase->account','$accountInfobase->identity',$returnMoney,'$money_time',1,$available_cash,4,'$trade_desc','$reason','系统',1)";
+        $this->sqlArray[] = $sql;
+
+        // 修改用余额
+        $this->sqlArray[] = "update account_detailed  set available_cash=$available_cash,cash=$cash where  account_identity='$account_identity' ";
+
+        // 新增用户中奖信息
+        $content = $type == 1 ? '您的单式投注订单' . $order_id . '于' . $money_time . '成功回款' . $returnMoney . '该次投注流程结束,如有疑问请联系客服'
+            : '您的串式投注订单' . $order_id . '于' . $money_time . '成功回款' . $returnMoney . '该次投注流程结束,如有疑问请联系客服';
+        $sql = "insert into account_news(identity,account_identity,title,content,details,write_time,read_status,type) values ";
+        $sql .= "('$info_identity','$account_identity','投注订单回款通知','$content','$content','$money_time',-1,1)";
+        $this->sqlArray[] = $sql;
+
+
+        // 新增中奖记录表
+        $old = $this->money_prize_map[$order_id];
+        $table = 'money_prize';
+        if (isset($this->money_prize_map[$order_id])) {
+            $this->sqlArray[] = "update $table  set money=$money,prize_money=$returnMoney, get_money= $returnMoney - $money where  order_id='$order_id'";
         } else {
-            $ret = DB::table('settlement_middle_detail')
-                ->insertGetId([
-                    'game_code' => $game_code,
-                    'match_id' => $match_id,
-                    'account_identity' => $account_ident,
-                    'bet_type' => $bet_type,
-                    'order_id' => $order_id,
-                    'money' => $money
-                ]);
-        }
-        if (!$ret) {
-            throw  new  \Exception("更新数据异常(bt:$bet_type  od:$order_id  ret:$ret)");
+            $sql = "insert into  $table (info_identity,order_id,account_identity,account_name,game_name,buy_identity,money,money_time,status,prize_money,get_money) values ";
+            $sql .= "('$info_identity','$order_id','$account_identity','$accountInfo->account','$game_name','$buy_identity',$money,'$money_time',1,$returnMoney,$returnMoney - $money)";
+            $this->sqlArray[] = $sql;
         }
+
         return true;
     }
 
+
+    //改状态
     private function cgStatus($game_code, $match_id, $change_status)
     {
+        $table1 = "st_" . $game_code . "_result";
+        $table2 = "st_" . $game_code . "_competition";
+
         if ($change_status) {
-            DB::table("st_" . $game_code . "_result")->where(['match_id' => $match_id])->update(['status' => 3]);
-            DB::table("st_" . $game_code . "_competition")->where(['match_id' => $match_id])->update(['status' => 3]);
+            $this->sqlArray[] = "update $table1 set  status=3  where   match_id=$match_id ";
+            $this->sqlArray[] = "update $table2 set  status=3  where   match_id=$match_id ";
         }
     }
 
+    //校验是否同一场比赛的订单处理
+    private function Match_check($idsArray, $betType)
+    {
+        array_walk($idsArray, function (&$item, $key) {
+            $item = "'" . $item . "'";
+        });
+
+        $idString = implode(",", $idsArray);
+
+        $table = "money_buy_simplex";
+        $sql = "select game_code,match_id   from  $table  where  status=1 and  order_id in ($idString)  group by  game_code,match_id ";
+
+        $ret = DB::select($sql);
+
+        return $ret;
+
+    }
+
+    private function RunSql()
+    {
+        $len = count($this->sqlArray);
+        $step = 2000;
+        $j = 1;
+        $pdo = DB::getPdo();
+        $tmp = [];
+        for ($i = 0; $i < $len; $i++) {
+            if ($j > $step || $i == ($len - 1)) {
+                if (empty($tmp)) {
+                    return;
+                }
+                $sqlstr = implode(";", $tmp);
+                $ret = $pdo->exec($sqlstr);
+                if (!$ret) {
+                    throw new  \Exception("运行sql发生错误!");
+                }
+                $tmp = [];
+                $j = 1;
+            } else {
+                $tmp[] = $this->sqlArray[$i];
+                $j++;
+            }
+        }
+        return true;
+    }
+
+
 }

+ 0 - 541
app/Lib/Settlement/SettlementSql.php

@@ -1,541 +0,0 @@
-<?php
-/**
- * Created by PhpStorm.
- * User: Administrator
- * Date: 2019/4/25
- * Time: 14:10
- */
-
-namespace App\Lib\Settlement;
-set_time_limit(600);
-ini_set('memory_limit', '256M');
-
-use Illuminate\Support\Facades\DB;
-use App\Models\Comendnotice  as ComendnoticeModel;
-
-use  App\Lib\Settlement\Adapter\ZqRule;
-use  App\Lib\Settlement\Adapter\LqRule;
-use  App\Lib\Settlement\Adapter\WqRule;
-use  App\Lib\Settlement\Adapter\BqRule ;
-
-
-class SettlementSql
-{
-
-    //用户的期末基本资料表 [uid]['account'=>$obj,'detail'=>$obj];
-     public  $AccountArrays = []  ;
-
-     //buy_match 里batch_id 相同的数据
-     public  $MatchBatchIdArrays = [] ;
-
-     //buy_str 批次号相同的记录
-    public  $BuyStrBatchIdArrays = [] ;
-
-    //所有比赛场次号相同的记录
-    public  $AllMatchIdArrays = [];
-
-    //比赛结束消息通知模型
-    public  $ComendNoticModel = null  ;
-
-    //返回的sql数组
-    private  $sqlArray = [] ;
-
-    public $gameType = '' ;  //类型
-    public $match_id = 0 ;  //比赛ID
-    public $resultId = 0 ; //比赛最终结果ID
-    public $resultModel = null ; //比赛最终结果对像MODEL
-    public $resultRecords = [] ; //比赛中间结果对像数组;
-
-    //类型映射
-    public $gameAllMap = [
-        'zq'=>'ZqRule',
-        'lq'=>'LqRule',
-        'wq'=>'WqRule',
-        'bq'=>'BqRule',
-    ];
-    private  $AdapterObj = null ;
-
-    private   $RefClass = null  ;
-
-
-    public function   GetSQL(){
-        return $this->makeData(1,'success',$this->sqlArray);
-    }
-
-
-
-    //按赛事批量结算
-    public function   doRun(){
-
-
-        try {
-            DB::beginTransaction ();
-
-            $ComendNoticModel = $this->getComendNoticeModel();
-            if (!$ComendNoticModel) {
-                DB::commit ();
-                return  $this->makeData(1,'没有要处理的数据,直接退出');
-            }
-            $this->writeStatusBegin($ComendNoticModel);
-
-            $allmatchs = DB::table('money_buy_match')->where(['game_code'=>$ComendNoticModel->game_code,'match_id'=>$ComendNoticModel->match_id,'result'=>0])->get();
-             if (empty($allmatchs)) {
-                $this->writeStatusEndOk($ComendNoticModel);
-                DB::commit();
-                return  $this->makeData(1,'本赛事无订单数据,退出');
-            }
-
-
-            $this->gameType = $ComendNoticModel->game_code ;
-            $this->match_id =  $ComendNoticModel->match_id ;
-
-            $this->setAdapterObj($ComendNoticModel->game_code);
-            $this->RefClass = new  \ReflectionClass(  $this->AdapterObj ) ;
-            $this->getCompResult($ComendNoticModel->game_code,$ComendNoticModel->match_id);
-
-
-            $this->Settlement_simplex($this->gameType,$this->match_id);
-            $this->Settlement_str($this->gameType,$this->match_id);
-
-
-            $this->writeStatusEndOk($ComendNoticModel);
-            DB::commit();
-            return  $this->makeData(1,'success-all');
-
-        }catch (\Exception $e){
-            DB::rollBack();
-            return $this->makeData(0,'false',['msg'=>$e->getMessage(),'code'=>$e->getCode()]) ;
-
-        }
-    }
-
-    //单式订单结算处理
-    private  function   Settlement_simplex($game_type,$match_id){
-        $buyModels = DB::table('money_buy_simplex')->where(['match_id'=>$match_id,'game_status'=>0])->get();
-        if (empty($buyModels)){ return true; }
-        $buymatchModles = DB::table('money_buy_match')->where(['match_id'=>$match_id,'bet_type'=>1,'result'=>0])->orderby('batch_id','asc')->get();
-        if (empty($buymatchModles)) { return true ; }
-
-        $buyKeyModel =  $buymatchKeyModles = [] ;
-        foreach ($buyModels as $val){
-            $batch_id = $val->batch_id;
-            $buyKeyModel[$batch_id] = $val;
-        }
-        foreach ($buymatchModles as $val){
-            $batch_id = $val->batch_id;
-            $buymatchKeyModles[$batch_id][] = $val;
-        }
-
-        foreach ($buyKeyModel as $batch_id=>$val){
-            $money = 0 ;
-            $allgame_status = 0 ;
-            foreach ($buymatchKeyModles as $sub_batch_id=>$fsval){
-
-                    foreach ($fsval as $sval) {
-                        $winorfalse = $this->winOrfalseInfo($sval);
-                        if (!in_array($winorfalse, [-1, 1, 2, 3, 4])) {
-                            throw  new  \Exception('胜负规则结果数据错!', 4005);
-                        }
-                        $this->makesql_up_buymatch_winorfalse($sval->id, $winorfalse, date("Y-m-d H:i:s"));
-
-                        if ($winorfalse != -1) {
-                            $peilvretarr = $this->winOddsCalculation([['odds' => $sval->odds, 'winOrLose' => $winorfalse]]);
-                            $money += $peilvretarr['returnMoney'] * $sval->bet_money;
-                            $allgame_status++;
-                        }
-                    }
-            }
-
-            $allgame_status = ($allgame_status>0 ) ?  1 : 2 ;
-
-            $sql = " update  money_buy_simplex   set   game_status=$allgame_status,wait_match_num=0,gain_money=$money where   match_id=$this->match_id and  batch_id='$batch_id'   ";
-            $this->sqlArray[] = $sql ;
-
-
-
-            if ($money >0){
-                $this->sql_accountdetail_money($val->account_identity,$money);
-                $this->sql_moneydetail_log($val,null,$money);
-            }
-
-            return true;
-        }
-
-    }
-
-    //串式订单结算处理
-    private function   Settlement_str($game_type,$match_id){
-           $matchModels = DB::table('money_buy_match')->where(['match_id'=>$match_id,'bet_type'=>2,'game_code'=>$game_type])->get();
-           if (empty($matchModels)) {  return true; }
-
-           $batch_ids_array = [] ;
-           $matchKeyModels = [] ;
-           foreach ($matchModels as $val){
-                $matchKeyModels[$val->batch_id][] = $val ;
-                if (!in_array($val->batch_id,$batch_ids_array)){
-                    $batch_ids_array[] = $val->batch_id;
-                }
-           }
-
-           $buyModels =  DB::table('money_buy_str')->whereIn( 'batch_id',$batch_ids_array)->get();
-           $buyKeyModels = [] ;
-           if (empty($buyModels)) { return true ; }
-           foreach ($buyModels  as $val){
-               $buyKeyModels[$val->batch_id][] = $val ;
-           }
-
-           foreach ($matchKeyModels as $key=>$sval_2){
-               foreach ($sval_2 as $sval){
-                       if ( $sval->match_id != $this->match_id ){ continue ; }
-
-                       $winorfalse = $this->winOrfalseInfo($sval);
-                       if (!in_array($winorfalse,[-1,1,2,3,4])){     throw  new  \Exception('胜负规则结果数据错!',4005);     }
-
-                       $this->makesql_up_buymatch_winorfalse($sval->id,$winorfalse,date("Y-m-d H:i:s"));
-                       $sql = "update money_buy_str  set  wait_match_num=wait_match_num-1 where  batch_id=$sval->batch-id ";
-                       $this->sqlArray[] = $sql ;
-                       $sval->result = $winorfalse ;
-
-                       if ($winorfalse == -1){
-                              //一条出错,全部作为错误处理
-                              $this->makesql_up_serial_lose($sval);
-                              break;
-                       }
-
-                       if (!isset($buyKeyModels[$key]['0'])){ throw  new  \Exception('购买主记录不存在,数据有问题');}
-                       if ($buyKeyModels[$key]['0']->wait_match_num <=1 ){
-                           $oddsarr = [];
-                           //串式最后一条记录了,需要做结算处理了
-                           foreach (  $matchKeyModels[$key] as $fval){
-                                    $oddsarr[] = ['odds'=>$fval->odds,'winOrLose'=>$fval->result] ;
-                                    $peilvArray = $this->winOddsCalculation($oddsarr);
-                           }
-                           foreach  ($buyKeyModels[$key] as $buyModel){
-                               $money = sprintf("%.2f",$buyModel->money * $peilvArray['returnMoney']) ;
-                               $sql = "update  money_buy_str set gain_money=$money,game_status=1  where  batch_id='$key' and id=$buyModel->id ";
-                               $this->sqlArray[] = $sql ;
-
-                               $this->sql_accountdetail_money($buyModel->account_identity,$money);
-                               $this->sql_moneydetail_log($buyModel,null,$money);
-                           }
-                           break;
-                   }
-               }
-
-           }
-
-
-    }
-
-    //输赢结果判断 $sval 为 money_buy_match  Model; 结果为  -1输  1赢  2平  3赢半平半  4输半平半
-    private  function  winOrfalseInfo($sval){
-        $fun = $sval->odds_code ;
-        $fun2 = $sval->p_code ;
-
-        if ($sval->p_code != 'gj'){
-            if (empty($this->resultModel) ||  empty($this->resultRecords)){
-                throw  new \Exception('非冠军比赛结果数据不能为空');
-            }
-
-            if ( $this->RefClass->hasMethod($fun) ){
-                $winorfalse = $this->AdapterObj->$fun($sval,$this->resultModel,$this->resultRecords);
-            }elseif ( $this->RefClass->hasMethod($fun2) ){
-                $winorfalse = $this->AdapterObj->$fun2($sval,$this->resultModel,$this->resultRecords);
-            }else{
-                throw new \Exception('没有找到玩法输赢判断规则',40010);
-            }
-        }else{
-            $this->getGjDatas($sval);
-            if (empty($this->gjModel)){
-                throw  new \Exception('冠军比赛结果数据不能为空');
-            }
-
-            if ( $this->RefClass->hasMethod($fun) ){
-                $winorfalse = $this->AdapterObj->$fun($sval,$this->gjModel,[]);
-            }elseif ( $this->RefClass->hasMethod($fun2) ){
-                $winorfalse = $this->AdapterObj->$fun2($sval,$this->gjModel,[]);
-            }else{
-                throw new \Exception('没有找到玩法输赢判断规则',40010);
-            }
-        }
-
-        return $winorfalse ;
-    }
-
-    /**
-     * 注单返现计算
-     * @param mixed $dataArray 结果表数据 [['odds'=>xx,'winOrLose'=>1],[...]];
-     * @return array 注单返现额
-     */
-    private function   winOddsCalculation($dataArray){
-        $returnMoney = 1;
-        // 循环计算每注返现赔率
-        foreach ($dataArray as $value) {
-            $odds = floatval($value['odds']);
-            // 因结果不同更改赔率
-            switch (intval($value['winOrLose'])) {
-                case 1:
-                    $oddsDiscount = 1 + $odds * 1;
-                    break;
-                case 2:
-                    $oddsDiscount = 1;
-                    break;
-                case 3:
-                    $oddsDiscount = 1 + $odds * 0.5;
-                    break;
-                default:
-                    $oddsDiscount = 0.5;
-            }
-            // 计算每注返现
-            $returnMoney = $returnMoney * $oddsDiscount;
-        }
-        // 计算赚钱
-        $earnMoney = $returnMoney - 1;
-
-        return ['earnMoney' => $earnMoney, 'returnMoney' => $returnMoney];
-    }
-
-
-
-
-    /**
-     * UUID 生成
-     */
-    public  static  function UUID() {
-        $prefix = '';
-        $uuid = '';
-        $str = md5(uniqid(mt_rand(), true));
-        $uuid = substr($str, 0, 8) . '-';
-        $uuid .= substr($str, 8, 4) . '-';
-        $uuid .= substr($str, 12, 4) . '-';
-        $uuid .= substr($str, 16, 4) . '-';
-        $uuid .= substr($str, 20, 12);
-        return $prefix . $uuid;
-    }
-
-
-    private function  sql_accountdetail_money($acount ,$moneycg){
-            $sql =  "update  account_detailed  set available_cash=available_cash+$moneycg,cash=cash+$moneycg where   account_identity='$acount' ";
-            $this->sqlArray[] = $sql ;
-    }
-
-    private function sql_moneydetail_log($allbuyModel,$model,$money_diff){
-
-            $uuid = self::UUID();
-            $dtime = date("Y-m-d H:i:s");
-            $detailModel = DB::table('account_detailed')->where('account_identity',$allbuyModel->account_identity)->first();
-            if (!$detailModel){
-                throw  new   \Exception('查无此用户数据account_detail='.$allbuyModel->account_identity,41002);
-            }
-            $money_cash =  $detailModel->cash ;
-
-            $SQL  = "insert into money_details(identity,trade_id,account_name,account_identity,money,money_time,money_type,trade_desc,status,money_cash,trade_type) values";
-            $SQL .= "('$uuid','$allbuyModel->order_id','$allbuyModel->account_name','$allbuyModel->account_identity','$money_diff','$dtime',1,'中奖收入','1','$money_cash',4)" ;
-
-            $this->sqlArray[] = $SQL ;
-
-    }
-
-    //生成串式失败的逻辑sql;
-    private function  makesql_up_serial_lose($model){
-            $batchid = $model->batch_id ;
-            $sql = "update  money_buy_match   set  result=-1  where  bet_type=2 and  batch_id=$batchid  ";
-            $this->sqlArray[] = $sql;
-
-            $sql = "update  money_buy_str   set   game_status=3,wait_match_num=0 where   batch_id=$batchid   ";
-            $this->sqlArray[] = $sql ;
-
-            return true ;
-    }
-
-    private function  makesql_up_buymatch_winorfalse($id,$result,$utime){
-        $sql = " update  money_buy_match  set  result=$result,utime=$utime  where id=$id  limit 1";
-        $this->sqlArray[] = $sql;
-        return true;
-    }
-
-     //设置 输赢 解析规则适配器
-    private  function  setAdapterObj($game_type){
-        $game_type = strtolower($game_type);
-        if ( !isset($this->gameAllMap)){  throw  new \Exception('赛事类型错误-'.$game_type,4002);   return false;  }
-
-        switch ($game_type){
-            case 'bq':
-                $this->AdapterObj = new BqRule();
-                break;
-            case  'lq':
-                $this->AdapterObj = new LqRule();
-                break;
-            case  'wq':
-                $this->AdapterObj = new WqRule();
-                break;
-            case  'zq':
-               $this->AdapterObj = new ZqRule();
-                break;
-        }
-        return  true ;
-    }
-
-
-    //返回数据
-    private function  makeData($status=1,$message='success',$data=''){
-        return [
-            'status' => $status ,
-            'message' =>$message,
-            'data' => $data ,
-        ] ;
-    }
-
-    //写处理状态
-    public function  writeStatusBegin($comendnticeModel){
-
-        $comendnticeModel->status = 1 ;
-        $comendnticeModel->done_time = date("Y-m-d H:i:s");
-        $comendnticeModel->pcount ++ ;
-        $comendnticeModel->logs = 'begin|';
-        $ret = $comendnticeModel->save();
-
-        return  $ret;
-    }
-
-    //写处理状态结束
-    public function  writeStatusEndOk($comendnticeModel){
-
-        $comendnticeModel->status = 4 ;
-        $comendnticeModel->done_time = date("Y-m-d H:i:s");
-        $comendnticeModel->logs = $comendnticeModel->logs.'end ok';
-        $ret = $comendnticeModel->save();
-
-        return  $ret;
-    }
-
-
-
-    //是否有需要进行结果算处理的赛事记录
-    public  function   getComendNoticeModel(){
-            $ret = (new ComendnoticeModel())->where('status',0)->orderby('id','asc')->first();
-
-            $this->ComendNoticModel = $ret;
-            return $ret;
-    }
-
-
-
-
-    //获取到某个用户的account模型和detail模型,用于用户的余额计算等使用
-    public function  getUserInfo($account_name){
-         if (isset($this->AccountArrays[$account_name])){
-             return $this->AccountArrays['$account_name'];
-         }
-
-         $accountModel = DB::table('account')->where('account',$account_name)->first();
-         if (!$accountModel){
-             throw  new   \Exception('查无此用户数据account='.$account_name,41002);
-         }
-
-         $detailModel = DB::table('account_detailed')->where('account_identity',$accountModel->identity)->first();
-
-         if (!$detailModel){
-             throw  new   \Exception('查无此用户数据account_detail='.$accountModel->identity,41002);
-         }
-         $ret = [
-             'account'=>$detailModel,
-             'detail' => $detailModel ,
-         ];
-         $this->AccountArrays[$account_name] = $ret ;
-         $this->AccountArrays[$accountModel->identity] = $ret ;
-
-         return $ret;
-     }
-
-    //获取到某个用户某个赛事的下单记录集[]
-    public function  GetMatchBatchIdArrays($batch_id,$type){
-            if (isset($this->MatchBatchIdArrays[$type][$batch_id])){
-                // return   $this->MatchBatchIdArrays[$type][$batch_id];
-            }
-            $all = DB::table("money_buy_match")->where(['batch_id',$batch_id,'result'=>0])->get();
-            if (!$all) {
-                throw  new  \Exception('无效的Money_buy_str->batch_id='.$batch_id , 41001);
-            }
-            $this->MatchBatchIdArrays[$type][$batch_id] = $all ;
-            return $all ;
-    }
-
-    //根据购买批次 获取下单信息
-    public function  GetBuyStrBatchIdArrays($batch_id,$type){
-
-        if (isset($this->BuyStrBatchIdArrays[$batch_id])){
-            // return   $this->BuyStrBatchIdArrays[$batch_id];
-        }
-
-        if ($type==2)
-        {
-            $all = DB::table("money_buy_str")->where(['batch_id'=>$batch_id,'game_status'=>0])->get();
-        }else{
-            $all = DB::table("money_buy_simplex")->where(['batch_id'=>$batch_id,'game_status'=>0])->get();
-        }
-
-        if (!$all) {
-            throw  new  \Exception('无效的batch_id='.$batch_id , 41001);
-        }
-       // $this->BuyStrBatchIdArrays[$batch_id] = $all ;
-        return $all ;
-
-    }
-
-
-    //得到比赛最终结果记录 和 中间结果记录
-    public function  getCompResult($type,$match_id){
-        $model = null ;
-        switch ($type){
-            case 'bq':
-                $model = DB::table('st_bq_result')->where('match_id',$match_id)->first();
-                $models = DB::table('st_bq_result_record')->where('match_id',$match_id)->orderBy('id','asc')->get()->toArray();
-                break;
-            case  'lq':
-                $model = DB::table('st_lq_result')->where('match_id',$match_id)->first();
-                $models = DB::table('st_lq_result_record')->where('match_id',$match_id)->orderBy('id','asc')->get()->toArray();
-                break;
-            case  'wq':
-                $model = DB::table('st_wq_result')->where('match_id',$match_id)->first();
-                $models = DB::table('st_wq_result_record')->where('match_id',$match_id)->orderBy('id','asc')->get()->toArray();
-                break;
-            case  'zq':
-                $model = DB::table('st_zq_result')->where('match_id',$match_id)->first();
-                $models = DB::table('st_zq_result_record')->where('match_id',$match_id)->orderBy('id','asc')->get()->toArray();
-                break;
-        }
-
-        /*
-        if (empty($model) || empty($models)){
-            throw  new   \Exception('没找到比赛结果记录match_id_'.$type.'-'.$match_id,4007);
-            return false;
-        }
-        */
-
-        $this->resultModel = $model;
-        $this->resultRecords = $models ;
-
-        $ret = [
-            'result' => $model,
-            'records' => $models ,
-        ];
-        return $ret;
-
-    }
-
-
-    //冠军比赛结果
-    public function  getGjDatas($matchModel){
-        if ( !empty($this->gjModel) ) {  return $this->gjModel ; }
-        $table = 'st_'.$matchModel->game_code.'_league_result';
-        $where = ['lg_id'=>$matchModel->lg_id,'game_name'=>$matchModel->odds_code];
-        $model = DB::table($table)->where($where)->first();
-        if (!empty($model)){
-            $this->gjModel = $model ;
-        }
-        return $model ;
-    }
-
-
-}

+ 131 - 98
app/Lib/Settlement/SettlementWinFail.php

@@ -28,6 +28,8 @@ class SettlementWinFail
 
     public $gameType = '';  //类型
     public $match_id = 0;  //比赛ID
+    public $bet_type = 0;   //1单式  2串式
+
 
     public $resultModel = null; //比赛最终结果对像MODEL
     public $resultRecords = []; //比赛中间结果对像数组;
@@ -37,6 +39,8 @@ class SettlementWinFail
 
     public $buyKeyMatchIdModels = [];   //单式投注里 [手动更改,同一场比赛不同结果的情况]    订单按批次号,比赛号存放,用于查订单的数组
 
+    public $sqlArray = [];
+
 
     //类型映射
     public $gameAllMap = [
@@ -63,10 +67,9 @@ class SettlementWinFail
             DB::beginTransaction();
             $this->writeStatusBegin($ComendNoticModel);
 
-            //$allmatchs = DB::table('money_buy_match')->where(['game_code' => $ComendNoticModel->game_code, 'match_id' => $ComendNoticModel->match_id, 'result' => 0])->get();
-            $allmatchs = DB::table('money_buy_match')->where(['game_code' => $ComendNoticModel->game_code, 'match_id' => $ComendNoticModel->match_id])->get();
+            $allmatchs = DB::table('money_buy_match')->where(['game_code' => $ComendNoticModel->game_code, 'match_id' => $ComendNoticModel->match_id])->count();
 
-            if (count($allmatchs) == 0) {
+            if ($allmatchs == 0) {
                 $this->writeStatusEndOk($ComendNoticModel);
                 $this->cgStatus();
                 DB::commit();
@@ -80,12 +83,14 @@ class SettlementWinFail
             $this->RefClass = new  \ReflectionClass($this->AdapterObj);
             $this->getCompResult($ComendNoticModel->game_code, $ComendNoticModel->match_id);
 
-
             $this->Settlement_simplex($this->gameType, $this->match_id);
             $this->Settlement_str($this->gameType, $this->match_id);
 
             $this->cgStatus();
             $this->writeStatusEndOk($ComendNoticModel);
+
+            $this->RunSql();
+
             DB::commit();
             return $this->makeData(1, 'success-all');
 
@@ -98,94 +103,108 @@ class SettlementWinFail
 
     private function cgStatus()
     {
-        DB::table("st_" . $this->ComendNoticModel->game_code . "_result")->where(['match_id' => $this->ComendNoticModel->match_id])->update(['status' => 2]);
-        DB::table("st_" . $this->ComendNoticModel->game_code . "_competition")->where(['match_id' => $this->ComendNoticModel->match_id])->update(['status' => 2]);
+        $this->sqlArray[] = "update  st_" . $this->ComendNoticModel->game_code . "_result set status=2 where  match_id= '" . $this->ComendNoticModel->match_id . "'";
+        $this->sqlArray[] = "update  st_" . $this->ComendNoticModel->game_code . "_competition set status=2 where  match_id= '" . $this->ComendNoticModel->match_id . "'";
     }
 
     //只处理某个订单下面的某场比赛的输赢结果
     public function ProcWinInfoByOneOrder($match_id, $order_id, $bet_type = 1)
     {
-        if ($bet_type == 1) {
-            $buyModel = DB::table('money_buy_simplex')->where(['order_id' => $order_id, 'match_id' => $match_id])->first();
-            if (empty($buyModel)) {
-                throw  new  \Exception('没找到订单记录.' . $match_id . '-' . $order_id . '-' . $bet_type);
-            }
-            $matchModes = DB::table('money_buy_match')->where(['batch_id' => $buyModel->batch_id, 'match_id' => $match_id, 'bet_type' => 1])->get();
-            if (count($matchModes) <= 0) {
-                throw  new  \Exception('无match记录' . $match_id . '-' . $order_id . '-' . $bet_type);
+        try {
+            DB::beginTransaction();
+
+            if ($bet_type == 1) {
+                $buyModel = DB::table('money_buy_simplex')->where(['order_id' => $order_id, 'match_id' => $match_id])->first();
+                if (empty($buyModel)) {
+                    throw  new  \Exception('没找到订单记录.' . $match_id . '-' . $order_id . '-' . $bet_type);
+                }
+                foreach ($buyModel as $val) {
+                    $this->buyKeyMatchIdModels[$val->batch_id][$val->match_id] = $val;
+                }
+
+                $matchModes = DB::table('money_buy_match')->where(['batch_id' => $buyModel->batch_id, 'match_id' => $match_id, 'bet_type' => 1])->get();
+                if (count($matchModes) <= 0) {
+                    throw  new  \Exception('无match记录' . $match_id . '-' . $order_id . '-' . $bet_type);
+                }
+            } else {
+                $buyModel = DB::table('money_buy_str')->where(['order_id' => $order_id])->first();
+                if (empty($buyModel)) {
+                    throw  new  \Exception('没找到订单记录' . $match_id . '-' . $order_id . '-' . $bet_type);
+                }
+
+                $matchModes = DB::table('money_buy_match')->where(['batch_id' => $buyModel->batch_id, 'match_id' => $match_id, 'bet_type' => 2])->get();
+                if (count($matchModes) <= 0) {
+                    throw  new  \Exception('无match记录' . $match_id . '-' . $order_id . '-' . $bet_type);
+                }
             }
-        } else {
-            $buyModel = DB::table('money_buy_str')->where(['order_id' => $order_id])->first();
-            if (empty($buyModel)) {
-                throw  new  \Exception('没找到订单记录' . $match_id . '-' . $order_id . '-' . $bet_type);
+
+            $this->gameType = $matchModes['0']->game_code;
+            $this->match_id = $match_id;
+            $this->bet_type = $bet_type ;
+
+            $this->setAdapterObj($this->gameType);
+            $this->RefClass = new  \ReflectionClass($this->AdapterObj);
+            $this->getCompResult($this->gameType, $match_id);
+            if (empty($this->resultModel)) {
+                throw  new  \Exception("没有比赛记录,操作中止!" . $this->gameType . '-' . $match_id);
             }
-            $matchModes = DB::table('money_buy_match')->where(['batch_id' => $buyModel->batch_id, 'match_id' => $match_id, 'bet_type' => 2])->get();
-            if (count($matchModes) <= 0) {
-                throw  new  \Exception('无match记录' . $match_id . '-' . $order_id . '-' . $bet_type);
+
+            foreach ($matchModes as $sval) {
+                $winorfalse = $this->winOrfalseInfo($sval);
+                $wininfo = $winorfalse['result'];
+                $matchinfo = $winorfalse['matchResult'];
+                $this->makesql_up_buymatch_winorfalse($sval->id, $wininfo, date("Y-m-d H:i:s"), $matchinfo);
             }
-        }
 
-        $this->gameType = $matchModes['0']->game_code;
-        $this->match_id = $match_id;
+            $this->doRun();
 
-        $this->setAdapterObj($this->gameType);
-        $this->RefClass = new  \ReflectionClass($this->AdapterObj);
-        $this->getCompResult($this->gameType, $match_id);
-        if (empty($this->resultModel)) {
-            throw  new  \Exception("没有比赛记录,操作中止!" . $this->gameType . '-' . $match_id);
-        }
+            DB::commit();
+            return $this->makeData();
 
-        foreach ($matchModes as $sval) {
-            $winorfalse = $this->winOrfalseInfo($sval);
-            $wininfo = $winorfalse['result'];
-            $matchinfo = $winorfalse['matchResult'];
-            $this->makesql_up_buymatch_winorfalse($sval->id, $wininfo, date("Y-m-d H:i:s"), $matchinfo);
+        } catch (\Exception $e) {
+            DB::rollBack();
+            return $this->makeData(0, 'false', ['msg' => $e->getMessage(), 'code' => $e->getCode(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
         }
-        return $this->makeData();
+
     }
 
 
     //单式订单结算处理
     private function Settlement_simplex($game_type, $match_id)
     {
-        //$buyModels = DB::table('money_buy_simplex')->where(['match_id' => $match_id, 'game_status' => 0])->get();
-        $buyModels = DB::table('money_buy_simplex')->where(['match_id' => $match_id])->get();
+
+        $buyModels = DB::table('money_buy_simplex')->where(['match_id' => $match_id, 'game_code' => $game_type])->get();
+        $this->bet_type = 1 ;
 
         if (count($buyModels) == 0) {
             return true;
         }
 
-        //$buymatchModles = DB::table('money_buy_match')->where(['match_id' => $match_id, 'bet_type' => 1, 'result' => 0, 'game_code' => $game_type])->orderby('batch_id', 'asc')->get();
         $buymatchModles = DB::table('money_buy_match')->where(['match_id' => $match_id, 'bet_type' => 1, 'game_code' => $game_type])->orderby('batch_id', 'asc')->get();
         if (count($buymatchModles) == 0) {
             return true;
         }
 
-
-        $buyKeyModel = $buymatchKeyModles = [];
+        $buymatchKeyModles = [];
         foreach ($buyModels as $val) {
-            $batch_id = $val->batch_id;
-            $buyKeyModel[$batch_id] = $val;
             $this->buyKeyMatchIdModels[$val->batch_id][$val->match_id] = $val;
         }
+
         foreach ($buymatchModles as $val) {
             $batch_id = $val->batch_id;
             $buymatchKeyModles[$batch_id][] = $val;
         }
 
-
-        //foreach ($buyKeyModel as $batch_id => $val) {
-            foreach ($buymatchKeyModles as $sub_batch_id => $fsval) {
-                foreach ($fsval as $sval) {
-                    $winorfalse = $this->winOrfalseInfo($sval);
-                    $wininfo = $winorfalse['result'];
-                    $matchinfo = $winorfalse['matchResult'];
-                    $this->makesql_up_buymatch_winorfalse($sval->id, $wininfo, date("Y-m-d H:i:s"), $matchinfo);
-                    $gs_val = ($wininfo == 1) ? 1 : ($wininfo == -1 ? 2 : 3);
-                    DB::table('money_buy_simplex')->where(['batch_id' => $sval->batch_id, 'match_id' => $sval->match_id, 'game_code' => $sval->game_code])->update(['game_status' => $gs_val]);
-                }
+        foreach ($buymatchKeyModles as $sub_batch_id => $fsval) {
+            foreach ($fsval as $sval) {
+                $winorfalse = $this->winOrfalseInfo($sval);
+                $wininfo = $winorfalse['result'];
+                $matchinfo = $winorfalse['matchResult'];
+                $this->makesql_up_buymatch_winorfalse($sval->id, $wininfo, date("Y-m-d H:i:s"), $matchinfo);
+                $gs_val = ($wininfo == 1) ? 1 : ($wininfo == -1 ? 2 : 3);
+                DB::table('money_buy_simplex')->where(['batch_id' => $sval->batch_id, 'match_id' => $sval->match_id, 'game_code' => $sval->game_code])->update(['game_status' => $gs_val]);
             }
-       // }
+        }
 
         return true;
     }
@@ -197,6 +216,8 @@ class SettlementWinFail
         if (count($matchModels) == 0) {
             return true;
         }
+        $this->bet_type = 2 ;
+
 
         $batch_ids_array = [];
         $matchKeyModels = [];
@@ -207,7 +228,9 @@ class SettlementWinFail
             }
         }
 
-        $buyModels = DB::table('money_buy_str')->whereIn('batch_id', $batch_ids_array)->get();
+        $buyModels = DB::table('money_buy_str')->whereIn('batch_id', array_map(function ($i) {
+            return "'$i'";
+        }, $batch_ids_array))->get();
         $buyKeyModels = [];
 
         if (count($buyModels) == 0) {
@@ -223,7 +246,7 @@ class SettlementWinFail
                 if ($thissaisi->status == 4) {
                     $this->makesql_up_buymatch_winorfalse($sval->id, 2, date("Y-m-d H:i:s"), '赛事取消[结果和处理]');
                     $sql = "update money_buy_str  set  wait_match_num=wait_match_num-1 where  batch_id='$sval->batch_id' ";
-                    DB::update($sql);
+                    $this->sqlArray[] = $sql;
                     continue;
                 }
                 if ($sval->match_id != $this->match_id) {
@@ -234,8 +257,7 @@ class SettlementWinFail
                 $matchinfo = $winorfalse['matchResult'];
                 $this->makesql_up_buymatch_winorfalse($sval->id, $wininfo, date("Y-m-d H:i:s"), $matchinfo);
 
-                $sql = "update money_buy_str  set  wait_match_num=wait_match_num-1 where  batch_id='$sval->batch_id' ";
-                DB::update($sql);
+                $this->sqlArray[] = "update money_buy_str  set  wait_match_num=wait_match_num-1 where  batch_id='$sval->batch_id' ";
             }
         }
     }
@@ -250,13 +272,10 @@ class SettlementWinFail
             throw  new \Exception('单式投注结果和对应订单关联有误!');
         }
 
-
         if ($sval->p_code != 'gj') {
-
             if (count($this->resultModel) <= 0) {
                 throw  new \Exception('非冠军比赛结果数据不能为空');
             }
-
             //如果手动更改了结果,就用更改后的结果,否则用默认的结果
             if ($sval->bet_type == 1 && $this->buyKeyMatchIdModels[$sval->batch_id][$sval->match_id]->result_flag == 1) {
                 $now_result = json_decode($this->buyKeyMatchIdModels[$sval->batch_id][$sval->match_id]->single_result, true);
@@ -264,10 +283,10 @@ class SettlementWinFail
                 $now_result = $this->resultModel;
             }
 
-            if ($this->RefClass->hasMethod($fun)) {
-                $winorfalse = $this->AdapterObj->$fun($sval, $now_result, []);
-            } elseif ($this->RefClass->hasMethod($fun2)) {
+            if ($this->RefClass->hasMethod($fun2)) {
                 $winorfalse = $this->AdapterObj->$fun2($sval, $now_result, []);
+            } elseif ($this->RefClass->hasMethod($fun)) {
+                $winorfalse = $this->AdapterObj->$fun($sval, $now_result, []);
             } else {
                 throw new \Exception('没有找到玩法输赢判断规则-01-' . $sval->id, 40010);
             }
@@ -298,15 +317,16 @@ class SettlementWinFail
             throw new \Exception('输赢结果异常!');
         }
 
-
         return $winorfalse;
     }
 
 
     private function makesql_up_buymatch_winorfalse($id, $result, $utime, $matchResult = '')
     {
-        $ret = DB::table('money_buy_match')->where(['id' => $id])->update(['result' => $result, 'utime' => $utime, 'matchResult' => $matchResult]);
-        return $ret;
+        $matchResult = str_replace(";", ";", $matchResult);
+        $sql = "update money_buy_match set result=$result, utime='$utime',matchResult='$matchResult' where   id=$id ";
+        $this->sqlArray[] = $sql;
+        return true;
     }
 
     //设置 输赢 解析规则适配器
@@ -349,26 +369,15 @@ class SettlementWinFail
     //写处理状态
     public function writeStatusBegin($comendnticeModel)
     {
-
-        $comendnticeModel->status = 1;
-        $comendnticeModel->done_time = date("Y-m-d H:i:s");
-        $comendnticeModel->pcount++;
-        $comendnticeModel->logs = 'begin|';
-        $ret = $comendnticeModel->save();
-
-        return $ret;
+        $this->sqlArray[] = "update  comendnotice set status=1,pcount=pcount+1 ,done_time='" . date("Y-m-d H:i:s") . "',logs='begin|'  where id=$comendnticeModel->id";
+        return true;
     }
 
     //写处理状态结束
     public function writeStatusEndOk($comendnticeModel)
     {
-
-        $comendnticeModel->status = 4;
-        $comendnticeModel->done_time = date("Y-m-d H:i:s");
-        $comendnticeModel->logs = $comendnticeModel->logs . 'end ok';
-        $ret = $comendnticeModel->save();
-
-        return $ret;
+        $this->sqlArray[] = "update  comendnotice set status=4,done_time='" . date("Y-m-d H:i:s") . "',logs='" . $comendnticeModel->logs . ' end ok' . "'  where id=$comendnticeModel->id";
+        return true;
     }
 
 
@@ -380,8 +389,6 @@ class SettlementWinFail
         } else {
             $ret = (new ComendnoticeModel())->where('status', 0)->orderby('id', 'asc')->first();
         }
-
-
         $this->ComendNoticModel = $ret;
         return $ret;
     }
@@ -394,47 +401,46 @@ class SettlementWinFail
         switch ($type) {
             case 'bq':
                 $model = DB::table('st_bq_result')->where('match_id', $match_id)->orderby('id', 'asc')->get();
-                $models = DB::table('st_bq_result_record')->where('match_id', $match_id)->orderBy('id', 'asc')->get()->toArray();
+                //$models = DB::table('st_bq_result_record')->where('match_id', $match_id)->orderBy('id', 'asc')->get()->toArray();
                 break;
             case  'lq':
                 $model = DB::table('st_lq_result')->where('match_id', $match_id)->orderby('id', 'asc')->get();
-                $models = DB::table('st_lq_result_record')->where('match_id', $match_id)->orderBy('id', 'asc')->get()->toArray();
+                //$models = DB::table('st_lq_result_record')->where('match_id', $match_id)->orderBy('id', 'asc')->get()->toArray();
                 break;
             case  'wq':
                 $model = DB::table('st_wq_result')->where('match_id', $match_id)->orderby('id', 'asc')->get();
-                $models = DB::table('st_wq_result_record')->where('match_id', $match_id)->orderBy('id', 'asc')->get()->toArray();
+                //$models = DB::table('st_wq_result_record')->where('match_id', $match_id)->orderBy('id', 'asc')->get()->toArray();
                 break;
             case  'zq':
                 $model = DB::table('st_zq_result')->where('match_id', $match_id)->orderby('id', 'asc')->get();
-                $models = DB::table('st_zq_result_record')->where('match_id', $match_id)->orderBy('id', 'asc')->get()->toArray();
+                //$models = DB::table('st_zq_result_record')->where('match_id', $match_id)->orderBy('id', 'asc')->get()->toArray();
                 break;
         }
 
         $this->resultModel = $model;
-        $this->resultRecords = $models;
 
         $ret = [
             'result' => $model,
-            'records' => $models,
+            'records' => [],
         ];
         return $ret;
 
     }
 
     //根据比赛ID,获取赛事数据,主要用于处理是否有作废的情况
-    public function getCompostionDatas($game_code, $batch_id)
+    public function getCompostionDatas($game_code, $match_id)
     {
-        $batch_id = intval($batch_id);
-        if (isset($this->CompostionDatas[$batch_id])) {
-            return $this->getCompostionDatas[$game_code][$batch_id];
+        $match_id = intval($match_id);
+        if (isset($this->CompostionDatas[$game_code][$match_id])) {
+            return $this->getCompostionDatas[$game_code][$match_id];
         }
 
         $table = 'st_' . $game_code . '_competition';
-        $ret = DB::table($table)->where('match_id', $batch_id)->first();
+        $ret = DB::table($table)->where('match_id', $match_id)->first();
         if (count($ret) <= 0) {
-            throw new  \Exception('根据比赛ID获取赛事数据有误-' . $game_code . '-' . $batch_id);
+            throw new  \Exception('根据比赛ID获取赛事数据有误-' . $game_code . '-' . $match_id);
         }
-        $this->CompostionDatas[$game_code][$batch_id] = $ret;
+        $this->CompostionDatas[$game_code][$match_id] = $ret;
         return $ret;
     }
 
@@ -455,4 +461,31 @@ class SettlementWinFail
         return $model;
     }
 
+    private function RunSql()
+    {
+        $len = count($this->sqlArray);
+        $step = 2000;
+        $j = 1;
+        $pdo = DB::getPdo();
+        $tmp = [];
+        for ($i = 0; $i < $len; $i++) {
+            if ($j > $step || $i == ($len - 1)) {
+                if (empty($tmp)) {
+                    return;
+                }
+                $sqlstr = implode(";", $tmp);
+                $pdo->exec($sqlstr);
+
+                $tmp = [];
+                $j = 1;
+            } else {
+                $tmp[] = $this->sqlArray[$i];
+                $j++;
+            }
+        }
+
+        return true;
+    }
+
+
 }

+ 1 - 1
app/Models/MoneyBuyStr.php

@@ -270,7 +270,7 @@ class MoneyBuyStr extends BaseModel {
             }
 
             if($data[$i]->result != '未处理'){
-                $data[$i]->result = $data[$i]->result.'<br>('.$data[$i]->matchResult.')';
+                $data[$i]->result = $data[$i]->result.'<br>('.$data[$i]->matchresult.')';
             }
         }
         return $data->toArray();

+ 4 - 4
app/Models/SportsNoteList.php

@@ -176,7 +176,7 @@ class SportsNoteList extends BaseModel {
                             if($content[$b]->result=='未处理'){
                                 $data[$i]->content = $data[$i]->content.$result[$c]->odds_name.'<br>'.$content[$b]->condition.' '.$data[$i]->team.'@'.$content[$b]->odds.' ¥'.$content[$b]->bet_money.'<br>';
                             }else{
-                                $data[$i]->content = $data[$i]->content.$result[$c]->odds_name.'<br>'.$content[$b]->condition.' '.$data[$i]->team.'@'.$content[$b]->odds.' ¥'.$content[$b]->bet_money.'<br><span>'.$content[$b]->result.'</span>('.$content[$b]->matchResult.')<br>';
+                                $data[$i]->content = $data[$i]->content.$result[$c]->odds_name.'<br>'.$content[$b]->condition.' '.$data[$i]->team.'@'.$content[$b]->odds.' ¥'.$content[$b]->bet_money.'<br><span>'.$content[$b]->result.'</span>('.$content[$b]->matchresult.')<br>';
                             }
                         }
                     }
@@ -184,7 +184,7 @@ class SportsNoteList extends BaseModel {
                         if($content[$b]->result=='未处理'){
                             $data[$i]->content = $data[$i]->content.$content[$b]->odds_code.'<br>'.$content[$b]->condition.' '.$data[$i]->team.'@'.$content[$b]->odds.' ¥'.$content[$b]->bet_money.'<br>';
                         }else{
-                            $data[$i]->content = $data[$i]->content.$content[$b]->odds_code.'<br>'.$content[$b]->condition.' '.$data[$i]->team.'@'.$content[$b]->odds.' ¥'.$content[$b]->bet_money.'<br><span>'.$content[$b]->result.'</span>('.$content[$b]->matchResult.')<br>';
+                            $data[$i]->content = $data[$i]->content.$content[$b]->odds_code.'<br>'.$content[$b]->condition.' '.$data[$i]->team.'@'.$content[$b]->odds.' ¥'.$content[$b]->bet_money.'<br><span>'.$content[$b]->result.'</span>('.$content[$b]->matchresult.')<br>';
                         }
                     }
                 }
@@ -441,7 +441,7 @@ class SportsNoteList extends BaseModel {
                             if($content[$b]->result=='未处理'){
                                 $data[$i]->content = $data[$i]->content.$result[$c]->odds_name.'<br>'.$content[$b]->condition.' '.$data[$i]->team.'@'.$content[$b]->odds.' ¥'.$content[$b]->bet_money.'<br>';
                             }else{
-                                $data[$i]->content = $data[$i]->content.$result[$c]->odds_name.'<br>'.$content[$b]->condition.' '.$data[$i]->team.'@'.$content[$b]->odds.' ¥'.$content[$b]->bet_money.'<br><span>'.$content[$b]->result.'</span>('.$content[$b]->matchResult.')<br>';
+                                $data[$i]->content = $data[$i]->content.$result[$c]->odds_name.'<br>'.$content[$b]->condition.' '.$data[$i]->team.'@'.$content[$b]->odds.' ¥'.$content[$b]->bet_money.'<br><span>'.$content[$b]->result.'</span>('.$content[$b]->matchresult.')<br>';
                             }
                         }
                     }
@@ -449,7 +449,7 @@ class SportsNoteList extends BaseModel {
                         if($content[$b]->result=='未处理'){
                             $data[$i]->content = $data[$i]->content.$content[$b]->odds_code.'<br>'.$content[$b]->condition.' '.$data[$i]->team.'@'.$content[$b]->odds.' ¥'.$content[$b]->bet_money.'<br>';
                         }else{
-                            $data[$i]->content = $data[$i]->content.$content[$b]->odds_code.'<br>'.$content[$b]->condition.' '.$data[$i]->team.'@'.$content[$b]->odds.' ¥'.$content[$b]->bet_money.'<br><span>'.$content[$b]->result.'</span>('.$content[$b]->matchResult.')<br>';
+                            $data[$i]->content = $data[$i]->content.$content[$b]->odds_code.'<br>'.$content[$b]->condition.' '.$data[$i]->team.'@'.$content[$b]->odds.' ¥'.$content[$b]->bet_money.'<br><span>'.$content[$b]->result.'</span>('.$content[$b]->matchresult.')<br>';
                         }
                     }
                 }