vali 6 жил өмнө
parent
commit
d172d4a84b

+ 33 - 31
app/Http/Response/Response.php

@@ -5,6 +5,7 @@ namespace App\Http\Response;
 class Response
 {
     const SUCCESS = 1;
+    const FAILED = 0;
     //体育数据入库操作
     const HANDLE_ERRORS = 10010;
     const ABNORMAL = 10011;
@@ -49,42 +50,43 @@ class Response
 
     private static $errorMsgs = [
         self::SUCCESS => '成功',
+        self::FAILED => '失败',
         //===体育数据写入===
-        self::HANDLE_ERRORS =>'数据处理失败',
-        self::ABNORMAL =>'提交数据异常',
-        self::UPDATE_ERROR =>'数据更新失败',
-        self::INSERT_ERROR =>'数据插入失败',
-        self::COUNTRY_ERROR =>'国家不存在',
-        self::AREA_ERROR =>'地区不存在',
-        self::LEAGUE_ERROR =>'联赛不存在',
-        self::MATCH_ERROR =>'赛事不存在',
-        self::LOCAL_LEAGUE_ERROR =>'写入联赛关联记录失败',
-        self::ADD_ODDS_ERROR =>'赛事赔率写入失败',
-        self::ADD_ODDS_R_ERROR =>'赛事赔率记录写入失败',
-        self::ADD_LG_R_ERROR =>'联赛结果写入失败',
-        self::ADD_MATCH_R_ERROR =>'赛事结果写入失败',
-        self::ADD_MATCH_R_R_ERROR =>'赛事结果记录写入失败',
-        self::LG_LASTTIME_ERROR =>'联赛赛季结束时间不存在',
-        self::HALF_MATCH_ERROR =>'所属上半场赛事不存在',
+        self::HANDLE_ERRORS => '数据处理失败',
+        self::ABNORMAL => '提交数据异常',
+        self::UPDATE_ERROR => '数据更新失败',
+        self::INSERT_ERROR => '数据插入失败',
+        self::COUNTRY_ERROR => '国家不存在',
+        self::AREA_ERROR => '地区不存在',
+        self::LEAGUE_ERROR => '联赛不存在',
+        self::MATCH_ERROR => '赛事不存在',
+        self::LOCAL_LEAGUE_ERROR => '写入联赛关联记录失败',
+        self::ADD_ODDS_ERROR => '赛事赔率写入失败',
+        self::ADD_ODDS_R_ERROR => '赛事赔率记录写入失败',
+        self::ADD_LG_R_ERROR => '联赛结果写入失败',
+        self::ADD_MATCH_R_ERROR => '赛事结果写入失败',
+        self::ADD_MATCH_R_R_ERROR => '赛事结果记录写入失败',
+        self::LG_LASTTIME_ERROR => '联赛赛季结束时间不存在',
+        self::HALF_MATCH_ERROR => '所属上半场赛事不存在',
         self::AUTH_ERROR => '无权操作',
-        self::LOCAL_MATCH_ERROR =>'写入赛事关联记录失败',
-        self::BROADCAST_ERROR =>'写入直播数据失败',
+        self::LOCAL_MATCH_ERROR => '写入赛事关联记录失败',
+        self::BROADCAST_ERROR => '写入直播数据失败',
         //===更新赛事状态===
-        self::MATCHID_NULL =>'未获取到相关赛事',
-        self::UPSTATUS_ERROR =>'赛事状态更新失败',
-        self::UPMATCHTAG_ERROR =>'赛事tag更新失败',
+        self::MATCHID_NULL => '未获取到相关赛事',
+        self::UPSTATUS_ERROR => '赛事状态更新失败',
+        self::UPMATCHTAG_ERROR => '赛事tag更新失败',
         //===更新赔率状态===
-        self::ODDS_SOLE_ERR =>'更新赔率状态失败',
+        self::ODDS_SOLE_ERR => '更新赔率状态失败',
         //===获取用户 token===
         self::TOKEN_ERR => '用户token异常,请重新获取',
         //===联赛uuid 为空====
-        self::LG__UUID_NULL=> '联赛uuid为空',
+        self::LG__UUID_NULL => '联赛uuid为空',
         //===未获取到数据源lg_id===
-        self::S_LG_ID_NULL =>'未获取到数据源lg_id',
+        self::S_LG_ID_NULL => '未获取到数据源lg_id',
         //===未获取到本地lg_id===
         self::L_LG_ID_NULL => '未获取到本地lg_id',
         //===写请求数据日志记录失败===
-        self::SPORTS_RECORD_ERR=>'写请求数据日志记录失败',
+        self::SPORTS_RECORD_ERR => '写请求数据日志记录失败',
 
     ];
 
@@ -93,28 +95,28 @@ class Response
         return isset(static::$errorMsgs[$code]) ? static::$errorMsgs[$code] : '';
     }
 
