<?php
class Service_AsnProccess
{
    protected $_orderCode = null;
    protected $_products = null;
    protected $_customerId = null;
    protected $_customerInfo = null;
    protected $_warehouseId = null;
    protected $_error;
    protected $_pro;
    protected $_receiving = array();
    protected $_date = '';

	public static function getAsnStatus(){
		$status[0] = Ec_Lang::getInstance()->getTranslate('delete');//'删除';
		$status[1] = Ec_Lang::getInstance()->getTranslate('Draft');//'草稿';
		$status[2] = Ec_Lang::getInstance()->getTranslate('Confirm');//'确认';
		$status[3] = Ec_Lang::getInstance()->getTranslate('PendingAudit');//'待审核';
		$status[4] = Ec_Lang::getInstance()->getTranslate('Audited');//'已审核';
		$status[5] = Ec_Lang::getInstance()->getTranslate('onway');//'在途';
		$status[6] = Ec_Lang::getInstance()->getTranslate('ReceiptOf');//'收货中';
		$status[7] = Ec_Lang::getInstance()->getTranslate('ReceiptComplete');//'收货完成';
		return $status;
	}
    public static $itemStatus = array(
        0 => 'Awaiting',
        1 => 'Receiving',
        2 => 'Finished',
    );

    public static $AsnType = array(
        0 => 'Normal',
        1 => 'By Po',
        2 => 'Refund',
        3 => 'Reject',
        4 => 'Return',
    );
	public static function getAsnType(){
		$status[0] = Ec_Lang::getInstance()->getTranslate('Standard');//'标准';
		//$status[1] = Ec_Lang::getInstance()->getTranslate('OrdersReturns');//'订单退货';
		//$status[2] = Ec_Lang::getInstance()->getTranslate('SpecifyTheProductBackPieces');//'指定产品退件';
		//$status[3] = Ec_Lang::getInstance()->getTranslate('Transit');//'中转';
		return $status;
	}
    public static $applicationType = array(
        1 => 'avrived',
        2 => 'receive',
        3 => 'putaway',
    );

    //异常状态
    public static $underreviewStatus = array(
        0 => 'Normal', //无
        1 => 'Abnormal',
    );

    
    public function __construct($pro = 'R'){
      
        $this->_pro = $pro;
        $this->_date = date('Y-m-d H:i:s');
    }



