<?php
namespace App\Models;
use DB;
class NagentCountrecord extends BaseModel {

	protected $table = "nagent_countrecord";
	public $timestamps = false;
	
	//验证游戏对应期号代理业绩是否统计
	protected function checkIscount($game,$no){
		$res = $this->where('game',$game)->where('no',$no)->first();
		if($res && $res->status==1)return -8505013002;	//本期游戏已统计
		if(!$res)return array();
		return $res->toArray();
	}

	//获取对应游戏对应期代理业绩
	protected function getWaterBygn($game,$no,$uid='',$page=1,$total=1){
        DB::connection()->enableQueryLog();
        $buyobj = '\App\Models\Game' . ucfirst($game) . '_Buy'; //游戏注单表模型
        $buyinfo = $buyobj::select(DB::raw("cast(account_identity as uuid),sum(money) as money"));    //投注数据获取
        if(!empty($uid)){
            $buyinfo = $buyinfo->where('account_identity',$uid);    //获取指定用户注单数据
        }

        $nno = array();
        if(is_array($no)){  //多期游戏投注数据获取
        	$redata = array();
            $tno = array();
            if(!empty($uid)){
                $iscountno = $this->select('no')->where('game',$game)->where('status',1)->whereIn('no',$no)->get();
                if($iscountno && count($iscountno->toArray())>0){
                    foreach ($iscountno->toArray() as $k => $v) {
                        $tno[] = $v['no'];
                    }
                }
                foreach ($no as $k => $v) {
                    if(in_array($v, $tno))continue;
                    $nno[] = $v;
                }
            }
            //删除原已统计游戏期记录
        	$res = $this->where('game',$game)->whereIn('no',$no)->delete();

            //添加新统计游戏期记录
        	foreach ($no as $key => $value) {
        		$redata[] = array(
		            'game' => $game,
		            'no' => $value,
		            'status' => 1,
		        );
        	}
    		$res = $this->insert($redata);
    		if($res<0)return -8505013102;

            //按用户分组获取投注金额
        	$buyinfo = $buyinfo->whereIn('no',$no);
        }else{
            //验证并更新或添加游戏期统计记录
            if($page==1){
                $res = $this->checkUpinData($game,$no);
                if(is_numeric($res))return $res;
            }

            //按用户分组获取投注金额
        	$buyinfo = $buyinfo->where('no',$no);
            $sumcount = $buyinfo->where('delstatus',1)->groupBy('account_identity')->count();
            if(empty($sumcount) || $sumcount<1)return 1;
            $total = (empty($total) || !is_numeric($total) || $total<1)?1:$total;
            $page = (empty($page) || !is_numeric($page) || $page<1)?1:$page;
            $limit = ceil($sumcount/$total);
            $offset = ($page-1) * $limit;
            $buyinfo = $buyinfo->limit($limit)->offset($offset);
        }
        $buyinfo = $buyinfo->where('delstatus',1)->groupBy('account_identity')->get();
        /*$queries = DB::getQueryLog();
        print_r($queries);*/
        if(!$buyinfo || count($buyinfo->toArray())<1)return 1;
        $buyinfo = $buyinfo->toArray();
        if(!empty($nno)){
            $tbinfo = $buyobj::select(DB::raw("account_identity,sum(money) as money"))->where('delstatus',1)->where('account_identity','<>',$uid)->whereIn('no',$nno)->groupBy('account_identity')->get();
            if($tbinfo && count($tbinfo->toArray())>0)$buyinfo = array_merge($buyinfo,$tbinfo->toArray());
        }
        return $buyinfo;
	}

	//是否统计游戏对应期验证及更新
	protected function checkUpinData($game,$no){
		$record = $this->checkIscount($game,$no); //验证当期游戏数据是否已统计
        if($record<0)return 1;

        //更新或添加将统计期游戏记录
        $redata = array(
            'game' => $game,
            'no' => $no,
            'status' => 1,
        );
        $res = $this->addOrUpdate($record,$redata);
        if($res<0)return $res;
        return array();
	}