-    public static function generate($front = '',$errCode, $data = [], $errMsg = '')
+    public static function generate($front = '', $errCode, $data = [], $errMsg = '')
     {
         $rs['status'] = $errCode;
         $rs['msg'] = $errMsg;
         $rs['msg'] OR $rs['msg'] = static::getMsg($errCode) ?: static::$errorMsgs[static::FAILED];
-        $rs['msg'] = $front.$rs['msg'];
+        $rs['msg'] = $front . $rs['msg'];
         $rs['data'] = $data;
 //        return response()->json($rs, 200, ['Content-Type' => 'application/json; charset=UTF-8'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
-        return json_encode($rs,JSON_UNESCAPED_UNICODE);
+        return json_encode($rs, JSON_UNESCAPED_UNICODE);
         exit();
     }
 
     public static function success($data = [])
     {
-        return static::generate('',Response::SUCCESS, $data);
+        return static::generate('', Response::SUCCESS, $data);
         exit();
     }
 
-    public static function throwError($errCode, $errMsg = '',$data = [])
+    public static function throwError($errCode, $errMsg = '', $data = [])
     {
         $errMsg OR $errMsg = static::getMsg($errCode);
-        throw new BusinessException($errMsg, $errCode,$data);
+        throw new BusinessException($errMsg, $errCode, $data);
     }
 
 }

+ 516 - 0
app/Logic/SettelementLogic.php