 /**
     * @author william-fan
     * @todo 备货表单数据验证
     * @param array $data
     * @return array('ask' => 0, 'msg' => array(), 'data' => array());
     */
    public static function validate(&$data = array())
    {
    	$error = array();
        if (empty($data)) {
        	$error[]=Ec_Lang::getInstance()->getTranslate('DataError');//'数据出错';
        	return $error;
        }
        if ("" == $data['warehouseId']) {
        	$error[] = Ec_Lang::getInstance()->getTranslate('WarehouseRequired');//"仓储必填";
        }
		
		if($data['receive_model_type']=='0'){
			//备货模式
			if(!isset($data['product_sku']) || empty($data['product_sku'])){
				$error[] = Ec_Lang::getInstance()->getTranslate('ProductsMusBeSelected');//"必须选择产品";
			}	
			
		}else{
				$error[] = Ec_Lang::getInstance()->getTranslate('ASNSchemaError');//"ASN模式错误";			
		
		}
		$customerId = $data['customer_id'];				
		if(empty($customerId)){		
			$error[] = Ec_Lang::getInstance()->getTranslate('customer_info_required');// '客户ID必填';		
		}else{
			$customer = Service_Customer::getByField($customerId,'customer_id');
			if(empty($customer)){			
				$error[] = Ec_Lang::getInstance()->getTranslate('customer_info_required');// '客户ID必填';
			}
			$data['customer_code'] =  $customer ['customer_code'];
			
		
		}
		
		
		if(!(isset($data['is_delivery']) && ($data['is_delivery']=='0' || $data['is_delivery']=='1'))){
			$error[] = Ec_Lang::getInstance()->getTranslate('is_delivery_required');
		}
        if($data['ref_code']==''){
        	$error[] = Ec_Lang::getInstance()->getTranslate('CustomerReferenceRequired');// '客户参考号必填';
        }else{
        	
        }
		
        if($data['ie_port']==''){
        	$error[] = Ec_Lang::getInstance()->getTranslate('ImportexportPortsRequred');//'进出口口岸必填';
        }
		
        if($data['form_type']==''){
        	$error[] = Ec_Lang::getInstance()->getTranslate('BusinessTypeRequired');//'业务类型必填';
        }
        /* if($data['form_type']==''){
        	$error[] = '业务类型必填';
        }
        if($data['traf_name']==''){
        	$error[] = Ec_Lang::getInstance()->getTranslate('LicensePlateNumber').Ec_Lang::getInstance()->getTranslate('require');//'车牌号必填';
        } */
        if($data['wrap_type']==''){
        	$error[] = Ec_Lang::getInstance()->getTranslate('PackingTypeRequred');//'包装种类必填';
        }
		
        if($data['pack_no']==''){
        	$error[] = Ec_Lang::getInstance()->getTranslate('TotalNumberRequred');//'总件数必填';
        }else{
					
			        if(!preg_match('/[0-9]+/i',$data['pack_no']) || !is_numeric($data['pack_no']) ||  $data['pack_no']<1 ){
        				$error[] =Ec_Lang::getInstance()->getTranslate('packNoError');//'总件数必须为正';
        			}
		
		}
				

        if($data['trade_mode']==''){
        	$error[] =Ec_Lang::getInstance()->getTranslate('RegulatoryApproachRequred');//'监管方式必填';
        }
        if($data['trans_mode']==''){
        	$error[] = Ec_Lang::getInstance()->getTranslate('TransactionMethod').Ec_Lang::getInstance()->getTranslate('require');//'成交方式必填'; 
        }
 	
		 if($data['ref_code']!='' && empty($data['ASNCode'])){
		 		$condition = array('reference_no'=>$data['ref_code'],'customer_id'=>$customerId,'receiving_status_arr'=>array('1','2','3','4','5','6','7'));
		 		$receivings = Service_Receiving::getByCondition($condition,'reference_no');
				if($receivings){
					$error[] = Ec_Lang::getInstance()->getTranslate('CustomerReferenceNumberExistence'); //"参考号已经存在";
				}		 
		 }    	
        
		
		//判断产品
		
		if(isset($data['po_tb_id']) && !empty($data['po_tb_id']) ) {
				
				foreach($data['po_tb_id'] as $po_tb_id){
					if($po_tb_id){
						$PurchaseOrderTrackingBody = Service_PurchaseOrderTrackingBody::getByField($po_tb_id,'po_tb_id');
						if(empty($PurchaseOrderTrackingBody)){
		    				$error[]=Ec_Lang::getInstance()->getTranslate('DataError');//'数据出错 
							break;       					
						
						}else{
						    if($PurchaseOrderTrackingBody['is_created_asn'] == '1'){							  
							  $error[]=Ec_Lang::getInstance()->getTranslate('AddIsCreateASNFail');
							  break;
							}
							
						}
					}
				
				}
				
		
		}else{
		    $error[]=Ec_Lang::getInstance()->getTranslate('DataError');//'数据出错';
        	return $error;
		
		}
		
		if(isset($data['product_id_list']) && !empty($data['product_id_list']) ) {        	
		$product_id_list = $data['product_id_list'];
		$sum = 0;
		$sku =  $data['sku'];//数量列表
		
		foreach ($product_id_list as $k=>$product_id) {
			$product = Service_Product::getByField($product_id,'product_id');
			$product_sku = $data['product_sku'][$k];				
			if(!$product){				
				$error[] = "product sku:[{$product_sku}] ".Ec_Lang::getInstance()->getTranslate('ProductDoesNotExist');
				continue;
			}else{
				//if(!preg_match('/[0-9]+/i',$sku[$k]) || $sku[$k]<0){
					//$error[] = "产品SKU:[{$v}]的数量".Ec_Lang::getInstance()->getTranslate('NumberMustBeAnInteger');
				//}
				//判断产品是否是普通产品
				if(!in_array($product['product_type'], array('0'))){
					$error[] = "product sku:[{$product_sku}] ".Ec_Lang::getInstance()->getTranslate('ProductTypeError');
				}
        else {
          $hsCode = trim($product['hs_code']);
          $hsCode = Service_Hscodes::getByField($hsCode, 'hs_code');

          if (empty($hsCode)) {
            $error[] = '产品SKU[' . $product_sku . ']对应海关编码[' . $hsCode['hs_code'] . ']不存在';
          }
          elseif ($hsCode && -1 === (int) $hsCode['hs_code_status']) {
            $error[] = '产品SKU[' . $product_sku . ']对应海关编码[' . $hsCode['hs_code'] . ']已禁用';
          }
        }
				if($product['product_status']!='1'){
					$error[] = "product sku:[{$product_sku}] ".Ec_Lang::getInstance()->getTranslate('ProductStatusError');
				}
			}
		}
        
		
	  	$total_weight = 0;
	 	if(isset($data['sku']) && !empty($data['sku']) ) {
        	$product_sku_array = $data['product_sku'];
			$number_array = $data['sku'];
        	foreach ($product_id_list as $k=>$product_id) {
        			$number = trim($number_array[$k]);
					$product = Service_Product::getByField($product_id,'product_id');
					if(!$product){ continue;}					
					$total_weight+=	$product['product_weight']*	$number;
					$sku = $product_sku_array[$k];
        			if(!(preg_match('/^[0-9]+$/i',$number) && is_numeric($number) && $number>0)){
        				$error[] = "产品SKU[{$sku}]".Ec_Lang::getInstance()->getTranslate('NumberMustBeAnInteger');
        			}
        	}
        }
		
		
        if(isset($data['declared_value']) && !empty($data['declared_value']) ) {
        	$declare	  = $data['declared_value'];
        	foreach ($declare as $keyd=>$valuen){
        		$sku = $product_sku_array[$keyd];
        		$valuen = trim($valuen);
        		if(!is_numeric($valuen) || $valuen<=0){
        			$error[] = "产品SKU[{$sku}]".'申报价值必须是数字';
        		}
        	}
        }
        
        
		if($data['roughweight']==''){
				$error[] = "毛重必填.";
		}elseif(!(is_numeric($data['roughweight']) && $data['roughweight']>0)){       	
        		$error[] = Ec_Lang::getInstance()->getTranslate('roughweightError');//毛重        	
        }else{
			
			if(isset($data['product_sku']) && !empty($data['product_sku']) ) {
				if(!($total_weight>0 && $data['roughweight']>$total_weight)){
					$error[] = "毛重要大于净重({$total_weight} KG).";
				}
			}
		}
		
		
		}//if($data['receive_model_type']!='1')备货
		//$data['asn_order']
		
	

		return $error;
    }	


  
    /**
     * @author william-fan
     * @todo 创建一条新的 ASN 信息 事务处理 (备货模式)
     * @param $order ASN ,$item ASN产品 ,$customerId 客户ID
     * @return array('ask' => 0, 'msg' => '','Error'=>array(array('errorCode'=>'','errorMessage')), 'ASNCode' => '');
     */
    public function createTransaction($data)
    {
        $result = array('ask' => 0, 'msg' => '', 'error' => array(), 'ASNCode' => '');		
        $error = self::validate($data);
		
			
        //var_dump($error);
        //exit('cccnnn');
        if(!empty($error)){
        	$result['error'] = $error;
        	return $result;
        }		
				
        try {
            $DB = Common_Common::getAdapter();
            $DB->beginTransaction();
            $date = date('Y-m-d H:i:s');
            if (isset($data['ref_code']) && $data['ref_code'] != '') {
                $r = self::checkReferenceNo(array('reference_no' => $data['ref_code'], 'customer_id' => $customerId,'receiving_status_arr'=>array('1','2','3','4','5','6','7')));
            	if (!empty($r)) {
            		throw new Exception(Ec_Lang::getInstance()->getTranslate('CustomerReferenceNumberExistence'));
            	}
            }                 
           
            
            $ASNCode = $this->createCode();
            $receiving['receiving_code']	= $ASNCode;
            $receiving['reference_no'] 		= $data['ref_code'];
            $receiving['warehouse_id']		= $data['warehouseId'];
            $receiving['customer_id']		= $data['customer_id'];
            $receiving['customer_code'] 	= $data['customer_code'];        
            $receiving['receiving_type']	= 0;
            $receiving['receiving_status']	= '3';
            $receiving['receiving_add_time']= $date;
            $receiving['is_delivery']		= $data['is_delivery'];	
            //以下新增的内容
            //$receiving['refercence_form_id']= $data['refercence_form_id'];
            $receiving['ie_port']			= $data['ie_port'];
            $receiving['form_type']			= $data['form_type'];
            $receiving['traf_name']			= $data['traf_name'];
            $receiving['wrap_type']			= $data['wrap_type'];
            $receiving['pack_no']			= $data['pack_no'];
            $receiving['traf_mode']			= $data['traf_mode'];
			$receiving ['trade_mode']		= $data ['trade_mode'];
			$receiving ['trans_mode'] 		= $data ['trans_mode'];
			$receiving['roughweight']		= $data['roughweight'];

			$receiving ['haveconta'] = '0';
			$receiving ['conta_id'] = '';
			$receiving ['conta_model'] = '';
			$receiving ['conta_wt'] = '0';
			
			$receiving ['receiving_description'] = $data ['instructions'];
			$receiving['receive_model_type'] = '0';
			
			
			if (! isset ( $receiving ['receiving_type'] ) || $receiving ['receiving_type'] === '') {
				throw new Exception (Ec_Lang::getInstance()->getTranslate('ASNTypeIsEmpty'));
			}

           
			
            $receiving_id = Service_Receiving::add($receiving);
     
            $customerCode = $data['customer_code'];	
			
			$product_id_list = $data['product_id_list'];
			$product_sku = $data['product_sku'];//sku列表           
            $sku_quantity =  $data['sku'];//产品数量			
			$po_tb_ids = $data['po_tb_id'];
			$haveDeclare = false;	
				
           	if(isset($data['declared_value'])){
            	$haveDeclare=true;
            	$declare =$data['declared_value'];
            }	
			
			$asnProducts = array();			
			foreach($product_id_list as $k=>$product_id){
                    $product = Service_Product::getByField($product_id,'product_id');					
				    if($haveDeclare){
						$declare_vale = $declare[$k];
					}else{
						$declare_vale = $product['product_declared_value'];
					}
					$asnProduct['product_id'] = $product_id;
					$asnProduct['declare_vale'] = $declare_vale;
					$asnProduct['product_barcode'] = $product['product_barcode'];
					$asnProduct['product_sku'] = $product['product_sku'];
					$asnProduct['sku_quantity'] = $sku_quantity[$k];
					$asnProduct['po_tb_id'] = $po_tb_ids[$k];
 					$asnProducts[] = $asnProduct;
			
			}
			
			
			$combineAsnProducts = array();//用于订单详细
			foreach ($asnProducts as $row) {
			 	$product_id = $row['product_id'];
				if(isset($combineAsnProducts[$product_id])){
					$combineAsnProducts[$product_id]['sku_quantity'] += $row['sku_quantity'];					
				}else{
					$combineAsnProducts[$product_id]['product_id'] = $row['product_id'];
					$combineAsnProducts[$product_id]['declare_vale'] = $row['declare_vale'];
					$combineAsnProducts[$product_id]['product_barcode'] = $row['product_barcode'];
					$combineAsnProducts[$product_id]['product_sku'] = $row['product_sku'];
					$combineAsnProducts[$product_id]['sku_quantity'] = $row['sku_quantity'];
					
				}		 
			 
			}  
			
			
			        
			
            foreach ($asnProducts as $row) {              
            	
				$po_tb_id = $row['po_tb_id'];
				$row = array();
				$row['is_created_asn'] = '1' ;
				$row['receiving_id'] = $receiving_id; 
            	if(!Service_PurchaseOrderTrackingBody::update($row,$po_tb_id,'po_tb_id')){
            		throw new Exception(Ec_Lang::getInstance()->getTranslate('AddIsCreateASNFail'));
            	}			
            	
            }//已经生成ASN
			


            foreach ($combineAsnProducts as $row) {         
               
            	$receivingDetail = array(
            			'receiving_id'=>$receiving_id,
            			'receiving_code'=>$ASNCode,
            			'rd_status'=>'0',
            			'product_id'=>$row['product_id'],
            			'product_barcode'=>$row['product_barcode'],
            			'op_declared_value'=>trim($row['declare_vale']),
            			'rd_receiving_qty'=>trim($row['sku_quantity']),
            			'rd_add_time'=>$date
            	);					
				
            	$receivingDetailArr[] = $receivingDetail;
            	if(!Service_ReceivingDetail::add($receivingDetail)){
            		throw new Exception(Ec_Lang::getInstance()->getTranslate('AddASNDetailsFail'));
            	}
				
				
            	
            }			
			
			
			

            $note = 'create';
            foreach ($receivingDetailArr as $val) {
            	$productRow = Service_Product::getByField($val['product_id'], 'product_id', array('product_sku'));
            	$note .= ' sku:' . $productRow['product_sku'] . ' quantity:' . $val['rd_receiving_qty'] . ' ';
            }
            $ASNLog = array(
            		'receiving_id'=>$receiving_id,
            		'receiving_code' => $ASNCode,
            		'user_id'=>'-1',
            		'customer_code' => $customerCode,
            		'rl_note' => $note,
            		'rl_add_time'=>$date,
                    'rl_status_from'=>'1',
                    'rl_status_to'=>'1',
            		'rl_ip'=>Common_Common::getIP()
            );
            self::createAsnLog($ASNLog);		
			$customerId = $receiving['customer_id'];
	   		//改为自动运行程序提交审核
	   		/**$ftProcess = new Service_FtpMessageProcess();
	   		$fml_id = $ftProcess->addSendMessage($ASNCode);
	   		$ftProcess->ftpSendMessage($fml_id);*/
	   		/*$aMessage['fmt_code'] = 'MRK';
	   		$aMessage['fmt_type'] = 'BSG011';
	   		$aMessage['refercence_no'] = $ASNCode;
	   		$aMessage['fml_status'] = 1;
	   		$aMessage['fml_add_time'] = date('Y-m-d H:i:s');
	   		Service_FtpMessageSendlist::add($aMessage);*/

            if($receiving['receive_model_type']=="1"){
                $goodsIdArr = Service_OrderProduct::getGoodsId($receiving['receiving_code']);
                $sumNetWeight = Service_OrderProduct::calNetWeightByCondition(array('receiving_code'=>$receiving['receiving_code']));
            }else{
                $goodsIdArr = Service_ReceivingDetail::getGoodsId($receiving['receiving_code']);
                $sumNetWeight = Service_ReceivingDetail::sumNetWeight($receiving['receiving_code']);
            }
            $goodsIdArr = array_chunk($goodsIdArr,35);
            $subIndex = 1;
            //$gross_wt = ($receiving['roughweight']-$sumNetWeight)/count($goodsIdArr);
            $totalNetWeight = $sumNetWeight;
            foreach($goodsIdArr as $gk=>$gv){
                if($subIndex<10){
                    $sub_receiving_code = $receiving['receiving_code']."-0".$subIndex;
                }else{
                    $sub_receiving_code = $receiving['receiving_code']."-".$subIndex;
                }
                $subIndex++;
                $receivingXml = array(
                    'receiving_code'=>$receiving['receiving_code'],
                    'sub_receiving_code'=>$sub_receiving_code,
                    'gross_wt'=>'0',
                    'net_wt'=>'0',
                    'pack_no'=>'0',
                    'refercence_form_id'=>'',
                    'rx_add_time'=>date("Y-m-d H:i:s"),
                    'receiving_xml_status'=>'3',
                );
                Service_ReceivingXml::add($receivingXml);
                $RXdbObj = new Table_ReceivingXml();
                $rxId = $RXdbObj->getAdapter()->lastInsertId();
                $net_wt = 0;
                $pack_no = 0;
                $G_NO_index = 1;
                foreach($gv as $goods_id){
                    if($receiving['receive_model_type']=="1"){
                        $productList = Service_OrderProduct::getJoinProductByCondition(array('goods_id'=>$goods_id,'receiving_code'=>$receiving['receiving_code']));
                    }else{
                        $productList = Service_ReceivingDetail::getJoinProductByCondition(array('goods_id'=>$goods_id,'receiving_code'=>$receiving['receiving_code']));
                    }
                    $productRow = Service_Product::getByField($productList[0]['product_id'],'product_id',"*");
                    $currencyRow = Service_Currency::getByField($productRow['currency_code'],'currency_code',"*");
                    $receivingXmlDetail = array(
                        'rx_id'=>$rxId,
                        'from_id'=>$receiving['receiving_code'],
                        'sub_receiving_code'=>$sub_receiving_code,
                        'g_no'=>$G_NO_index,
                        'goods_id'=>$productList[0]['goods_id'],
                        'merger_g_no'=>$G_NO_index,
                        'code_ts'=>$productList[0]['hs_code'],
                        'g_name_cn'=>$productList[0]['hs_goods_name'],
                        //'decl_price'=>"",
                        'curr'=>$currencyRow['currency_hs_code'],
                        'qty_1'=>0,
                        'unit_1'=>'',
                        'qty_2'=>'',
                        'unit_2'=>'',
                    );

                    $g_qty = 0;
                    $decl_total = 0;
                    $decl_price = 0;
                    foreach($productList as $p){
                        if($receiving['receive_model_type']=="1"){
                            $quantity = $p['op_quantity'];
                            $g_qty+=$p['op_quantity'];
                        }else{
                            $quantity = $p['rd_receiving_qty'];
                            $g_qty+=$p['rd_receiving_qty'];
                        }

                        $hemList = Service_HsElementMap::getByCondition(array('product_id'=>$p['product_id']), 'hem_detail');
                        $elements = array();

                        foreach($hemList as $hemRow) $elements[] = $hemRow['hem_detail'];
                        $receivingXmlDetail['g_model'] = implode('|',$elements);
                        $hs_uom_map = Service_HsUomMap::getByField($p['product_id'],'product_id',"*");
                        $quantitylaw1 = isset($hs_uom_map['hum_quantity_law'])?$hs_uom_map['hum_quantity_law']:'0';
                        $receivingXmlDetail['qty_1'] += $quantitylaw1*$quantity;
                        $quantitylaw2 = isset($hs_uom_map['hum_quantity_second'])?$hs_uom_map['hum_quantity_second']:"0";
                        $receivingXmlDetail['qty_2'] += $quantitylaw2*$quantity;
                        if(!empty($hs_uom_map)) $hs_uom = Service_HsUom::getByField($hs_uom_map['hu_id'],'hu_id',"*");
                        $receivingXmlDetail['unit_1'] = isset($hs_uom['pu_code_law'])?$hs_uom['pu_code_law']:"";
                        $receivingXmlDetail['unit_2'] = isset($hs_uom['pu_code_second'])?$hs_uom['pu_code_second']:"";
                        $product = Service_Product::getByField($p['product_id'],"product_id","*");
                        $decl_total += $product['product_declared_value']*$quantity;
                        $receivingXmlDetail['g_unit'] = $product['pu_code'];

                    }
                    $pack_no+=$g_qty;
                    if($receiving['receive_model_type']=="1"){
                        $ntWeight = Service_OrderProduct::calNetWeightByCondition(array('goods_id'=>$goods_id,'receiving_code'=>$receiving['receiving_code']));
                    }else{
                        $ntWeight = Service_ReceivingDetail::calNetWeightByCondition(array('goods_id'=>$goods_id,'receiving_code'=>$receiving['receiving_code']));
                    }
                    $net_wt+= $ntWeight;
                    $decl_price = sprintf("%.4f",$decl_total/$g_qty);
                    $receivingXmlDetail['decl_price'] = $decl_price;
                    $receivingXmlDetail['g_qty'] = $g_qty;
                    $receivingXmlDetail['decl_total'] = $decl_total;
                    Service_ReceivingXmlDetail::add($receivingXmlDetail);
                    $G_NO_index++;
                }
                $updateReceivingXml = array(
                    //'gross_wt'=>$net_wt+$gross_wt,
                    'net_wt'=>$net_wt,
                    //'pack_no'=>$pack_no,
                );
                Service_ReceivingXml::update($updateReceivingXml,$sub_receiving_code,'sub_receiving_code');

                $aMessage['fmt_code'] = 'MRK';
                $aMessage['fmt_type'] = 'BSG011';
                $aMessage['refercence_no'] = $sub_receiving_code;
                $aMessage['fml_status'] = 1;
                $aMessage['fml_add_time'] = date('Y-m-d H:i:s');
                Service_FtpMessageSendlist::add($aMessage);

            }
            $rxList = Service_ReceivingXml::getByCondition(array('receiving_code'=>$ASNCode),"*");
            $growWeight = $receiving['roughweight'];
            $packNo = $receiving['pack_no'];
            $divPackNo = $receiving['pack_no'];
            foreach($rxList as $kk=>$rx){

                $gross_wt = ($rx['net_wt']/$totalNetWeight)*$growWeight;
                $rx_pack_no = ($rx['net_wt']/$totalNetWeight)*$packNo;
                if($gross_wt<=1) {
                    $gross_wt = 1;
                }
                if($kk==count($rxList)-1){
                    $rx_pack_no = $divPackNo;
                }else{
                    if($rx_pack_no<=1){
                        $rx_pack_no = 1;
                    }else{
                        $rx_pack_no = floor($rx_pack_no);
                    }
                    $divPackNo = $divPackNo - $rx_pack_no;
                }

                $updateReceivingXml = array(
                    'gross_wt'=>$gross_wt,
                    //'net_wt'=>$net_wt,
                    'pack_no'=>$rx_pack_no,
                );
                Service_ReceivingXml::update($updateReceivingXml,$rx['sub_receiving_code'],'sub_receiving_code');
            }

	   		if($receiving['is_delivery']=='1'){
	   			//提货的ASN要提货费
	   			//冻结提货费
	   			$objOtherCalculte = new Common_CalculateOtherFee();
	   			$keys = array(
	   					'warehouseId' => $receiving['warehouse_id'],
	   					'receiving_code'=>$ASNCode,
	   			);
	   			$objOtherCalculte->setParams($keys);
	   			$otherfeeArr = $objOtherCalculte->getOtherFee('TIHUO');
	   			$otherfee_tihuo = $otherfeeArr['data']['otherFee']['tihuo'];
				
	   			if($otherfee_tihuo['price']>0){
	   				$balanceProcess = new Service_CustomerBalanceProcess();
	   				$feeResult =  $balanceProcess->freezeASNFee($ASNCode, $customerId,$receiving);
	   				if($feeResult !== true) {
	   					throw new Exception($feeResult);
	   				}
	   			}
	   		}			
			
			$law_weight = Service_ReceivingDetail::sumLawWeight($ASNCode);
			
   		if($law_weight > $receiving['roughweight']) {
   			throw new Exception("法定单位为千克的SKU的总重量[".$law_weight."]大于ASN毛重[".$receiving['roughweight']."]，请修改SKU的法定单位重量");
   		}
			
            $result['ask']='1';
            $result['msg'] = "收货订单[{$ASNCode}]创建成功."; //'ASN创建成功';
            $result['ASNCode'] = $ASNCode;
            //$DB->rollBack();
            $DB->commit();
        }  catch (Exception $e) {
            $DB->rollBack();
            $result['error'][] = $e->getMessage();
            $result['msg'] = $e->getMessage();
            return $result;
        }
        return $result;    
    }

 
    /**
     * @author william-fan
     * @todo 检查 receiving 表 ref_id 字段值(客户参考号)的唯一性
     *  $referenceNo已存在返回 false;不存在返回 true;
     */
    public static function checkReferenceNo($params = array())
    {
        $condition = array(
            'reference_no' => $params['reference_no'],
            'customer_id' => $params['customer_id'],
            'receiving_status_arr'=>$params['receiving_status_arr']
        );
        $rows = Service_Receiving::getByCondition($condition, '*');
        return $rows;
    }

  

