<?php
namespace App\Api\Controller;

use Biz\Money\Moneycopy;
use Biz\Money\Money;
use Biz\Account\AccountManager;
/*
 * Class Register
 * @package App\Api\Controller
 * User: junghwi
 * Date: 2019/3/21
 */
class Betorder extends BaseController{

    private $simplex_money = 0; //单式投注总额
    public function init() {
        $this->time = date('Y-m-d H:i:s',time());
        $this->MC = new Moneycopy();
        $this->M = new Money();
        $this->accountManager = new AccountManager();
        $this->commonFunction =  C()->get('commonFunction');

    }
    /**
     * 单式串式分类
     * @param  [array] $res 投注数据
     * @return  [array] $data
     *
     */
    public function Classify(array $res){
        if(empty($res)){
            Render('', '7003',lang('Errors','Api')->get('error-7003'));
        }
        $data['single'] = [];//单式
        $data['bunch'] = [];//串式
        $last[] = $res[count($res)-1];
        unset($res[count($res)-1]);
        foreach ($last as $k =>$v){
            foreach ($v as $kk =>$vv){
                $num = $kk+1;
                //验证联赛是否存在
                $this->verify_league($vv['ballId'],(int)$vv['lg_id'],$num);
                //验证赛事是否存在
                $this->verify_match($vv['ballId'],$vv['match_id'],$num);
                //验证球类代码是否有效
                $this->verify_gameType($vv['ballId'],$num);
                //验证赛事下赔率玩法是否有效
                $this->verify_odds($vv['ballId'],$vv['odds_only'],$vv['odds'],$vv['condition'],$num);
            }
        }
        foreach($res as $k => $v){
            //根据类型分组
            if($v['type'] == '1'){
                $data['single'][$k] = array_merge($last[0][$v['index']],$v);
            }else{
                $data['bunch'][$k] = $v;
            }
        }
        if(!empty($data['bunch'])){
            $data['bunch'] = array_merge_recursive($data['bunch'],$last);
        }
        return $data;
    }

    /**
     * 根据赛事ID分组
     * @param  [array] $data 球类数据
     * @return  [array] $data
     */
    public function Group_ball($data = []){
        if(empty($data)){
            return $data;
        }
        foreach($data as $k => $v){
            if(!isset($data[$v['match_id']])){
                $data[$v['match_id']][] = $v;
                unset($data[$k]);
            }else{
                $data[$v['match_id']][] = $v;
                unset($data[$k]);
            }
        }
        return $data;
    }

    /**
     * 单式投注数据处理
     * @param  [array] $res 单式投注数据
     * @return  [int] 1 成功 其他失败
     * @param  [int]  $batch_id 批量ID
     */
    public function Simplex_bet(array $res,array $userInfo,$batch_id){
        if(empty($res)||empty($userInfo)||empty($batch_id)){
            Render('', '7003',lang('Errors','Api')->get('error-7003'));
        }
        //验证与判断投注了几种
        foreach($res as $k => $v){
            $num = $k + 1;
            if(empty($v['bet_amount'])){
                $msg = '第'.$num.'条'.lang('Errors','Api')->get('error-5105');
                Render([], '5105',$msg);
            }
            //根据类型分组
            if(!isset($res[$v['ballId']])){
                $res[$v['ballId']][] = $v;
                unset($res[$k]);
            }else{
                $res[$v['ballId']][] = $v;
                unset($res[$k]);
            }

        }
        //球类联赛分类并且插入数据库
        foreach($res as $k => $v){
            $gamedate = $this->Group_ball($res[$k]);
            $this->Simplex_bet_insert($gamedate,$userInfo,$k,$batch_id);
        }
    }