@@ -0,0 +1,516 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: Administrator
+ * Date: 2019/7/15
+ * Time: 16:52
+ */
+
+namespace App\Logic;
+
+use App\Http\Response\Response;
+use App\Lib\Settlement\SettlementBase;
+use Illuminate\Database\Capsule\Manager as DB;
+
+trait SettelementLogic
+{
+
+    private $SettlementBase;
+
+    private $PDatas = [];
+
+
+    //全部结算 结束要改结算和比赛状态
+    private function doSettelement($request, $response, $paras)
+    {
+        $this->PDatas = [];
+
+        try {
+            list($order_ids, $bettype, $settype, $game_code, $match_id, $change_status) = $this->requestpara($request, $response, $paras);
+
+            if (empty($order_ids)) {
+                $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);
+                    goto LABRETURN;
+                    return;
+                } else {
+                    throw  new \Exception('订单号不能为空!');
+                }
+                unset($needs_matchs);
+            }
+
+            if ($bettype == 1) {
+                $chekArr = $this->Match_check($order_ids, $bettype);
+                if (empty($chekArr) || count($chekArr) != 1) {
+                    throw  new \Exception('不同场比赛不能同时结算!');
+                }
+            }
+
+            if (!$this->DataPre($order_ids, $bettype, $settype, $game_code, $match_id, $change_status)) {
+                throw new  \Exception('没找到订单信息');
+            }
+            $this->UndoSettlement();
+
+
+            while (true) {
+                if ($this->httpserver->taskWorkingNum->get() > intval($this->config['sets']['task_worker_num'])) {
+                    co::sleep(30);
+                } else {
+                    $order_id = trim(array_shift($order_ids));
+
+                    if (empty($order_id)) {
+                        break;
+                    }
+
+
+                    $nowBuyDatasMainModel = $this->PDatas['Money_buy_Orders_Array'][$order_id];
+                    if ($nowBuyDatasMainModel->settle_status == 2 && $settype == 1) {
+                        continue;
+                    }
+
+                    $account_indent = $nowBuyDatasMainModel->account_identity;
+                    $batch_id = $nowBuyDatasMainModel->batch_id;
+
+                    $paras = [
+                        'type' => 'Settelement',
+                        'bet_type' => $bettype,
+                        'set_type' => $settype,
+                        'order_id' => $order_id,
+                        'game_code' => $nowBuyDatasMainModel->game_code,
+                        'match_id' => $match_id,
+                        'simplexData' => $nowBuyDatasMainModel,
+                        'matchDatas' => $this->PDatas['Money_buy_Match_array'][$batch_id],
+                        'settelementMidDataID' => isset($this->PDatas['settlement_middle_detail_array'][$bettype][$order_id]) ? $this->PDatas['settlement_middle_detail_array'][$bettype][$order_id]->id : 0,
+                        'account' => $this->PDatas['account_map_array'][$account_indent]->account,
+                        'money_prize' => isset($this->PDatas['money_prize_map'][$order_id]) ? $this->PDatas['money_prize_map'][$order_id]->id : 0
+                    ];
+
+                    $this->onTask($this->httpserver, $paras);
+                }
+            }
+            $this->cgStatus($game_code, $match_id, $change_status);
+
+            LABRETURN:
+            $data = Response::generate('', 1, ['cost' => (microtime(true) - $request->server['request_time_float'])], 'succes ');
+            $response->end($data);
+            return;
+        } catch (\Exception $e) {
+            $this->PDatas = [];
+
+            $data = Response::generate('', 10, '', $e->getMessage() . '--' . $e->getFile() . '--' . $e->getLine());
+            $response->end($data);
+            return;
+        }
+
+    }
+
+
+    private function Task_Settelement($serv, $task)
+    {
+        $order_id = $task['order_id'];
+        $bet_type = $task['bet_type'];
+        $table = ($bet_type == 1) ? "money_buy_simplex" : 'money_buy_str';
+
+        try {
+            if ($task['bet_type'] == 1) {
+                $this->singOrder($serv, $task);
+            } else {
+                $this->ChuanOrder($serv, $task);
+            }
+        } catch (\Exception $e) {
+            $e = str_replace(";", ";", $e->getMessage());
+            $sql = "update  $table  set  remark='$e' where  order_id='$order_id' ";
+            $this->sqltoRedisqueue($sql);
+        }
+    }
+
+
+    /**
+     * 单式注单结算
+     * @param mixed $order_id 注单ID
+     */
+    private function singOrder($serv, $task)
+    {
+        $matchDatas = $task['matchDatas'];
+        $simplexData = $task['simplexData'];
+        $account_identity = $simplexData->account_identity;
+        $bet_type = $task['bet_type'];
+        $order_id = $task['order_id'];
+        $match_id = $task['match_id'];
+        $game_code = $task['game_code'];
+        $account = $task['account'];
+        $money_prize = $task['money_prize'];
+
+        foreach ($matchDatas as $val) {
+            if (!in_array($val->result, [-1, 1, 2, 3, 4])) {
+                throw  new  \Exception('match比赛结果异常或还没有输赢结果->' . $val->id);
+            }
+        }
+
+
+        if (empty($this->SettlementBaseObj)) {
+            $settlementBase = new \App\Lib\Settlement\SettlementBase();
+        } else {
+            $settlementBase = $this->SettlementBaseObj;
+        }
+
+        $returnMoney = 0;
+        $oddsResult = [];
+        foreach ($matchDatas as $k => $v) {
+            if ($v->result == -1) {
+                continue;
+            }
+            $oddsResult[0]['winOrLose'] = $v->result;
+            $oddsResult[0]['odds'] = $v->odds;
+            $getReturnMoney = $settlementBase->stringOdds($oddsResult);
+            $returnMoney += $getReturnMoney['returnMoney'] * $v->bet_money;
+        }
+        $returnMoney = sprintf("%.2f", substr(sprintf("%.3f", $returnMoney), 0, -1));
+        // 判断盈亏  1 赢  2 输  3 平
+        $game_status = $returnMoney > $simplexData->money ? 1 : ($returnMoney == $simplexData->money ? 3 : 2);
+        // 修改投注表状态及盈亏
+        $this->sqltoRedisqueue(["update money_buy_simplex set settle_status=2, game_status=$game_status,gain_money=$returnMoney  where order_id='$order_id' "]);
+
+        $this->WriteOrAddSettlement($game_code, $match_id, $bet_type, $order_id, $account_identity, $returnMoney);
+        $this->insertData(
+            $order_id,
+            $returnMoney,
+            $account_identity,
+            1,
+            $game_code,
+            $simplexData->info_identity,
+            $simplexData->money,
+            $match_id,
+            $account,
+            $money_prize
+        );
+
+    }
+
+    private function WriteOrAddSettlement($game_code, $match_id, $bet_type, $order_id, $account_ident, $money)
+    {
+        if (intval($money * 100) == 0) {
+            return;
+        }
+
+        if ($this->set_type == 2 && isset($this->settlement_middle_detail_array[$bet_type][$order_id])) {
+            $this->sqltoRedisqueue("update  settlement_middle_detail  set  money=$money  where game_code='$game_code' and bet_type=$bet_type and order_id='$order_id' ");
+        } else {
+            $this->sqltoRedisqueue("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;
+    }
+
+
+    private function ChuanOrder($serv, $task)
+    {
+        $matchDatas = $task['matchDatas'];
+        $simplexData = $task['simplexData'];
+        $account_identity = $simplexData->account_identity;
+        $bet_type = $task['bet_type'];
+        $order_id = $task['order_id'];
+        $match_id = $task['match_id'];
+        $game_code = $task['game_code'];
+        $account = $task['account'];
+        $money_prize = $task['money_prize'];
+
+        foreach ($matchDatas as $val) {
+            if (!in_array($val->result, [-1, 1, 2, 3, 4])) {
+                throw  new  \Exception('match比赛结果异常或还没有输赢结果->' . $val->id);
+            }
+        }
+
+
+        $batch_id = $simplexData->batch_id;
+        $matchModels = $matchDatas;
+        if (count($matchModels) <= 0) {
+            throw  new  \Exception('match 数据异常-' . $batch_id);
+        }
+
+
+        if (empty($this->SettlementBaseObj)) {
+            $settlementBase = new \App\Lib\Settlement\SettlementBase();
+        } else {
+            $settlementBase = $this->SettlementBaseObj;
+        }
+
+
+        $newTime = date('Y-m-d H:i:s');
+        if ($simplexData->status == 1) {
+            $in_array = [];
+            foreach ($matchModels as $val) {
+                if (!in_array($val->result, [-1, 1, 2, 3, 4])) {
+                    throw  new  \Exception('match 比赛结果异常或还没有输赢结果->' . $val->id);
+                }
+
+                if ($val->result == -1) {
+                    $this->sqltoRedisqueue("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];
+            }
+
+            $chuanNum = intval(substr($simplexData->str_type, 0, 1));
+            $lasPeilv = $settlementBase->stringComputing([$in_array, $chuanNum]);
+            $money = floatPointDigit($this->BuyDatasMainModel->money * $lasPeilv);
+
+        } else {
+            $money = $simplexData->money;
+        }
+
+        $this->sqltoRedisqueue(" 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, $account, $money_prize);
+
+        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, $account = '', $money_prizeID = 0)
+    {
+
+        // 添加流水记录
+        $info_identity = UUID();
+        $money_time = date('Y-m-d H:i:s', time());
+        $trade_desc = $type == 1 ? '单式投注订单回款' : '串式投注订单回款';
+        $reason = $type == 1 ? '单式投注订单回款' : '串式投注订单回款';
+
+        $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','$account','$account_identity',$returnMoney,'$money_time',1,0,4,'$trade_desc','$reason','系统',1)";
+
+        $this->sqltoRedisqueue($sql);
+
+        // 修改用余额
+        $this->sqltoRedisqueue("update account_detailed  set available_cash=available_cash+$money,cash=cash+$money 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->sqltoRedisqueue($sql);
+
+        // 新增中奖记录表
+        $table = 'money_prize';
+        if ($money_prizeID) {
+            $this->sqltoRedisqueue("update $table  set money=$money,prize_money=$returnMoney, get_money= $returnMoney - $money where  id=$money_prizeID");
+        } else {
+            $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','$account','$game_name','$buy_identity',$money,'$money_time',1,$returnMoney,$returnMoney - $money)";
+            $this->sqltoRedisqueue($sql);
+        }
+        return true;
+    }
+
+
+    //数据预批量获取
+    private function DataPre($order_ids, $bettype, $settype, $game_code, $match_id, $change_status)
+    {
+
+        //DB::connection()->enableQueryLog();
+        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')->whereIn('order_id', $order_ids)->get();
+        }
+        //print_r(DB::getQueryLog());
+
+        if (empty($ret) || count($ret) <= 0) {
+            return false;
+        }
+
+        foreach ($ret as $val) {
+            $this->PDatas['Money_buy_Orders_Array'][$val->order_id] = $val;
+            $orderarr[] = $val->order_id;
+            $this->PDatas['Money_buy_Orders_batch_Array'][$val->batch_id][] = $val;
+            $tmpbatchid[] = $val->batch_id;
+            $userindentys[] = $val->account_identity;
+        }
+
+        $tmpbatchid = array_unique($tmpbatchid);
+        $userindentys = array_unique($userindentys);
+
+        if ($bettype == 1) {
+            $ret = DB::table('money_buy_match')->where(['game_code' => $game_code, 'match_id' => $match_id])->whereIn('batch_id', $tmpbatchid)->get();
+        } else {
+            $ret = DB::table('money_buy_match')->where(['game_code' => $game_code])->whereIn('batch_id', $tmpbatchid)->get();
+        }
+        foreach ($ret as $val) {
+            $this->PDatas['Money_buy_Match_array'][$val->batch_id][] = $val;
+        }
+
+        $ret = DB::table('account_detailed')->whereIn('account_identity', $userindentys)->get();
+        foreach ($ret as $val) {
+            $this->PDatas['account_indentity_map_array'][$val->account_identity] = $val;
+        }
+
+        $ret = DB::table('account')->whereIn('identity', $userindentys)->get();
+        foreach ($ret as $val) {
+            $this->PDatas['account_map_array'][$val->identity] = $val;
+        }
+
+        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->PDatas['settlement_middle_detail_array'][$val->bet_type][$val->order_id] = $val;
+                }
+            }
+
+
+            $order_str_1 = array_map(function ($item) {
+                return "'$item'";
+            }, $orderarr);
+            $order_str = implode(",", $order_str_1);
+
+            if ($change_status) {
+                if ($bettype == 1) {
+                    $sql_tmp = "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 {
+                    $sql_tmp = "update $moneytable set  settle_status=1, gain_money=0  where order_id in ($order_str)  ";
+                }
+                $this->sqltoRedisqueue($sql_tmp);
+            }
+        }
+
+        $ret = DB::table('money_prize')->whereIn('order_id', $order_ids)->get();
+        if ($ret) {
+            foreach ($ret as $val) {
+                $this->PDatas['money_prize_map'][$val->order_id] = $val;
+            }
+        }
+
+        return true;
+    }
+
+
+    private function requestpara($request, $response, $paras)
+    {
+        $idoarr = explode(",", $paras['order_ids']);
+        $order_ids = array_map(function ($i) {
+            return strval($i);
+        }, $idoarr);
+        $bettype = $paras['bettype'];
+        $settype = $paras['settype'];
+        $game_code = $paras['game_code'];
+        $match_id = $paras['match_id'];
+        $change_status = $paras['change_status'];
+
+        if (intval($match_id) <= 0) {
+            throw  new \Exception('赛事ID不能为空!');
+            return;
+        }
+
+        if (empty($game_code)) {
+            throw  new \Exception('赛事类型不能为空!');
+        }
+
+        if (!in_array($bettype, [1, 2])) {
+            throw  new \Exception('订单类型参数错误!');
+        }
+
+        if (!in_array($settype, [1, 2])) {
+            throw  new \Exception('结算参数错误');
+        }
+
+        $this->PDatas['bettype'] = $bettype;
+        $this->PDatas['settype'] = $settype;
+        $this->PDatas['game_code'] = $game_code;
+        $this->PDatas['match_id'] = $match_id;
+
+
+        $ret = [$order_ids, $bettype, $settype, $game_code, $match_id, $change_status];
+
+        return $ret;
+    }
+
+    private function getSBaseObj()
+    {
+        if (empty($this->SettlementBase)) {
+            $this->SettlementBase = new  SettlementBase();
+        }
+        return $this->SettlementBase;
+    }
+
+    //改状态
+    private function cgStatus($game_code, $match_id, $change_status)
+    {
+        $table1 = "st_" . $game_code . "_result";
+        $table2 = "st_" . $game_code . "_competition";
+
+        if ($change_status) {
+            $this->sqltoRedisqueue("update $table1 set  status=3  where   match_id=$match_id ");
+            $this->sqltoRedisqueue("update $table2 set  status=3  where   match_id=$match_id ");
+        }
+    }
+
+    //得么一个临时变量
+    private function GP($name)
+    {
+        return $this->PDatas[$name];
+    }
+
+
+    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 UndoSettlement()
+    {
+
+        if (empty($this->PDatas['settlement_middle_detail_array'])) {
+            return true;
+        }
+
+        $bet_type = $this->GP('bettype');
+        $nowArray = $this->PDatas['settlement_middle_detail_array'][$bet_type];
+
+        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;
+        }
+
+        $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;
+    }
+
+
+}

