SettlementSql.php 18 KB

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