	//整理统一代理业绩数据
	protected function handleWater($gameinfo,$game,$arr,$uid=''){
		$sgi = array();   //按日期分组汇总年月日、对应日期期号组
		foreach ($gameinfo as $k => $v) {
			$date = date('Y-m-d',strtotime($v['open_time']));
			$sgi[$date]['open_time'] = $date;
			$sgi[$date]['no'][] = $v['info_no'];
		}

        //获取整理各用户对应日期业绩
		foreach ($sgi as $pk => $pv) {
			$buyinfo = $this->getWaterBygn($game,$pv['no'],$uid); //获取对应游戏指定期投注信息
            if(is_numeric($buyinfo))continue;

            foreach ($buyinfo as $k => $v) {
                if(empty($v['account_identity']))continue;
                $arr['buyinfo'][$v['account_identity']][$game] = $v['money'];
                if(!in_array($v['account_identity'], $arr['uid']))
                $arr['uid'][]  = $v['account_identity'];
                $arr['pid'][$v['account_identity']]  = array();
            }
		}
		return $arr;
	}

    //真人游戏代理业绩数据获取处理
    protected function getRealData($game,$arr,$stime,$etime,$uid=''){
        $date = date('Y-m-d',strtotime($stime));

        $buyobj = '\\App\\Model\\' . ucfirst($game) . '_betting_ogrbv'; //游戏注单表模型

        $stime = strtotime($stime);
        $etime = strtotime($etime);
        if($game=='kygame' || $game == 'lcqpgame'|| $game == 'lygame'){
            $tkey = 'GameEndTime';
            $buyinfo = $buyobj::select(DB::raw('cast(account_identity as uuid),sum("AllBet") as money'));    //投注数据获取
        }else if($game=='aggame'){
            $tkey = 'recalcuTime';
            $buyinfo = $buyobj::select(DB::raw('cast(account_identity as uuid),sum("betAmount") as money'));    //投注数据获取
        }else if($game=='hjgame'){
            $tkey = 'bet_time';
            $buyinfo = $buyobj::select(DB::raw('cast(account_identity as uuid),sum("bet_amount") as money'));    //投注数据获取
        }else{
            $tkey = 'AddTime';
            $buyinfo = $buyobj::select(DB::raw('cast(account_identity as uuid),sum("BettingAmount") as money'));    //投注数据获取
        }

        $updatestatus = $buyobj::where('count_status',2);
        if(!empty($uid)){
            $buyinfo = $buyinfo->where('account_identity',$uid);    //获取指定用户注单数据
            $updatestatus = $updatestatus->where('account_identity',$uid); 
        }

        //更新游戏统计状态为已统计
        $updatestatus = $updatestatus->update(['count_status'=>1]);
        if($updatestatus<0)return -8505013102;

        //按用户分组获取投注金额
        $buyinfo = $buyinfo->where($tkey,'>=',$stime)->where($tkey,'<=',$etime)->groupBy('account_identity')->get();
        /*$queries = DB::getQueryLog();
        print_r($queries);*/

        if(!$buyinfo || count($buyinfo->toArray())<1)return $arr;
        foreach ($buyinfo->toArray() as $k => $v) {
            if(empty($v['account_identity']))continue;
            $arr['buyinfo'][$v['account_identity']][$game] = $v['money'];
            if(!in_array($v['account_identity'], $arr['uid']))
            $arr['uid'][]  = $v['account_identity'];
            $arr['pid'][$v['account_identity']]  = array();
        }

        return $arr;
    }

