<?php
class Service_LogisticPackProcess extends Common_Service
{
	public function __construct()
    {
        $this->_date = date('Y-m-d H:i:s');
    }
    
    /**
     * 运单装袋
     * @author william-fan
     * @param string $order_code
     * @param string $ob_no 袋号
     * @param string $tracking_number
     * @param string $so_code
     * @return array
     */
    public function scanPack($order_code, $ob_no) {
    	$result = array('state'=>0, 'error'=>'');
    	$db = Common_Common::getAdapter();
    	$db->beginTransaction();
    	$session = new Zend_Session_Namespace('userAuthorization');
    	$user=$session->user;
    	$userId = $user['user_id'];
    	try {
            $ob_no=strtoupper($ob_no);
            $logisticOrder = Service_LogisticsOrder::getByField($order_code,'logistics_code');
            $error = array();
            if(empty($logisticOrder)){
            	$error[] = '该运单不存在';
            }else{
            	if($logisticOrder['lo_status']!='4'){
            		$error[] = '改运单不是收货完成,不能装袋';
            	}
            }
            $packOrderRow = array(
           		'pack_code'=>$ob_no,
           		'orders_code'=>$order_code,
            	'operator'=>$userId,
            	'add_time'=>$this->_date,		
            );
            Service_PackOrder::add($packOrderRow);
            
            $packLogRow = array(
            	'pack_code'=>$ob_no,
            	'from_status'=>'0',
            	'to_status'=>'0',
            	'content'=>'订单装袋,扫描运单,运单服务商单号为:'.$logisticOrder['ref_tracking_number'],
            	'operator'=>$userId,
            	'add_time'=>$this->_date,				
            );
			Service_PackLog::add($packLogRow);            
			//更新运单
			$orderRow = array(
				'lo_status'=>'5',
				'lo_update_time'=>$this->_date,	
			);
			Service_LogisticsOrder::update($orderRow, $logisticOrder['logistics_code'],'logistics_code');
    		//添加运单日志
			$logisticOrderLog = array(
					'logistics_code'=>$order_code,
					'lol_comment'=>'运单扫描装袋',
					'lol_create_time'=>$this->_date,
					'lol_operator'=>$userId,
					'lol_ip'=>Common_Common::getIP(),
					'order_status_from'=>'4',
					'order_status_to'=>'5',
			);
			Service_LogisticsOrderLog::add($logisticOrderLog);
			
    		//提交事务
    		$db->commit();
    		//$db->rollback();
    		$result['state'] = 1;
    	} catch (Exception $e) {
    		$db->rollback();
    		$result['error'] = $e->getMessage();
    	}
    	return $result;
    }
    /**
     * 完成装袋
     * @author william-fan
     * @param array $aOutboundBag
     * @param float $total_weight
     * @return string|boolean 成功返回true
     */
    public function finishBag($package) {
    	$poList = Service_PackOrder::getByCondition(array('pack_code'=>$package['pack_code']));
    	if(empty($poList)) return '包袋中没有订单，无法完成装袋';
    	//事务
    	$db = Common_Common::getAdapter();
    	$db->beginTransaction();
    	$session = new Zend_Session_Namespace('userAuthorization');
    	$user=$session->user;
    	$userId = $user['user_id'];
    	try {
	    	foreach($poList as $order) {
	    		//订单
	    		$aOrder = Service_LogisticsOrder::getByField($order['orders_code'], 'logistics_code');
	    		if(intval($aOrder['lo_status'])!==5) throw new Exception('状态异常：运单跟踪号['.$aOrder['ref_tracking_number'].']不是装袋加挂状态');
	    		$uOrder['lo_update_time'] = date('Y-m-d H:i:s');
	    		$uOrder['lo_status'] = '6';
	    		$upresult = Service_LogisticsOrder::update($uOrder, $order['orders_code'], 'logistics_code');
	    		if($upresult){
	    			$logisticOrderLog = array(
	    					'logistics_code'=>$aOrder['logistics_code'],
	    					'lol_comment'=>'运单装袋完成',
	    					'lol_operator'=>$userId,
	    					'lol_ip'=>Common_Common::getIP(),
	    					'order_status_from'=>'5',
	    					'order_status_to'=>'6',
	    					'lol_create_time'=>date('Y-m-d H:i:s')
	    			);
	    			Service_LogisticsOrderLog::add($logisticOrderLog);
	    		}else{
	    			throw new Exception("更新订单状态出错");	
	    		}
	    	}
	    	$updateRow['status'] = 1;
	    	$updateRow['update_time'] = date('Y-m-d H:i:s');
	    	Service_Pack::update($updateRow, $package['pack_id']);
	    	//提交
	    	$db->commit();
	    	//$db->rollback();
    	} catch (Exception $e) {
    		$db->rollback();
    		return $e->getMessage();
    	}  	
    	return true;
    }
    