    /**
     * 单式投注单个球类数据插入
     * @param  [array] $data 单式投注数据
     * @param  [array] $userInfo 用户信息
     * @param  [type] $game_code 球类代码
     * @param  [int]  $batch_id 批量ID
     * @return  [int] 1 成功 其他失败
     */
    public function Simplex_bet_insert($data,$userInfo,$game_code,$batch_id){
        if(empty($data)||empty($userInfo)||empty($game_code)){
            Render('', '7003',lang('Errors','Api')->get('error-7003'));
        }
        foreach($data as $k => $v){
            $OrderID = OrderID();//生成订单ID
            $UUID = UUID(); //生成信息ID
            $bet_money = 0; //赛事总投注额
            $prize_money = 0; //可赢额
            foreach($v as $kk => $vv){
                $bet_money += $vv['bet_amount'];
                $prize_money +=  $vv['odds']* $vv['bet_amount'];
                $matchData =[
                    'odds_id' =>$vv['id'],
                    'home_team' => $vv['home_team'],
                    'guest_team' => $vv['guest_team'],
                    'condition' => $vv['condition'],
                    'odds' => $vv['odds'],
                    'odds_code' => $vv['odds_code'],
                    'p_code' => $vv['p_code'],
                    'odds_only' => $vv['odds_only'],
                    'match_id' => $vv['match_id'],
                    'game_code' => $game_code,
                    'lg_id' => $vv['lg_id'],
                    'batch_id' => $batch_id,
                    'bet_type' => 1,
                    'bet_money' => $vv['bet_amount'],
                    'ctime' => $this->time,
                    'utime' => $this->time
                ];
                //插入数据源
                $moneyBuyMatch = lm('MoneyBuyMatch','Api')->insert($matchData);
                if(!$moneyBuyMatch){
                    Render('','3205',lang('errors','Api')->get('error-3205'));
                }
            }
            $order =[
                'info_identity' => $UUID,
                'account_name' => $userInfo['account'],
                'account_identity' => $userInfo['account_identity'],
                'order_id' => $OrderID,
                'game_code' => $game_code,
                'batch_id' => $batch_id,
                'match_id' => $k,
                'game_no'  => "",
                'prize_money'=> $prize_money,
                'money' => $bet_money, //投注金额
                'money_time' => $this->time
            ];
            $insert = lm("MoneyBuySimplex",'Api')->insert($order);
            if(!$insert){
                Render('','3205',lang('errors','Api')->get('error-3205'));
            }
            $insertMoney  = $this->M->insertMoney($userInfo['account_identity'],$bet_money,$OrderID,1,"",$UUID,$userInfo);
            if($insertMoney!=1){
                Render('', $insertMoney,lang('Errors','Api')->get('error'.$insertMoney));
            }
            $this->M->fanshui($userInfo['account_identity'],$userInfo['account'],$bet_money,$OrderID);//反水
        }
    }

    public function Bet(){

        $userInfo = $this->getAgent();//获取用户信息
        $data = $_REQUEST['data'];
        $bet_money = $_REQUEST['bet_money'];
        if(empty($data)||empty($bet_money)){
            Render('', '51029',lang('Errors','Api')->get('error-51029'));
        }
        //获取用户金额信息
        if(!$this->M->verifyMoney($bet_money,$userInfo['cash'])){
            Render('', '4204',lang('Errors','Api')->get('error-4204'));
        }
        $batch_id = strtotime(date('Y-m-d H:i:s',time())).mt_rand('1','99');//批量ID
        //执行数据插入
        try {
            _beginTransaction();//开启事务
            $data = $this->Classify($data);
            if(!empty($data['single'])){
                $this->Simplex_bet($data['single'],$userInfo,$batch_id);//单式数据处理
            }
            if(!empty($data['bunch'])){
                $data_all = $data['bunch'][count($data['bunch'])-1];//获取最后一个数组
                unset($data['bunch'][count($data['bunch'])-1]);//删除最后一个元素
                $this->stringBet($data['bunch'],$data_all,$userInfo,$batch_id);
            }
            _commit();//提交
            Render('', '1',lang('Errors','Api')->get('error-1'));
        } catch (Exception $e) {
            _rollBack();//回滚
            print $e->getMessage();
        }
}

    /**
     * token获取用户详情
     */
    public function getAgent() {
        $checkToken = $this->accountManager->checkEffectiveTime();
        if ($checkToken['status'] != 1) {
            Render($checkToken['data'], $checkToken['status'], lang('commons')->get('user does login'));
        };
        $result = $this->accountManager->refreshToken();
        return $result['data'];
    }

