<?php

namespace Admin\Controller;
use Think\Controller;

/**
 * 聚合渠道结算接口对接
 * @author cz
 * TODO: 罚款的游戏没有流水不统计,补点为0 无法重算
 */
class SubCompanyStatementSetController extends Controller {
	public $cpapihost;
	public $TYPE=[
		"0"=>"周结",
		"1"=>"月结",
		"2"=>"补点"
	];
	public $token = "LYHTQDJS";

	public function _initialize(){
		$cpapihost = M("Kv")->field("value")->where("`key` = 'aggregate_cp_settlement_api'")->find();
		
		if(empty($cpapihost)){
			echo "请先设置请求接口aggregate_cp_settlement_api的值".PHP_EOL;die;
		}
		$this->cpapihost = $cpapihost['value'];
		// $this->synGame();
	}

	//同步游戏表
	// protected function synGame()
	// {
	// 	$mainGame = M("Game","tab_")->select();
	// 	SM()->execute("truncate table tab_game");
	// 	M("game","tab_",SUBSITE_DB)->addAll($mainGame);
	// }
	/**
	 * Undocumented function
	 *
	 * @param [type] $begin 开始时间 2020-04-01
	 * @param string $end 结束时间,默认今天
	 * @param string $company all/pc/cp/pu 全部 下游公司 上游 下游个人
	 * @return void
	 */
	public function setFreeDateCount($begin,$end='',$utime=false,$company='all')
	{
		if($end == '') $end = $begin;
		//判断日期格式
		$patten = "/^\d{4}[\-](0?[1-9]|1[012])[\-](0?[1-9]|[12][0-9]|3[01])$/";
		if (!preg_match($patten, $begin)) {
			die("开始时间格式错误");
		}
		if (!preg_match($patten, $end)) {
			die("结束时间格式错误");
		}
		if(strtotime($end) < strtotime($begin)){
			die("结束时间不能比开始时间小");
		}
		if(strtotime($end)+86399-24*3600 > time()){
			die("结束时间不能大于当前");
		}

		$starttime = $begin?strtotime($begin):mktime(0,0,0,date('m'),date('d'),date('Y'));
		$endtime = $end?strtotime($end)+86399:$starttime+86399;
		$datelist = get_date_list($starttime,$endtime,1);
		$countdate = count($datelist);
		for($i=0;$i<$countdate;$i++){
			$this->setDailyCount($datelist[$i],$company);
		}		
		if($utime){
			M("Kv","sub_",SUBSITE_DB)->where("`key` = 'sub_company_statement'")->save(["value"=>$utime]);
		}
	}
	public function setDailyCount($stime="now",$company='all')
    {
		if(!IS_CLI){
			die("只支持脚本访问");
		}
		if($stime=="now"){
			$stime=time();
		}else{
			$stime = strtotime($stime);
		}
		$nowdate = date("Y-m-d",$stime);
		$d = (int)date("d",$stime);
		$w = (int)date("w",$stime);
		if($w == 1){
			if($company == "all"){
				// echo $nowdate.":".PHP_EOL;
				// echo "--周结begin".PHP_EOL;

				$this->cpStatement(0,$stime);
				// echo "∟----CP周结统计ok".PHP_EOL;

				$this->promoteCompanyStatement(0,$stime);
				// echo "∟----推广公司周结统计ok".PHP_EOL;
			}
			if($company == "cp"){
				$this->cpStatement(0,$stime);
				echo "∟----CP周结统计ok".PHP_EOL;
			}
			if($company == "pc"){
				$this->promoteCompanyStatement(0,$stime);
				echo "∟----推广公司周结统计ok".PHP_EOL;
			}
		}
		if($d == 1){
			if($company == "all"){
				// echo $nowdate.":".PHP_EOL;
				// echo "--月结&补点begin".PHP_EOL;

				$this->cpStatement(1,$stime);
				// echo "∟----CP月结&补点统计ok".PHP_EOL;

				$this->promoteCompanyStatement(1,$stime);
				$this->officeCompanyStatement($stime); //官方结算
				// echo "∟----官方/推广公司月结统计ok".PHP_EOL;

				$this->promoteUserPool(1,$stime);
				// echo "∟----推广个人月结统计ok".PHP_EOL;
			}
			if($company == "cp"){
				$this->cpStatement(1,$stime);
				echo "∟----CP月结&补点统计ok".PHP_EOL;
			}
			if($company == "pc"){
				$this->promoteCompanyStatement(1,$stime);
				$this->officeCompanyStatement($stime); //官方结算
				echo "∟----官方/推广公司月结&补点统计ok".PHP_EOL;
			}
			if($company == "pu"){
				$this->promoteUserPool(1,$stime);
				echo "∟----推广个人月结&补点统计ok".PHP_EOL;
			}
		}
		// if($w != 1 && $d != 1){
		// 	echo $nowdate."非月初,无需任何处理".PHP_EOL;
		// }
	}
	/**
	 * 上游结算
	 * @param [string] $type 0:周结 1:月结 2:周结补点
	 */
	public function cpStatement($type,$stime,$company_id=false,$recount=true)
	{
		$t = $this->setBeginAndEndTime($type,$stime);;
		$begintime = $t[0];
		$endtime = $t[1];
		if($company_id === false){
			//非重算
			$where = [
				"_string"=>"first_company_type = '1' OR  second_company_type = '1'"
			];
		}else{
			$where = [
				"_string"=>"(first_company_type = '1' AND  first_company_id in ({$company_id}) ) OR (second_company_type = '1' AND  second_company_id in ({$company_id}) )"
			];
		}
		//获取哪些要结算
		if($type == 1){
			$where['settlement_type']=2;
			$cpDbRes = M("CompanyRelation","tab_")->where($where)->select();
		}else{
			$where['settlement_type']=1;
			$cpDbRes = M("CompanyRelation","tab_")->where($where)->select();
		}

		$cpList=[];
		$js_id = [];//己方公司
		foreach ($cpDbRes as $k => $v) {
			if($v['first_company_type'] == 1){
				$cpList[$v['first_company_id']] =$v;
				$js_id[] =$v['second_company_id'];
			}else{
				$cpList[$v['second_company_id']] =$v;
				$js_id[] =$v['first_company_id'];
			}
			
		}
		if(count($js_id) ==0 || count($cpList) == 0){return ;}

		$cp_id = implode(",",array_flip(array_flip(array_keys($cpList))));//已绑定关系
		$js_id = implode(",",array_unique($js_id));
		//获取cp公司
		$cpmap = [
			"id"=>['in',$cp_id],
			"_string"=>"(validity_start_time > 0 AND validity_end_time = 0 ) OR  validity_end_time >= {$endtime}"
		];
		$tmpp = M("Partner","tab_")->field("id,partner,link_man,link_phone,address,company_tax_no,payee_name,bank_account,opening_bank,channel_rate,invoice_rate,taxation_rate,company_type,ali_user,ali_account,has_advance_charge,has_server_fee,server_fee")->where($cpmap)->select();
		if(empty($tmpp)){
			return true;
		}
		$cp =[];
		foreach ($tmpp as $v) {
			$cp[$v['id']]=$v;
		}
		$cp_id =  implode(",",array_column($tmpp,"id")); //结算的id
		unset($tmpp);
		//获取己方公司
		$our = [];
		$tmpp = M("CompanyInfo","tab_")->field("id,partner,link_man,link_phone,address,company_tax_no,payee_name,bank_account,opening_bank")->where(["id"=>['in',$js_id]])->select();
		foreach ($tmpp as $v) {
			$our[$v['id']]=$v;
		}
		unset($tmpp);
		unset($js_id);
		//获取本地数据
		$locals = $this->getLocalStatementData($begintime,$endtime,$cp_id);
		//获取聚合数据
		$sign = md5($begintime.$endtime."1".$this->token);
		$arr = [
			"begintime"=>$begintime,
			"endtime"=>$endtime,
			"type"=>1,
			"sign"=>$sign,
			"cp_id"=>$cp_id
		];
		$dataurl .= $this->cpapihost."&".http_build_query($arr);
		$html = file_get_contents($dataurl);
		//防止并发压力
		sleep(3);
		$rsp = json_decode($html,true);
		if($rsp['code'] != 1){
			echo $rsp['error'].PHP_EOL;die;
		}else{
			$rsp = $rsp['data'];
		}
		//整合数据本地
	
		foreach($locals as $k=>$v){
			$cpList[$k]["list"] = $v["list"];
		}
		//整合数据,聚合
		foreach($rsp as $k=>$v){

			if(isset($cpList[$k]["list"])){
				//已经存在
				foreach($rsp[$k]["list"] as $ke=>$va){
					if(isset($cpList[$k]["list"][$ke])){
						$cpList[$k]["list"][$ke]['pay_money'] += $va['pay_money'];
						$cpList[$k]["list"][$ke]['aggregate_money'] += $va['pay_money'];
					}else{
						$va['aggregate_money'] = $va['pay_money'];
						$va['platform_money'] = 0;
						$cpList[$k]["list"][$ke] = $va;
					}
				}
			}else{
				$cpList[$k]["list"]  = $v["list"];
			}
			
		}
		//比例计算及保存
		// TODO:此处不判断现游戏名=原包名,但却不是同一款游戏
		$verify_log=json_encode(["create_user"=>"system","create_time"=>date("Y-m-d H:i:s")]);
		$GameDb = M("Game","tab_");
		$StatementDb = SM("CompanyStatement","tab_");
		$statement_begin_time = date("Y.m.d",$begintime);
		$statement_end_time = date("Y.m.d",$endtime);
		$MainStatementDb = M("CompanyStatement","tab_"); //主站结算单
		foreach($cpList as $k=>$v){
			//
			$sub_company_id = ($v['first_company_type'] == 1 ? $v['first_company_id'] : $v['second_company_id']);
			$ratio_str = ($v['first_company_type'] == 1 ? 'first_ratio' : 'second_ratio');
			$mainWhere = [
				"company_belong"=>9,
				"company_id" => $sub_company_id,
				"statement_begin_time"=>$begintime,
				"statement_end_time"=>$endtime
			];
			$add_data = $MainStatementDb->where($mainWhere)->find();
			if(empty($add_data)) continue; //主站必须有数据
			$add_data['statement_info'] = json_decode($add_data['statement_info'],true);
			foreach ($add_data['statement_info'] as $index => $item) {
				$igm = $item['game_name'];
				if(isset($v['list'][$igm])){
					$add_data['statement_info'][$index]['platform_money'] = $v['list'][$igm]['platform_money'];
					$add_data['statement_info'][$index]['aggregate_money'] = $v['list'][$igm]['aggregate_money'];
					$game_pay_amount = $v['list'][$igm]['platform_money']-0+$v['list'][$igm]['aggregate_money'];
					$ratio  = getGameCpRadio($item['relation_game_id'], $game_pay_amount, true) - 0;
					$add_data['statement_info'][$index]['ratio'] = $ratio;
				}else{
					$add_data['statement_info'][$index]['platform_money'] = 0;
					$add_data['statement_info'][$index]['aggregate_money'] = 0;
					$add_data['statement_info'][$index]['ratio'] = 0;
				}
			}
			unset($add_data['id'],$add_data['remark'],$add_data['confirm_status'],$add_data['confirm_log']);
			$add_data['verify_status'] = 0;
			$add_data['verify_log'] = $verify_log;
			$add_data['op_time'] =time();
			$add_data['statement_info'] = json_encode($add_data['statement_info'],JSON_UNESCAPED_UNICODE);
			//添加
			if($recount && $company_id !== false){
				//非重算
				return $add_data;
			}
			// var_dump($add_data);
			$StatementDb->add($add_data);
		}
	}
	