+ 0 - 15
app/Logic/settelementLogic.php

@@ -1,15 +0,0 @@
-<?php
-/**
- * Created by PhpStorm.
- * User: Administrator
- * Date: 2019/7/15
- * Time: 16:52
- */
-
-namespace app\Logic;
-
-
-class settelementLogic
-{
-
-}

+ 43 - 17
commands/clientws4.php

@@ -12,28 +12,25 @@ require __DIR__ . '/../vendor/autoload.php';
 \datainf\lib\boot::init();
 
 use  App\Lib\ModelBase;
-//use Illuminate\Database\Capsule\Manager as DB;
+use Illuminate\Database\Capsule\Manager as DB;
 
 ModelBase::init();
 //var_dump($obj);
 //var_dump(DB::table('datainf_log')->where('id',766)->first());
-
-ModelBase::init()->getConnection()->disconnect();
-echo "---------------------\n\n\n";
+//ModelBase::init()->getConnection()->disconnect();
+echo "---------------------\n\n";
 
 
 //$obj->getConnection()->disconnect();
 
 //var_dump(DB::table('datainf_log')->where('id',766)->first());
+/*
 $sql = "select * from  datainf_log where id in (766,767) ";
 $pdo = ModelBase::init()->getConnection()->getPdo();
 foreach ($pdo->query($sql ) as $row) {
     print_r($row); //你可以用 echo($GLOBAL); 来看到这些值
 }
-
-
-
-
+*/
 
 
 /*
@@ -59,9 +56,33 @@ $ret = $model->save();
 print_r([$ret,$model->toArray()]);
 */
 