    /*
     * 针对指定用户，生成一个新的相应 AsnCode
     * @return ASNCode
     */
    public function createCode()
    {
        if ($this->_pro == '') {
            //$this->_pro = 'RE';
            $this->_pro = 'BHR';
        }
        $this->_pro = strtoupper($this->_pro);
        //return Common_GetNumbers::getCode('ASN', '', $this->_pro);
        return Common_GetNumbers::getOnlyCode('ASNOnly',$this->_pro);
    }

    /*
    * 针对指定用户，生成一个新的相应 BoxCode
    * @return BoxCode
    */
    public function createBoxCode()
    {
        return Merchant_Service_GetNumbers::getCode($this->_customerId, 'box', 'P');
    }

    /*
     *  创建日志
     */
    public static function createAsnLog($row)
    {
        $row['rl_add_time'] = date('Y-m-d H:i:s');
        $row['rl_ip'] = Common_Common::getIP();
        Service_ReceivingLog::add($row);
    }

    /*
     * 根据ASN订单号，获取ASN信息
     */
    public static function getAsnInfo($asnCode, $customerCode = '')
    {
        $result = array('ask' => 0, 'message' => '', 'Error' => array(), 'result' => array());
        $asnRow = Service_Receiving::getByField($asnCode, 'receiving_code');
        if (empty($asnRow) || $asnRow['customer_id'] != $customerCode) {
            $result['message'] = 'AsnCode:' . $asnCode . '不存在';
            $result['Error'][] = array('errorCode' => '20013', 'errorMessage' => 'AsnCode:' . $asnCode . ' can not be found.');
            return $result;
        }

        $asnDetail = array();
        if($asnRow['receive_model_type']=='1'){
            $orderCodes = Service_ReceivingOrderDetail::getOrderCodes($asnCode);
            $asnDetail = Service_ReceivingOrderDetail::getXmlProducts($orderCodes, $asnCode);
            $asnRow['net_weight'] = number_format(Service_ReceivingOrderDetail::sumNetWeight($asnCode),2,'.','');
        } else {
            $asnDetail = Service_ReceivingDetail::getXmlProducts($asnCode);
            $asnRow['net_weight'] = number_format(Service_ReceivingDetail::sumNetWeight($asnCode),2,'.','');
        }
        $productList = array();
        foreach($asnDetail as $info) {
            $hemList = Service_HsElementMap::getByCondition(array('product_id'=>$info['product_id']), 'hem_detail');
            $p = Service_Product::getByField($info['product_id'],"product_id","*");
            if($info['goods_id']!=$p['goods_id']){
                $goods = Service_Goods::getByField($info['goods_id'],'goods_id',"*");
                $info['product_model'] = $goods['g_model'];
            }else{
                $elements = array();
                foreach($hemList as $hemRow) $elements[] = $hemRow['hem_detail'];
                $info['product_model'] = implode('|',$elements);
            }
            $info['quantity_law'] = $info['hum_quantity_law'] ;
            $total_price = sprintf("%.2f", $info['total_price']);
            //$info['product_unit_price'] = sprintf("%.4f", $info['product_declared_value']/$info['hum_quantity_law']);
            $info['product_unit_price'] = sprintf("%.4f", $total_price/$info['quantity_law']);
            $info['quantity_second'] =  $info['hum_quantity_second'];
            //$info['product_total_price'] = sprintf("%.2f", $info['product_declared_value']*$info['quantity']);
            $info['product_total_price'] = $total_price;
            $productList[] = $info;
        }

        $warehouseAll = Common_DataCache::getWareHouse();
        $warehouseCode = $warehouseAll[$asnRow['warehouse_id']]['warehouse_code'];
        $asnRow['warehouse_name'] = $warehouseCode;
        $asnRow['form_id'] = $asnRow['receiving_code'];
        $asnData = array(
            'asnRow' => $asnRow,
            'ASNCode' => $asnRow['receiving_code'],
            'addTime' => $asnRow['receiving_add_time'],
            'lastModifyTime' => $asnRow['receiving_update_time'],
            'warehouseCode' => $warehouseCode,
            'ASNDetail' => $productList,
        );
        $result['result'] = $asnData;
        $result['ask'] = 1;
        return $result;
    }