	/**
	 * 获取本地上游结算
	 */
	public function getLocalStatementData($begintime,$endtime,$cp_id)
	{
		$game_where = "partner_id in ({$cp_id})";
		$game = M('game','tab_');
		$gameDbRes = $game->field("id,relation_game_name as game_name,partner_id as cp_id,original_package_name,select_package_name")->where($game_where)->select();
		$gameList=[];
		foreach ($gameDbRes as $k => $v) {
			$gameList[$v['id']] =$v;
		}
		//获取所有id
		$gmstr = implode(",",array_flip(array_flip(array_column($gameDbRes,'id')))); 
		//获取支付记录
		$paywhere = [
			"pay_status"=>1,
			"pay_game_status"=>1,
			"payed_time"=>["BETWEEN",[$begintime,$endtime]],
			"game_id"=>["in",$gmstr]
		];
		D("Spend")->addSubsiteWhere($paywhere);
		$paydb = M('spend','tab_');
		$paylist = $paydb->field("game_id,SUM(pay_amount) pay_amount")->where($paywhere)->group("game_id")->select();
		if(empty($paylist)){
			return [];
		}
		//绑定价格
		foreach ($paylist as $k => $v) {
			$gameList[$v['game_id']]['pay_money'] =$v["pay_amount"];
		}
		unset($paylist);
		//按游戏名称及cp整理数据
		$cplList = [];
		foreach ($gameList as $k => $v) {
			if($v['pay_money'] <= 0) continue; //0值不发送
			//兼容旧数据的上游结算
			$hasOtherName = false;
			if(empty($v['original_package_name'])){
				$game_name = $v['game_name'];
			}else{
                if($v['select_package_name'] == 0){
                    $game_name = $v['original_package_name'];
					$hasOtherName = $v['game_name'];
                }else{
                    $game_name = $v['game_name'];
                    $hasOtherName = $v['original_package_name'];
                }
			}
			$cp_id = $v['cp_id'];
			unset($v['cp_id']);
			$ymoney = $cplList[$cp_id]['list'][$game_name]["pay_money"]?:0;
			$cplList[$cp_id]['list'][$game_name]["pay_money"] =$ymoney+$v["pay_money"];
			$cplList[$cp_id]['list'][$game_name]["platform_money"] = $cplList[$cp_id]['list'][$game_name]["pay_money"];
			$cplList[$cp_id]['list'][$game_name]["aggregate_money"] = 0;
			//兼容旧数据结算,旧数据有可能不使用原包名结算
			if($hasOtherName !== false){
				$cplList[$cp_id]['list'][$hasOtherName]["pay_money"] = $cplList[$cp_id]['list'][$game_name]["pay_money"];
				$cplList[$cp_id]['list'][$hasOtherName]["platform_money"] = $cplList[$cp_id]['list'][$game_name]["platform_money"];
				$cplList[$cp_id]['list'][$hasOtherName]["aggregate_money"] = $cplList[$cp_id]['list'][$game_name]["aggregate_money"];
			}
		}
		return $cplList;
	}
	//官方结算
	public function officeCompanyStatement($stime,$recount=false)
	{
		
		$t = $this->setBeginAndEndTime(1,$stime);
		$begintime = $t[0];
		$endtime = $t[1];
		//获取官方信息
		$pc_map = [
			"id"=>["IN",$pc_id],
			"_string"=>"(validity_start_time > 0 AND validity_end_time = 0 ) OR  validity_end_time >= {$endtime}",
			"company_type"=>1
		];
		//获取pc公司
		$company = M("CompanyInfo","tab_")->field("id,partner,link_man,link_phone,address,company_tax_no,payee_name,bank_account,opening_bank")->where("partner = '海南万盟天下科技有限公司'")->find();
		$first_party_info = json_encode($company,JSON_UNESCAPED_UNICODE);
		$company['partner'] = C("OFFICIEL_CHANNEL");
		$second_party_info = json_encode($company,JSON_UNESCAPED_UNICODE);
		$add_data=[
			"first_party_info"=>$first_party_info,
			"second_party_info"=>$second_party_info,
			"pay_type"=>2,
			"withdraw_type"=>1,
			"statement_begin_time"=>$begintime,
			"statement_end_time"=>$endtime,
			"statement_money"=>0,
			"pay_amount"=>0,
			"platform_amount"=>0,
			"verify_log"=>json_encode(["create_user"=>"system","create_time"=>date("Y-m-d H:i:s")]),
			"op_time"=>time(),
			"is_payment"=>2,
			"statement_info"=>[],
			"company_belong"=>0,
			"company_name"=>C("OFFICIEL_CHANNEL"),
			"company_id"=>0,
			"company_type"=>1
		];
		
		//获取渠道及发票税率
		$fax_ratio =  0; //税费费率
		$company_belong = 0;

		
	
		$Promote = M("Promote","tab_");
		$Spend = SM("Spend","tab_");
		$spenMap = [
			"s.pay_status"=>1,
			"s.payed_time"=>['between', [$begintime,$endtime]],
			"s.promote_id"=>0
		];
		D("Spend")->addSubsiteWhere($spenMap,"s");
		$list =  $Spend->alias('s')->field('sum(s.pay_amount) pay_amount,g.relation_game_id,g.relation_game_name game_name')->where($spenMap)->group('relation_game_id')
					->join("left join tab_game g on s.game_id = g.id")
					->select();
		if(empty($list)){return;}
		$statement_begin_time = date("Y.m.d",$begintime);
		$statement_end_time = date("Y.m.d",$endtime);

		foreach ($list as $k => $v) {
			$v['fax_ratio'] = 0;
			$v['statement_begin_time']=$statement_begin_time;
			$v['statement_end_time']=$statement_end_time;
			$v['ratio']=0;
			$v['sum_money'] = 0;
			$v['statement_type']=0;
			$v['platform_money'] = $v['pay_amount'];
			$v['aggregate_money'] = 0;

			$add_data['platform_amount'] += $v['pay_amount'];
			$add_data['pay_amount'] += $v['pay_amount'];
			$add_data['statement_info'][] = $v;
		}
		$add_data['statement_info'] = json_encode($add_data['statement_info'],JSON_UNESCAPED_UNICODE);
		if($recount){
			//非重算
			return $add_data;
		}
		SM("CompanyStatement","tab_")->add($add_data);		
	}

