<?php
class Service_ReceivingBatch extends Common_Service
{
    /**
     * @var null
     */
    public static $_modelClass = null;

    /**
     * @return Table_ReceivingDetail|null
     */
    public static function getModelInstance()
    {
        if (is_null(self::$_modelClass)) {
            self::$_modelClass = new Table_ReceivingBatch();
        }
        return self::$_modelClass;
    }

    /**
     * @param $row
     * @return mixed
     */
    public static function add($row)
    {
        $model = self::getModelInstance();
        return $model->add($row);
    }


    /**
     * @param $row
     * @param $value
     * @param string $field
     * @return mixed
     */
    public static function update($row, $value, $field = "rb_id")
    {
        $model = self::getModelInstance();
        return $model->update($row, $value, $field);
    }

    /**
     * @param $value
     * @param string $field
     * @return mixed
     */
    public static function delete($value, $field = "rb_id")
    {
        $model = self::getModelInstance();
        return $model->delete($value, $field);
    }

    /**
     * @param $value
     * @param string $field
     * @param string $colums
     * @return mixed
     */
    public static function getByField($value, $field = 'rb_id', $colums = "*")
    {
        $model = self::getModelInstance();
        return $model->getByField($value, $field, $colums);
    }

    /**
     * @return mixed
     */
    public static function getAll()
    {
        $model = self::getModelInstance();
        return $model->getAll();
    }

    /**
     * @param array $condition
     * @param string $type
     * @param int $pageSize
     * @param int $page
     * @param string $order
     * @return mixed
     */
    public static function getByCondition($condition = array(), $type = '*', $pageSize = 0, $page = 1, $order = "")
    {
        $model = self::getModelInstance();
        return $model->getByCondition($condition, $type, $pageSize, $page, $order);
    }

    /**
     * @param $val
     * @return array
     */
    public static function validator($val)
    {
        $validateArr = $error = array();
        
        return  Common_Validator::formValidator($validateArr);
    }