    //验证联赛是否存在
    public function verify_league($game_code,$lg_id,$num = 1){
        if(empty($lg_id)){
            $msg = '第'.$num.'条'.lang('Errors','Api')->get('error-5112');
            Render([], '5112',$msg);
        }

        //根据球类代码 获取相关model
        $model = $this->commonFunction->getModels($game_code);
        $model_league = $model['model_league'];
        $info = lm($model_league,'Sports')
            ->select('id')
            ->where('lg_id',$lg_id)
            ->first();
        if(empty($info)){
            $msg = '第'.$num.'条'.lang('Errors','Api')->get('error-5113');
            Render([], '5113',$msg);
        }
    }

    /**
     * 赛事是否存在或结束
     * @param  [type] $game_code 球类代码
     * @param  [type] $match_id  赔率ID
     * @param  [type] $num 循环键值
     * $@param  [type]type_str 串式
     *
     */
    public  function verify_match($game_code,$match_id,$num = 1){
        if(empty($match_id)){
                $msg = '第'.$num.'条'.lang('Errors','Api')->get('error-5109');
                Render([], '5109',$msg);
        }
        //根据球类代码 获取相关model
        $models = $this->commonFunction->getModels($game_code);
        $model_match = $models['model_match'];
        $info = lm($model_match,'Sports')
            ->select('status')
            ->where('status', '<', '2')
//            ->where('us_time','>',qgmdate('Y-m-d H:i:s','', -4))
            ->where('source','hg3535')
            ->where('match_id',$match_id)
            ->first();
        if(empty($info)){
            $msg = '第'.$num.'条'.lang('Errors','Api')->get('error-5103');
            Render([], '5103',$msg);
        }
        $info = $info->toarray();
        if($info['status'] == 2){
            $msg = '第'.$num.'条'.lang('Errors','Api')->get('error-5108');
            Render([], '5108',$msg);
        }
        return $info;
    }

    /**
     * 验证球类是否存在
     * @param  [type] $game_code 球类代码
     * @param  [type] $num 第几条
     */
    public  function verify_gameType($game_code,$num){
        if(empty($game_code)){
            $msg = '第'.$num.'条数据'.lang('Errors','Api')->get('error-5102');
            Render([], '5102', $msg);
        }
        $info = lm('GameType','Sports')->where('game_code',$game_code)->first();
        if(empty($info)){
            $msg = '第' . $num . '条数据' . lang('Errors', 'Api')->get('error-5102');
            Render([], '5102', $msg);
        }
        return $info;
    }

    /**
     * 验证赔率是否存在
     * @param  [type] $game_code 球类代码
     *  @param  [type] $odds_id 赔率IDkk
     *
     */
    public function verify_odds($game_code,$odds_only,$odds,$condition,$num = 1){
        if (empty($odds_only)){
            $msg = '第'.$num.'条数据'.lang('Errors','Api')->get('error-5111');
            Render([], '5111', $msg);
        }
        if(empty($odds)){
            $msg = '第'.$num.'条数据'.lang('Errors','Api')->get('error-7029');
            Render([], '7029', $msg);
        }
        //根据球类代码 获取相关model
        $models = $this->commonFunction->getModels($game_code);
        $model_odds = $models['model_odds'];
        $model_odds_record = $models['model_odds_record'];
        //匹配赔率是否过期
        $odds_info = lm($model_odds,'Sports')
            ->join($model_odds_record,$model_odds_record.'.odds_only',$model_odds.'.odds_only')
            ->select($model_odds_record.'.odds',$model_odds_record.'.condition')
            ->where($model_odds.'.odds_only',$odds_only)
            ->first();
        if(empty($odds_info)){
            $msg = '第'.$num.'条数据'.lang('Errors','Api')->get('error-7051');
            Render([], '7051', $msg);
        }
        $odds_info = $odds_info->toarray();
        if($condition != $odds_info['condition']){
            $msg = '第'.$num.'条数据'.lang('Errors','Api')->get('error-7047');
            Render([], '7047', $msg);
        }
        if($odds != $odds_info['odds']){
            $msg = '第'.$num.'条数据'.lang('Errors','Api')->get('error-7049');
            Render([], '7049', $msg);
        }
        return $odds_info;
    }