    //代理业绩计算
    protected function CountWaters($uinfo,$ctime)
    {
        $nagent = '\App\Models\Nagent_detailed';
        $nagentwater = '\App\Models\Nagent_countwater';

        //获取已统计数据
        $waterInfo = $nagentwater::whereIn('count_time', array($ctime['wtime'],$ctime['ctime']))->whereIn('agent_identity', $uinfo['uid'])->get();
        $uwinfo = array();
        if($waterInfo && count($waterInfo->toArray())>0){
            foreach ($waterInfo->toArray() as $k => $v) {
                $uwinfo[$v['agent_identity']][$v['time_type']] = $v;
            }
        }
        //print_r($uwinfo);
        /*print_r($uinfo['uname']);
        print_r($uinfo['pid']);
        print_r($uinfo);exit;*/
        $indata = array();
        $udata = array();
        if (is_array($uinfo['pid']) && count($uinfo['pid']) > 0){
            foreach ($uinfo['pid'] as $pk => $pv) {
                //代理业绩统计
                $curmoney = $uinfo['buyinfo'][$pk];
                if(!isset($uwinfo[$pk][2])){
                    $user = $uinfo['uname'][$pk];
                    $type = 1;
                    $indata = $this->getAddData($curmoney, $user, $ctime['ctime'], $pk, $type,$indata);
                    if ($indata < 0)return $indata;

                    $indata = $this->getAddData($curmoney, $user, $ctime['wtime'], $pk, $type,$indata);
                    if ($indata < 0)return $indata;
                }else{
                    //周统计更新数据处理
                    $kwater = 'agent_water';
                    $type = 1;

                    //更新周统计
                    $uwinfo[$pk][2] = $this->UpdateCountData($uwinfo[$pk][2], $kwater, $curmoney);
                    if ($uwinfo[$pk][2] < 1)return $uwinfo[$pk][2];

                    //日统计数据处理
                    if (!isset($uwinfo[$pk][1])) {
                        $indata = $this->getAddData($curmoney, $uwinfo[$pk][2]['agent_user'], $ctime['ctime'], $pk, $type,$indata);
                        if ($indata < 0)return $indata;
                    } else {
                        //更新日统计
                        $uwinfo[$pk][1] = $this->UpdateCountData($uwinfo[$pk][1], $kwater, $curmoney);
                        if ($uwinfo[$pk][1] < 1)return $uwinfo[$pk][1];
                    }
                }

                //代理父级业绩统计
                $allpi = count($pv);
                if($allpi>0){
                    foreach ($pv as $k => $v) {
                        //$pk:用户ID；$v:父级ID
                        if(!isset($uwinfo[$v][2])){
                            $user = $uinfo['uname'][$v];
                            $type = (($k+1) == $allpi) ? 2 : 3;
                            
                            $indata = $this->getAddData($curmoney, $user, $ctime['ctime'], $v, $type,$indata);
                            if ($indata < 0)return $indata;

                            $indata = $this->getAddData($curmoney, $user, $ctime['wtime'], $v, $type,$indata);
                            if ($indata < 0)return $indata;
                        }else{
                            //周统计更新数据处理
                            $kwater = (($k+1) == $allpi) ? 'zt_water' : 'group_water';
                            $type = (($k+1) == $allpi) ? 2 : 3;

                            //更新周统计
                            $uwinfo[$v][2] = $this->UpdateCountData($uwinfo[$v][2], $kwater, $curmoney);
                            if ($uwinfo[$v][2] < 1)return $uwinfo[$v][2];

                            //日统计数据处理
                            if (!isset($uwinfo[$v][1])) {
                                $indata = $this->getAddData($curmoney, $uwinfo[$v][2]['agent_user'], $ctime['ctime'], $v, $type,$indata);
                                if ($indata < 0)return $indata;
                            } else {
                                //更新日统计
                                $uwinfo[$v][1] = $this->UpdateCountData($uwinfo[$v][1], $kwater, $curmoney);
                                if ($uwinfo[$v][1] < 1)return $uwinfo[$v][1];
                            }
                        }
                    }
                }
                
            }
        }
        
        //更新或添加统计数据：添加数据二维关联或索引数据；更新数据三维数据
        $res = $nagentwater::udadData($indata,$uwinfo);
        return $res;
    }

    //代理父级信息获取，处理代理业绩数据为ID=>金额形式
    protected function getNpinfo($arr){
        //获取代理父级信息
        $agent = \App\Models\Nagent_detailed::select('parent_path','agent_identity')->whereIn('agent_identity', $arr['uid'])->get();
        if (!$agent || count($agent->toArray()) < 1) {
            return 0;
        }

        foreach ($agent->toArray() as $k => $v) {
            $parent = explode(',', $v['parent_path']);
            foreach ($parent as $pk => $pv) {
                if(empty($pv) || $pv=='f615dac7-afd9-a3ad-7b73-030454bd159c' || is_numeric($pv))continue;
                $arr['pid'][$v['agent_identity']][] = $pv;
                if(!in_array($pv, $arr['uid']))$arr['uid'][] = $pv;
            }
        }

        $allainfo = \App\Models\Account::select('account','identity')->whereIn('identity', $arr['uid'])->get();
        if (!$allainfo || count($allainfo->toArray()) < 1) {
            return 0;
        }

        foreach ($allainfo->toArray() as $k => $v) {
            $arr['uname'][$v['identity']] = $v['account'];
        }
        return $arr;
    }

    //周统计、日统计数据更新
    protected function UpdateCountData($water,$kwater,$money,$dsum=0,$game=''){
        $gwater = json_decode($water['game_water'],1);
        if(is_array($money)){
            $allmoney = 0;
            foreach ($money as $k => $v) {
                $gwater[$k][$kwater] = isset($gwater[$k][$kwater])?$gwater[$k][$kwater]+$v:$v;
                if($kwater != 'agent_water'){
                    $gwater[$k]['sum_water'] = isset($gwater[$k]['sum_water'])?$gwater[$k]['sum_water']+$v:$v;
                    $dsum += $v;
                }
                $allmoney += $v;
            }
            $money = $allmoney;
        }else{
            $gwater[$game][$kwater] = isset($gwater[$game][$kwater])?$gwater[$game][$kwater]+$money:$money;
            $gwater[$game]['sum_water'] = isset($gwater[$game]['sum_water'])?$gwater[$game]['sum_water']+$dsum:$dsum;
        }

        $water[$kwater] += $money;
        $water['update_time'] = date('Y-m-d H:i:s');
        $water['game_water'] = json_encode($gwater);
        $water['sum_water'] += $dsum;

        return $water;
    }

