SettlementSql.php 18 KB

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