    public function printAsn($ASNCode = '',$customerId){
        $result = array('ask' => 0, 'message' => '确认失败', 'error' => array());
        $receiving = Service_Receiving::getByField($ASNCode,'receiving_code');
        $error = array();
        //print_r($receiving);exit;
        if(empty($receiving)){
            $error[]='ASN无效';
        }else{
            if($receiving['receiving_status']!='4'){
                $error[]='ASN状态错误';
            }
        }
        if(empty($customerId)){
            $result['message'] = '客户错误';
            return $result;
        }
        if(!empty($error)){
            $result['error'] = $error;
            return $result;
        }

        if($receiving['customer_id']!=$customerId){
            $result['message'] = '该ASN和客户不一致';
            return $result;
        }
        //$session	= new Zend_Session_Namespace('customerAuth');
        //$sessionData = $session->data;
        $userAuth = new Zend_Session_Namespace('userAuthorization');
        $warehouse_id = $userAuth->warehouseId;
        $user_id = $userAuth->userId;
        try {
            $DB = Common_Common::getAdapter();
            $DB->beginTransaction();
            $receivingRow = array(
                'receiving_status'=>'5',
                'receiving_update_time'=>date('Y-m-d H:i:s',time()),
            );
            if(!Service_Receiving::update($receivingRow, $ASNCode,'receiving_code')){
                throw new Exception("ASN状态更新失败");
            }
            if($receiving['receive_model_type']=="1"){
                $rod = Service_ReceivingOrderDetail::getByCondition(array('receiving_code'=>$receiving['receiving_code']),"*");
                foreach($rod as $rodk=>$rodv){
                    $o = Service_Orders::getByField($rodv['order_code'],"order_code","*");
                    //$w = Service_Warehouse::getByField($o['warehouse_id'],"warehouse_id","*");
                    $shipOrderTracking = array(
                        'order_code'=>$o['order_code'],
                        'sot_location'=>"运输途中",
                        'sot_add_time'=>date("Y-m-d H:i:s"),
                        'warehouse_id'=>$o['warehouse_id'],
                        'sot_description'=>'集货ASN运输途中',
                        'sot_type'=>'0',
                        'sot_time_offset'=>'',
                        'tracking_number'=>$o['order_code'],
                        'ref_tracking_number'=>'',
                        'status_desc'=>'已提交',
                        'user_id'=>$user_id
                    );
                    Service_ShipOrderTracking::add($shipOrderTracking);
                }
            }

            $conDetail = array(
                'receiving_code'=>$ASNCode,
            );
            $receivingDetail = Service_ReceivingDetail::getByCondition($conDetail);
            if(!empty($receivingDetail)){
                foreach ($receivingDetail as $keyde=>$valuede){
                    $product = Service_Product::getByField($valuede['product_id']);

                    $conInventory = array(
                        'customer_id'=>$customerId,
                        'product_id'=>$valuede['product_id'],
                        'warehouse_id'=>$receiving['warehouse_id']
                    );
                    $productInventory = Service_ProductInventory::getByCondition($conInventory);
                    if(empty($productInventory)){
                        //添加一条product_inventory 记录
                        $productInventoryRow = array(
                            'product_barcode'=>$product['product_barcode'],
                            'customer_id'=>$customerId,
                            'product_id'=>$product['product_id'],
                            'warehouse_id'=>$receiving['warehouse_id'],
                            'pi_onway'=>$valuede['rd_receiving_qty'],
                            'pi_add_time'=>date('Y-m-d H:i:s',time()),
                        );
                        Service_ProductInventory::add($productInventoryRow);
                        $productInventoryLogRow = array(
                            'product_id'=>$product['product_id'],
                            'product_barcode'=>$product['product_barcode'],
                            'warehouse_id'=>$receiving['warehouse_id'],
                            'reference_code'=>$valuede['receiving_code'],
                            'user_id'=>'-1',
                            'pil_onway'=>$valuede['rd_receiving_qty'],
                            'pil_ip'=>Common_Common::getIP(),
                            'from_it_code'=>'Audited',
                            'to_it_code'=>'onway',
                            'pil_add_time'=>date('Y-m-d H:i:s',time()),
                            'pil_note'=>'清单打印',
                            'pil_quantity'=>$valuede['rd_receiving_qty'],
                        );
                        Service_ProductInventoryLog::add($productInventoryLogRow);
                    }else{
                        $inventory = $productInventory[0];
                        //修改product_inventory 记录
                        $productInventoryRow = array(
                            'pi_onway'=>$valuede['rd_receiving_qty']+$inventory['pi_onway'],
                            'pi_update_time'=>date('Y-m-d H:i:s',time()),
                        );
                        Service_ProductInventory::update($productInventoryRow, $inventory['pi_id']);
                        $productInventoryLogRow = array(
                            'product_id'=>$product['product_id'],
                            'product_barcode'=>$product['product_barcode'],
                            'warehouse_id'=>$receiving['warehouse_id'],
                            'reference_code'=>$valuede['receiving_code'],
                            'user_id'=>'-1',
                            'pil_onway'=>$valuede['rd_receiving_qty'],
                            'pil_pending'=>$inventory['pi_pending'],
                            'pil_sellable'=>$inventory['pi_sellable'],
                            'pil_unsellable'=>$inventory['pi_unsellable'],
                            'pil_reserved'=>$inventory['pi_reserved'],
                            'pil_shipped'=>$inventory['pi_shipped'],
                            'pil_ip'=>Common_Common::getIP(),
                            'from_it_code'=>'Audited',
                            'to_it_code'=>'onway',
                            'pil_add_time'=>date('Y-m-d H:i:s',time()),
                            'pil_note'=>'清单打印',
                            'pil_quantity'=>$valuede['rd_receiving_qty'],
                        );
                        Service_ProductInventoryLog::add($productInventoryLogRow);
                    }
                    //修改产品的have_asn字段
                    $productRow = array(
                        'have_asn'=>'1',
                        'product_update_time'=>date('Y-m-d H:i:s')
                    );
                    Service_Product::update($productRow, $valuede['product_id']);
                }
            }

            $customerRow = Service_Customer::getByField($customerId);
            $ASNLog = array(
                'receiving_id'=>$receiving['receiving_id'],
                'receiving_code' => $ASNCode,
                'rl_type'=>'-1',
                'user_id'=>$user_id,
                'customer_code' => $customerRow['customer_code'],
                'rl_note' => "打印ASN单",
                'rl_status_from'=>$receiving['receiving_status'],
                'rl_status_to'=>'5',
                'rl_add_time'=>date('Y-m-d H:i:s',time()),
                'rl_ip'=>Common_Common::getIP()
            );
            self::createAsnLog($ASNLog);

            $rab = array(
                'receiving_id'=>$receiving['receiving_id'],
                'receiving_code'=>$ASNCode,
                'onway_time'=>date("Y-m-d H:i:s")
            );
            Service_ReceivingAttribute::add($rab);

            $result['ask']='1';
            $result['message'] = 'ASN状态更新成功';
            //$DB->rollBack();
            $DB->commit();
        } catch (Exception $e) {
            $DB->rollBack();
            $result['error'][] = $e->getMessage();
            $result['message'] = $e->getMessage();
            return $result;
        }
        return $result;
    }