	/**
	 * 下游结算
	 */
	public function promoteCompanyStatement($type,$stime,$recount_company_id=false,$recount=true)
	{
		$t = $this->setBeginAndEndTime($type,$stime);
		$begintime = $t[0];
		$endtime = $t[1];
		$statement_begin_time = date("Y.m.d",$begintime);
		$statement_end_time = date("Y.m.d",$endtime);
		$verify_log=json_encode(["create_user"=>"system","create_time"=>date("Y-m-d H:i:s")]);

		//获取主站数据begin
		$MainStatementDb = M("CompanyStatement","tab_"); //主站结算单
		$mainWhere = [
			"company_belong"=>["neq",9],
			"withdraw_type"=>["neq",3],
			"statement_begin_time"=>$begintime,
			"statement_end_time"=>$endtime
		];
		if($recount_company_id !== false){
			$mainWhere['company_id'] = $recount_company_id;
		}
		$statementList = $MainStatementDb->where($mainWhere)->select();
		$StatementDb = SM("CompanyStatement","tab_");
		$RewardRecord = SM("RewardDetail","tab_");
		if(empty($statementList)) return false;
		foreach ($statementList as $k => $v) {
			$v['statement_info'] = json_decode($v['statement_info'],true);
			$v['statement_money'] = 0;
			$v['pay_amount'] = 0;
			$v['verify_status'] = 0;
			$v['verify_log'] = $verify_log;
			$company_id = $v['company_id'];
			unset($v['id'],$v['remark'],$v['confirm_status'],$v['confirm_log']);
			foreach ($v['statement_info'] as $gameindex => &$game) {
				if($game['statement_type'] > 0){
					unset($v['statement_info'][$gameindex]);
					continue;
				}
				$relation_game_id = $game['relation_game_id'];
				$game['pay_amount'] = $this->getRelationGameIdSpend($company_id,$relation_game_id,$begintime,$endtime);
				if($game['pay_amount'] <= 0){
					unset($v['statement_info'][$gameindex]);
					continue;
				}
				$v['pay_amount'] += $game['pay_amount'];
				$game['sum_money'] = round($game['pay_amount']*$game['ratio']*(100-$game['fax_ratio'])/100/100,2);
				$v['statement_money'] += $game['sum_money'];
			}
			$v['platform_amount'] = $v['pay_amount'];
			//奖罚
			$rrmap = ["confirm_time" => ['between', [$begintime,$endtime]],"company_type"=>2,"company_id"=>$company_id,"settlement_type"=>2];
			$rfres = $RewardRecord->field("IFNULL(SUM(CASE WHEN type = 1 THEN amount ELSE 0 END),0) as reward_count,IFNULL(SUM(CASE WHEN type = 2 THEN amount ELSE 0 END),0) as fine_count")->where($rrmap)->find();

			if($rfres['reward_count'] > 0){
				$reward_count = $rfres['reward_count'];
				$v['statement_info'][] = array(
					"statement_begin_time"=>$statement_begin_time,
					"statement_end_time"=>$statement_end_time,
					'statement_type'=>2,
					"game_name"=>"奖励",
					'pay_amount'=>$reward_count,
					'sum_money'=>$reward_count,
				);
				$v['statement_money'] += $reward_count;
				$v['pay_amount'] += $reward_count;
			}
			if($rfres['fine_count'] > 0){
				$fine_count = $rfres['fine_count'];
				$v['statement_info'][] = array(
					"statement_begin_time"=>$statement_begin_time,
					"statement_end_time"=>$statement_end_time,
					'statement_type'=>1,
					"game_name"=>"罚款",
					'pay_amount'=>$fine_count,
					'sum_money'=>$fine_count,
				);
				$v['statement_money'] -= $fine_count;
				$v['pay_amount'] -= $fine_count;;
			}
			$v['statement_info'] = json_encode($v['statement_info'],JSON_UNESCAPED_UNICODE);
			if($type == 2 && $v['statement_money'] == 0){
				//金额为0不补点
				continue;
			}
			if($v['platform_amount'] == 0){
				continue;		
			}
			//添加
			if($recount === true && $recount_company_id !== false){
				//非重算
				return $v;
			}
			$StatementDb->add($v);
		}
	}
	//设定开始结束时间
	protected function setBeginAndEndTime($type,$stime){
		if($type == 0){
			$begintime = mktime(0,0,0,date('m',$stime),date('d',$stime)-7,date('Y',$stime));
			$endtime = mktime(0,0,0,date('m',$stime),date('d',$stime),date('Y',$stime))-1;
		}else{
			$thismonth = date('m',$stime);
			$thisyear = date('Y',$stime);
			if ($thismonth == 1) {
				$lastmonth = 12;
				$lastyear = $thisyear - 1;
			} else {
				$lastmonth = $thismonth - 1;
				$lastyear = $thisyear;
			}
			$lastStartDay = $lastyear . '-' . $lastmonth . '-1';
			$lastEndDay = $lastyear . '-' . $lastmonth . '-' . date('t', strtotime($lastStartDay));
			$begintime = strtotime($lastStartDay);//上个月的月初时间戳
			$endtime = strtotime($lastEndDay)+24*3600-1;//上个月的月末时间戳
		}
		return [$begintime,$endtime];
	}
    /**
     * 返回结算流水类型
     */
	protected function getTurnoverType($relation_game_id = 0, $company_id = 0, $begin_time = 0, $end_time = 0){
        $company_belong = M("promote_company","tab_")->field("company_belong")->where(['id'=>$company_id])->find();

        if (!$company_belong) {
            return 0;
        }

        $turnover_where = [
            "relation_game_id"=>$relation_game_id,
            "company_id"=>$company_id,
            "_string"=>"begin_time <={$end_time} AND ( end_time = 0 OR end_time >= {$begin_time})"
        ];
        $turnover_type = D("CompanyGameRatio")->field("turnover_type")->where($turnover_where)->find();

        if (!$turnover_type) {
            $turnover_where = [
                "company_belong"=>$company_belong['company_belong'],
                "relation_game_id"=>$relation_game_id,
                "company_id"=>0,
                "_string"=>"begin_time <={$end_time} AND ( end_time = 0 OR end_time >= {$begin_time})"
            ];
            $turnover_type = D("CompanyGameRatio")->field("turnover_type")->where($turnover_where)->find();
        }

        //判断特殊比例是否存在,存在直接返回结算流水类型
        if (!$turnover_type) {

            //判断公司内外团类型是否存在,不存在直接返回0
            if (!$company_belong) {
                return 0;
            } else {
                $company_belong = $company_belong['company_belong'];
            }
            $mould_where = [
                "relation_game_id"=>$relation_game_id,
                "company_belong"=>$company_belong,
                "_string"=>"begin_time <={$end_time} AND ( end_time = 0 OR end_time >= {$begin_time})"
            ];
            $mould_data = M("game_ratio_mould","tab_")->where($mould_where)->find();
            //判断游戏比例模板是否存在,不存在直接返回0,否则返回查询的类型
            if ($mould_data) {
                return $mould_data['turnover_type'];
            } else {
                return 0;
            }

        } else {
            return $turnover_type['turnover_type'];
        }

    }