    /**
     * 处理串式投注
     * $data_str 各串式 数据
     * $data_all 所有赛事 数据
     * $userInfo 用户数据
     * $batch_id 批次号
     */
    public function stringBet($data_str=[],$data_all=[],$userInfo=[],$batch_id=0){
        //验证串式投注是否合法
        $this->verify_stringType($data_all);
        //获取串式 总赛事数量
        $groupNum = count($data_all);//总数量

        $orderData = [];
        foreach ($data_str as $k=>$v){
            //字符串替换
            $str = str_ireplace("串","_",$v['type']);
            //获取type 3_12
            $after = substr($str,strpos($str,"_")+1);
            //当前串式 值
            $sonNum = substr($str,0,strrpos($str,"_"));
            //获取倍数
            if((int)$after == 1){
                $multiple = $this->getMultiple($groupNum,(int)$sonNum);
            }else{
                $multiple =(int)$after;
            }

            //获取当前串式投注金额及可赢金额
            if($after == 1){
                $money_all = $this->getmakeMoney((int)$sonNum,$v['bet_amount'],$multiple,$data_all,$after);
            }else{
                $money_all = $this->getStrAllMoney((int)$sonNum,$v['bet_amount'],$multiple,$data_all,$after);
            }
            //投注金额
            $moneyData = $money_all['moneyData'];
            //可赢金额
            $prize_money = $money_all['prize_money'];
            $uuid = UUID();
            $orderID = OrderID();

            $orderData[$k]['info_identity'] = $uuid;
            $orderData[$k]['account_name'] = $userInfo['account'];
            $orderData[$k]['account_identity'] = $userInfo['account_identity'];
            $orderData[$k]['order_id'] = $orderID;
            $orderData[$k]['game_no'] = "";
            $orderData[$k]['money'] = $moneyData;//$pay_money//总投注金额
            $orderData[$k]['money_time'] = $this->time;//下注时间
            $orderData[$k]['prize_money'] = $prize_money;//$expect_money ;//预期总可赢金额
            $orderData[$k]['str_type'] = $v['type'];//串式类型
            $orderData[$k]['batch_id'] = $batch_id;//批次号
            $orderData[$k]['wait_match_num'] = count($data_all);//批次号

            //写资金变动表
            $insertMoney  = $this->M->insertMoney($userInfo['account_identity'],$moneyData,$orderID,1,"",$uuid,$userInfo);
            if($insertMoney!=1){
                Render('', $insertMoney,lang('Errors','Api')->get('error'.$insertMoney));
            }
            $this->M->fanshui($userInfo['account_identity'],$userInfo['account'],$moneyData,$orderID);//反水
        }

        //写注单 表
        $moneyBuy = lm('MoneyBuyStr','Api')->insert($orderData);

        if(!$moneyBuy){
            Render('','3205',lang('errors','Api')->get('error-3205'));
        }


        foreach ($data_all as $kk=>$vv){
            $getModels = $this->commonFunction->getModels($vv['ballId']);
            $model_match = $getModels['model_match'];

            $matchData[] = [
                'batch_id'=>$batch_id,
                'odds_id'=>$vv['id'],
                'home_team'=>$vv['home_team'],
                'guest_team'=>$vv['guest_team'],
                'condition'=>$vv['condition'],
                'odds'=>$vv['odds'],
                'odds_code'=>$vv['odds_code'],
                'p_code'=>$vv['p_code'],
                'odds_only'=>$vv['odds_only'],
                'status'=>0,
                'match_id'=>$vv['match_id'],
                'game_code'=>$vv['ballId'],
                'lg_id'=> $vv['lg_id'],//lm($model_match,"Sports")->select('lg_id')->where('match_id',$vv['match_id'])->first()->lg_id,
                'ctime'=>$this->time,//写入时间
                'utime' => $this->time,
                'bet_type'=>2
            ];
        }
        //写赔率数据表
        $moneyBuyMatch = lm('MoneyBuyMatch','Api')->insert($matchData);
        if(!$moneyBuyMatch){
            Render('','3205',lang('errors','Api')->get('error-3205'));
        }

        return true;
    }

    /**
     * 计算串式投注 倍率
     * $groupNum 总赛事 数量
     * $sonNum 当前串式 数量
     */
    public function getMultiple($groupNum = 0,$sonNum = 0){

        if($groupNum and $sonNum){
            $group =1;
            for($i = $groupNum ; $i >($groupNum - $sonNum);$i--) {
                $group = $group * $i;
            }

            $son =1;
            for($i = $sonNum ; $i >0;$i--) {
                $son = $son * $i;
            }
        }
        return $group/$son;
    }