    public function split9610($receivingCode){
        $receiving = Service_Receiving::getByField($receivingCode,'receiving_code');

        if($receiving['receive_model_type']=="1"){
            $goodsIdArr = Service_OrderProduct::getGoodsId($receiving['receiving_code']);
            $sumNetWeight = Service_OrderProduct::calNetWeightByCondition(array('receiving_code'=>$receiving['receiving_code']));
        }else{
            $goodsIdArr = Service_ReceivingDetail::getGoodsId($receiving['receiving_code']);
            $sumNetWeight = Service_ReceivingDetail::sumNetWeight($receiving['receiving_code']);
        }
        $goodsIdArr = array_chunk($goodsIdArr,35);
        $subIndex = 1;
        //$gross_wt = ($receiving['roughweight']-$sumNetWeight)/count($goodsIdArr);
        $numberIndex = 65;
        foreach($goodsIdArr as $gk=>$gv){
            if($subIndex<10){
                $sub_receiving_code = $receiving['receiving_code'].chr($numberIndex);
                $subReceivingCode2 = $receiving['receiving_code']."-0".$subIndex;
            }else{
                $sub_receiving_code = $receiving['receiving_code'].chr($numberIndex);
                $subReceivingCode2 = $receiving['receiving_code']."-".$subIndex;
            }
            $subIndex++;
            $receivingXml = array(
                'receiving_code'=>$receiving['receiving_code'],
                'sub_receiving_code'=>$sub_receiving_code,
                'gross_wt'=>'0',
                'net_wt'=>'0',
                'pack_no'=>'0',
                'refercence_form_id'=>'',
                'rx_add_time'=>date("Y-m-d H:i:s"),
                'receiving_xml_status'=>'3',
            );
            Service_ReceivingXml::add($receivingXml);
            $RXdbObj = new Table_ReceivingXml();
            $rxId = $RXdbObj->getAdapter()->lastInsertId();
            $net_wt = 0;
            $pack_no = 0;
            $G_NO_index = 1;
            foreach($gv as $goods_id){
                if($receiving['receive_model_type']=="1"){
                    $productList = Service_OrderProduct::getJoinProductByCondition(array('goods_id'=>$goods_id,'receiving_code'=>$receiving['receiving_code']));
                }else{
                    $productList = Service_ReceivingDetail::getJoinProductByCondition(array('goods_id'=>$goods_id,'receiving_code'=>$receiving['receiving_code']));
                }
                $productRow = Service_Product::getByField($productList[0]['product_id'],'product_id',"*");
                $currencyRow = Service_Currency::getByField($productRow['currency_code'],'currency_code',"*");
                $receivingXmlDetail = array(
                    'rx_id'=>$rxId,
                    'from_id'=>$receiving['receiving_code'],
                    'sub_receiving_code'=>$sub_receiving_code,
                    'g_no'=>$G_NO_index,
                    'goods_id'=>$productList[0]['goods_id'],
                    'merger_g_no'=>$G_NO_index,
                    'code_ts'=>$productList[0]['hs_code'],
                    'g_name_cn'=>$productList[0]['hs_goods_name'],
                    //'decl_price'=>"",
                    'curr'=>$currencyRow['currency_hs_code'],
                    'qty_1'=>0,
                    'unit_1'=>'',
                    'qty_2'=>'',
                    'unit_2'=>'',
                );

                $g_qty = 0;
                $decl_total = 0;
                $decl_price = 0;
                foreach($productList as $p){
                    if($receiving['receive_model_type']=="1"){
                        $quantity = $p['op_quantity'];
                        $g_qty+=$p['op_quantity'];
                    }else{
                        $quantity = $p['rd_receiving_qty'];
                        $g_qty+=$p['rd_receiving_qty'];
                    }

                    $hemList = Service_HsElementMap::getByCondition(array('product_id'=>$p['product_id']), 'hem_detail');
                    $elements = array();

                    foreach($hemList as $hemRow) $elements[] = $hemRow['hem_detail'];
                    $receivingXmlDetail['g_model'] = implode('|',$elements);
                    $hs_uom_map = Service_HsUomMap::getByField($p['product_id'],'product_id',"*");
                    $quantitylaw1 = isset($hs_uom_map['hum_quantity_law'])?$hs_uom_map['hum_quantity_law']:'0';
                    $receivingXmlDetail['qty_1'] += $quantitylaw1*$quantity;
                    $quantitylaw2 = isset($hs_uom_map['hum_quantity_second'])?$hs_uom_map['hum_quantity_second']:"0";
                    $receivingXmlDetail['qty_2'] += $quantitylaw2*$quantity;
                    if(!empty($hs_uom_map)) $hs_uom = Service_HsUom::getByField($hs_uom_map['hu_id'],'hu_id',"*");
                    $receivingXmlDetail['unit_1'] = isset($hs_uom['pu_code_law'])?$hs_uom['pu_code_law']:"";
                    $receivingXmlDetail['unit_2'] = isset($hs_uom['pu_code_second'])?$hs_uom['pu_code_second']:"";
                    $product = Service_Product::getByField($p['product_id'],"product_id","*");
                    $decl_total += $product['product_declared_value']*$quantity;
                    $receivingXmlDetail['g_unit'] = $product['pu_code'];
                    $receivingXmlDetail['putrec_seqno'] = $product['putrec_seqno'];

                }
                $pack_no+=$g_qty;
                if($receiving['receive_model_type']=="1"){
                    $ntWeight = Service_OrderProduct::calNetWeightByCondition(array('goods_id'=>$goods_id,'receiving_code'=>$receiving['receiving_code']));
                }else{
                    $ntWeight = Service_ReceivingDetail::calNetWeightByCondition(array('goods_id'=>$goods_id,'receiving_code'=>$receiving['receiving_code']));
                }
                $net_wt+= $ntWeight;
                $decl_price = sprintf("%.4f",$decl_total/$g_qty);
                $receivingXmlDetail['decl_price'] = $decl_price;
                $receivingXmlDetail['g_qty'] = $g_qty;
                $receivingXmlDetail['decl_total'] = $decl_total;
                Service_ReceivingXmlDetail::add($receivingXmlDetail);
                $G_NO_index++;
            }
            $erx = Service_ReceivingXml::getByField($subReceivingCode2,'sub_receiving_code',"*");
            $updateReceivingXml = array(
                'gross_wt'=>$erx['gross_wt'],
                'net_wt'=>$net_wt,
                'pack_no'=>$erx['pack_no'],
            );
            Service_ReceivingXml::update($updateReceivingXml,$sub_receiving_code,'sub_receiving_code');

            $aMessage['fmt_code'] = 'MRK-RQJT';
            $aMessage['fmt_type'] = 'BSG011';
            $aMessage['refercence_no'] = $sub_receiving_code;
            $aMessage['fml_status'] = 1;
            $aMessage['fml_add_time'] = date('Y-m-d H:i:s');
            Service_FtpMessageSendlist::add($aMessage);

        }

    }