	//获取推广公司推广金额
	protected function getPuPromoteSpend(&$pcList,$idarr,$begintime,$endtime){
		$res = [];
		$statement_begin_time = date("Y.m.d",$begintime);
		$statement_end_time = date("Y.m.d",$endtime);
		//获取推广员
		if(count($idarr) == 0){return $res;}
		$Promote = M("Promote","tab_");
		$Spend = SM("Spend","tab_");
		$spenMap = [
			"s.pay_status"=>1,
			"s.payed_time"=>['between', [$begintime,$endtime]],
			"s.is_check"=>1
		];
		D("Spend")->addSubsiteWhere($spenMap,"s");
		for ($i=0; $i <count($idarr); $i++) {
			$company_id = $idarr[$i];

			$pres = $Promote->field("id,account")->where("company_id = '{$company_id}'")->select();
			if(empty($pres)){continue;}
			$spenMap['s.promote_id']=["in",array_column($pres,"id")];
			$promote_a = [];
			foreach($pres as $key=>$value){
				$promote_a[$value['id']] = $value['account'];
			}
			unset($pres);
			//获取支付记录
			$list =  $Spend
					->alias('s')
					->field("sum(s.pay_amount) pay_amount,s.game_id,g.relation_game_id,g.relation_game_name game_name,g.game_type_name")
					->where($spenMap)
					->group('game_id')
					->join("left join tab_game g on s.game_id = g.id")
					->select();

			if(empty($list)){unset($pcList[$company_id]);continue;}
			$game = [];
			foreach($list as $k=>$v){
				if(isset($game[$v['relation_game_id']])){
					$game[$v['relation_game_id']]['pay_amount'] += $v['pay_amount'];
				}else{
					$game[$v['relation_game_id']] = $v;
				}
			}
			//同cp,同一个原包名的共享总流水分成
			$game_ids = implode(",",array_keys($game));
			$game_ids = $this->getModuleRatioGame($company_id,$game_ids,$begintime,$endtime);
			$sameGame =  $this->getTheSameGame($game_ids);

			if(!empty($sameGame)){
				foreach ($sameGame as $k => $v) {
					$temp = 0;
					for ($j=0; $j < count($v); $j++) {
                        $temp += $game[$v[$j]]['pay_amount'];
					}
					$sameGame[$k] = $temp;
				}
				foreach ($sameGame as $k => $v) {
					$game[$k]['pay_amount']= $v;
				}
			}
			// if($company_id == 23) dd($game);
			//计算比例
			$pay_amount = 0;
			$sum_money = 0;
			$statementInfo = [];
			foreach ($game as $k => $v) {
				$company_belong = $pcList[$company_id]['company_belong'];
				$gameOther =$this->getPuGameRatio($company_id,$company_belong,$k,$v['pay_amount'],$begintime,$endtime);
				$v['ratio'] = $gameOther[0];
				$v['sum_money'] = $gameOther[1];
				$v['statement_begin_time'] = $statement_begin_time;
				$v['statement_end_time'] = $statement_end_time;
				$statementInfo[] = $v;

				$pay_amount  += $v['pay_amount'];
				$sum_money  += $v['sum_money'];
			}
			$pcList[$company_id]['statement_info'] = $statementInfo;
			$pcList[$company_id]['pay_amount'] = $pay_amount;
			$pcList[$company_id]['sum_money'] = $sum_money;
		}
	}
	 public function promoteUserPool($type,$stime,$recount = false){
		$t = $this->setBeginAndEndTime($type,$stime);
		$begintime = $t[0];
		$endtime = $t[1];

		$statementInfo = $this->doPromoteUserPool($user,1,$stime,$recount);
		if($recount){
			SM("user_statement","sub_")->where([
				"statement_begin_time"=>$begintime,
				"statement_end_time"=>$endtime
			])->delete();
		}
		SM("user_statement","sub_")->add($statementInfo);
	}