+function getIds($type, $match_id, $game_code = '')
+{
+    $return = [];
+    if ($type == 1) {
+        $ret = DB::table('money_buy_simplex')->where(['match_id' => $match_id])->get();
+        if ($ret) {
+            foreach ($ret as $val) {
+                $return[] = $val->order_id;
+            }
+        }
+        return $return;
+    } else {
+        $ret = DB::table('money_buy_str')->leftJoin('money_buy_match', 'money_buy_match.batch_id', '=', 'money_buy_str.batch_id')->where(['money_buy_match.match_id' => $match_id, 'money_buy_match.game_code' => $game_code])->get();
+        if ($ret) {
+            foreach ($ret as $val) {
+                $return[] = $val->order_id;
+            }
+        }
+        return $return;
+    }
+}
 
-/*
-function request_post($url = '', $param = '') {
+$ids = getIds(1, 866, 'zg');
+echo "ids_len:" . count($ids) . "\n";
+
+function request_post($url = '', $param = '')
+{
     if (empty($url) || empty($param)) {
         return false;
     }
@@ -69,7 +90,7 @@ function request_post($url = '', $param = '') {
     $postUrl = $url;
     $curlPost = $param;
     $ch = curl_init();//初始化curl
-    curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
+    curl_setopt($ch, CURLOPT_URL, $postUrl);//抓取指定网页
     curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
     curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
@@ -80,14 +101,19 @@ function request_post($url = '', $param = '') {
     return $data;
 }
 
-$data=[
-    'token'=>'xxxx',
-    'ccav'=>'ccav',
+$data = [
+    'token' => 'O9Z8zK15629128605d28285cb15dc',
+    'order_ids' => implode(",", $ids),
+    'bettype' => 1,
+    'settype' => 2,
+    'game_code' => 'zq',
+    'match_id' => 866,
+    'change_status' => 1
 ];
 
-$ret = request_post('http://192.168.2.200:9093/abcd',$data);
-print_r($ret);
-*/
+$ret = request_post('http://192.168.2.200:9094/Settelement', $data);
+echo "返回:" . print_r($ret, true) . "\n\n";
+
 
 
 /*

+ 1 - 0
commands/init.sh

@@ -1,3 +1,4 @@
 #!/bin/sh
 cd  /home/swooleProV2/dataInterface/commands
 /usr/local/bin/php  /home/swooleProV2/dataInterface/commands/bootHttp.php
+/usr/local/bin/php  /home/swooleProV2/dataInterface/commands/bootSettelementHttp.php

+ 15 - 5
datainf/lib/boot.php

@@ -1,7 +1,9 @@
 <?php
-namespace  datainf\lib;
-ini_set('date.timezone','Asia/Shanghai');
+
+namespace datainf\lib;
+ini_set('date.timezone', 'Asia/Shanghai');
 ini_set('memory_limit', '512M');
+
 /**
  *
  * Created by PhpStorm.
@@ -9,20 +11,28 @@ ini_set('memory_limit', '512M');
  * Date: 2019/5/20
  * Time: 9:19
  */