    public static function PendingAsn($ASNCode){
        $result = array('ask' => 0, 'message' => '确认失败', 'error' => array());
        $receiving = Service_Receiving::getByField($ASNCode,'receiving_code');
        $error = array();
        //print_r($receiving);exit;
        /*if(empty($receiving)){
            $error[]='ASN无效';
        }else{
            if($receiving['receiving_status']!='2'){
                $error[]='入库单状态错误';
            }
        }
        if(!empty($error)){
            $result['error'] = $error;
            return $result;
        }*/
        try {
            $DB = Common_Common::getAdapter();
            $DB->beginTransaction();
            $receivingRow = array(
                'receiving_status'=>'3',	//方便测试暂时为4
                'receiving_update_time'=>date('Y-m-d H:i:s',time()),
            );
            if(!Service_Receiving::update($receivingRow, $ASNCode,'receiving_code')){
                throw new Exception("ASN移至待审核失败");
            }
            //$customerRow = Service_Customer::getByField($customerId);
            $ASNLog = array(
                'receiving_id'=>$receiving['receiving_id'],
                'receiving_code' => $ASNCode,
                'rl_type'=>'-1',
                'user_id'=>'-1',
                'customer_code' => $receiving['customer_code'],
                'rl_note' => "移动ASN至待审核",
                'rl_status_from'=>$receiving['receiving_status'],
                'rl_status_to'=>'3',	//方便测试暂时为4
                'rl_add_time'=>date('Y-m-d H:i:s',time()),
                'rl_ip'=>Common_Common::getIP()
            );
            self::createAsnLog($ASNLog);
            //改为自动运行程序提交审核
            /**$ftProcess = new Service_FtpMessageProcess();
            $fml_id = $ftProcess->addSendMessage($ASNCode);
            $ftProcess->ftpSendMessage($fml_id);*/
            /*$aMessage['fmt_code'] = 'MRK';
            $aMessage['fmt_type'] = 'BSG011';
            $aMessage['refercence_no'] = $ASNCode;
            $aMessage['fml_status'] = 1;
            $aMessage['fml_add_time'] = date('Y-m-d H:i:s');
            Service_FtpMessageSendlist::add($aMessage);*/

            self::split9610($ASNCode);
            $objOtherCalculte = new Common_CalculateOtherFee();
            if($receiving['is_delivery']=='1'){
                //提货的ASN要提货费
                //冻结提货费
                $keys = array(
                    'warehouseId' => $receiving['warehouse_id'],
                    'receiving_code'=>$ASNCode,
                );
                $objOtherCalculte->setParams($keys);
                $otherfeeArr = $objOtherCalculte->getOtherFee('TIHUO');
                $otherfee_tihuo = $otherfeeArr['data']['otherFee']['tihuo'];
                //print_r($otherfee_tihuo);
                if($otherfee_tihuo['price']>0){
                    $balanceProcess = new Service_CustomerBalanceProcess();
                    $feeResult =  $balanceProcess->freezeASNFee($ASNCode, $receiving['customer_id']);
                    if($feeResult !== true) {
                        throw new Exception($feeResult);
                    }
                }
            }
            if($receiving['receive_model_type']==0){
                $keys = array(
                    'warehouseId' => $receiving['warehouse_id'],
                    'receiving_code'=>$ASNCode,
                );
                $objOtherCalculte->setParams($keys);
                //入库费
                $otherfeeArr = $objOtherCalculte->getOtherFee('RUKU');
                $otherfee_ruku = $otherfeeArr['data']['otherFee']['ruku'];
                if($otherfee_ruku['price']>0){
                    //$balanceProcess = new Service_CustomerBalanceProcess($customerId);
                    $feeResult =  Service_CustomerBalanceProcess::freezeOtherFee($otherfee_ruku['price'],$otherfee_ruku['currency_code'],$ASNCode,$otherfee_ruku['fee_id'],'ASN提交扣入库费，冻结余额',$receiving['customer_id']);
                }
                //散租费
                $otherfeeArr = $objOtherCalculte->getOtherFee('SANZU');
                $otherfee_sanzu = $otherfeeArr['data']['otherFee']['sanzu'];
                if($otherfee_sanzu['price']>0){
                    //$balanceProcess = new Service_CustomerBalanceProcess($customerId);
                    $feeResult =  Service_CustomerBalanceProcess::freezeOtherFee($otherfee_sanzu['price'],$otherfee_sanzu['currency_code'],$ASNCode,$otherfee_sanzu['fee_id'],'ASN提交扣散租费，冻结余额',$receiving['customer_id']);
                }
                //操作费-M
                $otherfeeArr = $objOtherCalculte->getOtherFee('CZF-M');
                $otherfee_czfm = $otherfeeArr['data']['otherFee'][strtolower('CZF-M')];
                if($otherfee_czfm['price']>0){
                    //$balanceProcess = new Service_CustomerBalanceProcess($customerId);
                    $feeResult =  Service_CustomerBalanceProcess::freezeOtherFee($otherfee_czfm['price'],$otherfee_czfm['currency_code'],$ASNCode,$otherfee_czfm['fee_id'],'ASN提交扣操作费-M，冻结余额',$receiving['customer_id']);
                }
            }
            $result['ask']='1';
            $result['message'] = '入区单已提交至待审核';
            //$DB->rollBack();
            $DB->commit();

        } catch (Exception $e) {
            $DB->rollBack();
            $result['error'][] = $e->getMessage();
            $result['message'] = $e->getMessage();
            return $result;
        }
        //print_r($result);exit;
        return $result;
    }