	/**
	 * 下游个人汇总单
	 */
	public function doPromoteUserPool(&$user,$type,$stime,$recount = false)
	{
		$t = $this->setBeginAndEndTime($type,$stime);
		$begintime = $t[0];
		$endtime = $t[1];

		$where = [
			"_string"=>"first_company_type = '2' OR  second_company_type = '2'"
		];
		$pcDbRes = M("CompanyRelation","tab_")->where($where)->select();

		
		$pcList=[];
		$js_id = [];//己方公司
		foreach ($pcDbRes as $k => $v) {
			if($v['first_company_type'] == 2){
				$pcList[$v['first_company_id']] =$v;
				$js_id[] =$v['second_company_id'];
			}else{
				$pcList[$v['second_company_id']] =$v;
				$js_id[] =$v['first_company_id'];
			}
		}
		//获取pc公司
		$pc_id = implode(",",array_flip(array_flip(array_keys($pcList))));
		$pu_map = [
			"id"=>["IN",$pc_id],
			"_string"=>"(validity_start_time > 0 AND validity_end_time = 0 ) OR  validity_end_time >= {$endtime}",
			"company_type"=>2
		];
		$tmpp = M("PromoteCompany","tab_")
				->field("id,company_name partner,company_belong,company_type")
				->where($pu_map)
				->select();
		if(count($tmpp)<1){return;}

		$pc =[];
		$Promote = M("Promote","tab_");
		foreach ($tmpp as $v) {
			$pc[$v['id']]=$v;
		}
		unset($tmpp);
		$this->getPuPromoteSpend($pc,array_unique(array_keys($pc)),$begintime,$endtime);
		
		$StatementDb = SM("user_statement","sub_");
		$res = [
			"statement_begin_time"=>$begintime,
			"statement_end_time"=>$endtime,
			"statement_money"=>0,
			"pay_amount"=>0,
			"op_time"=>time(),
			"remark"=>''
		];
		$statementInfo = [];
		foreach($pc as $k=>$v){
			$res['pay_amount'] += $v['pay_amount'];
			$res['statement_money'] += $v['sum_money'];
			unset($v['pay_amount'],$v['sum_money']);
			$statementInfo[] = $v;
		}
		$res['statement_info'] = json_encode($statementInfo,JSON_UNESCAPED_UNICODE);
		return $res;
	}
	/**
	 * 保存信息汇总信息
	 */
	public function savePromotateUserPool($data){
		if(IS_CLI){
			$op_name ="system";
		}else{
			$op_name =$_SESSION['onethink_admin']['user_auth']["username"];
		}
		if(empty($data['create_lack_ids']) && empty($data['del_lack_ids']) && empty($data['info_ids'])){ //补点为空不重算
            return ;
        }
		if($data['statement_money'] == 0){
			$data['verify_status'] = 5;
			$data['verify_log'] = json_encode(["create_user"=>$op_name,"create_time"=>date("Y-m-d H:i:s"),"verify_user"=>"system","verify_time"=>date("Y-m-d H:i:s"),"payment_user"=>"system","payment_time"=>date("Y-m-d H:i:s")]);
		}else{
			$data['verify_log'] = json_encode(["create_user"=>$op_name,"create_time"=>date("Y-m-d H:i:s")]);
		}
		$data['create_lack_ids'] = implode(",",$data['create_lack_ids']);
		$data['del_lack_ids'] = implode(",",$data['del_lack_ids']);
		$info = implode(",",$data['info_ids']);
		unset($data['info_ids']);
		$id = SM("company_statement_pool","tab_")->add($data);
		//回写
		if(!empty($info)){
			$save["pool_id"]=$id;
			SM("company_statement_info","tab_")->where("id in ({$info})")->save($save);
		}
		if(!empty($data['del_lack_ids'])){
			SM("company_lack_statement_info","tab_")->where("id in ({$data['del_lack_ids']})")->save(["is_pool"=>1]);
		}
	}