    /**
     * @param array $params
     * @return array
     */
    public  function getFields()
    {
        $row = array(
        
              'E0'=>'rb_id',
              'E1'=>'rb_code',
              'E2'=>'customer_code',
              'E3'=>'warehouse_id',
              'E4'=>'status',
              'E5'=>'problem_status',
              'E6'=>'underreview_status',
              'E7'=>'add_time',
              'E8'=>'submit_time',
              'E9'=>'last_modified_time',
              'E10'=>'remark',
              'E11'=>'oper_userid',
        );
        return $row;
    }
	/**
	 * @author william-fan
	 * @todo 得到区外仓的运输方式
	 **/
    public static function getShipMethod(){
    /*	$shipMethod = array(
    		'BH-MMP'=>'BH-MMP 瑞典小包挂号',
			'SWPT'=>'SWPT 瑞典小包平邮',
			'HQSWGH'=>'HQSWGH 环球易购瑞典小包挂号',
    		//'HKDHL'=>'HKDHL 香港敦豪国际速递'
            'BH-SGP'=>'BH-SGP 新加坡邮政小包平邮',
            'BH-SGG'=>'BH-SGG 新加坡邮政小包挂号',
            'CJ-DGMG'=>'CJ-DGMG 德国邮政小包挂号',
            'CJ-DGMP'=>'CJ-DGMP 德国邮政小包平邮',
            'HKPG' => 'HKPG 香港小包 挂号',
            'HKPP' => 'HKPP 香港小包 平邮',
    	);*/
      // 获取仓库为QWCQH或ALL可用的运输方式
      $shipMethod = array();
      $warehouse  = Service_Warehouse::getByField('QWCQH', 'warehouse_code');
      $sm         = Service_ShippingMethod::getByCondition(array(
        'sm_status'        => 1,
        'warehouse_id_arr' => array(0, (int) $warehouse['warehouse_id']),
      ));
      $sm = Common_Common::multisort($sm);
      if (!empty($sm)) {
        foreach ($sm as $item) {
          $shipMethod[$item['sm_code']] = $item['sm_code'] . ' ' . $item['sm_name_cn'];
        }
      }

    	return $shipMethod;
    }
    public static function getStatus(){
    	$status = array(
    		'0'=>'草稿',
    		'1'=>'已收货',	
    	);
    	return $status;		
    }
    /**
     * @author william-fan
     * @todo 用于创建到货总单
     */
    public function createBatchProcess($customer_code){
    	$receivingBatchCondition = array(
    		'customer_code'=>$customer_code,
    		'status'=>'0',
    	);
    	$receingBatch = Service_ReceivingBatch::getByCondition($receivingBatchCondition,'*');
    	$result = array (
    			"ask" => 0,
    			"message" => "创建到货总单失败",
    			'receivingData'=>'',
    	);
    	$_userAuth = new Zend_Session_Namespace('userAuthorization');
    	if(empty($receingBatch)){
    		$db = Common_Common::getAdapter ();
    		$db->beginTransaction ();
    		$dateTime = date('Y-m-d H:i:s',time());
    		try {
    			//$result = $this->ceiveBack ( $cuId,$qty );
    			if(empty($customer_code)){
    				throw new Exception('客户代码必填');
    			}else{
    				$customer = Service_Customer::getByField($customer_code,'customer_code');
    				if(empty($customer)){
    					throw new Exception('您输入的客户不存在');
    				}else{
    					if($customer['customer_status']!='2'){
    						throw new Exception('该客户暂时不可用');
    					}
    				}
    			}
    			$receiving_code = Common_GetNumbers::getCode('receingBatch', $customer_code, 'REB'); // 借领用号
    			$receivingBatchRow['rb_code'] = strtoupper($receiving_code);
    			$receivingBatchRow['customer_code'] = strtoupper($customer_code);
    			$receivingBatchRow['warehouse_id'] = '1';
    			$receivingBatchRow['add_time'] = $dateTime;
    			$receivingBatchRow['submit_time'] = $dateTime;
    			$receivingBatchRow['last_modified_time'] = $dateTime;
    			$receivingBatchRow['oper_userid'] = isset($_userAuth->userId) ? $_userAuth->userId : '0';
    			$rb_id = Service_ReceivingBatch::add($receivingBatchRow);
    			if($rb_id){
    				$receivingBatchLog = array(
    						'rb_code' => $receivingBatchRow['rb_code'],
    						'from_status' => '0',
    						'to_status' => '0',
    						'action' => "新增到货总单",
    						'content' => "新增到货总单",
    						'operator' => isset($_userAuth->userId) ? $_userAuth->userId : '0',
    						'add_time' => $dateTime
    				);
    				Service_ReceivingBatchLog::add($receivingBatchLog);
    			}else{
    				throw new Exception('创建到货单出错');
    			}
    			$receivingBatchRow['rb_id'] = $rb_id;
    			$result['ask'] = '1';
    			$result['message'] = 'success';
    			$result['receivingData'] = $receivingBatchRow;
    			$db->commit ();
    			//$db->rollback ();
    		} catch ( Exception $e ) {
    			$db->rollback ();
    			$result = array (
    					"ask" => 0,
    					"message" => $e->getMessage (),
    					'errorCode' => $e->getCode ()
    			);
    		}
    	}else{
    		//存在receivingBatch 数据
    		$result['ask'] = '1';
    		$result['message'] = '';
    		$result['receivingData'] = $receingBatch[0];
    	}
    	return $result;
    }
    
