SettlementSql.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Administrator
  5. * Date: 2019/4/25
  6. * Time: 14:10
  7. */
  8. namespace App\Lib\Settlement;
  9. set_time_limit(600);
  10. ini_set('memory_limit', '256M');
  11. use Illuminate\Support\Facades\DB;
  12. use App\Models\Comendnotice as ComendnoticeModel;
  13. use App\Lib\Settlement\Adapter\ZqRule;
  14. use App\Lib\Settlement\Adapter\LqRule;
  15. use App\Lib\Settlement\Adapter\WqRule;
  16. use App\Lib\Settlement\Adapter\BqRule ;
  17. class SettlementSql
  18. {
  19. //用户的期末基本资料表 [uid]['account'=>$obj,'detail'=>$obj];
  20. public $AccountArrays = [] ;
  21. //buy_match 里batch_id 相同的数据
  22. public $MatchBatchIdArrays = [] ;
  23. //buy_str 批次号相同的记录
  24. public $BuyStrBatchIdArrays = [] ;
  25. //所有比赛场次号相同的记录
  26. public $AllMatchIdArrays = [];
  27. //比赛结束消息通知模型
  28. public $ComendNoticModel = null ;
  29. //返回的sql数组
  30. private $sqlArray = [] ;
  31. public $gameType = '' ; //类型
  32. public $match_id = 0 ; //比赛ID
  33. public $resultId = 0 ; //比赛最终结果ID
  34. public $resultModel = null ; //比赛最终结果对像MODEL
  35. public $resultRecords = [] ; //比赛中间结果对像数组;
  36. //类型映射
  37. public $gameAllMap = [
  38. 'zq'=>'ZqRule',
  39. 'lq'=>'LqRule',
  40. 'wq'=>'WqRule',
  41. 'bq'=>'BqRule',
  42. ];
  43. private $AdapterObj = null ;
  44. private $RefClass = null ;
  45. public function GetSQL(){
  46. return $this->makeData(1,'success',$this->sqlArray);
  47. }
  48. //按赛事批量结算
  49. public function doRun(){
  50. try {
  51. DB::beginTransaction ();
  52. $ComendNoticModel = $this->getComendNoticeModel();
  53. if (!$ComendNoticModel) {
  54. DB::commit ();
  55. return $this->makeData(1,'没有要处理的数据,直接退出');
  56. }
  57. $this->writeStatusBegin($ComendNoticModel);
  58. $allmatchs = DB::table('money_buy_match')->where(['game_code'=>$ComendNoticModel->game_code,'match_id'=>$ComendNoticModel->match_id,'result'=>0])->get();
  59. if (empty($allmatchs)) {
  60. $this->writeStatusEndOk($ComendNoticModel);
  61. DB::commit();
  62. return $this->makeData(1,'本赛事无订单数据,退出');
  63. }
  64. $this->gameType = $ComendNoticModel->game_code ;
  65. $this->match_id = $ComendNoticModel->match_id ;
  66. $this->setAdapterObj($ComendNoticModel->game_code);
  67. $this->RefClass = new \ReflectionClass( $this->AdapterObj ) ;
  68. $this->getCompResult($ComendNoticModel->game_code,$ComendNoticModel->match_id);
  69. $this->Settlement_simplex($this->gameType,$this->match_id);
  70. $this->Settlement_str($this->gameType,$this->match_id);
  71. $this->writeStatusEndOk($ComendNoticModel);
  72. DB::commit();
  73. return $this->makeData(1,'success-all');
  74. }catch (\Exception $e){
  75. DB::rollBack();
  76. return $this->makeData(0,'false',['msg'=>$e->getMessage(),'code'=>$e->getCode()]) ;
  77. }
  78. }
  79. //单式订单结算处理
  80. private function Settlement_simplex($game_type,$match_id){
  81. $buyModels = DB::table('money_buy_simplex')->where(['match_id'=>$match_id,'game_status'=>0])->get();
  82. if (empty($buyModels)){ return true; }
  83. $buymatchModles = DB::table('money_buy_match')->where(['match_id'=>$match_id,'bet_type'=>1,'result'=>0])->orderby('batch_id','asc')->get();
  84. if (empty($buymatchModles)) { return true ; }
  85. $buyKeyModel = $buymatchKeyModles = [] ;
  86. foreach ($buyModels as $val){
  87. $batch_id = $val->batch_id;
  88. $buyKeyModel[$batch_id] = $val;
  89. }
  90. foreach ($buymatchModles as $val){
  91. $batch_id = $val->batch_id;
  92. $buymatchKeyModles[$batch_id][] = $val;
  93. }
  94. foreach ($buyKeyModel as $batch_id=>$val){
  95. $money = 0 ;
  96. $allgame_status = 0 ;
  97. foreach ($buymatchKeyModles as $sub_batch_id=>$fsval){
  98. foreach ($fsval as $sval) {
  99. $winorfalse = $this->winOrfalseInfo($sval);
  100. if (!in_array($winorfalse, [-1, 1, 2, 3, 4])) {
  101. throw new \Exception('胜负规则结果数据错!', 4005);
  102. }
  103. $this->makesql_up_buymatch_winorfalse($sval->id, $winorfalse, date("Y-m-d H:i:s"));
  104. if ($winorfalse != -1) {
  105. $peilvretarr = $this->winOddsCalculation([['odds' => $sval->odds, 'winOrLose' => $winorfalse]]);
  106. $money += $peilvretarr['returnMoney'] * $sval->bet_money;
  107. $allgame_status++;
  108. }
  109. }
  110. }
  111. $allgame_status = ($allgame_status>0 ) ? 1 : 2 ;
  112. $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' ";
  113. $this->sqlArray[] = $sql ;
  114. if ($money >0){
  115. $this->sql_accountdetail_money($val->account_identity,$money);
  116. $this->sql_moneydetail_log($val,null,$money);
  117. }
  118. return true;
  119. }
  120. }
  121. //串式订单结算处理
  122. private function Settlement_str($game_type,$match_id){
  123. $matchModels = DB::table('money_buy_match')->where(['match_id'=>$match_id,'bet_type'=>2,'game_code'=>$game_type])->get();
  124. if (empty($matchModels)) { return true; }
  125. $batch_ids_array = [] ;
  126. $matchKeyModels = [] ;
  127. foreach ($matchModels as $val){
  128. $matchKeyModels[$val->batch_id][] = $val ;
  129. if (!in_array($val->batch_id,$batch_ids_array)){
  130. $batch_ids_array[] = $val->batch_id;
  131. }
  132. }
  133. $buyModels = DB::table('money_buy_str')->whereIn( 'batch_id',$batch_ids_array)->get();
  134. $buyKeyModels = [] ;
  135. if (empty($buyModels)) { return true ; }
  136. foreach ($buyModels as $val){
  137. $buyKeyModels[$val->batch_id][] = $val ;
  138. }
  139. foreach ($matchKeyModels as $key=>$sval_2){
  140. foreach ($sval_2 as $sval){
  141. if ( $sval->match_id != $this->match_id ){ continue ; }
  142. $winorfalse = $this->winOrfalseInfo($sval);
  143. if (!in_array($winorfalse,[-1,1,2,3,4])){ throw new \Exception('胜负规则结果数据错!',4005); }
  144. $this->makesql_up_buymatch_winorfalse($sval->id,$winorfalse,date("Y-m-d H:i:s"));
  145. $sql = "update money_buy_str set wait_match_num=wait_match_num-1 where batch_id=$sval->batch-id ";
  146. $this->sqlArray[] = $sql ;
  147. $sval->result = $winorfalse ;
  148. if ($winorfalse == -1){
  149. //一条出错,全部作为错误处理
  150. $this->makesql_up_serial_lose($sval);
  151. break;
  152. }
  153. if (!isset($buyKeyModels[$key]['0'])){ throw new \Exception('购买主记录不存在,数据有问题');}
  154. if ($buyKeyModels[$key]['0']->wait_match_num <=1 ){
  155. $oddsarr = [];
  156. //串式最后一条记录了,需要做结算处理了
  157. foreach ( $matchKeyModels[$key] as $fval){
  158. $oddsarr[] = ['odds'=>$fval->odds,'winOrLose'=>$fval->result] ;
  159. $peilvArray = $this->winOddsCalculation($oddsarr);
  160. }
  161. foreach ($buyKeyModels[$key] as $buyModel){
  162. $money = sprintf("%.2f",$buyModel->money * $peilvArray['returnMoney']) ;
  163. $sql = "update money_buy_str set gain_money=$money,game_status=1 where batch_id='$key' and id=$buyModel->id ";
  164. $this->sqlArray[] = $sql ;
  165. $this->sql_accountdetail_money($buyModel->account_identity,$money);
  166. $this->sql_moneydetail_log($buyModel,null,$money);
  167. }
  168. break;
  169. }
  170. }
  171. }
  172. }
  173. //输赢结果判断 $sval 为 money_buy_match Model; 结果为 -1输 1赢 2平 3赢半平半 4输半平半
  174. private function winOrfalseInfo($sval){
  175. $fun = $sval->odds_code ;
  176. $fun2 = $sval->p_code ;
  177. if ($sval->p_code != 'gj'){
  178. if (empty($this->resultModel) || empty($this->resultRecords)){
  179. throw new \Exception('非冠军比赛结果数据不能为空');
  180. }
  181. if ( $this->RefClass->hasMethod($fun) ){
  182. $winorfalse = $this->AdapterObj->$fun($sval,$this->resultModel,$this->resultRecords);
  183. }elseif ( $this->RefClass->hasMethod($fun2) ){
  184. $winorfalse = $this->AdapterObj->$fun2($sval,$this->resultModel,$this->resultRecords);
  185. }else{
  186. throw new \Exception('没有找到玩法输赢判断规则',40010);
  187. }
  188. }else{
  189. $this->getGjDatas($sval);
  190. if (empty($this->gjModel)){
  191. throw new \Exception('冠军比赛结果数据不能为空');
  192. }
  193. if ( $this->RefClass->hasMethod($fun) ){
  194. $winorfalse = $this->AdapterObj->$fun($sval,$this->gjModel,[]);
  195. }elseif ( $this->RefClass->hasMethod($fun2) ){
  196. $winorfalse = $this->AdapterObj->$fun2($sval,$this->gjModel,[]);
  197. }else{
  198. throw new \Exception('没有找到玩法输赢判断规则',40010);
  199. }
  200. }
  201. return $winorfalse ;
  202. }
  203. /**
  204. * 注单返现计算
  205. * @param mixed $dataArray 结果表数据 [['odds'=>xx,'winOrLose'=>1],[...]];
  206. * @return array 注单返现额
  207. */
  208. private function winOddsCalculation($dataArray){
  209. $returnMoney = 1;
  210. // 循环计算每注返现赔率
  211. foreach ($dataArray as $value) {
  212. $odds = floatval($value['odds']);
  213. // 因结果不同更改赔率
  214. switch (intval($value['winOrLose'])) {
  215. case 1:
  216. $oddsDiscount = 1 + $odds * 1;
  217. break;
  218. case 2:
  219. $oddsDiscount = 1;
  220. break;
  221. case 3:
  222. $oddsDiscount = 1 + $odds * 0.5;
  223. break;
  224. default:
  225. $oddsDiscount = 0.5;
  226. }
  227. // 计算每注返现
  228. $returnMoney = $returnMoney * $oddsDiscount;
  229. }
  230. // 计算赚钱
  231. $earnMoney = $returnMoney - 1;
  232. return ['earnMoney' => $earnMoney, 'returnMoney' => $returnMoney];
  233. }
  234. /**
  235. * UUID 生成
  236. */
  237. public static function UUID() {
  238. $prefix = '';
  239. $uuid = '';
  240. $str = md5(uniqid(mt_rand(), true));
  241. $uuid = substr($str, 0, 8) . '-';
  242. $uuid .= substr($str, 8, 4) . '-';
  243. $uuid .= substr($str, 12, 4) . '-';
  244. $uuid .= substr($str, 16, 4) . '-';
  245. $uuid .= substr($str, 20, 12);
  246. return $prefix . $uuid;
  247. }
  248. private function sql_accountdetail_money($acount ,$moneycg){
  249. $sql = "update account_detailed set available_cash=available_cash+$moneycg,cash=cash+$moneycg where account_identity='$acount' ";
  250. $this->sqlArray[] = $sql ;
  251. }
  252. private function sql_moneydetail_log($allbuyModel,$model,$money_diff){
  253. $uuid = self::UUID();
  254. $dtime = date("Y-m-d H:i:s");
  255. $detailModel = DB::table('account_detailed')->where('account_identity',$allbuyModel->account_identity)->first();
  256. if (!$detailModel){
  257. throw new \Exception('查无此用户数据account_detail='.$allbuyModel->account_identity,41002);
  258. }
  259. $money_cash = $detailModel->cash ;
  260. $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";
  261. $SQL .= "('$uuid','$allbuyModel->order_id','$allbuyModel->account_name','$allbuyModel->account_identity','$money_diff','$dtime',1,'中奖收入','1','$money_cash',4)" ;
  262. $this->sqlArray[] = $SQL ;
  263. }
  264. //生成串式失败的逻辑sql;
  265. private function makesql_up_serial_lose($model){
  266. $batchid = $model->batch_id ;
  267. $sql = "update money_buy_match set result=-1 where bet_type=2 and batch_id=$batchid ";
  268. $this->sqlArray[] = $sql;
  269. $sql = "update money_buy_str set game_status=3,wait_match_num=0 where batch_id=$batchid ";
  270. $this->sqlArray[] = $sql ;
  271. return true ;
  272. }
  273. private function makesql_up_buymatch_winorfalse($id,$result,$utime){
  274. $sql = " update money_buy_match set result=$result,utime=$utime where id=$id limit 1";
  275. $this->sqlArray[] = $sql;
  276. return true;
  277. }
  278. //设置 输赢 解析规则适配器
  279. private function setAdapterObj($game_type){
  280. $game_type = strtolower($game_type);
  281. if ( !isset($this->gameAllMap)){ throw new \Exception('赛事类型错误-'.$game_type,4002); return false; }
  282. switch ($game_type){
  283. case 'bq':
  284. $this->AdapterObj = new BqRule();
  285. break;
  286. case 'lq':
  287. $this->AdapterObj = new LqRule();
  288. break;
  289. case 'wq':
  290. $this->AdapterObj = new WqRule();
  291. break;
  292. case 'zq':
  293. $this->AdapterObj = new ZqRule();
  294. break;
  295. }
  296. return true ;
  297. }
  298. //返回数据
  299. private function makeData($status=1,$message='success',$data=''){
  300. return [
  301. 'status' => $status ,
  302. 'message' =>$message,
  303. 'data' => $data ,
  304. ] ;
  305. }
  306. //写处理状态
  307. public function writeStatusBegin($comendnticeModel){
  308. $comendnticeModel->status = 1 ;
  309. $comendnticeModel->done_time = date("Y-m-d H:i:s");
  310. $comendnticeModel->pcount ++ ;
  311. $comendnticeModel->logs = 'begin|';
  312. $ret = $comendnticeModel->save();
  313. return $ret;
  314. }
  315. //写处理状态结束
  316. public function writeStatusEndOk($comendnticeModel){
  317. $comendnticeModel->status = 4 ;
  318. $comendnticeModel->done_time = date("Y-m-d H:i:s");
  319. $comendnticeModel->logs = $comendnticeModel->logs.'end ok';
  320. $ret = $comendnticeModel->save();
  321. return $ret;
  322. }
  323. //是否有需要进行结果算处理的赛事记录
  324. public function getComendNoticeModel(){
  325. $ret = (new ComendnoticeModel())->where('status',0)->orderby('id','asc')->first();
  326. $this->ComendNoticModel = $ret;
  327. return $ret;
  328. }
  329. //获取到某个用户的account模型和detail模型,用于用户的余额计算等使用
  330. public function getUserInfo($account_name){
  331. if (isset($this->AccountArrays[$account_name])){
  332. return $this->AccountArrays['$account_name'];
  333. }
  334. $accountModel = DB::table('account')->where('account',$account_name)->first();
  335. if (!$accountModel){
  336. throw new \Exception('查无此用户数据account='.$account_name,41002);
  337. }
  338. $detailModel = DB::table('account_detailed')->where('account_identity',$accountModel->identity)->first();
  339. if (!$detailModel){
  340. throw new \Exception('查无此用户数据account_detail='.$accountModel->identity,41002);
  341. }
  342. $ret = [
  343. 'account'=>$detailModel,
  344. 'detail' => $detailModel ,
  345. ];
  346. $this->AccountArrays[$account_name] = $ret ;
  347. $this->AccountArrays[$accountModel->identity] = $ret ;
  348. return $ret;
  349. }
  350. //获取到某个用户某个赛事的下单记录集[]
  351. public function GetMatchBatchIdArrays($batch_id,$type){
  352. if (isset($this->MatchBatchIdArrays[$type][$batch_id])){
  353. // return $this->MatchBatchIdArrays[$type][$batch_id];
  354. }
  355. $all = DB::table("money_buy_match")->where(['batch_id',$batch_id,'result'=>0])->get();
  356. if (!$all) {
  357. throw new \Exception('无效的Money_buy_str->batch_id='.$batch_id , 41001);
  358. }
  359. $this->MatchBatchIdArrays[$type][$batch_id] = $all ;
  360. return $all ;
  361. }
  362. //根据购买批次 获取下单信息
  363. public function GetBuyStrBatchIdArrays($batch_id,$type){
  364. if (isset($this->BuyStrBatchIdArrays[$batch_id])){
  365. // return $this->BuyStrBatchIdArrays[$batch_id];
  366. }
  367. if ($type==2)
  368. {
  369. $all = DB::table("money_buy_str")->where(['batch_id'=>$batch_id,'game_status'=>0])->get();
  370. }else{
  371. $all = DB::table("money_buy_simplex")->where(['batch_id'=>$batch_id,'game_status'=>0])->get();
  372. }
  373. if (!$all) {
  374. throw new \Exception('无效的batch_id='.$batch_id , 41001);
  375. }
  376. // $this->BuyStrBatchIdArrays[$batch_id] = $all ;
  377. return $all ;
  378. }
  379. //得到比赛最终结果记录 和 中间结果记录
  380. public function getCompResult($type,$match_id){
  381. $model = null ;
  382. switch ($type){
  383. case 'bq':
  384. $model = DB::table('st_bq_result')->where('match_id',$match_id)->first();
  385. $models = DB::table('st_bq_result_record')->where('match_id',$match_id)->orderBy('id','asc')->get()->toArray();
  386. break;
  387. case 'lq':
  388. $model = DB::table('st_lq_result')->where('match_id',$match_id)->first();
  389. $models = DB::table('st_lq_result_record')->where('match_id',$match_id)->orderBy('id','asc')->get()->toArray();
  390. break;
  391. case 'wq':
  392. $model = DB::table('st_wq_result')->where('match_id',$match_id)->first();
  393. $models = DB::table('st_wq_result_record')->where('match_id',$match_id)->orderBy('id','asc')->get()->toArray();
  394. break;
  395. case 'zq':
  396. $model = DB::table('st_zq_result')->where('match_id',$match_id)->first();
  397. $models = DB::table('st_zq_result_record')->where('match_id',$match_id)->orderBy('id','asc')->get()->toArray();
  398. break;
  399. }
  400. /*
  401. if (empty($model) || empty($models)){
  402. throw new \Exception('没找到比赛结果记录match_id_'.$type.'-'.$match_id,4007);
  403. return false;
  404. }
  405. */
  406. $this->resultModel = $model;
  407. $this->resultRecords = $models ;
  408. $ret = [
  409. 'result' => $model,
  410. 'records' => $models ,
  411. ];
  412. return $ret;
  413. }
  414. //冠军比赛结果
  415. public function getGjDatas($matchModel){
  416. if ( !empty($this->gjModel) ) { return $this->gjModel ; }
  417. $table = 'st_'.$matchModel->game_code.'_league_result';
  418. $where = ['lg_id'=>$matchModel->lg_id,'game_name'=>$matchModel->odds_code];
  419. $model = DB::table($table)->where($where)->first();
  420. if (!empty($model)){
  421. $this->gjModel = $model ;
  422. }
  423. return $model ;
  424. }
  425. }