	/**
	 * 获取公司额为信息
	 */
	public function getCompanyOtherInfo($company_info,$company_id)
	{
		$pl =  M("promote_company","tab_")
				->alias('pc')
				->field("p.account,p.company_relation,IFNULL(s.real_name,'-') nickname")
				->join("left join (select company_id,account,company_relation,admin_id from tab_promote where level = 1 group by company_id ) p on p.company_id = pc.id")//获取会长
				->join("left join sys_member s on s.uid = p.admin_id")
				->where("pc.id = {$company_id}")
				->find();
		$company = array_merge($company_info,$pl);
		$company['company_relation_str'] =getCompanyRelation($company['company_relation']);
		$company['company_belong_str'] =getCompanyBlong($company['company_belong']);
		$company['company_type_str'] = "个人";
		return $company;
		
	}
	/**
	 * 获取游戏分类名称
	 */
	public function getGameTypeName($relation_game_id){
		return M("Game","tab_")->field("game_type_name")->where("relation_game_id = '{$relation_game_id}'")->find()['game_type_name'];
	}
	/**
	 * 获取公司比例加成
	 * @param [type] $paymount 支付金额
	 * @param [type] $turnover_ratio 梯度
	 */
    protected function getCompanyRatio($paymount,$turnover_ratio)
    {
        $ratio = 0;
        foreach($turnover_ratio as $k=>$v){
            if($v['instanceof'] == 1){
                if($paymount >= $v['turnover']){
                    $ratio = $v['ratio'];
                }
            }else{
                if($paymount > $v['turnover']){
                    $ratio = $v['ratio'];
                }
            }
        }
        return $ratio;
    }