    /**
     * 加挂
     * @author solar
     * @param string $ob_no
     * @param string $sb_code
     * @param number $ob_weight
     */
    public function mount($ob_no, $sb_code, $ob_weight) {
    	//事务
    	$db = Common_Common::getAdapter();
    	$db->beginTransaction();
    	try {
	    	$obdList = Service_OutboundBagDetail::getByCondition(array('ob_no'=>$ob_no));
	    	foreach($obdList as $obdRow) {
	    		//订单
	    		$aOrder = Service_Orders::getByField($obdRow['order_code'], 'order_code');
	    		$uOrder['update_time'] = date('Y-m-d H:i:s');
	    		$uOrder['order_status'] = 10;
	    		Service_Orders::update($uOrder, $obdRow['order_code'], 'order_code');
	    		Service_OrderLog::log($aOrder['order_id'], $aOrder['order_code'], 9, 10, 0, '加挂');
	    		//物流订单
	    		$uOrderShip['so_status'] = 3;
	    		$uOrderShip['so_update_time'] = date('Y-m-d H:i:s');
	    		Service_ShipOrder::update($uOrderShip, $obdRow['so_code'], 'so_code');
	    		//记录订单操作节点
	    		$oonRow['order_id'] = $obdRow['order_id'];
	    		$oonRow['order_code'] = $obdRow['order_code'];
	    		$oonRow['oot_code'] = 'ship';
	    		$oonRow['oon_add_time'] = date('Y-m-d H:i:s');
	    		$oonRow['user_id'] = Service_User::getUserId();
	    		Service_OrderOperationNode::add($oonRow);
	    		//记录时间
	    		$ootRow['ship_time'] = date('Y-m-d H:i:s');
	    		$ootRow['ship_user_id'] = Service_User::getUserId();
	    		$ootRow['update_time'] = date('Y-m-d H:i:s');
	    		Service_OrderOperationTime::update($ootRow, $obdRow['order_id'], 'order_id');
	    	}
	    	//更新包袋状态
	    	$updateRow['ob_status'] = 2;
	    	$updateRow['ob_update_time'] = date('Y-m-d H:i:s');
	    	Service_OutboundBag::update($updateRow, $ob_no, 'ob_no');
	    	//添加出货总单行
	    	$sbdRow['sb_code'] = $sb_code;
	    	$sbdRow['ob_no'] = $ob_no;
	    	$sbdRow['ob_weight'] = $ob_weight;
	    	$sbdRow['creater_id'] = Service_User::getUserId();
	    	$sbdRow['sbd_add_time'] = date('Y-m-d H:i:s');
	    	Service_ShipBatchDetail::add($sbdRow);
    		//提交
	    	$db->commit();
    	} catch (Exception $e) {
    		$db->rollback();
    		return $e->getMessage();
    	}  	
    	return true;
    }
    
    /**
     * 完成加挂
     * @author solar
     * @param string $sb_code
     * @return boolean|string
     */
    public function finishMount($sb_code) {
        $userAuth = new Zend_Session_Namespace('userAuthorization');
        $user_id = $userAuth->userId;
    	$aShipBatch = Service_ShipBatch::getByField($sb_code, 'sb_code');
    	if(intval($aShipBatch['sb_status'])!==0) return '出货总单不在草稿状态，无法完成加挂';
    	$count = Service_ShipBatchDetail::getByCondition(array('sb_code'=>$sb_code), 'count(*)');
    	if(!$count) return '出货总单还没有包袋，无法完成加挂';
    	//事务
    	$db = Common_Common::getAdapter();
    	$db->beginTransaction();
    	try {
	        $ShipBatchDetail = Service_ShipBatchDetail::getByCondition(array('sb_code'=>$sb_code),"*");
	        foreach($ShipBatchDetail as $key=>$value){
	            $obd = Service_OutboundBagDetail::getByCondition(array('ob_no'=>$value['ob_no']),"*");
	            foreach($obd as $k=>$v){
	                $orderRow = Service_Orders::getByField($v['order_code'],"order_code","*");
	                //订单 到 物流完成
	                $updateOrder = array(
	                    'order_status'=>11,					
	                    'update_time'=>date("Y-m-d H:i:s"),
	                );
	                Service_Orders::update($updateOrder,$v['order_code'],"order_code");
	                $orderLog = array(
	                    'order_id'=>$orderRow['order_id'],
	                    'order_code' => $v['order_code'],
	                    'ol_type'=>'0',
	                    'order_status_from'=>$orderRow['order_status'],
	                    'order_status_to' => '11',
	                    'ol_add_time' => date('Y-m-d H:i:s',time()),
	                    'user_id'=> $user_id,
	                    'ol_ip'=>Common_Common::getIP()
	                );
	                Service_OrderLog::add($orderLog);
	            }
	        }
			$now = date('Y-m-d H:i:s');
	    	$uShipBatch['sb_status'] = 1;	//方便测试，暂时为2
	    	$uShipBatch['sb_update_time'] = $now;
			$uShipBatch['sb_ship_time'] = $now;
	    	$sbRet = Service_ShipBatch::update($uShipBatch, $sb_code, 'sb_code');
	        $sbLog = array(
	            'sb_id'=>$aShipBatch['sb_id'],
	            'sb_code'=>$aShipBatch['sb_code'],
	            'sbl_type'=>1,
	            'user_id'=>$user_id,
	            'sbl_status_from'=>$aShipBatch['sb_status'],
	            'sbl_status_to'=>'1',
	            'sbl_note'=>'已完成',
	            'sbl_add_time'=>$now,
	            'sbl_ip'=>Common_Common::getIP()
	        );
	        Service_ShipBatchLog::add($sbLog);
	    	$sbaUpdate['pack_no'] = $count;
	    	$sbaUpdate['wrap_type'] = '2';//固定是纸箱
	    	$sbaRet = Service_ShipBatchAttribute::update($sbaUpdate, $sb_code, 'sb_code');
	    	//提交
	    	$db->commit();
    	} catch (Exception $e) {
    		$db->rollback();
    		return '内部错误';
    	}
    	return true;
    }
    
}