    public static function confirmASn($ASNCode = ''){
        $result = array('ask' => 0, 'message' => '确认失败', 'error' => array());
        $receiving = Service_Receiving::getByField($ASNCode,'receiving_code');
        $error = array();
        $pdfSmcode=array( '4PX-LYT_GH', //A6
            '4PX-EU_PACKET', //DS
            '4PX-RU_POST-LINK_RMAIL', //BA
            '4PX-HKDHL', //A1
            '4PX-YX', //AI
            '4PX-SG_ordinary_mail+' ,
            'PNLN','PNLG','BH-AZAT-G',
            'DHL-BH03',
            'BH-POST-NL',
            'BH-SFEP',
        );
        $sendOrderInfoSmcode=array(
            '4PX-Singapo_SPack_IMAIR', //B1
            '4PX-OZXBTH', //BB
        );
        if(empty($receiving)){
            $error[]='ASN无效';
            $return['message'] = $result['message'].'ASN无效';
        }else{
            if($receiving['receiving_status']!='1'){
                $error[]='ASN状态错误';
                $return['message'] = $result['message'].'ASN状态错误';
            }
        }
        if(!empty($error)){
            $result['error'] = $error;
            return $result;
        }
        //判断法定单位总和是否大于毛重
        $law_weight = 0;
        if($receiving['receive_model_type']==0) {
            $law_weight = Service_ReceivingDetail::sumLawWeight($ASNCode);
        } else if($receiving['receive_model_type']==1) {
            $law_weight = Service_ReceivingOrderDetail::sumLawWeight($ASNCode);
        }
        if($law_weight > $receiving['roughweight']) {
            $result['message'] = '法定单位为千克的SKU的总重量['.$law_weight.']大于ASN毛重['.$receiving['roughweight'].']，请修改SKU的法定单位重量';
            return $result;
        }

        try {
            $DB = Common_Common::getAdapter();
            $DB->beginTransaction();
            $receivingRow = array(
                'receiving_status'=>'2',
                'receiving_update_time'=>date('Y-m-d H:i:s',time()),
            );
            if(!Service_Receiving::update($receivingRow, $ASNCode,'receiving_code')){
                throw new Exception("ASN确认失败");
            }
            //$customerRow = Service_Customer::getByField($customerId);
            $ASNLog = array(
                'receiving_id'=>$receiving['receiving_id'],
                'receiving_code' => $ASNCode,
                'rl_type'=>'1',
                'user_id'=>'-1',
                'customer_code' => '',
                'rl_note' => "确认ASN单",
                'rl_status_from'=>$receiving['receiving_status'],
                'rl_status_to'=>'2',
                'rl_add_time'=>date('Y-m-d H:i:s',time()),
                'rl_ip'=>Common_Common::getIP()
            );




            if($receiving['receive_model_type']=='0'){
                $conDetail = array(
                    'receiving_code'=>$ASNCode,
                );
                $receivingDetail = Service_ReceivingDetail::getByCondition($conDetail);
                if(!empty($receivingDetail)){
                    $totalWeight = 0;
                    foreach ($receivingDetail as $keyde=>$valuede){
                        $product = Service_Product::getByField($valuede['product_id']);
                        if(empty($product) || $product['product_type']=='1'){continue;}
                        $totalWeight +=  $product['product_weight']*$valuede['rd_receiving_qty'];

                    }
                }

            }//备货



            if($receiving['receive_model_type']=='1'){

                $conDetail = array(
                    'receiving_code'=>$ASNCode,
                );
                $totalWeight = 0;
                $receivingDetail = Service_ReceivingOrderDetail::getByCondition($conDetail);
                if(!empty($receivingDetail)){
                    $totalWeight = 0;
                    $noTracingOrder=array();
                    $noSendInfoOrder=array();
                    $errorMsg='';
                    foreach ($receivingDetail as $keyde=>$valuede){
                        $totalWeight+= Service_Orders::calculateWeight($valuede['order_code']);
                        $orderInfo= Service_Orders::getByField($valuede['order_code'],'order_code');
                        if(in_array($orderInfo['sm_code'],$pdfSmcode)){
                            if(empty($orderInfo['ref_tracking_number'])){
                                $noTracingOrder[]=$orderInfo['order_code'];

                            }
                        }
                        if(in_array($orderInfo['sm_code'],$sendOrderInfoSmcode)){
                            if($orderInfo['sync_status']!='1'){
                                $noSendInfoOrder[]=$orderInfo['order_code'];
                            }
                        }
                    }
                    if(!empty($noTracingOrder)){
                        $errorMsg.='订单'.implode(",",$noTracingOrder).'没有获取到服务商单号<br/>';
                    }
                    if(!empty($noSendInfoOrder)){
                        $errorMsg.='运输渠道【'.implode("】【",$noSendInfoOrder).'】订单：'.implode(",",$noSendInfoOrder).'信息没有推送到4PX<br/>';
                    }
                    if(!empty($errorMsg)){
                        throw new Exception($errorMsg);
                    }

                }

            }




            $roughweight = $receiving['roughweight'];
            if($roughweight<$totalWeight){
                throw new Exception("ASN重量({$roughweight}KG)小于净重({$totalWeight}KG)");
            }

            self::createAsnLog($ASNLog);
            $result['ask']='1';
            $result['message'] = 'ASN确认成功';
            //$DB->rollBack();
            $DB->commit();
        } catch (Exception $e) {
            $DB->rollBack();
            $result['error'][] = $e->getMessage();
            $result['message'] = $e->getMessage();
            return $result;
        }
        //print_r($result);exit;
        return $result;
    }

 
	




  

}

?>