<?php
namespace app\retail\controller;
use think\Controller;
use think\Db;
class Index extends Base{

   
     //订单签收15天后改为已完成，不支持发起售后
     public function index(){  
      
       $perfix=config("database.prefix");
	   $now=time()-api('zhouqi')*86400;//15天
	   //更新订单状态	
	   $sql="UPDATE ".$perfix."order SET status=4 WHERE `status=3 and confirm_time`>= ".$now;	
	   	$where[]=['status','=',3];
	   	$where[]=['confirm_time','>=',$now];
	   	$arr=db('order')->where($where)->setField('status',4);
	   	
	   //dump($sql);
        //$arr=Db::query($sql);
		//按订单比例
		if(api('retail_type')==1){
			
			//分销结算	
				$map[]=['status','=',4];
				$list=db('order')->where($map)->select();
				
				foreach($list as $k=>$v){
					
					$uid=$v['uid'];
					$money=$v['total_money'];
					if(api("fenxiao")){	  
						$this->getParents($uid,$money);	
				   }
				}
		}
		//固定佣金
		if(api('retail_type')==2){
			
			//分销结算	
				$map[]=['status','=',4];
				$list=db('order')->where($map)->select();
				
				foreach($list as $k=>$v){
					$where[]=["order_sn",'=',$v['order_sn']];
					$where[]=["uid",'=',$v['uid']];
					$sales=db('sales')->where($where)->select();
					$pid=get_user($v['uid'],'pid');
					$user=db('user')->where('id',$pid)->find();
					$account=0.00;
					foreach($sales as $ko=>$vo){
						$sku[]=["id",'=',$vo['sku_id']];
						$money=db('sku')->where($sku)->value('money');//佣金
						$account+=$money;
					}
					$total=$user['account']+$account;
					db('sales')->where('id',$pid)->setField("account",$total);
					 $save2["uid"]=$pid;
					 $save2["type"]=3;//分销佣金
					 $save2["money"]=$account;//充值金额
					 $save2["create_time"]=time();
					 $save2["content"]="分销提成";
					 $save2["total"]=$total;//充值后剩余金额
					 db("account_log")->insert($save2); 
					 if(api("fenxiao")){	  
						$this->getParents($pid,$account);	
				     }
				}
		}
		
		
		
	
			    $res["code"]=1;
				$res["from"]="bymall";
				header('Content-Type:application/json; charset=utf-8');
				print_r( json_encode($res,JSON_UNESCAPED_UNICODE));
	
		
      }
     //分销结算
  	public   function getParents($id = 0,$money,$level=1){
		if($level>3){
			return '';
		}
	    $map['id'] = $id;
		$data=db("user")->where($map)->field("id,pid")->find();
		if(isset($data["pid"])){ 
			$map2['id'] =$data["pid"];
			$uid=$data["pid"];
             $u["id"]=$uid; 
			 $percent=(float)api("l".$level)/100;
			 $money=$money*$percent;
		     $in=db("user")->where($u)->find(); 
			 $save["account"]=$in["account"]+$money;
			db("user")->where($u)->update($save);
			
			
		     $save2["uid"]=$uid;
             $save2["type"]=3;//分销佣金
			 $save2["money"]=$money;//充值后剩余金额
			 $save2["create_time"]=time();
			 $save2["content"]=$level."级分销提成";
			 $save2["total"]=$save["account"];//充值后剩余金额
             db("account_log")->insert($save2); 
			$this->getParents($uid,$money,$level+1);
        }
		
	}


	
}