    /**
     * @author william-fan
     * @todo 用于创建到货单运单关联
     */
    public function createBatchOrderProcess($rb_code,$weight,$order_code,$country=''){
    	$result = array (
    			"ask" => 0,
    			"message" => "运单和到货总单关联失败",
    			'receivingData'=>'',
    			'error'=>'',
    			'count'=>'0',
    			'tracking_number'=>'',
    			'scanTracking'=>'0',
    			'logistic_code'=>'',
    	);
    	$_userAuth = new Zend_Session_Namespace('userAuthorization');
    	$order_code = strtoupper($order_code);
    	$dateTime = date('Y-m-d H:i:s',time());
    	$receivingBatch = Service_ReceivingBatch::getByField($rb_code,'rb_code');
    	$error = array();
    	$scanTracking = '0'; //扫描的是订单号
    	if(empty($receivingBatch)){
    		$error[] = "到货总单不存在";
    	}else{
    		if($receivingBatch['status']=='1'){
    			$error[] = '到货总单已收货';
    		}
    	}
    	if(!(is_numeric($weight) && $weight>0)){
    		$error[] = '总量必须是大于0的数字';
    	}
    	$logistic_order = Service_LogisticsOrder::getByField($order_code,'logistics_code');
    	if(empty($logistic_order)){
    		$logistic_order= Service_LogisticsOrder::getByField($order_code,'ref_tracking_number');
    		if(!empty($logistic_order)){
    			$scanTracking = '1'; //扫描的是运单号
    		}
    	}
    	if(empty($logistic_order)){
    		$error[] = '该运单不存在';
    	}else{
    		$order_code = $logistic_order['logistics_code'];
    		if($logistic_order['lo_status']!='2'){
    			$error[] = '该运单不是已提交状态';
    		}else{
    			$customer = Service_Customer::getByField($logistic_order['customer_id']);
    			if(strtoupper($receivingBatch['customer_code'])!=strtoupper($customer['customer_code'])){
    				$error[] = '该运单不属于该客户无法扫描';
    			}
    		}
    		$trackingNumber = $logistic_order['ref_tracking_number'];
    	}
    	if($country==''){
    		$error[] = '国家必填';
    	}
    	if(!empty($error)){
    		$result['error'] = $error;
    		return $result;
    	}
    	$db = Common_Common::getAdapter ();
    	$db->beginTransaction ();
    	try{
    		$receivingBatchOrderRow = array(
    				'logistics_code'=>$order_code,
    				'rb_code'=>$rb_code,
    				'weight'=>$weight,
                    'user_id'=>isset($_userAuth->userId) ? $_userAuth->userId : '0',
    				'sm_code'=>$logistic_order['sm_code'],
    				'add_time'=>$dateTime,
    		);
    		//print_r($receivingBatchOrderRow);
    		Service_ReceivingBatchOrder::add($receivingBatchOrderRow);
    		 
    		$logisticOrderRow = array(
    			'lo_status'=>'3',
    			'lo_update_time'=>$dateTime		
    		);
    		Service_LogisticsOrder::update($logisticOrderRow, $logistic_order['lo_id']);
    		//更新订单国家
    		$orderAddressRow = array(
    			'loa_country'=>$country,
    		);
    		Service_LogisticsOrderAddress::update($orderAddressRow, $order_code,'logistics_code');
    		$logisticOrderLog = array(
    				'logistics_code'=>$order_code,
    				'lol_comment'=>'收货扫描运单',
    				'lol_create_time'=>$dateTime,
    				'lol_operator'=>isset($_userAuth->userId) ? $_userAuth->userId : '0',
    				'lol_ip'=>Common_Common::getIP(),
    				'order_status_from'=>$logistic_order['lo_status'],
    				'order_status_to'=>'3',
    		);
    		Service_LogisticsOrderLog::add($logisticOrderLog);
    		$batchOrderCondition = array(
    			'rb_code'=>$rb_code,
    		);
    		$count = Service_ReceivingBatchOrder::getByCondition($batchOrderCondition,'count(*)');
    		//以下为扣费操作
            //解冻金额
            $balanceProcess = new Service_CustomerBalanceProcess();
            $unfeeResult =  $balanceProcess->logisticsUnFreezeFee($order_code, $logistic_order['customer_id']);
            if($unfeeResult !== true) {
                throw new Exception($unfeeResult);
            }
            //扣款
            $sop = new Service_ShipOrderProcess();
            $financeResult = $sop->shipLogisticsFee($order_code,$logistic_order['customer_id'],$weight,$country);
            if($financeResult !== true) throw new Exception($financeResult);
    		
    		
    		$result['count'] = $count;
    		$result['ask'] = '1';
    		$result['tracking_number'] =$trackingNumber;
    		$result['message'] = '扫描成功';
    		$result['scanTracking'] = $scanTracking;
    		$result['logistic_code'] = $logistic_order['logistics_code'];
        $result['smCode'] = $logistic_order['sm_code'];
        $receivingCountry = Service_Country::getByField((int) $country, 'country_id');
        $result['countryCode'] = $receivingCountry ? $receivingCountry['country_code'] : '';
    		$db->commit ();
    		//$db->rollback ();
    	}catch(Exception $e){
    		$db->rollback ();
    		$result = array (
    				"ask" => 0,
    				"message" => $e->getMessage (),
    				'errorCode' => $e->getCode ()
    		);
    	}
    	return $result;
    }