    /**
     * 获取游戏奖罚
     */
    protected function getPromoteUserGameRewardRecord($cpmpamy_id,$begintime,$endtime)
    {

        $begintime = strtotime(str_replace('.','-',$begintime));
        $endtime = strtotime(str_replace('.','-',$endtime))+86499;

        //获取所有公司的奖罚
        $rrmap = array(
            "d.confirm_time" => ['between', [$begintime,$endtime]],
            "d.company_type"=>2,
            "d.company_id"=>$cpmpamy_id,
            "d.settlement_type"=>2,
//            "relation_game_id"=>$relation_game_id,
        );

        $rfres = M("RewardDetail","tab_")
            ->alias("d")
            ->field("
					IFNULL(SUM(CASE WHEN type = 1 THEN amount ELSE 0 END),0) as reward,
					IFNULL(SUM(CASE WHEN type = 2 THEN amount ELSE 0 END),0) as fine")
            ->join('tab_reward_record as r on d.record_id = r.id', 'LEFT')
            ->where($rrmap)
            ->group("company_id")
            ->find();

//        $rfres = M('reward_record', 'tab_')
//            ->alias('r')
//            ->field("
//					IFNULL(SUM(CASE WHEN type = 1 THEN amount ELSE 0 END),0) as reward,
//					IFNULL(SUM(CASE WHEN type = 2 THEN amount ELSE 0 END),0) as fine")
//            ->where($rrmap)
//            ->join('tab_reward_detail as d on d.record_id = r.id', 'LEFT')
//            ->group("company_id")
//            ->find();
//        if ($relation_game_id == 191 && $cpmpamy_id == 334) {
//            dump($rfres);
//        }

        if(empty($rfres)){
            return false;
        }else{
            return $rfres;
        }
    }

    /**
     * 获取上游游戏奖罚
     */
    protected function getPromoteUserGameRewardRecordCp($cpmpamy_id,$begintime,$endtime)
    {

        $begintime = strtotime(str_replace('.','-',$begintime));
        $endtime = strtotime(str_replace('.','-',$endtime))+86499;

        //获取所有公司的奖罚
        $rrmap = array(
            "d.confirm_time" => ['between', [$begintime,$endtime]],
            "d.company_type"=>1,
            "d.company_id"=>$cpmpamy_id,
            "d.settlement_type"=>2,
//            "relation_game_id"=>$relation_game_id,
        );

        $rfres = M("RewardDetail","tab_")
            ->alias("d")
            ->field("
					IFNULL(SUM(CASE WHEN type = 1 THEN amount ELSE 0 END),0) as reward,
					IFNULL(SUM(CASE WHEN type = 2 THEN amount ELSE 0 END),0) as fine")
            ->join('tab_reward_record as r on d.record_id = r.id', 'LEFT')
            ->where($rrmap)
            ->group("company_id")
            ->find();

        if(empty($rfres)){
            return false;
        }else{
            return $rfres;
        }
    }

	/**
	 * 获取公司奖罚
	 */
    protected function getPromoteUserRewardRecord($cpmpamy_id,$begintime,$endtime)
    {
		//获取所有公司的奖罚
		$rrmap = array(
			"d.confirm_time" => ['between', [$begintime,$endtime]],
			"d.company_type"=>2,
			"d.company_id"=>$cpmpamy_id,
			"d.settlement_type"=>2,
		);
		$rfres = M("RewardDetail","tab_")
				->alias("d")
				->field("
					IFNULL(SUM(CASE WHEN type = 1 THEN amount ELSE 0 END),0) as reward,
					IFNULL(SUM(CASE WHEN type = 2 THEN amount ELSE 0 END),0) as fine")
				->where($rrmap)
				->group("company_id")
				->find();
		if(empty($rfres)){
			return false;
		}else{
			return $rfres;
		}
	}
	/**
	 * 获取比例
	 *
	 * @param [type] $amount 总额
	 * @param [type] $ratio 默认比例
	 * @param [type] $turnover_ratio 比例梯度
	 * @return void
	 */
	protected function getTurnoverRatio($amount,$ratio,$turnover_ratio)
	{
		if(empty($turnover_ratio)){
			return $ratio;
		}
		if(!is_array($turnover_ratio)){
			$turnover_ratio = json_decode($turnover_ratio,true);
		}
		foreach($turnover_ratio as $k=>$v){
			if($v['instanceof'] == 1){
				if($amount >= $v['turnover']){
					$ratio = $v['ratio'];
				}
			}else{
				if($amount > $v['turnover']){
					$ratio = $v['ratio'];
				}
			}
		}
		return $ratio;
	}
	
	protected function getRelationGameIdSpend($company_id,$relation_game_id,$begintime,$endtime)
	{
		$res = [];
		//获取推广员
		$Promote = M("Promote","tab_");
		$Spend = SM("Spend","tab_");
		$spenMap = [
			"s.pay_status"=>1,
			"s.payed_time"=>['between', [$begintime,$endtime]],
			"s.is_check"=>1
		];

		$company_id = $company_id;
		$pres = $Promote->field("group_concat(id) ids,count(id) count")->where("company_id = '{$company_id}'")->group("company_id")->find();
		if($pres['count'] ==0 ){return 0;}
		$spenMap['s.promote_id']=["in",$pres['ids']];
		//游戏
		
		$game_id = D("Game")->changeRelationGameidToGameid($relation_game_id);
		// dd($game_id);
		$spenMap['s.game_id'] =['in',$game_id];
		D("Spend")->addSubsiteWhere($spenMap);
			//获取支付记录
		$pay_amount =  $Spend->alias('s')->field('sum(s.pay_amount) pay_amount')->where($spenMap)->find();
		return $pay_amount['pay_amount'] ?? 0;
	}

	protected function getRelationGameIdPromoteSpend($promote_id,$relation_game_id,$begintime,$endtime)
	{
		$res = [];
		//获取推广员
		$Promote = M("Promote","tab_");
		$Spend = SM("Spend","tab_");
		$spenMap = [
			"s.pay_status"=>1,
			"s.payed_time"=>['between', [$begintime,$endtime]],
			"s.is_check"=>1
		];
		D("Spend")->addSubsiteWhere($spenMap);

		$Pmap = [
			"chain"=>["LIKE","%/{$promote_id}/%"],
			"_logic"=>"OR",
			"id"=>$promote_id
		];
		$pres = $Promote->field("group_concat(id) ids,count(id) count")->where($Pmap)->group("company_id")->find();
		if($pres['count'] ==0 ){return 0;}
		$spenMap['s.promote_id']=["in",$pres['ids']];
		//游戏
		
		$game_id = D("Game")->changeRelationGameidToGameid($relation_game_id);
		// dd($game_id);
		$spenMap['s.game_id'] =['in',$game_id];
			//获取支付记录
		$pay_amount =  $Spend->alias('s')->field('sum(s.pay_amount) pay_amount')->where($spenMap)->find();
		return $pay_amount['pay_amount'] ?? 0;
	}
	/**
	 * 获取游戏是否有特殊比例,返回没有特殊比例的游戏
	 * return string "148,157"
	 */
	protected function getModuleRatioGame($company_id,$relation_game_ids,$begintime,$endtime){

		$where = [
			"relation_game_id"=>["in",$relation_game_ids],
			"company_id"=>$company_id,
			"_string"=>"begin_time <={$endtime} AND ( end_time = 0 OR end_time >= {$begintime})"
		];
		$dbres = D("CompanyGameRatio")->field("relation_game_id")->where($where)->select();

		if (!$dbres) {
            $company_belong = M("promote_company","tab_")->field("company_belong")->where(['id'=>$company_id])->find();

            $where = [
                "company_id"=>0,
                "company_belong"=>$company_belong['company_belong'],
                "relation_game_id"=>["in",$relation_game_ids],
                "_string"=>"begin_time <={$endtime} AND ( end_time = 0 OR end_time >= {$begintime})"
            ];
            $dbres = D("CompanyGameRatio")->field("relation_game_id")->where($where)->select();
        }

		if(is_string($relation_game_ids)) $relation_game_ids = explode(",",$relation_game_ids);

		$array_mer = [];

        foreach ($relation_game_ids as $key => $value) {
            $turnover_type = $this->getTurnoverType($value,$company_id,$begintime,$endtime);

            if ($turnover_type == 2 || $turnover_type == 3 || $turnover_type == 4) {

                $mercy_game = M("game",'tab_')->field("original_package_name")->where(['relation_game_id'=>$value])->find()['original_package_name'];

                $original_game_id = M("game",'tab_')
                    ->field("relation_game_id")
                    ->where(['original_package_name'=>$mercy_game,'relation_game_id'=>['neq',$value]])
                    ->group("relation_game_id")
                    ->select();

                foreach ($original_game_id as $k => $v) {

                    if(!in_array($v['relation_game_id'], $relation_game_ids)){

                        $array_mer[] = $v['relation_game_id'];

                    }

                }

            }

        }

        $relation_game_ids = array_merge($relation_game_ids,$array_mer);


		if(empty($dbres)){
			return implode(",",$relation_game_ids);
		}else{
			$dbres = array_column($dbres,"relation_game_id");
			$diff =  array_diff($relation_game_ids,$dbres);

			return implode(",",$diff);
		}
	}

	/**
	 * 识别游戏为同款游戏,共享流水分成比例
	 * return [
	 * 	148 =>["148","157"],
	 *  157=>["148","157"]
	 * ]
	 */
	protected function getTheSameGame($relation_game_ids)
	{
		if(empty($relation_game_ids)) return [];
		$where = [
			"id"=>["in",$relation_game_ids]
		];
		$Gameinfo = D("Game")->field("relation_game_id,partner_id,original_package_name")->where($where)->select();
		if(empty($Gameinfo)){
			return [];
		}
		$data = [];
		foreach ($Gameinfo as $k => $v) {
			if(empty($v['original_package_name'])) continue;
			if(!isset($data[$v['partner_id']])){
				$data[$v['partner_id']] = [];
			}
			if(!isset($data[$v['partner_id']][$v['original_package_name']])){
				$data[$v['partner_id']][$v['original_package_name']] = [$v['relation_game_id']];
			}else{
				$data[$v['partner_id']][$v['original_package_name']][] = $v['relation_game_id'];
			}
		}
		$senddata = [];
		foreach ($data as $k => $partenr) {
			foreach($partenr as $ke => $game){
				$gamecount = count($game);
				if($gamecount > 1){
					for ($i=0; $i < $gamecount; $i++) { 
						$senddata[$game[$i]] = $game;
					}
				}
			}
		}
		return $senddata;
	}
	/**
	 * 获取下游个人游戏分成比例,不计其他,只计算最后一条
	 */
	protected function getPuGameRatio($company_id,$company_belong,$relation_game_ids,$pay_amount,$begin_time,$end_time){
		$flag = false;
		$ratio = 0;
		$turnover_ratio = '';
		$where = [
			"relation_game_id"=>$relation_game_ids,
			"company_id"=>$company_id,
			"_string"=>"begin_time <={$end_time} AND ( end_time = 0 OR end_time >= {$begin_time})"
		];
		$dbres = M("CompanyGameRatio","tab_")->where($where)->order('begin_time desc')->find();
		!empty($dbres) && $flag = true;
		if(!$flag){
			$where = [
				"relation_game_id"=>$relation_game_ids,
				"company_belong"=>$company_belong,
				"_string"=>"begin_time <={$end_time} AND ( end_time = 0 OR end_time >= {$begin_time})"
			];
			$dbres = M("CompanyGameRatio","tab_")->where($where)->order('begin_time desc')->find();
			!empty($dbres) && $flag = true;
		}
		if(!$flag){
			$where = [
				"relation_game_id"=>$relation_game_ids,
				"company_belong"=>$company_belong,
				"_string"=>"begin_time <={$end_time} AND ( end_time = 0 OR end_time >= {$begin_time})"
			];
			$dbres = M("GameRatioMould","tab_")->where($where)->order('begin_time desc')->find();
			!empty($dbres) && $flag = true;
		}
		if($flag){
			$ratio = $dbres['ratio'];
			$turnover_ratio = $dbres['turnover_ratio'];
		}
		$ratio = $this->getTurnoverRatio($pay_amount,$ratio,$turnover_ratio);
		$sum_money = round($pay_amount * $ratio / 100,2);
		return [$ratio,$sum_money];
	}

	
	/**
	 * 重算接口
	 * 不进行结算方式重算
	 * @param [type] $id 原数据id
	 * @param string $admin_user 操作用户
	 * @return void bool
	 */
	public function updateCompanyStatementData($id,$admin_user='system')
	{
		//获取数据
		$StatementDb = SM("CompanyStatement","tab_");
		$dbres = $StatementDb->where("id='{$id}'")->find();
		//获取时间
		$stime  = $dbres['statement_end_time']-0+1;
		$company_id = $dbres['company_id'];

		if($company_id == 0){
			$savedata = $this->officeCompanyStatement($stime,true);
		}else{
			if($dbres['company_belong'] == 9){
				//上游
				$savedata = $this->cpStatement($dbres['withdraw_type'],$stime,$company_id);
			}else{
				$savedata = $this->promoteCompanyStatement($dbres['withdraw_type'],$stime,$company_id);
			}
		}
		//重写用户
		$savedata['verify_log'] = json_encode(["create_user"=>$admin_user,"create_time"=>date("Y-m-d H:i:s")]);
		$savedata['verify_status'] = 0;
		$savedata['confirm_status'] = 0;
		$savedata['confirm_log'] = '';
		$savedata['id'] = $dbres['id'];
		return $StatementDb->save($savedata);
	}

}