<?php
class pinche_groupModel extends model{
	public $table="mod_pinche_group";
	public $maxnum=4;
	public function __construct(){
		parent::__construct();
	}
	
	public function joinGroup($orderid){
		M("user")->begin();
		$order=MM("pinche","pinche_order")->selectRow("orderid=".$orderid);
		
		if(empty($order) || $order["ispay"]==0 || $order["status"]!=0){
			M("user")->rollback();
			return false;
		}
		
		$lineid=MM("pinche","pinche_line")->selectRow("lineid=".$order["lineid"]);
		$driver=MM("pinche","pinche_driver")->getFree($order["lineid"]);
		
		 
		if(empty($driver)){
			$driverid=0; 
		}else{
			$driverid=$driver["driverid"]; 
		}
		//包车
		if($order["usernum"]==$this->maxnum){
			if($driverid==0){
				$status=0;
			}else{
				$status=1;
			}
			$gid=$this->insert(array(
				"lineid"=>$order["lineid"],
				"dateline"=>time(),
				"usernum"=>$order["usernum"],
				"freenum"=>0,
				"status"=>$status,
				"driverid"=>$driverid,
				"money"=>$order["money"],
				"ptime"=>1
			));
			MM("pinche","pinche_order")->update(array(
				"driverid"=>$driverid,
				"gid"=>$gid,
				"status"=>1
			),"orderid=".$orderid);
			if($driverid){
				MM("pinche","pinche_driver_line")->update(array(
					"status"=>2
				),"driverid=".$driverid." AND lineid=".$order["lineid"]);
			}
			M("user")->commit();
			return true;
		}	
		$group=$this->selectRow(array(
			"where"=>"lineid=".$order["lineid"]." AND status=0 AND freenum>=".$order["usernum"],
			"order"=>"gid ASC"
		));
		if(empty($group)){
			$gid=$this->insert(array(
				"lineid"=>$order["lineid"],
				"dateline"=>time(),
			));
			$group=$this->selectRow("gid=".$gid);
		}
		//拼车成团
		if($order["usernum"]==$group["freenum"]){
			$money=MM("pinche","pinche_order")->selectOne(array(
				"where"=>"gid=".$group["gid"]." or orderid=".$orderid,
				"fields"=>" sum(money) as mmoney "
			));
			if($driverid==0){
				$status=0;
			}else{
				$status=1;
				MM("pinche","pinche_driver_line")->update(array(
					"status"=>2
				),"driverid=".$driverid." AND lineid=".$order["lineid"]);
			}
			$this->update(array(
				"usernum"=>$group["usernum"]+$order["usernum"],
				"freenum"=>0,
				"money"=>$money,
				"driverid"=>$driverid,
				"status"=>$status,
				"ptime"=>time()-$group["dateline"]
			),"gid=".$group["gid"]);
			MM("pinche","pinche_order")->update(array(
				"driverid"=>$driverid,
				"gid"=>$group["gid"],
				"status"=>1
			),"gid=".$group["gid"]." or orderid=".$orderid);
		}else{
			MM("pinche","pinche_order")->update(array(
				"gid"=>$group["gid"],
				"status"=>1
			),"orderid=".$orderid);
			$this->update(array(
				"usernum"=>$group["usernum"]+$order["usernum"],
				"freenum"=>$this->maxnum-$order["usernum"]-$group["usernum"],			
				"ptime"=>time()-$group["dateline"]
			),"gid=".$group["gid"]);
		}
		
		M("user")->commit();
	}
	
}