    /**
     * @author william-fan
     * @todo 用于添加到货详情
     */
    public function createBatchDetailProcess($smDate,$rb_code){
    	$result = array(
    			'ask'=>'0',
    			'message'=>'完成到货总单失败',
    			'data'=>'',
    	);
    	$dateTime = date('Y-m-d H:i:s',time());
    	$receivingBatch = Service_ReceivingBatch::getByField($rb_code,'rb_code');
    	$_userAuth = new Zend_Session_Namespace('userAuthorization');
    	$error = array();
    	if(empty($receivingBatch)){
    		$error[] = "到货总单不存在";
    	}else{
    		if($receivingBatch['status']=='1'){
    			$error[] = '到货总单已收货';
    		}
    	}
    	$receingBatchOrderConditionAll = array('rb_code'=>$rb_code);
    	$haveSmArr=Service_ReceivingBatchOrder::getByCondition($receingBatchOrderConditionAll,array('sm_code'));
    	//print_r($haveSmArr);
		//校验输入的数据
		//print_r($smDate);
		$warring = 0 ;
		if(!empty($smDate)){
			$smArr = array();
			foreach($smDate as $key=>$ordetail){
				if(!(is_numeric($ordetail['weight']) && $ordetail['weight']>0 )){
					$error[] = "{$ordetail['smCode']}重量必须填写,并且是数字";
					$warring++;
				}
				// $ordetail['bagQty'];
				if(!(is_int($ordetail['bagQty']+0) && $ordetail['bagQty']>0 )){
					$error[] = "{$ordetail['smCode']}袋数必须填写,并且是正整数";
					$warring++;
				}
				if(!(is_int($ordetail['packQty']+0) && $ordetail['packQty']>0 )){
					$error[] = "{$ordetail['smCode']}件数必须填写,并且是正整数";
					$warring++;
				}
				if(in_array($ordetail['smCode'],$smArr)){
					$error[] = "{$ordetail['smCode']}不允许重复";
				}
				$smArr[] = $ordetail['smCode'];
				$receingBatchOrderCondition = array(
					'rb_code'=>$rb_code,
					'sm_code'=>$ordetail['smCode'],	
				);
				/* $count=Service_ReceivingBatchOrder::getByCondition($receingBatchOrderCondition,'count(*)');
				if($count!=$ordetail['packQty']){
					$error[] = "填写{$ordetail['smCode']}运输方式{$ordetail['packQty']}件，实际扫描了{$count}件";
				} */
			}
		}else{
			$error[] = "数据不完整";
		}
		if(!empty($haveSmArr)){
			foreach($haveSmArr as $keysm=>$vasm){
				if(!in_array($vasm['sm_code'], $smArr)){
					$error[] ="系统已扫描{$vasm['sm_code']},您未选中该运输方式";
				}
			}
		}
		if($warring==0 && !empty($error)){
			if(!empty($smDate)){
				Service_ReceivingBatchDetail::delete($rb_code,'rb_code');
				foreach($smDate as $key=>$ordetail){
					$receivingBatchDetailRow = array(
							'rb_code'=>$rb_code,
							'rbdetail_status'=>'2',
							'sm_code'=>$ordetail['smCode'],
							'BagQty'=>$ordetail['bagQty'],
							'PackageQty'=>$ordetail['packQty'],
							'TotalWeight'=>$ordetail['weight']
					);
					Service_ReceivingBatchDetail::add($receivingBatchDetailRow);
				}
			}
		}
    	if(!empty($error)){
    		$result['error'] = $error;
    		return $result;
    	}
    	$db = Common_Common::getAdapter ();
    	$db->beginTransaction ();
    	try {
    		Service_ReceivingBatchDetail::delete($rb_code,'rb_code');
    		foreach($smDate as $key=>$ordetail){
    			$receivingBatchDetailRow = array(
    				'rb_code'=>$rb_code,
    				'rbdetail_status'=>'2',
    				'sm_code'=>$ordetail['smCode'],
    				'BagQty'=>$ordetail['bagQty'],
    				'PackageQty'=>$ordetail['packQty'],
    				'TotalWeight'=>$ordetail['weight']							
    			);
    			Service_ReceivingBatchDetail::add($receivingBatchDetailRow);
    		}
    		
    		$receingBatchRow = array(
    			'status'=>'1',
    			'last_modified_time'=>$dateTime,	
    		);
    		
    		Service_ReceivingBatch::update($receingBatchRow, $rb_code,'rb_code'); //更新送货单到已收件
    		
    		$condition = array(
    			'rb_code'=>$rb_code,
    		);
    		
    		$receingBatchOrders = Service_ReceivingBatchOrder::getByCondition($condition,'*');
    		if(!empty($receingBatchOrders)){
    			foreach($receingBatchOrders as $ro=>$vo){
    				$logisticOrders=Service_LogisticsOrder::getByField($vo['logistics_code'],'logistics_code');
    				if($logisticOrders['lo_status']!='3'){
    					throw new Exception("{$vo['logistics_code']}不是装袋加挂状态");
    				}
    				$logisticOrderLog = array(
    						'logistics_code'=>$vo['logistics_code'],
    						'lol_comment'=>'完成到货总单',
    						'lol_create_time'=>$dateTime,
    						'lol_operator'=>isset($_userAuth->userId) ? $_userAuth->userId : '0',
    						'lol_ip'=>Common_Common::getIP(),
    						'order_status_from'=>'3',
    						'order_status_to'=>'4',
    				);
    				Service_LogisticsOrderLog::add($logisticOrderLog);
    				$logisticOrderRow  = array(
    					'lo_status'=>'4',
    					'lo_update_time'=>$dateTime	
    				);
    				
    				Service_LogisticsOrder::update($logisticOrderRow,$vo['logistics_code'],'logistics_code'); //更新运单到4 收货完成
    			}
    		}
    		$receivingBatchLog = array(
    				'rb_code' => $rb_code,
    				'from_status' => '0',
    				'to_status' => '1',
    				'action' => "完成到货总单",
    				'content' => "完成到货总单",
    				'operator' => isset($_userAuth->userId) ? $_userAuth->userId : '0',
    				'add_time' => $dateTime
    		);
    		Service_ReceivingBatchLog::add($receivingBatchLog);
    		/* $receingOrderDetailRow = array(
    			'rbdetail_status'=>'2',
    		);
    		Service_ReceivingBatchOrder::update($receingOrderDetailRow, $rb_code,'rb_code'); */
    		$result['ask']='1';
    		$result['message'] = "完成到货总单";
    		//$db->rollback ();
    		$db->commit();
    	}catch ( Exception $e ) {
    		$db->rollback ();
    		$result = array (
    			"ask" => 0,
    			"message" => $e->getMessage (),
    			'errorCode' => $e->getCode ()
    		);
    	}
    	return $result;
    }
    /**
     * @author william-fan
     * @todo 校验错误和警告
     */
    public function createBatchDetailCheck($smDate,$rb_code){
    	$result = array(
    			'ask'=>'0',
    			'message'=>'提交数据错误',
    			'data'=>'',
    			'waring'=>'',
    	);
    	$dateTime = date('Y-m-d H:i:s',time());
    	$receivingBatch = Service_ReceivingBatch::getByField($rb_code,'rb_code');
    	$_userAuth = new Zend_Session_Namespace('userAuthorization');
    	$error = array();
    	if(empty($receivingBatch)){
    		$error[] = "到货总单不存在";
    	}else{
    		if($receivingBatch['status']=='1'){
    			$error[] = '到货总单已收货';
    		}
    	}
    	$receingBatchOrderConditionAll = array('rb_code'=>$rb_code);
    	$haveSmArr=Service_ReceivingBatchOrder::getByCondition($receingBatchOrderConditionAll,array('sm_code'));
    	//print_r($haveSmArr);
    	//校验输入的数据
    	//print_r($smDate);
    	$warring = 0 ;
    	$waringArr = '';
    	if(!empty($smDate)){
    		$smArr = array();
    		foreach($smDate as $key=>$ordetail){
    			if(!(is_numeric($ordetail['weight']) && $ordetail['weight']>0 )){
    				$error[] = "{$ordetail['smCode']}重量必须填写,并且是数字";
    				$warring++;
    			}
    			// $ordetail['bagQty'];
    			if(!(is_int($ordetail['bagQty']+0) && $ordetail['bagQty']>0 )){
    				$error[] = "{$ordetail['smCode']}袋数必须填写,并且是正整数";
    				$warring++;
    			}
    			if(!(is_int($ordetail['packQty']+0) && $ordetail['packQty']>0 )){
    				$error[] = "{$ordetail['smCode']}件数必须填写,并且是正整数";
    				$warring++;
    			}
    			if(in_array($ordetail['smCode'],$smArr)){
    				$error[] = "{$ordetail['smCode']}不允许重复";
    			}
    			$smArr[] = $ordetail['smCode'];
    			$receingBatchOrderCondition = array(
    					'rb_code'=>$rb_code,
    					'sm_code'=>$ordetail['smCode'],
    			);
    			$count=Service_ReceivingBatchOrder::getByCondition($receingBatchOrderCondition,'count(*)');
    			if($count!=$ordetail['packQty']){
    				$waringArr[] = "填写{$ordetail['smCode']}运输方式{$ordetail['packQty']}件，实际扫描了{$count}件";
    			}
    		}
    	}else{
    		$error[] = "数据不完整";
    	}
    	if(!empty($haveSmArr)){
    		foreach($haveSmArr as $keysm=>$vasm){
    			if(!in_array($vasm['sm_code'], $smArr)){
    				$error[] ="系统已扫描{$vasm['sm_code']},您未选中该运输方式";
    			}
    		}
    	}
    	
    	$result['waring'] = $waringArr;
    	if(empty($error)){
    		$result['ask'] = '1';
    	}else{
    		$result['error'] = $error;
    	}
    	return $result;
    }
    /**
     * @author willliam-fan
     * @todo 用于删除到货单运单关联 receiving_batch_order
     */
    public function deleteBatchOrderProcess($rbo_id){
    	$result = array(
    			'ask'=>'0',
    			'message'=>'删除失败',
    			'data'=>'',
    	);
    	$dateTime = date('Y-m-d H:i:s',time());
    	$receivingBatchOrder = Service_ReceivingBatchOrder::getByField($rbo_id);
    	$_userAuth = new Zend_Session_Namespace('userAuthorization');
    	if(!empty($receivingBatchOrder)){
    		$logisticOrder = Service_LogisticsOrder::getByField($receivingBatchOrder['logistics_code'],'logistics_code');
    		if(!empty($logisticOrder) && $logisticOrder['lo_status']=='3'){
    			$db = Common_Common::getAdapter ();
    			$db->beginTransaction ();
    			try{
    				Service_ReceivingBatchOrder::delete($rbo_id);
    				
    				$logisticOrderRow = array(
    						'lo_status'=>'2',
    						'lo_update_time'=>$dateTime
    				);
    				Service_LogisticsOrder::update($logisticOrderRow, $receivingBatchOrder['logistics_code'],'logistics_code');

    				$logisticOrderLog = array(
    						'logistics_code'=>$receivingBatchOrder['logistics_code'],
    						'lol_comment'=>'删除扫描的订单',
    						'lol_create_time'=>$dateTime,
    						'lol_operator'=>isset($_userAuth->userId) ? $_userAuth->userId : '0',
    						'lol_ip'=>Common_Common::getIP(),
    						'order_status_from'=>'3',
    						'order_status_to'=>'2',
    				);
    				Service_LogisticsOrderLog::add($logisticOrderLog);
    				$batchOrderCondition = array(
    						'rb_code'=>$receivingBatchOrder['rb_code'],
    				);
                    //退款
                    $cbp = new Service_CustomerBalanceProcess();
                    $refund = $cbp->logisticsRefund($logisticOrder['logistics_code'],$logisticOrder['customer_id']);
                    if($refund !== true) throw new Exception($refund);
    				$result['ask']='1';
    				$result['message'] = '删除成功';
    				$db->commit ();
    			}catch (Exception $e){
    				$db->rollback ();
    				$result = array (
    						"ask" => 0,
    						"message" => $e->getMessage (),
    				);
    			}
    		}
    	}else{
    		$result['message'] = '该运单不存在或者未扫描';
    	}
    	return $result;
    }
    /**
     * @author william-fan
     * @todo 添加运输方式
     */
    public function createSMDetailProcess($smDate,$rb_code){
    	$result = array(
    			'ask'=>'0',
    			'message'=>'添加到货运输方式详情失败',
    			'data'=>'',
    	);
    	$dateTime = date('Y-m-d H:i:s',time());
    	$receivingBatch = Service_ReceivingBatch::getByField($rb_code,'rb_code');
    	$_userAuth = new Zend_Session_Namespace('userAuthorization');
    	$error = array();
    	if(empty($receivingBatch)){
    		$error[] = "到货总单不存在";
    	}else{
    		if($receivingBatch['status']=='1'){
    			$error[] = '到货总单已收货';
    		}
    	}
    	$receingBatchOrderConditionAll = array('rb_code'=>$rb_code);
    	$haveSmArr=Service_ReceivingBatchOrder::getByCondition($receingBatchOrderConditionAll,array('sm_code'));
    	//print_r($haveSmArr);
    	//校验输入的数据
    	//print_r($smDate);
    	$warring = 0 ;
    	if(!empty($smDate)){
    		$smArr = array();
    		foreach($smDate as $key=>$ordetail){
    			if(!(is_numeric($ordetail['weight']) && $ordetail['weight']>0 )){
    				$error[] = "{$ordetail['smCode']}重量必须填写,并且是数字";
    				$warring++;
    			}
    			// $ordetail['bagQty'];
    			if(!(is_int($ordetail['bagQty']+0) && $ordetail['bagQty']>0 )){
    				$error[] = "{$ordetail['smCode']}袋数必须填写,并且是正整数";
    				$warring++;
    			}
    			if(!(is_int($ordetail['packQty']+0) && $ordetail['packQty']>0 )){
    				$error[] = "{$ordetail['smCode']}件数必须填写,并且是正整数";
    				$warring++;
    			}
    			if(in_array($ordetail['smCode'],$smArr)){
    				$error[] = "{$ordetail['smCode']}不允许重复";
    			}
    			$smArr[] = $ordetail['smCode'];
    			$receingBatchOrderCondition = array(
    					'rb_code'=>$rb_code,
    					'sm_code'=>$ordetail['smCode'],
    			);
    		}
    	}else{
    		$error[] = "数据不完整";
    	}
    	if(!empty($error)){
    		$result['error'] = $error;
    		return $result;
    	}
    	$db = Common_Common::getAdapter ();
    	$db->beginTransaction ();
    	try {
    	    if($warring==0){
		    	if(!empty($smDate)){
		    		Service_ReceivingBatchDetail::delete($rb_code,'rb_code');
		    		foreach($smDate as $key=>$ordetail){
		    			$receivingBatchDetailRow = array(
		    				'rb_code'=>$rb_code,
		    				'rbdetail_status'=>'1',
		    				'sm_code'=>$ordetail['smCode'],
		    				'BagQty'=>$ordetail['bagQty'],
		    				'PackageQty'=>$ordetail['packQty'],
		    				'TotalWeight'=>$ordetail['weight']
		    			);
		    			Service_ReceivingBatchDetail::add($receivingBatchDetailRow);
		    		}
		    	}
    		}
    		$result['ask']='1';
    		$result['message'] = "添加到货运输方式详情成功";
    		//$db->rollback ();
    		$db->commit();
    	}catch ( Exception $e ) {
    		$db->rollback ();
    		$result = array (
    				"ask" => 0,
    				"message" => $e->getMessage (),
    				'errorCode' => $e->getCode ()
    		);
    	}
    	return $result;
    }
}