    //统计数据处理
    private function handleCountdata($type,$gwater,$money){
        if ($type == 1) {
            if(!empty($gwater)){
                $gwater['agent_water'] += $money;
            }else{
                $gwater = array(
                    'agent_water' => $money,
                    'zt_water' => 0,
                    'group_water' => 0,
                    'sum_water' => 0,
                );
            }   
        } else {
            if(empty($gwater)){
                $gwater = array(
                    'agent_water' => 0,
                    'zt_water' => ($type == 2) ? $money : 0,
                    'group_water' => ($type == 2) ? 0 : $money,
                    'sum_water' => $money,
                );
            }else{
                $gwater['zt_water'] += ($type == 2) ? $money : 0;
                $gwater['group_water'] += ($type == 2) ? 0 : $money;
                $gwater['sum_water'] += $money;
            }   
        }
        return $gwater;
    }

    //获取周统计、日统计记录数据
    protected function getAddData($money,$user,$counttime,$uid,$type,$indata,$game=''){
        if(empty($user)){
            $auser = \App\Models\Nagent_detailed::select('agent_user')->where('agent_identity',$uid)->first();
            if(!isset($auser->agent_user))return -200102;
            $user = $auser->agent_user;
        }
        
        $gwater = array();
        $gswater = array();
        $uck = $uid.$counttime;
        if(isset($indata[$uck])){
            $gwater = array(
                'agent_water' => $indata[$uck]['agent_water'],
                'zt_water' => $indata[$uck]['zt_water'],
                'group_water' => $indata[$uck]['group_water'],
                'sum_water' => $indata[$uck]['sum_water'],
            );
            $gswater = json_decode($indata[$uck]['game_water'],1);
        }
        if(is_array($money)){
            $allmoney = 0;
            foreach ($money as $k => $v) {
                $allmoney += $v;
                $gswater[$k] = isset($gswater[$k])?$gswater[$k]:array();
                $gswater[$k] = $this->handleCountdata($type,$gswater[$k],$v);
            }
            $money = $allmoney;
        }
        $gwater = $this->handleCountdata($type,$gwater,$money);
        
        if(isset($indata[$uck])){
            $indata[$uck]['agent_water'] = $gwater['agent_water'];
            $indata[$uck]['zt_water'] = $gwater['zt_water'];
            $indata[$uck]['group_water'] = $gwater['group_water'];
            $indata[$uck]['sum_water'] = $gwater['sum_water'];
            $indata[$uck]['update_time'] = date('Y-m-d H:i:s');
            if(empty($game)){
                $indata[$uck]['game_water'] = json_encode($gswater);
            }else{
                $indata[$uck]['game_water'] = json_encode(array($game => $gwater));
            }
        }else{
            $indata[$uck] = $gwater;
            $indata[$uck]['agent_user'] = $user;
            $indata[$uck]['agent_identity'] = $uid;
            $indata[$uck]['count_time'] = $counttime;
            $indata[$uck]['time_type'] = count(explode('-', $counttime))==2?2:1;
            $indata[$uck]['update_time'] = date('Y-m-d H:i:s');
            if(empty($game)){
                $indata[$uck]['game_water'] = json_encode($gswater);
            }else{
                $indata[$uck]['game_water'] = json_encode(array($game => $gwater));
            }
        }
          
        return $indata;
    }

	//添加或更新统计游戏信息
	protected function addOrUpdate($record,$data){
		if(!empty($record) && isset($record['id'])){
			$res = $this->where('id',$record['id'])->update($data);
		}else{
			$res = $this->insert($data);
		}
		if($res<1)return -8505013102;
		return 1; 
	}

    //格式化时间为日期和年周
    protected function getFormatTime($ctime){
        $time['ctime'] = date('Y-m-d',strtotime($ctime));
        $y = date('Y',strtotime($ctime));
        $m = date('m',strtotime($ctime));
        $w = date('W',strtotime($ctime));
        if($m==12 && $w==1)$y+=1;
        $time['wtime'] = $y . '-' . $w;
        return $time;
    }
}