+
 use datainf\lib\GlobConfigs;
 
 class boot
 {
-    public static  function init(){
+    public static function init()
+    {
         self::loadConsts();
-
+        self::loadfunction();
     }
 
-    public static function  loadConsts(){
+    public static function loadConsts()
+    {
         require_once(realpath(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'Mconsts.php');
         GlobConfigs::getInstance()->getAll();
     }
 
+    public static function loadfunction()
+    {
+        require_once(realpath(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'functions.php');
+    }
+
 
 }
 

+ 33 - 0
datainf/lib/functions.php

@@ -0,0 +1,33 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: Administrator
+ * Date: 2019/7/16
+ * Time: 17:46
+ */
+
+//保留小数位数
+function floatPointDigit($data, $long = 2)
+{
+    $long = intval($long);
+    $for1 = "%." . $long . "f";
+    $for2 = "%." . ($long + 1) . "f";
+    return sprintf($for1, substr(sprintf($for2, $data), 0, -1));
+}
+
+/**
+ * UUID 生成
+ */
+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;
+}
+

+ 61 - 59
datainf/logic/HttpServerSettelement.php

@@ -15,6 +15,8 @@ use App\Logic\WinfailLogic;
 use datainf\lib\GlobConfigs;
 use Illuminate\Database\Capsule\Manager as DB;
 use swoole;
+use App\Logic\SettelementLogic;
+
 
 class HttpServerSettelement
 {
@@ -24,6 +26,8 @@ class HttpServerSettelement
     private $redisonfig = [];
     const   SQLKEY = 'ALLSQLKEY';
 
+    use SettelementLogic;
+
     public function __construct($config)
     {
         $this->httpserver = new \swoole\http\server($config['host'], $config['port']);
@@ -71,7 +75,7 @@ class HttpServerSettelement
         $paras = array_merge(['request_time' => date("H:i:s")], !empty($request->get) ? $request->get : [], !empty($request->post) ? $request->post : []);
 
         $request_uri = substr($request->server['request_uri'], 1);
-        $urls = ['WinFail', 'SettelementAll', 'SettelementSome'];
+        $urls = ['WinFail', 'Settelement'];
 
         if (!in_array($request_uri, $urls)) {
             $data = Response::generate('', 0, '', '无效的url');
@@ -89,7 +93,7 @@ class HttpServerSettelement
         if ($check_token) {
             $token = isset($paras['token']) ? $paras['token'] : '';
             if (empty($token) || empty($this->Tokencheck($token))) {
-                $data = Response::generate('', 6, '', '无效的token');
+                $data = Response::generate('', 6, '', '安全验证失败!');
                 $response->end($data);
                 return;
             }
@@ -100,13 +104,8 @@ class HttpServerSettelement
             return $this->doWinFailse($request, $response, $paras);
         }
 
-
-        if ($request_uri == 'SettelementSome') {
-            return $this->doSettelementSome($request, $response, $paras);
-        }
-
-        if ($request_uri == 'SettelementAll') {
-            return $this->doSettelementSome($request, $response, $paras);
+        if ($request_uri == 'Settelement') {
+            return $this->doSettelement($request, $response, $paras);
         }
 
         return;
@@ -120,6 +119,10 @@ class HttpServerSettelement
             $this->Task_winfalse($serv, $task);
         }
 
+        if ($task['type'] == 'Settelement') {
+            $this->Task_Settelement($serv, $task);
+        }
+
         $this->httpserver->taskWorkingNum->sub();
     }
 
@@ -187,7 +190,7 @@ class HttpServerSettelement
             }
             unset($logic_obj, $noticeModel, $AdapterObj, $result, $moneySimples, $matchs_1, $matchs_2, $RefClass);
 
-            $data = Response::generate('', 1, '', 'ok ret' . $request->server['request_time_float'] . '-' . microtime(true));
+            $data = Response::generate('', 1, ['cost' => (microtime(true) - $request->server['request_time_float'])], 'succes ');
             $response->end($data);
             return;
 
@@ -201,59 +204,54 @@ class HttpServerSettelement
     }
 
 
-    //部分结算
-    private function doSettelementSome($request, $response, $paras)
-    {
-
-
-    }
-
-    //全部结算
-    private function doSettelementAll($request, $response, $paras)
-    {
-
-    }
-
-
     /////
     private function Task_winfalse($serv, $task)
     {
-        $moneyBuy = $task['moneySimple'];
-        $matchModel = $task['matchModel'];
-
-        $logic = WinfailLogic::getInstance();
-        $AdapterObj = $logic->getAdapterObj($matchModel->game_code);
-        $RefClass = new  \ReflectionClass($AdapterObj);
-
-        //如果手动更改了结果,就用更改后的结果,否则用默认的结果
-        if ($matchModel->bet_type == 1 && $moneyBuy['result_flag'] == 1) {
-            $now_result = [json_decode($moneyBuy['single_result'])];
-        } else {
-            foreach ($task['result'] as $key => $val) {
-                $now_result[] = $val;
+        try {
+            $moneyBuy = $task['moneySimple'];
+            $matchModel = $task['matchModel'];
+
+            $logic = WinfailLogic::getInstance();
+            $AdapterObj = $logic->getAdapterObj($matchModel->game_code);
+            $RefClass = new  \ReflectionClass($AdapterObj);
+
+            //如果手动更改了结果,就用更改后的结果,否则用默认的结果
+            if ($matchModel->bet_type == 1 && $moneyBuy['result_flag'] == 1) {
+                $now_result = [json_decode($moneyBuy['single_result'])];
+            } else {
+                foreach ($task['result'] as $key => $val) {
+                    $now_result[] = $val;
+                }
             }
-        }
 
-        $fun1 = $matchModel->odds_code;
-        $fun2 = $matchModel->p_code;
+            $fun1 = $matchModel->odds_code;
+            $fun2 = $matchModel->p_code;
 
-        if ($RefClass->hasMethod($fun1)) {
-            $winorfalse = $AdapterObj->$fun1($matchModel, $now_result, []);
-        } elseif ($RefClass->hasMethod($fun2)) {
-            $winorfalse = $AdapterObj->$fun2($matchModel, $now_result, []);
-        }
-        if (!in_array($winorfalse['result'], [-1, 1, 2, 3, 4])) {
-            $winorfalse = ['result' => 2, 'matchResult' => 'noRuleError'];
-        }
+            $winorfalsedef = ['result' => 2, 'matchResult' => 'noRuleOrError'];
+            try {
+                if ($RefClass->hasMethod($fun1)) {
+                    $winorfalse = $AdapterObj->$fun1($matchModel, $now_result, []);
+                } elseif ($RefClass->hasMethod($fun2)) {
+                    $winorfalse = $AdapterObj->$fun2($matchModel, $now_result, []);
+                }
+            } catch (\Exception $e) {
+            }
+
+            if (!isset($winorfalse['result']) || !isset($winorfalse['matchResult']) || !in_array($winorfalse['result'], [-1, 1, 2, 3, 4])) {
+                $winorfalse = $winorfalsedef;
+            }
+
+            $sql_1 = $this->makesql_up_buymatch_winorfalse($matchModel->id, $winorfalse['result'], date("Y-m-d H:i:s"), $winorfalse['matchResult']);
+            $gs_val = ($winorfalse['result'] == 1) ? 1 : ($winorfalse['result'] == -1 ? 2 : 3);
+            if ($matchModel->bet_type == 1) {
+                $sql_2 = "update money_buy_simplex set  game_status=$gs_val where  batch_id='$matchModel->batch_id' and match_id='$matchModel->match_id' and  game_code='$matchModel->game_code' ";
+            } else {
+                $sql_2 = "update money_buy_str  set  wait_match_num=wait_match_num-1 where  batch_id='$matchModel->batch_id' ";
+            }
+            $this->sqltoRedisqueue([$sql_1, $sql_2]);
+        } catch (\Exception $e) {
 
-        $sql_1 = $this->makesql_up_buymatch_winorfalse($matchModel->id, $winorfalse['result'], date("Y-m-d H:i:s"), $winorfalse['matchResult']);
-        $gs_val = ($winorfalse['result'] == 1) ? 1 : ($winorfalse['result'] == -1 ? 2 : 3);
-        if ($matchModel->bet_type == 1) {
-            $sql_2 = "update money_buy_simplex set  game_status=$gs_val where  batch_id='$matchModel->batch_id' and match_id='$matchModel->match_id' and  game_code='$matchModel->game_code' ";
-        } else {
-            $sql_2 = "update money_buy_str  set  wait_match_num=wait_match_num-1 where  batch_id='$matchModel->batch_id' ";
         }
-        $this->sqltoRedisqueue([$sql_1, $sql_2]);
         return true;
     }
 
@@ -289,8 +287,12 @@ class HttpServerSettelement
         go(function () use ($cmdArray, $redisconfig) {
             $redis = new Swoole\Coroutine\Redis();
             $redis->connect($redisconfig['host'], $redisconfig['port']);
-            foreach ($cmdArray as $cmd) {
-                $redis->rpush(self::SQLKEY, $cmd);
+            if (is_array($cmdArray)) {
+                foreach ($cmdArray as $cmd) {
+                    $redis->lpush(self::SQLKEY, $cmd);
+                }
+            } else {
+                $redis->lpush(self::SQLKEY, $cmdArray);
             }
         });
     }
@@ -307,11 +309,11 @@ class HttpServerSettelement
             $max = 3000;
 
             for ($i = 0; $i < $max; $i++) {
-                $now = $redis->lpop(self::SQLKEY);
+                $now = $redis->rpop(self::SQLKEY);
                 if (empty($now)) {
                     break;
                 } else {
-                    $batchsql[] = $now;
+                    $batchsql[] = str_replace(";", ";", $now);
                 }
             }
             if (!empty($batchsql)) {