    /**
     * @param int $sonNum 当前串式数量
     * @param int $bet_amount 当前串式投注额
     * @param int $multiple 当前串式倍数
     * @param array $data_all 当前注单 所有投注数据
     * @return mixed
     * 计算当前串式投注总额、可赢总额
     */
    public function getmakeMoney($sonNum=0,$bet_amount=0,$multiple=0,$data_all=[],$after = 0){
        $allNum = count($data_all);//所有数量
        $odds_all = [];//所有投注项数据
        foreach ($data_all as $k=>$v){
            $odds_all[] = $v['odds']+1;
        }
        //投注总额
        $data['moneyData'] = (double)$bet_amount*(double)$multiple;
        if($sonNum == $allNum and (int)$after ==1){//N场赛事  N串一
            //获取所有赛事赔率乘积
            $odds = array_product($odds_all) - 1;
            //获取可赢金额
            $data['prize_money'] =  sprintf("%.2f",substr(sprintf("%.3f", $bet_amount*$odds), 0, -1));//floor($bet_amount*$odds*100)/100;//保留两位小数
        }

        if($sonNum < $allNum and (int)$after ==1){//例:N场赛事 <N串一
            $group = $this->commonFunction->combination($odds_all, $sonNum);

            foreach ($group as $k=>$v){
                $odds[] = array_product($v);
            }
            $odds = (array_sum($odds))-(count($odds));

            //获取可赢金额
            $data['prize_money'] =  sprintf("%.2f",substr(sprintf("%.3f", $bet_amount*$odds), 0, -1));//floor($bet_amount*$odds*100)/100;
        }

        return $data;
    }

    /**
     * 获取所有可用串式  N场赛事 2串1，3串1...N串1，N<11
     * 并计算 其投注可赢金额
     */
    public function getStrAllMoney($sonNum=0,$bet_amount=0,$multiple=0,$data_all=[],$after = 0){
        $d = [];
        for ($i=2;$i<($sonNum+1);$i++){
            $d[] = $i;
        }

        foreach ($d as $k=>$v){
            $multiple = $this->getMultiple($sonNum,$v);
            $money[] = $this->getmakeMoney($v,$bet_amount,$multiple,$data_all,1);
        }
        $data=array();
        foreach($money as $k=>$v){
            $data['moneyData']+=$v['moneyData'];
            $data['prize_money']+=$v['prize_money'];
        }
        return $data;
    }

    /**
     * 验证串式投注 是否合法
     * $data 串式 所有赛事
     */
    public function verify_stringType($data=[]){
        if($data){
            foreach($data as $k=>$v){
                if($v['match_id']==$v['match_id']){
                    $r[$v['match_id']][] = $v;
                }
            }
        }
        if($r){
            foreach ($r as $k=>$v){
                if(count($v) > 1){
                    $msg = lang('Errors','Api')->get('error-50038');
                    Render([], '50038',$msg);
                }
            }
        }
    }

    /**
     * 更新投注项相关数据
     */
    public function getBetData(){
        $data = $_REQUEST;
//        $data = [['game_code'=>'zq','match_id'=>3095448,'odds_id'=>623078],['game_code'=>'zq','match_id'=>3095448,'odds_id'=>623078]];
        foreach ($data as $k=>$v){
            $getModels = $this->commonFunction->getModels($v['game_code']);
            $model_match = $getModels['model_match'];
            $model_odds = $getModels['model_odds'];

            $oddsData = lm($model_match,"Sports")
                ->join($model_odds,$model_odds.'.match_id',$model_match.'.match_id')
                ->select($model_match.'.match_id',$model_match.'.match_date',$model_match.'.home_team',$model_match.'.guest_team',$model_odds.'.id as odds_id',$model_odds.'.p_code',$model_odds.'.odds_code',$model_odds.'.condition',$model_odds.'.odds',$model_odds.'.odds_only',$model_odds.'.status',$model_odds.'.sort')
                ->where($model_match.'.source',$this->source)
                ->where($model_match.'.match_id',$v['match_id'])
                ->where($model_odds.'.id',$v['odds_id'])
                //->where($model_odds.'.expire_time','>',date("Y-m-d H:i:s"))
                ->first();
            $oddsData->game_code = $v['game_code'];

            $betData[] = $oddsData;
        }

        Render($betData, '1', lang('Tips','Sports')->get('success'));
    }

}

