<?php
class Service_ShipOrderProcess
{
	public function __construct()
    {
        $this->_date = date('Y-m-d H:i:s');
    }
    
    /**
     * 订单出货
     * @author solar
     * @param int $order_id
     * @param string $order_code
     * @param string $ob_no
     * @param number $weight
     * @param string $tracking_number
     * @param string $so_code
     * @return array
     */
    public function delivery($order_id, $order_code, $ob_no, $weight, $tracking_number, $so_code,$sm_code,$volArr,$sm_piece) {
    	$result = array('state'=>0, 'error'=>'');
    	$db = Common_Common::getAdapter();
    	$db->beginTransaction();
    	try {
            $ob_no=strtoupper($ob_no);
            $tracking_number=strtoupper($tracking_number);
            $so_code=strtoupper($so_code);
            $order_code=strtoupper($order_code);
            $realWeight = $volArr['realWeight'];
            //改订单已经有的hs_code
            /*$orderHsCount = Service_OrderProduct::countOrderHscodeNum($order_code);
            if($orderHsCount>20){
                throw new Exception('此订单已有20个hs_code');
            }*/
            //限制hs_code
            /*$hscodeNum=Service_OutboundBagDetail::countHscodeNum($ob_no);
            if(($orderHsCount+$hscodeNum)>20) {
                throw new Exception('此袋子已有20个hs_code，请装在新的袋子中');
            }*/
            //处理重量啦啦啦
            $shipMethod = Service_ShippingMethod::getByField($sm_code,'sm_code',"*");
            $volWeight = 0;

            //计费重地址区分条件
            $cityId = 0;
            $aOrder = Service_Orders::getByField($order_code, 'order_code');
            $aAddress = Service_OrderAddressBook::getByField($order_code, 'order_code');
            $countryArr = Service_Country::getByField($aAddress['oab_country_id'],'country_id');
            if($aAddress['oab_country_id']=='253'){
                //美国的要加入城市
                $citys = Service_City::getByCondition(array('country_id' => $aAddress['oab_country_id'],'city_name'=>$aAddress['oab_city'],'sm_code' => $aOrder['sm_code']));
                if(empty($citys)){
                    $conditionCity = array(
                        'country_id'=>$aAddress['oab_country_id'],
                        'city_name'=>$aAddress['oab_city'],
                        'sm_code' =>'0'
                    );
                    $citys = Service_City::getByCondition($conditionCity,'*');
                }
                if(!empty($citys)){
                    $cityId = $citys[0]['city_id'];
                }
            }
            if($aAddress['oab_country_id']=='106'){
                //香港的要加入城市
                $citys = Service_City::getByCondition(array('country_id' => $aAddress['oab_country_id'],'city_name'=>$aAddress['oab_city'],'sm_code' => $aOrder['sm_code']));
                if(empty($citys)){
                    $conditionCity = array(
                        'country_id'=>$aAddress['oab_country_id'],
                        'city_name'=>$aAddress['oab_city'],
                        'sm_code' =>'0'
                    );
                    $citys = Service_City::getByCondition($conditionCity,'*');
                }
                if(!empty($citys)){
                    $cityId = $citys[0]['city_id'];
                }
            }
            if(in_array($shipMethod['sm_code'],array('HKDHL','CNDHL','BH-HKDHL','BH-3HPA','BH-3H','BH-UKECSLTYD','BH-UKECSLTRM','BH-CORREOS','BH-19EURDPDDE','BH-DAC','BH-SL018','BH-IESLTANPOST','DHL-TH','WWDHLP','WWDHLU'))){
                $shipOrder = Service_ShipOrder::getByField($order_code,'order_code',"*");
                $volWeight = $shipOrder['so_vol_weight'];
                $weight = $shipOrder['so_weight'];
                $realWeight = $volWeight>$weight?$volWeight:$weight;
            }else if ($shipMethod['sm_code']=="HKUPS-KW") {
                if($shipMethod['sm_is_volume']=="1"){
                    $shiWeight = 0;
                    foreach($volArr['volArr'] as $key=>$value){
                        $length = $value['length'];
                        $width = $value['width'];
                        $height = $value['height'];
                        $sweight = $value['weight'];
                        $op_id = $value['op_id'];
                        if($length>0 && $width>0 && $height>0 && $weight>0 && $shipMethod['sm_vol_rate']>0){
                            $vWeight = ($length*$width*$height)/$shipMethod['sm_vol_rate'];
                            $vWeight = sprintf('%.2f',$vWeight);
                            $volArr['volArr'][$key]['vol_weight'] = $vWeight;
                            $volWeight+=$vWeight;
                          ////  $sWeight+=$weight;  
                            //$shiWeight+=$vWeight>$sweight?$vWeight:$sweight;
                            $area = $this->getArea($shipMethod['sm_id'],$aOrder['warehouse_id'],$shipMethod['sm_calc_type'],$shipMethod['sm_fee_type'],$aAddress['oab_country_id'],0,$cityId);
                            if($shipMethod['sm_calc_type'] == '0'){
                                $eachRealWeight = $vWeight>$sweight?$vWeight:$sweight;
                                $bill_weight_row = $this->interval($area,$shipMethod['sm_id'],$aOrder['warehouse_id'],$shipMethod['sm_fee_type'],$eachRealWeight);
                                $bill_weight[$op_id] = $bill_weight_row;
                                $shiWeight += $bill_weight_row;
                            }else{
                                $bill_weight_row += $this->firstWeight($area,$shipMethod['sm_id'],$aOrder['warehouse_id'],$shipMethod['sm_fee_type'],$eachRealWeight);
                                $bill_weight[$op_id] = $bill_weight_row;
                                $shiWeight += $bill_weight_row;
                            }
                        }else{
                            throw new Exception('长、宽、高、实重、运输方式体积转换率都必须大于0');
                            break;
                        }
                        //break;
                    }
                    $realWeight = $shiWeight;
                }
            }/*BH-HKDHL不用录入体积了
            else if($shipMethod['sm_code']=="BH-HKDHL"){
                if($shipMethod['sm_is_volume']=="1"){
                    $shiWeight = 0;
                    foreach($volArr['volArr'] as $key=>$value){
                        $length = $value['length'];
                        $width = $value['width'];
                        $height = $value['height'];
                        $sweight = $value['weight'];
                        if($length>0 && $width>0 && $height>0 && $weight>0 && $shipMethod['sm_vol_rate']>0){
                            $vWeight = ($length*$width*$height)/$shipMethod['sm_vol_rate'];
                            $vWeight = sprintf('%.2f',$vWeight);
                            $volArr['volArr'][$key]['vol_weight'] = $vWeight;
                            $volWeight+=$vWeight;
                          ////  $sWeight+=$weight;  
                            $shiWeight+=$vWeight>$sweight?$vWeight:$sweight;
                        }else{
                            throw new Exception('长、宽、高、实重、运输方式体积转换率都必须大于0');
                            break;
                        }
                        //break;
                    }
                    $realWeight = $weight>$shiWeight?$weight:$shiWeight;
                }
            }
            */
            else{
                if($shipMethod['sm_is_volume']=="1"){
                    foreach($volArr['volArr'] as $key=>$value){
                        $length = $value['length'];
                        $width = $value['width'];
                        $height = $value['height'];
                        if($length>0 && $width>0 && $height>0 && $shipMethod['sm_vol_rate']>0){
                            $vWeight = ($length*$width*$height)/$shipMethod['sm_vol_rate'];
                            $vWeight = sprintf('%.2f',$vWeight);
                            $volArr['volArr'][$key]['vol_weight'] = $vWeight;
                            $volWeight+=$vWeight;
                        }else{
                            throw new Exception('长、宽、高、运输方式体积转换率都必须大于0');
                            break;
                        }
                        //break;
                    }
                    $realWeight = $volWeight>$weight?$volWeight:$weight;
                }
            }
			//检查订单扫描重量和产品净重
			$orderProductInfo	= Service_OrderProduct::getByCondition(array('order_code'=>$order_code));
			$weightTotal		= 0;
			foreach($orderProductInfo as $k=>$v){
				$productInfo	= Service_Product::getByField($v['product_id'],'product_id');
				if(1 == $productInfo['product_type']){
					$productCombineRelation = Service_ProductCombineRelation::getByCondition(array('product_id'=>$v['product_id']),"*");
					foreach($productCombineRelation as $k1=>$v1){
						$relationProduct = Service_Product::getByField($v1['pcr_product_id'],'product_id',"*");
						$weightTotal += $v['op_quantity']*$v1['pcr_quantity']*$relationProduct['product_weight'];
					}
				}else{
					$weightTotal += $v['op_quantity']*$productInfo['product_weight'];
				}
				$hsCode = Service_Hscodes::getByField($productInfo['hs_code'],'hs_code');
				if($hsCode['hs_code_status']=='-1'){
					throw new Exception("产品sku".$productInfo['product_sku']."海关编码已禁用");
				}
			}
			if($weight>0 && $weightTotal>$weight){
				throw new Exception('产品毛重['.$weightTotal.']大于录入订单重量['.$weight.']');
			}
            /*switch($shipMethod['sm_class_code']){
                case 'CRE':
                    foreach($volArr as $key=>$value){
                        $length = $value['length'];
                        $width = $value['width'];
                        $height = $value['height'];
                        if($length>0 && $width>0 && $height>0 && $shipMethod['sm_vol_rate']>0){
                            $vWeight = ($length*$width*$height)/$shipMethod['sm_vol_rate'];
                            $vWeight = sprintf('%.2f',$volWeight);
                            $volArr[$key]['vol_weight'] = $vWeight;
                            $volWeight+=$vWeight;
                        }else{
                            throw new Exception('长、宽、高、运输方式体积转换率都必须大于0');
                        }
                        break;
                    }
                    break;
                default:
                    break;
            }
			/*switch(strtoupper($sm_code)){
				case "SZY-EMS":
				case "HTTX-HKDHL":
					$length = $volArr['length'];
					$width = $volArr['width'];
					$height = $volArr['height'];
					$shipMethod = Service_ShippingMethod::getByField($sm_code,'sm_code');
					if($length>0 && $width>0 && $height>0 && $shipMethod['sm_vol_rate']>0){
						$volWeight = ($length*$width*$height)/$shipMethod['sm_vol_rate'];
						$volWeight = sprintf('%.2f',$volWeight);
						//$weight = $weight>$volWeight?$weight:$volWeight;
					}else{
						throw new Exception('长、宽、高、运输方式体积转换率都必须大于0');
					}
					break;
                case "UKTL":
                    $length = $volArr['length'];
                    $width = $volArr['width'];
                    $height = $volArr['height'];
                    $shipMethod = Service_ShippingMethod::getByField($sm_code,'sm_code');
                    if($length>0 && $width>0 && $height>0 && $shipMethod['sm_vol_rate']>0){
                        $volWeight = ($length*$width*$height)/$shipMethod['sm_vol_rate'];
                        $volWeight = sprintf('%.2f',$volWeight);
                        $weight = $weight>$volWeight?$weight:$volWeight;
                    }else{
                        throw new Exception('长、宽、高、运输方式体积转换率都必须大于0');
                    }
                    break;
				default:
					$volArr = '';
					break;	
			}*/
            
    		//物流信息和状态
    		$soResult = $this->shipping($so_code, $weight, $tracking_number,$volWeight,$volArr);
    		if(!is_array($soResult)) throw new Exception($soResult);
    		//创建包袋订单行
    		$obdResult = $this->addBagDetail($order_id, $order_code, $ob_no, $soResult['so_code'], $weight);
    		if(!$obdResult) throw new Exception('创建包袋订单行失败');
            $orderRow = Service_Orders::getByField($order_id,"order_id","*");

    		//订单状态
    		$updateRow['order_status'] = 8;
    		$updateRow['update_time'] = date('Y-m-d H:i:s');
    		$oResult = Service_Orders::update($updateRow, $order_id);

            $w = Service_Warehouse::getByField($orderRow['warehouse_id'],'warehouse_id','*');
            if($orderRow['order_mode_type']=="1"){
                $sotDescription = "集货订单出货装袋";
            }else{
                $sotDescription = "备货订单出货装袋";
            }
            $shipOrderTracking = array(
                'order_code'=>$order_code,
                'sot_location'=>$w['warehouse_desc'],
                'sot_add_time'=>date("Y-m-d H:i:s"),
                'warehouse_id'=>$orderRow['warehouse_id'],
                'sot_description'=>$sotDescription,
                'sot_type'=>'0',
                'sot_time_offset'=>'',
                'tracking_number'=>$order_code,
                'ref_tracking_number'=>'',
                'status_desc'=>'已装袋',
                'user_id'=>Service_User::getUserId(),
            );
            Service_ShipOrderTracking::add($shipOrderTracking);
			if(in_array($aOrder['sm_code'],array('ALBP-G','ALBP-P','BH-BPG','BH-BPP'))){
                $fmsl = array(
                    'fmt_code'=>$aOrder['sm_code'],
                    'fmt_type'=>$aOrder['sm_code'],
                    'refercence_no'=>$aOrder['order_code'],
                    'fml_status'=>'0',
                    'fml_add_time'=>date("Y-m-d H:i:s"),
                    'fml_update_time'=>date("Y-m-d H:i:s")
                );
                Service_FtpMessageSendlist::add($fmsl);
            }

            $uopt = array(
                'ship_time'=>date("Y-m-d H:i:s"),
                'ship_user_id'=>Service_User::getUserId(),
            );
            Service_OrderOperationTime::update($uopt,$order_code,'order_code');
            //除HKDHL外件数都设置成装袋时写的件数

            if( !in_array( $shipMethod['sm_code'], array( 'HKDHL', 'CNDHL', 'DHL-TH','WWDHLP','WWDHLU') ) ){
                if ($sm_piece>0) {
                    $updateShip['so_piece']=$sm_piece;
                    Service_ShipOrder::update($updateShip,$so_code,'so_code');   
                    //if(!$sresult) throw new Exception('件数异常'); 
                }
            }
    		$stateFrom = $orderRow['order_status'];
    		$olResult = Service_OrderLog::log($order_id, $order_code, $stateFrom, 8, 0, '订单出货');
    		if(!$oResult || !$olResult) throw new Exception('数据库异常，更改订单状态失败');
            //非环球客户才扣费
            if( Service_CustomerProcess::$HuanQiu != Service_CustomerProcess::getOwner( $aOrder['customer_code'] ) ) {
                //解冻预扣金额
                $unfreezeRet = Service_CustomerBalanceProcess::unfreezeFee($order_code);
                if($unfreezeRet !== true) throw new Exception($unfreezeRet);
                //扣运费 和其它费用
                $volArr['realWeight'] = $realWeight;
                $feeResult = $this->shipFee($order_code,$volArr);
                if($feeResult !== true) throw new Exception($feeResult);
            }

            if(isset($bill_weight) && !empty($bill_weight)){
              foreach ($bill_weight as $key => $value) {
                Service_ShipOrderDetail::update(array('sod_bill_weight'=>$value),$key,'op_id');
              }
            }
            //bug 之前扣会读取不到批次你妹啊
            if($orderRow['order_mode_type']=="0"){//集货模式的订单，无须扣库存  0:备货模式1:集货模式
                //扣库存
                $piResult = $this->reduceStock($order_code);
                if($piResult !== true) throw new Exception($piResult);
            }

    		//提交事务
    		$db->commit();
    		//$db->rollback();
    		$result['state'] = 1;
    		$result['so_code'] = $soResult['so_code'];
    	} catch (Exception $e) {
    		$db->rollback();
    		$result['error'] = '内部错误 '.$e->getMessage();
    	}
    	return $result;
    }

    /**
     * 订单出货（用于订单整进整出，参照delivery，稍微修改）
     * 
     * 订单整进整出的运输方式一定是自有渠道、集货模式
     */
    public function deliveryForOrderInOut($order_id, $order_code, $ob_no, $weight, $tracking_number, $so_code, $sm_code, $volArr) {
      $ob_no           = strtoupper(trim($ob_no));
      $tracking_number = strtoupper(trim($tracking_number));
      $so_code         = strtoupper(trim($so_code));
      $order_code      = strtoupper(trim($order_code));
      $hscodeNum       = Service_OutboundBagDetail::countHscodeNum($ob_no); // 计算包袋hs_code个数
      $volWeight       = 0; // 体积重

      /*if($hscodeNum >= 20) { // 限制hs_code个数
        throw new Exception('包袋【' . $ob_no . '】已有20个hs_code，请拆袋');
      }*/

      // 物流信息和状态
      $soResult = $this->shipping($so_code, $weight, $tracking_number, $volWeight, $volArr);

      if (!is_array($soResult)) {
        throw new Exception($soResult);
      }

      // 创建包袋订单行
      $obdResult = $this->addBagDetail($order_id, $order_code, $ob_no, $soResult['so_code'], $weight);

      if (!$obdResult) {
        throw new Exception('订单【' . $order_code . '】装袋【' . $ob_no . '】失败');
      }

      $orderRow = Service_Orders::getByField($order_id, 'order_id');

      // 更新订单状态
      $updateRow['order_status'] = 8;
      $updateRow['update_time']  = date('Y-m-d H:i:s');
      $oResult                   = Service_Orders::update($updateRow, $order_id);

      // 订单物流轨迹
      $w                 = Service_Warehouse::getByField($orderRow['warehouse_id'], 'warehouse_id');
      $shipOrderTracking = array(
        'order_code'          => $order_code,
        'sot_location'        => $w['warehouse_desc'],
        'sot_add_time'        => date("Y-m-d H:i:s"),
        'warehouse_id'        =>$orderRow['warehouse_id'],
        'sot_description'     => '集货订单出货装袋',
        'sot_type'            => 0,
        'sot_time_offset'     => '',
        'tracking_number'     => $order_code,
        'ref_tracking_number' => '',
        'status_desc'         => '已装袋',
        'user_id'             => Service_User::getUserId(),
      );
      Service_ShipOrderTracking::add($shipOrderTracking);

      // 订单操作时间更新
      $uopt = array(
        'ship_time'    => date("Y-m-d H:i:s"),
        'ship_user_id' => Service_User::getUserId(),
      );
      Service_OrderOperationTime::update($uopt, $order_code, 'order_code');

      $stateFrom = $orderRow['order_status'];
      $olResult  = Service_OrderLog::log($order_id, $order_code, $stateFrom, 8, 0, '订单出货');

      if (!$oResult || !$olResult) {
        throw new Exception('数据库异常，更改订单状态失败');
      }

      // 解冻预扣金额
      $unfreezeRet = Service_CustomerBalanceProcess::unfreezeFee($order_code);

      if(TRUE !== $unfreezeRet) {
        throw new Exception($unfreezeRet);
      }

      // 扣运费和其它费用
      $volArr['realWeight'] = $weight;
      $feeResult            = $this->shipFee($order_code, $volArr);

      if (TRUE !== $feeResult) {
        throw new Exception($feeResult);
      }
    }

    /**
     * @desc 扣运费  目前两个地方使用此方法,签出、重新计费
     * @param $order_code
     * @param array $volArr
     * @param int $rpType //是否记录应付 0=>不记录
     * @param int $readjustment //是否为重新计费 1：重新计费
     * @return bool|string
     */
    public static function shipFee($order_code,$volArr=array(),$rpType=1,$readjustment=0) {
        $userAuth                   = new Zend_Session_Namespace('userAuthorization');
        $aOrder                     = Service_Orders::getByField($order_code, 'order_code');
        $aShipOrder                 = Service_ShipOrder::getByField($order_code, 'order_code');
        $aAddress                   = Service_OrderAddressBook::getByField($order_code, 'order_code');
        $countryArr                 = Service_Country::getByField($aAddress['oab_country_id'],'country_id');
        $customerArr                = Service_Customer::getByField($aOrder['customer_code'],'customer_code',array('customer_saler_user_id','customer_currency'));
        $customerCurrencyRow        = Service_Currency::getByField($customerArr['customer_currency'],'currency_code',array('currency_code','currency_rate','currency_batch_number'));
        $shippingMethodArr          = Service_ShippingMethod::getByField($aOrder['sm_code'],'sm_code',array('sm_vol_rate','sm_is_volume'));
        $currency_batch_number      = $customerCurrencyRow['currency_batch_number']; /* 当前汇率编号 */
        $_otherfee_mix_arr          = Process_BillConfig::getOtherFeeArr();
        $fee_cost_detail            = array(); /* 费用及成本明细 */
        $spArr                      = array();
        $incomeArr                  = array(); /* 客户费用 应收 */
        $paymentArr                 = array(); /* 应付费用 */
        $realWeight                 = 0;
        $date                       = date('Y-m-d H:i:s');
        $remote_ip                  = Common_Common::getIP();
        $fee_weight = 0;
        //Begin 运输费用及成本计算
        if(0 == $readjustment){
            //非重新计算运费的情况
            $_cbl_note      = '订单出货，扣';
            $objCalculate   = new Common_CalculateShipping();
            $realWeight     = $aShipOrder['so_weight'];
            $keys           = array(
                'warehouseId'               => $aOrder['warehouse_id'],
                'countryId'                 => $aAddress['oab_country_id'],
                'smCode'                    => $aOrder['sm_code'],
                'weight'                    => $aShipOrder['so_weight'],
                'order_code'                => $order_code,
                'realWeight'                => $volArr['realWeight'],
                'customerCode'              => $aOrder['customer_code'],
            );
            if($aAddress['oab_country_id']=='253'){
                //美国的要加入城市
                $citys = Service_City::getByCondition(array('country_id' => $aAddress['oab_country_id'],'city_name'=>$aAddress['oab_city'],'sm_code' => $aOrder['sm_code']));
                if(empty($citys)){
                    $conditionCity = array(
                        'country_id'=>$aAddress['oab_country_id'],
                        'city_name'=>$aAddress['oab_city'],
                        'sm_code' =>'0'
                    );
                    $citys = Service_City::getByCondition($conditionCity,'*');
                }
                if(!empty($citys)){
                    $keys['cityId'] = $citys[0]['city_id'];
                }
            }
            if($aAddress['oab_country_id']=='106'){
                //香港的要加入城市
                $citys = Service_City::getByCondition(array('country_id' => $aAddress['oab_country_id'],'city_name'=>$aAddress['oab_city'],'sm_code' => $aOrder['sm_code']));
                if(empty($citys)){
                    $conditionCity = array(
                        'country_id'=>$aAddress['oab_country_id'],
                        'city_name'=>$aAddress['oab_city'],
                        'sm_code' =>'0'
                    );
                    $citys = Service_City::getByCondition($conditionCity,'*');
                }
                if(!empty($citys)){
                    $keys['cityId'] = $citys[0]['city_id'];
                }
            }
        } else if(1 == $readjustment){
            //重新计费的时间取装袋的时间
            $operateTime = Service_OrderOperationTime::getByField($order_code, 'order_code');
            $date = $operateTime['ship_time'];
            //重新计算运费的情况 被 Process_BusinessIncome 所调用
            $_cbl_note              = '重新计费，扣';
            $objCalculate           = new Common_ReCalculateShipping(); /* 重新计费的方法差异很大，另写新类 */

            $realWeight             = ($aShipOrder['so_service_provider_weight'] > $volArr['realWeight'])? $aShipOrder['so_service_provider_weight'] : $volArr['realWeight'];
            $logisticsCostRow       = Service_LogisticsCost::getByField($order_code, 'order_code', array('currency_code', 'currency_rate', 'smc_discount', 'price_batch_number', 'sm_baf', 'customer_currency_code', 'customer_currency_rate'));
            $costRecordingRow       = Service_CostRecording::getByField($order_code, 'order_code', array('currency_code', 'currency_rate', 'price_batch_number', 'currency_batch_number', 'sm_baf', 'provider_currency_code', 'provider_currency_rate'));
            $currency_batch_number  = $costRecordingRow['currency_batch_number'];
            $currencyLogRows        = Service_CurrencyLog::getByBatchnumber($currency_batch_number);
            $keys                   = array(
                'warehouseId'               => $aOrder['warehouse_id'],
                'countryId'                 => $aAddress['oab_country_id'],
                'smCode'                    => $aOrder['sm_code'],
                'weight'                    => $volArr['realWeight'],
                'order_code'                => $order_code,
                'realWeight'                => $volArr['realWeight'],
                'customerCode'              => $aOrder['customer_code'],
                'price_currency_code'       => $logisticsCostRow['currency_code'],          //运输价格币种
                'price_currency_rate'       => $logisticsCostRow['currency_rate'],          //运输价格币种汇率
                'smc_discount'              => $logisticsCostRow['smc_discount'],           //客户运输折扣
                'customer_currency_code'    => $logisticsCostRow['customer_currency_code'], //客户币种
                'customer_currency_rate'    => $logisticsCostRow['customer_currency_rate'], //客户币种汇率
                'provider_currency_code'    => $costRecordingRow['provider_currency_code'], //服务商币种 - costRecording
                'provider_currency_rate'    => $costRecordingRow['provider_currency_rate'], //服务商币种汇率 - costRecording
                'sm_baf'                      => $costRecordingRow['sm_baf'],                 //燃油费率，只对 CRE起作用 - costRecording
                'price_batch_number'        => $costRecordingRow['price_batch_number'],     //运输价格编号 - costRecording 或 logisticsCost
            );
            if($aAddress['oab_country_id']=='253'){
                //美国的要加入城市
                $citys = Service_City::getByCondition(array('country_id' => $aAddress['oab_country_id'],'city_name'=>$aAddress['oab_city'],'sm_code' => $aOrder['sm_code']));
                if(empty($citys)){
                    $conditionCity = array(
                        'country_id'=>$aAddress['oab_country_id'],
                        'city_name'=>$aAddress['oab_city'],
                        'sm_code' =>'0'
                    );
                    $citys = Service_City::getByCondition($conditionCity,'*');
                }
                if(!empty($citys)){
                    $keys['cityId'] = $citys[0]['city_id'];
                }
            }
            if($aAddress['oab_country_id']=='106'){
                //香港的要加入城市
                $citys = Service_City::getByCondition(array('country_id' => $aAddress['oab_country_id'],'city_name'=>$aAddress['oab_city'],'sm_code' => $aOrder['sm_code']));
                if(empty($citys)){
                    $conditionCity = array(
                        'country_id'=>$aAddress['oab_country_id'],
                        'city_name'=>$aAddress['oab_city'],
                        'sm_code' =>'0'
                    );
                    $citys = Service_City::getByCondition($conditionCity,'*');
                }
                if(!empty($citys)){
                    $keys['cityId'] = $citys[0]['city_id'];
                }
            }
        } else{
            //暂不存在第三种情况
        }

        /*switch(strtoupper($aOrder['sm_code'])){
            case "SZY-EMS":
            case "UKTL":
            case "HTTX-HKDHL":
                $keys['length'] = $volArr['volArr'][0]['length'];
                $keys['width']  = $volArr['volArr'][0]['width'];
                $keys['height'] = $volArr['volArr'][0]['height'];
                break;
            default:
                break;
        }*/
        if( $aOrder['sm_code'] == 'DGF-CARGO'){
            //获取空运相关的信息
            $orderShipping = Service_OrderShipping::getByField( $order_code,'order_code');
            $keys['aircode'] = $orderShipping['destination'];
        }
        $objCalculate->setParams($keys);
        $aCalculate = $objCalculate->getRate();
        if($aCalculate['state']=="0"){
            $message = "";
            foreach($aCalculate['error'] as $error){
                $message.=$error.";";
            }
            return $message;
        }
        $fee_weight = isset($aCalculate['data']['cost']['fee_weight'])?$aCalculate['data']['cost']['fee_weight']:0;
        //End 运输费用及成本计算
        //print_r($aCalculate);exit;
        if(isset($aCalculate['data']['sm']) && $aCalculate['data']['sm']['sm_channel']=='0'){
        //Begin 非自有运输方式扣物流运输费、燃油附加费

            //记录应收、应付
            $incomeArr = $paymentArr = array();
            if($aCalculate['state'] == 0) {
                return is_array($aCalculate['error']) ? implode(',', $aCalculate['error']) : $aCalculate['error'];
            }
            $fee = $aCalculate['data']['cost']['totalCost'];
            
            //生成一条成本费用的记录
            $sm = $aCalculate['data']['sm'];
            //服务商货币及汇率
            $providerRow            = Service_ServiceProvider::getByField($sm['sp_code'], 'sp_code', array('currency_code'));
            if(empty($providerRow)){
                throw new Exception('运输方式'.$sm['sm_code'].'服务商未设置！');
            }
            $providerCurrencyRow    = Service_Currency::getByField( $providerRow['currency_code'], 'currency_code', array('currency_code','currency_rate'));
            //成本货币及汇率
            $costCurrencyRow        = Service_Currency::getByField($aCalculate['data']['cost']['cost_currency_code'], 'currency_code', array('currency_code','currency_rate'));
            //成本费
            $costFee                = $aCalculate['data']['cost']['cost'];
            //单票成本
            $ticket_fare_cost       = isset($aCalculate['data']['cost']['one_ticket_cbcost'])?$aCalculate['data']['cost']['one_ticket_cbcost']:0;
            //燃油附加费
            //$fuel_addons = $aCalculate['data']['cost']['cost']*$sm['sm_baf'];
            $fuel_addons            = $aCalculate['data']['cost']['cost_baf'];
            if(in_array($sm['sm_class_code'], array("CPS","CRP","CRE"))){
                $total          = $aCalculate['data']['cost']['cost'] + $ticket_fare_cost ;
                if($sm['sm_class_code'] == "CRE"){
                    $total += $fuel_addons; //快递加上燃油附加费
                }else{
                    $fuel_addons    = 0;
                }
            }

            $costRecording = array(
                'order_code'                => $order_code,
                'customer_code'             => $aOrder['customer_code'],
                'reference_no'              => $aOrder['reference_no'],
                'tracking_number'           => $aShipOrder['tracking_number'],
                'sm_code'                   => $aOrder['sm_code'],
                'country_id'                => $aAddress['oab_country_id'],
                'weight'                    => $realWeight,
                'cost_fee'                  => $costFee,
                'ticket_fare'               => $ticket_fare_cost,
                'fuel_addons'               => $fuel_addons,
                'total_fee'                 => $total,
                'price_batch_number'        => $aCalculate['data']['cost']['price_batch_number'],   //价格编号,用于重算
                'currency_batch_number'     => $currency_batch_number,                              //汇率编号，用于重算
                'sm_baf'                    => $aCalculate['data']['sm']['sm_baf'],                 //燃油附加费率,用于重算
                'currency_code'             => $costCurrencyRow['currency_code'],                   //成本币种
                'currency_rate'             => $costCurrencyRow['currency_rate'],                   //成本币种汇率
                'provider_currency_code'    => $providerCurrencyRow['currency_code'],               //服务商币种
                'provider_currency_rate'    => $providerCurrencyRow['currency_rate'],               //服务商币种汇率
                'add_time'                  => $date,
                'update_time'               => $date,
            );
            //重新计费的情况
            $cRow = Service_CostRecording::getByField($order_code, 'order_code');
            if (empty($cRow)) {
                unset($costRecording['update_time']);
                Service_CostRecording::add($costRecording);
            } else {
                unset($costRecording['add_time']);
                unset($costRecording['currency_code']);
                unset($costRecording['price_batch_number']);
                unset($costRecording['sm_baf']);
                unset($costRecording['currency_rate']);
                unset($costRecording['provider_currency_code']);
                unset($costRecording['provider_currency_rate']);
                unset($costRecording['add_time']);
                Service_CostRecording::update($costRecording, $cRow['cr_id'], 'cr_id');
            }

            /**
             * Begin 应付
             */

            //运费（未包括其它费用项）
            if ($costFee > 0) {
                if (!isset($spArr[$sm['sp_code']])) {
                    $spRow = Service_ServiceProvider::getByField($sm['sp_code'], 'sp_code');
                    $spArr[$sm['sp_code']] = $spRow['currency_code'];
                }
                $convert_fee = Service_Currency::converByCode($aCalculate['data']['cost']['cost_currency_code'], $spArr[$sm['sp_code']], $costFee);
                $paymentArr[] = array(
                    'sp_code'               => $sm['sp_code'], //服务商代码
                    'ft_code'               => 'shipping',
                    'ut_code'               => 'KG',
                    'sm_code'               => $aOrder['sm_code'],
                    'bp_amount'             => $convert_fee,
                    'bp_org_amount'         => $costFee, //原金额
                    'currency_code'         => $aCalculate['data']['cost']['cost_currency_code'],
                    'currency_rate'         => $aCalculate['data']['cost']['currency_rate'],
                    'bp_chargeable_time'    => $date,
                );
            }
            //单票
            if($ticket_fare_cost>0){
                if (!isset($spArr[$sm['sp_code']])) {
                    $spRow = Service_ServiceProvider::getByField($sm['sp_code'], 'sp_code');
                    $spArr[$sm['sp_code']] = $spRow['currency_code'];
                }
                $convert_fee = Service_Currency::converByCode($aCalculate['data']['cost']['cost_currency_code'], $spArr[$sm['sp_code']], $ticket_fare_cost);
                $paymentArr[]=array(
                    'sp_code'               => $sm['sp_code'],//服务商代码
                    'ft_code'               => 'one_ticket_fee',
                    'ut_code'               => 'PCE',
                    'sm_code'               => $aOrder['sm_code'],
                    'bp_amount'             => $convert_fee,
                    'bp_org_amount'         => $ticket_fare_cost, //原金额
                    'currency_code'         => $aCalculate['data']['cost']['cost_currency_code'],
                    'currency_rate'         => $aCalculate['data']['cost']['currency_rate'],
                    'bp_chargeable_time'    => $date,
                );
            }
            //附加费
            if($fuel_addons>0){
                if (!isset($spArr[$sm['sp_code']])) {
                    $spRow = Service_ServiceProvider::getByField($sm['sp_code'], 'sp_code');
                    $spArr[$sm['sp_code']] = $spRow['currency_code'];
                }
                $convert_fee = Service_Currency::converByCode($aCalculate['data']['cost']['cost_currency_code'], $spArr[$sm['sp_code']], $fuel_addons);
                $paymentArr[]=array(
                    'sp_code'               => $sm['sp_code'],//服务商代码
                    'ft_code'               => 'additional_fee',
                    'ut_code'               => 'PCE',
                    'sm_code'               => $aOrder['sm_code'],
                    'bp_amount'             => $convert_fee,
                    'bp_org_amount'         => $fuel_addons,//原金额
                    'currency_code'         => $aCalculate['data']['cost']['cost_currency_code'],
                    'currency_rate'         => $aCalculate['data']['cost']['currency_rate'],
                    'bp_chargeable_time'    => $date,
                );
            }
            /**
             * End  应付
             */


            //运费
            $transport_fee = $aCalculate['data']['cost']['baseCost']+$aCalculate['data']['cost']['addCost']+$aCalculate['data']['cost']['pCost'];
           /* var_dump($aCalculate['data']['cost']['baseCost']);
            var_dump($aCalculate['data']['cost']['addCost']);
            var_dump($aCalculate['data']['cost']['pCost']);exit();*/
            if($sm['sm_class_code']=="CRP"){
                $transport_fee = $transport_fee + $aCalculate['data']['cost']['regCost'];
            }
   			
            //燃油附加费
            $fuel_addons = $aCalculate['data']['cost']['baseBaf'];
            if($sm['sm_class_code']=="CRP"||$sm['sm_class_code']=="CPS"){
                $fuel_addons = 0;
            }
            //单票费用
            $ticket_fare = isset($aCalculate['data']['cost']['baseTicketFee'])?$aCalculate['data']['cost']['baseTicketFee']:0;
            $totalFee = $transport_fee + $ticket_fare + $fuel_addons;
            //生成一条运费记录
            $logisticsCost = array(
                'order_code'                => $order_code,
                'customer_code'             => $aOrder['customer_code'],
                'reference_no'              => $aOrder['reference_no'],
                'tracking_number'           => $aShipOrder['tracking_number'],
                'sm_code'                   => $aOrder['sm_code'],
                'country_id'                => $aAddress['oab_country_id'],
                'weight'                    => $realWeight,
                'transport_fee'             => $transport_fee,
                'ticket_fare'               => $ticket_fare,
                'fuel_addons'               => $fuel_addons,
                'total_fee'                 => $totalFee,
                'currency_code'             => $aCalculate['data']['cost']['currency_code'],    //运输（费用）销售币种
                'currency_rate'             => $aCalculate['data']['cost']['currency_rate'],    //运输（费用）销售币种汇率
                'smc_discount'              => $aCalculate['data']['sm']['customer_discount'],  //客户运输方式折扣
                'price_batch_number'        => $aCalculate['data']['cost']['price_batch_number'], //价格编号,用于重算
                'sm_baf'                    => $aCalculate['data']['sm']['sm_baf'],             //燃油附加费率,用于重算
                'customer_currency_code'    => $customerCurrencyRow['currency_code'],           //客户币种
                'customer_currency_rate'    => $customerCurrencyRow['currency_rate'],           //客户币种汇率
                'add_time'                  => $date,
                'update_time'               => $date,
            );
            $lRow=Service_LogisticsCost::getByField($order_code,'order_code');
            if(empty($lRow)){
                unset($logisticsCost['update_time']);
                Service_LogisticsCost::add($logisticsCost);
            }else{
                unset($logisticsCost['currency_code']);
                unset($logisticsCost['currency_rate']);
                unset($logisticsCost['smc_discount']);
                unset($logisticsCost['price_batch_number']);
                unset($logisticsCost['sm_baf']);
                unset($logisticsCost['customer_currency_code']);
                unset($logisticsCost['customer_currency_rate']);
                unset($logisticsCost['add_time']);
                Service_LogisticsCost::update($logisticsCost,$lRow['lc_id'],'lc_id');
            }

            $feeArr = array(
                'currency_code' => $aCalculate['data']['cost']['currency_code'],
                'price'         => $fee,
            );
            if(1 == $readjustment){
                //重新计费的情况下，转换的金额也应该是根据原始汇率运算的结果
                $feeArr['convert_fee'] = sprintf('%.2f', $fee * $logisticsCostRow['currency_rate'] / $logisticsCostRow['customer_currency_rate']);
            }
            //扣运费
            $result = Service_CustomerBalanceProcess::deductFee($aOrder['customer_id'], $feeArr, '订单出货，扣运费', $order_code);
            if($result['ask'] == 0) return $result['error'];


            /**
             * Begin 应收
             */
            //运费

            $convert_fee = Service_Currency::converByCode($aCalculate['data']['cost']['currency_code'], $customerArr['customer_currency'], $transport_fee);
            $incomeArr[] = array(
                'customer_code'         => $aOrder['customer_code'],
                'ft_code'               => 'shipping',
                'ut_code'               => 'KG',
                'sm_code'               => $aOrder['sm_code'],
                'bi_amount'             => $convert_fee,
                'bi_org_amount'         => $transport_fee,
                'currency_code'         => $aCalculate['data']['cost']['currency_code'],//原币种
                'currency_rate'         => $aCalculate['data']['cost']['currency_rate'],
                'bi_chargeable_time'    => $date,
                'bi_note'               => '运费',
            );
            //单票费用
            if($ticket_fare>0){
                $convert_fee = Service_Currency::converByCode($aCalculate['data']['cost']['currency_code'], $customerArr['customer_currency'], $ticket_fare);
                $incomeArr[] = array(
                    'customer_code'         => $aOrder['customer_code'],
                    'ft_code'               => 'one_ticket_fee',
                    'ut_code'               => 'KG',
                    'sm_code'               => $aOrder['sm_code'],
                    'bi_amount'             => $convert_fee,
                    'bi_org_amount'         => $ticket_fare,
                    'currency_code'         => $aCalculate['data']['cost']['currency_code'],//原币种
                    'currency_rate'         => $aCalculate['data']['cost']['currency_rate'],
                    'bi_chargeable_time'    => $date,
                    'bi_note'               => '单票费用',
                );
            }
            //燃油附加费用
            if($fuel_addons>0){
                $convert_fee = Service_Currency::converByCode($aCalculate['data']['cost']['currency_code'], $customerArr['customer_currency'], $fuel_addons);
                $incomeArr[] = array(
                    'customer_code'         => $aOrder['customer_code'],
                    'ft_code'               => 'additional_fee',
                    'ut_code'               => 'KG',
                    'sm_code'               => $aOrder['sm_code'],
                    'bi_amount'             => $convert_fee,
                    'bi_org_amount'         => $fuel_addons,
                    'currency_code'         => $aCalculate['data']['cost']['currency_code'],//原币种
                    'currency_rate'         => $aCalculate['data']['cost']['currency_rate'],
                    'bi_chargeable_time'    => $date,
                    'bi_note'               => '燃油附加费用',
                );
            }

            /**
             * End 应收
             */

        //End 非自有运输方式扣物流运输费、燃油附加费
        }


        /* 扣其它费用 Begin */
        $objOtherCalculte           = new Common_CalculateOtherFee();
        if(1 == $readjustment){
            //重新计费，杂费以实际总量为准
            if(isset($volArr['weight'])){
                $keys['weight'] = $volArr['weight'];
            }
        }
        $keys['receiving_weight']   = $aShipOrder['so_weight'];
        $objOtherCalculte->setParams($keys);
        $otherfeeArr                = $objOtherCalculte->getOtherFee();
        $currencyCacheRows          = Common_DataCache::getCurrency();
        $_is_deduct                 = false;
        unset($otherfeeArr['data']['otherFee']['tihuo']);
        foreach($otherfeeArr['data']['otherFee'] as $otherfee_name => $otherfee_data){
            $fee_detail = $cost_detail = array();
            $otherfee_name = str_replace('-', '', strtolower($otherfee_name));
            switch($otherfee_name){
                case 'cangchu':
                case 'caozuo':
                case 'baoguan':
                case 'tihuo':
                case 'yunshu':
                case 'jianguanyunshu':
                //case 'ruku':
                case 'wuliucaozuo':
                case 'pianyuan':
                case 'wuliao':
                case 'guanli':
                case 'jianguanyunshu':
                case 'chaozhi':
                case 'BHDPDRemoteFee':
                case 'fbatax':
                case 'chaochang':
                case 'chaozhibaoguan':
                case 'kongyun':
                case 'gfx':
                case 'pod':
                case 'sxz':
                case '4pxduty':
                case '4pxgfxdq':
	            case '4pxpydq':
                case '4pxxymdd':
                //单独报关费
                case '4pxddbg':
                //超长超重费
                case '4pxcccz':
                case 'vat':
                case 'dispatchnotice':
                case 'guarantee':
                //case 'sanzu':
                case 'czfb':
                case 'thremote':
                case 'thfbatax':
                case 'wjfjf':
                    $_is_deduct = true;
                    break;
                default:
                    $_is_deduct = false;
                    break;
            }
            if(($aOrder['sm_code']!="BH-DPD"&&$otherfee_name=="BHDPDRemoteFee")||($aOrder['sm_code']=="BH-DPD"&&$otherfee_name=="pianyuan")||($aOrder['sm_code']=="BH-DPD"&&$otherfee_name=="BHDPDRemoteFee"&&$aOrder['is_remote_city']!="1")) continue;
            if(isset($_otherfee_mix_arr[$otherfee_name]['smcode'])){
            /* 某些杂费只针对特定的运输方式，或者排除特定的运输方式 */
                if('DENY' == $_otherfee_mix_arr[$otherfee_name]['smcode']['type']){
                    if(isset($_otherfee_mix_arr[$otherfee_name]['smcode'][$aOrder['sm_code']])){
                        $_is_deduct = false;
                    }
                }
                if('ALLOW' == $_otherfee_mix_arr[$otherfee_name]['smcode']['type']){
                    if(!isset($_otherfee_mix_arr[$otherfee_name]['smcode'][$aOrder['sm_code']])){
                        $_is_deduct = false;
                    }
                }
            }
            if( $aOrder['sm_code'] == 'DHL-TH') {
                if( $otherfee_name == 'pianyuan' || $otherfee_name == 'fbatax') {//哲盟的不用再算以前的偏远 关税
                    $_is_deduct = false;
                }
            } else {
                if( $otherfee_name == 'thremote' || $otherfee_name == 'thfbatax') {
                    $_is_deduct = false;
                }
            }
            if(($aOrder['order_mode_type'] == '1') && $otherfee_name == 'czfb'){//集货订单不收取操作费-B
                $_is_deduct = false;
            }
            /*if(!in_array($aOrder['sm_code'], array('BH-HKDHL','DHL-TH','DHL-BH03'))){
                $_is_deduct = false;
            }*/
            if(false == $_is_deduct){
                continue; /* 不需要扣费 */
            }
            if((($otherfee_name == 'dispatchnotice') && ($aOrder['dispatch_notice'] !='1')) || (($otherfee_name == 'guarantee') && ($aOrder['guarantee'] !='1'))){
                continue; /* 不需要扣费 */
            }
            if($otherfee_name == 'fbatax'){
                if($aOrder['is_fba_tax'] == '0'){
                    continue; /* 不需要扣费 */
                }
            }
            if (empty($otherfee_data['cost_currency_code'])) {
                $otherfee_data['cost_currency_code']=$otherfee_data['currency_code'];
            }
            if($otherfee_data['price'] > 0){
                if(1 == $readjustment){
                  if(empty($currencyLogRows)){
                      //若为空的情况下
                      $currencyLogRows = $currencyCacheRows;
                  }
                //重新计费的情况下，转换的金额也应该是根据原始汇率运算的结果
                    $otherfee_data['convert_fee']   = Service_CurrencyLog::converByCode($otherfee_data['currency_code'],$customerArr['customer_currency'],$otherfee_data['price'],$currency_batch_number);
                    $convert_fee                    = $otherfee_data['convert_fee'];
                    $otherfee_rate                  = $currencyLogRows[$otherfee_data['currency_code']]['currency_rate'];
                } else {
                    $convert_fee                    = Service_Currency::converByCode($otherfee_data['currency_code'], $customerArr['customer_currency'], $otherfee_data['price']);
                    $otherfee_rate                  = $currencyCacheRows[$otherfee_data['currency_code']]['currency_rate'];
                }

                $result = Service_CustomerBalanceProcess::deductFee($aOrder['customer_id'], $otherfee_data, $_cbl_note . $_otherfee_mix_arr[$otherfee_name]['binote'], $order_code, $_otherfee_mix_arr[$otherfee_name]['ftcode'], $otherfee_data['fee_id']);
                if(0 == $result['ask']) return $result['error'];

                //应收记录
                $incomeArr[] = array(
                    'customer_code'         => $aOrder['customer_code'],
                    'ft_code'               => $_otherfee_mix_arr[$otherfee_name]['ftcode'],
                    'ut_code'               => $_otherfee_mix_arr[$otherfee_name]['utcode'],
                    'sm_code'               => $aOrder['sm_code'],
                    'bi_amount'             => $convert_fee,
                    'bi_org_amount'         => $otherfee_data['price'],
                    'currency_code'         => $otherfee_data['currency_code'],
                    'currency_rate'         => $otherfee_rate,
                    'bi_chargeable_time'    => $date,
                    'bi_note'               => $_otherfee_mix_arr[$otherfee_name]['binote'],
                );
                $fee_detail = array(
                    'fee_amount_customer'           => $convert_fee,                                        //费用金额（客户）
                    'fee_currency_code_customer'    => $customerArr['customer_currency'],                   //费用币种（客户）
                    'discount_customer'             => $otherfee_data['discount'],                          //折扣率（客户）（1=100%）
                );
            }
            if(isset($otherfee_data['cost']) && $otherfee_data['cost'] > 0 && $otherfee_data['sp_code']!=''){
                if(!isset($spArr[$otherfee_data['sp_code']])){
                    $spRow = Service_ServiceProvider::getByField($otherfee_data['sp_code'],'sp_code');
                    $spArr[$otherfee_data['sp_code']] = $spRow['currency_code'];
                }
                if(1 == $readjustment){
                    $convert_fee    = Service_CurrencyLog::converByCode($otherfee_data['cost_currency_code'],$spArr[$otherfee_data['sp_code']],$otherfee_data['cost'],$currency_batch_number);
                    $otherfee_rate  = $currencyLogRows[$otherfee_data['cost_currency_code']]['currency_rate'];
                } else {
                    $convert_fee    = Service_Currency::converByCode($otherfee_data['cost_currency_code'], $spArr[$otherfee_data['sp_code']], $otherfee_data['cost']);
                    $otherfee_rate  = $currencyCacheRows[$otherfee_data['cost_currency_code']]['currency_rate'];
                }
                //应付记录
                $paymentArr[] = array(
                    'sp_code'               => $otherfee_data['sp_code'],       //服务商代码
                    'ft_code'               => $_otherfee_mix_arr[$otherfee_name]['ftcode'],
                    'ut_code'               => $_otherfee_mix_arr[$otherfee_name]['utcode'],
                    'sm_code'               => $aOrder['sm_code'],
                    'bp_amount'             => $otherfee_data['cost'],                    //服务商结算金额
                    'bp_org_amount'         => $otherfee_data['cost'],          //原金额
                    'currency_code'         => $otherfee_data['cost_currency_code'], //原币种
                    'currency_rate'         => $otherfee_rate,
                    'bp_chargeable_time'    => $date,
                    'bp_note'               => $_otherfee_mix_arr[$otherfee_name]['binote'],
                );
                $cost_detail = array(
                    'cost_amount_org'               => $otherfee_data['cost'],                              //成本金额（原始）
                    'cost_currency_code_org'        => $otherfee_data['cost_currency_code'],                     //成本币种（原始）
                    'cost_amount_sp'                => $otherfee_data['cost'],                                        //成本金额（服务商）
                    'cost_currency_code_sp'         => $otherfee_data['cost_currency_code'],                   //成本币种（服务商）
                    'sp_code'                       => $otherfee_data['sp_code'],                           //服务商代码
                );
            }

            if(!empty($fee_detail) || !empty($cost_detail)){
                $fee_cost_common    = array(
                    'code_number'                   => $order_code,                                         //单号
                    'code_type'                     => 1,                                                   //单号类型（1:区内单 2：区外单 3：ASN单）
                    'customer_code'                 => $aOrder['customer_code'],                            //客户代码
                    'reference_no'                  => $aOrder['reference_no'],                             //客户参考号
                    'tracking_number'               => $aShipOrder['tracking_number'],                      //服务商单号（跟踪号）
                    'sm_code'                       => $aOrder['sm_code'],                                  //运输方式代码
                    'country_code'                  => $countryArr['country_code'],                         //国际简称（二字码）
                    'fee_code'                      => $_otherfee_mix_arr[$otherfee_name]['ftcode'],        //费用编号
                    'fee_name'                      => $_otherfee_mix_arr[$otherfee_name]['binote'],        //费用名称
                    'fee_amount_org'                => $otherfee_data['price'],                             //费用金额（原始）
                    'fee_currency_code_org'         => $otherfee_data['currency_code'],                     //费用币种（原始）
                    'price_batch_number'            => $aCalculate['data']['cost']['price_batch_number'],   //运输价格编号
                    'currency_batch_number'         => $currency_batch_number,                              //货币汇率编号
                    'fee_time'                      => $date,                                               //扣费时间
                    'fee_time_recalculate'          => $date,                                               //重新扣费时间
                    'ip'                            => $remote_ip,                                          //扣费操作IP
                    'ip_recalculate'                => $remote_ip,                                          //重新扣费操作IP
                    'operator'                      => $userAuth->user['user_name'],                         //扣费操作人
                    'operator_recalculate'          => $userAuth->user['user_name'],                         //重新扣费操作人
                );
                $fee_cost_detail[]  = array_merge($fee_detail, $cost_detail, $fee_cost_common);
            }
        }
        /* 扣其它费用 End */
        //保险费
        if( $aOrder['insurance'] == 1 ) {
            $pObj = new Service_OtherFeeProcess();
            $address = Service_OrderAddressBook::getByField($aOrder['order_code'],'order_code');
            //获取保险费,返回的费用最多只有2位小数
            $param = array(
                'insuranceRate'=>$aOrder['insurance_rate'],
                'country'=>$address['oab_country_id'],
                'dealPrice'=>$aOrder['charge'],
                'dealCurrency'=>$aOrder['currency_code'],
                'orderCode'=>$aOrder['order_code'],
            );

            $insurance = $pObj->getAmount($aOrder['warehouse_id'],$aOrder['insurance_code'],$param,$readjustment);

            if( $insurance === false )
                return '获取保险费失败,'.implode(',',$pObj->getError());

            foreach( $insurance as $value ) {
                if( $value['amount'] == 0 )
                    continue;

                $feeItem = Service_OtherFee::getByField( $value['feeCode'],'fee_code');
                if( empty( $feeItem ) )
                    return '费用项目不存在';

                //扣费
                $insuranceFee = array(
                    'currency_code' => 'RMB',
                    'price' => $value['amount'],
                );
                $bNote = '订单出货，扣'.$feeItem['fee_name'].'费';
                $result = Service_CustomerBalanceProcess::deductFee($aOrder['customer_id'], $insuranceFee, $bNote, $aOrder['order_code'], 1, $feeItem['fee_id']);
                if(0 == $result['ask'])
                    return $result['error'];

                //应收记录
                $incomeArr[] = array(
                    'customer_code'         => $aOrder['customer_code'],
                    'ft_code'               => $feeItem['ft_code'],
                    'ut_code'               => 'PCE',
                    'sm_code'               => $aOrder['sm_code'],
                    'bi_amount'             => $value['amount'],
                    'bi_org_amount'         => $value['amount'],
                    'currency_code'         => 'RMB',
                    'currency_rate'         => 1,
                    'bi_chargeable_time'    => $date,
                    'bi_note'               => $feeItem['fee_name'].'费',
                );
                $fee_detail = array(
                    'fee_amount_customer'           => $value['amount'],                                        //费用金额（客户）
                    'fee_currency_code_customer'    => 'RMB',                   //费用币种（客户）
                    'discount_customer'             => 1,                          //折扣率（客户）（1=100%）
                );

                //获取服务商的币种
                if(!isset( $spArr[ $feeItem['sp_code'] ] ) ){
                    $spRow = Service_ServiceProvider::getByField( $feeItem['sp_code'], 'sp_code' );
                    $spArr[$feeItem['sp_code']] = $spRow['currency_code'];
                }
                //获取服务商币种汇率
                $rate = Service_OtherFeeProcess::getRate( $spArr[$feeItem['sp_code']], $readjustment, $aOrder['order_code']);
                if( $rate === false )
                    return '汇率不存在';

                //转换费用
                $convertFee = sprintf('%0.2f',$value['cost'] / $rate);
                //应付
                $paymentArr[] = array(
                    'sp_code'               => $feeItem['sp_code'],       //服务商代码
                    'ft_code'               => $feeItem['ft_code'],
                    'ut_code'               => 'PCE',
                    'sm_code'               => $aOrder['sm_code'],
                    'bp_amount'             => $convertFee,                    //服务商结算金额
                    'bp_org_amount'         => $value['cost'],          //原金额
                    'currency_code'         => 'RMB', //原币种
                    'currency_rate'         => $rate,
                    'bp_chargeable_time'   => $date,
                    'bp_note'               => $feeItem['fee_name'].'费',
                );
                $cost_detail = array(
                    'cost_amount_org'               => $value['cost'],                              //成本金额（原始）
                    'cost_currency_code_org'        => 'RMB',                     //成本币种（原始）
                    'cost_amount_sp'                => $convertFee,                                        //成本金额（服务商）
                    'cost_currency_code_sp'         => $spArr[$feeItem['sp_code']],                   //成本币种（服务商）
                    'sp_code'                       => $feeItem['sp_code'],                           //服务商代码
                );

                if(!empty($fee_detail) || !empty($cost_detail)){
                    $fee_cost_common    = array(
                        'code_number'                   => $order_code,                                         //单号
                        'code_type'                     => 1,                                                   //单号类型（1:区内单 2：区外单 3：ASN单）
                        'customer_code'                 => $aOrder['customer_code'],                            //客户代码
                        'reference_no'                  => $aOrder['reference_no'],                             //客户参考号
                        'tracking_number'               => $aShipOrder['tracking_number'],                      //服务商单号（跟踪号）
                        'sm_code'                       => $aOrder['sm_code'],                                  //运输方式代码
                        'country_code'                  => $countryArr['country_code'],                         //国际简称（二字码）
                        'fee_code'                      => $feeItem['fee_code'],        //费用编号
                        'fee_name'                      => $feeItem['fee_name'].'费', //费用名称
                        'fee_amount_org'                => $value['amount'],          //费用金额（原始）
                        'fee_currency_code_org'         => 'RMB',                     //费用币种（原始）
                        'price_batch_number'            => 0,   //运输价格编号
                        'currency_batch_number'         => $currency_batch_number,                              //货币汇率编号
                        'fee_time'                      => $date,                                               //扣费时间
                        'fee_time_recalculate'          => $date,                                               //重新扣费时间
                        'ip'                            => $remote_ip,                                          //扣费操作IP
                        'ip_recalculate'                => $remote_ip,                                          //重新扣费操作IP
                        'operator'                      => $userAuth->user['user_name'],                         //扣费操作人
                        'operator_recalculate'          => $userAuth->user['user_name'],                         //重新扣费操作人
                    );
                    $fee_cost_detail[]  = array_merge($fee_detail, $cost_detail, $fee_cost_common);
                }
            }
        }

        //更新物流订单
        $uShipOrder['so_shipping_fee']      = $result['fee'];
        $uShipOrder['so_update_time']       = date('Y-m-d H:i:s');
        $uShipOrder['so_fee_weight']        = $fee_weight;
        Service_ShipOrder::update($uShipOrder, $aShipOrder['so_id']);

        //更新订单
        $uOrder['shipping_fee_estimate']    = $result['fee'];
        $uOrder['update_time']              = date('Y-m-d H:i:s');
        Service_Orders::update($uOrder, $order_code, 'order_code');
        //业务数据
        //$_bb_volumne_weight = (1 == $shippingMethodArr['sm_is_volume'])? (($volArr['length'] * $volArr['width'] * $volArr['height']) / $shippingMethodArr['sm_vol_rate']) : 0;
        $_bb_volumne_weight = 0;
        if(1 == $shippingMethodArr['sm_is_volume'] && !in_array( $aOrder['sm_code'], array( 'HKDHL', 'CNDHL', 'DHL-TH','WWDHLP','WWDHLU') ) ){
            foreach($volArr['volArr'] as $key=>$value){
                $_bb_volumne_weight+=$value['length'] * $value['width'] * $value['height']/ $shippingMethodArr['sm_vol_rate'];
            }
        }
        $businessArr = array(
            'ds_code'                   => 'so',
            'customer_code'             => $aOrder['customer_code'],
            'warehouse_id'              => $aOrder['warehouse_id'],
            'sm_code'                   => $aOrder['sm_code'],
            'bb_volume_weight'          => $_bb_volumne_weight,
            'bb_charge_weight'          => $aShipOrder['so_weight'],
            'bb_delivered_weight'       => $aShipOrder['so_weight'],
            'bb_pieces'                 => $aOrder['parcel_quantity'],
            'bb_declared_value'         => $aOrder['parcel_declared_value'],
            'bb_declared_currency_code' => 'USD',
            'country_code'              => $countryArr['country_code'],
            'bb_postcode'               => $aAddress['oab_postcode'],
            'bb_charge_time'            => $aOrder['add_time'],
            'bb_declared_time'          => $date, //发货时间 此时间与服务商对接
            'bb_sales_id'               => $customerArr['customer_saler_user_id'],
            'bb_refer_code'             => $aOrder['order_code'],
            'bb_service_number'         => $aOrder['ref_tracking_number'],//ref_tracking_number
            'bb_reference_no'           => $aOrder['reference_no'],
        );
        $bsObj          = new Process_Business();
        $paymentArr     = ('0' == $rpType) ? array() : $paymentArr;
        $businessResult = $bsObj->businessFee($businessArr, $incomeArr, $paymentArr);
        if($businessResult['state']!='1'){
            return $businessResult['message'];
        }

        //更新 费用及成本明细表
        //Service_FeeCostDetail::delete($order_code, 'code_number'); /* 清除同一订单号的杂费 */
        $feecostdetailResult = Service_FeeCostDetail::addMultiRows($fee_cost_detail);
        return true;
    }

    /**
     * 订单装袋的时候更新物流信息和状态
     * @author solar
     * @param string $so_code
     * @param number $weight
     * @param string $tracking_number
     * @return boolean
     */
    public function shipping($so_code, $weight, $tracking_number,$volweight,$volArr) {
    	$row['tracking_number'] = $tracking_number;
    	$row['so_weight'] = $weight;
    	$row['so_status'] = 1;
    	$row['so_update_time'] = date('Y-m-d H:i:s');
        $row['so_vol_weight'] = $volweight;
    	/*if(!empty($volArr)){
    		$length = $volArr['length'];
    		$width = $volArr['width'];
    		$height = $volArr['height'];
    		if($length>0 && $width>0 && $height>0){
    			$row['so_length'] = $length;
    			$row['so_width'] = $width;
    			$row['so_height'] = $height;
    			$row['so_vol_weight'] = $volweight;
    		}else{
    			throw new Exception('长、宽、高必须是大于0数字');
    		}
    	}*/
        $fee_weight = $weight;
        if($volweight>$fee_weight){
            $fee_weight = $volweight;
        }
        $row['so_fee_weight'] = $fee_weight;
    	$result = Service_ShipOrder::update($row, $so_code, 'so_code');
    	if(!$result) return '更新物流信息和状态失败';
        $shipOrder = Service_ShipOrder::getByField($so_code,"so_code","*");
        $smRow = Service_ShippingMethod::getByField($shipOrder['sm_code'],"sm_code","*");
        $order = Service_Orders::getByField($shipOrder['order_code'],"order_code","*");
        if($smRow['sm_is_volume']=="1"&&!in_array($smRow['sm_code'],array('HKDHL','CNDHL','BH-HKDHL','BH-3HPA','BH-3H','BH-UKECSLTYD','BH-UKECSLTRM','BH-CORREOS','BH-19EURDPDDE','BH-DAC','BH-SL018','BH-IESLTANPOST','DHL-TH','WWDHLP','WWDHLU'))){
            Service_ShipOrderDetail::delete($shipOrder['order_code'],'order_code'); //删除ship_order_detail数据
            $so_weight = 0;
            $so_volWeight = 0;
            $index = 1;
            //print_r($volArr);exit;
            if (!empty($volArr)) {
               foreach($volArr['volArr'] as $key=>$value){
                $so_weight +=$value['weight'];
                //获取order_product信息
                $orderProduct = Service_OrderProduct::getByField($value['op_id']);
                $product = array();
                if(!empty($orderProduct)){
                    $product = Service_Product::getByField($orderProduct['product_id']);
                }
                $op_subtotal = 0;
                if(!empty($product)){
                    $op_subtotal = $orderProduct['op_quantity']*$product['product_sales_value'];
                }
                $volWeight=($value['length']*$value['width']*$value['height'])/$smRow['sm_vol_rate'];
                //throw new Exception('volWeight='.$volWeight);
                if ($smRow['sm_code']=="HKUPS-KW" || $smRow['sm_code']=='BH-HKDHL') {
                   $shipOrderDetailRow = array(
                    'so_code'=>$so_code,
                    'so_id'=>$shipOrder['so_id'],
                    'order_id'=>$order['order_id'],
                    'order_code'=>$order['order_code'],
                    'sub_tracking_number'=>$shipOrder['tracking_number']."-".$index,
                    'op_id'=>$value['op_id'],
                    'op_title'=>!empty($product)?$product['product_title']:'',
                    'sod_length'=>$value['length'],
                    'sod_width'=>$value['width'],
                    'sod_height'=>$value['height'],
                    'sod_weight'=>$value['weight'],
                    'sod_vol_weight'=>$volWeight,
                    'sod_quantity'=>$orderProduct['op_quantity'],
                    'op_description'=>$value['op_description'],
                    'cn_description'=>!empty($product)?$product['product_title']:'',
                    'hs_code'=>!empty($product)?$product['hs_code']:'',
                    'op_unit_price'=>!empty($product)?$product['product_sales_value']:'',
                    'op_subtotal'=>$op_subtotal,
                    'op_origin'=>'',
                    'op_declared_value'=>!empty($product)?$product['product_declared_value']:'',
                    'is_scaned'=>1
                  );

                }else{
                $shipOrderDetailRow = array(
                    'so_code'=>$so_code,
                    'so_id'=>$shipOrder['so_id'],
                    'order_id'=>$order['order_id'],
                    'order_code'=>$order['order_code'],
                    'sub_tracking_number'=>$shipOrder['tracking_number']."-".$index,
                    'op_id'=>$value['op_id'],
                    'op_title'=>!empty($product)?$product['product_title']:'',
                    'sod_length'=>$value['length'],
                    'sod_width'=>$value['width'],
                    'sod_height'=>$value['height'],
                    'sod_weight'=>$volWeight,
                    'sod_vol_weight'=>$volWeight,
                    'sod_quantity'=>$orderProduct['op_quantity'],
                    'op_description'=>$value['op_description'],
                    'cn_description'=>!empty($product)?$product['product_title']:'',
                    'hs_code'=>!empty($product)?$product['hs_code']:'',
                    'op_unit_price'=>!empty($product)?$product['product_sales_value']:'',
                    'op_subtotal'=>$op_subtotal,
                    'op_origin'=>'',
                    'op_declared_value'=>!empty($product)?$product['product_declared_value']:'',
                    'is_scaned'=>1
                  );
                }
                Service_ShipOrderDetail::add($shipOrderDetailRow);
                $index++;
            }
            }
            
        }else{
            Service_ShipOrderDetail::update(array('is_scaned'=>1), $so_code, 'so_code');
        }
    	return array('so_code'=>$so_code);
    }
    
    /**
     * 扣库存(订单装袋)
     * @author solar
     * @param string $order_code
     * @return boolean
     */
    public function reduceStock($order_code) {
    	$aQuantity = $this->statQuantity($order_code);
    	if(!is_array($aQuantity)) return $aQuantity;
    	$warehouse_id = Service_User::getUserWarehouseId();
    	$piProccess = new Service_ProductInventoryProcess();

        $order = Service_Orders::getByField( $order_code, 'order_code');
        $owner = Service_CustomerProcess::getOwner($order['customer_code']);
        $gstype = 'ShippedOrder';
        if(strtoupper($order['sm_code'])=='ZCCQ'){
            $gstype = 'TemporaryShippedOrder';
        }
    	foreach($aQuantity as $product_id=>$quantity) {
    		if($quantity==0) return '库存异常，产品['.$product_id.']代扣数量为0';
            //环球客户才做此操作
            if( $owner ==  Service_CustomerProcess::$HuanQiu ){
                $product = Service_Product::getByField( $product_id, 'product_id' );
                $notify = array(
                    'product_id' => $product_id,
                    'product_sku' => $product['product_sku'],
                    'customer_code' => $order['customer_code'],
                    'reason' => '订单装袋',
                    'quantity' => $quantity,
                    'referecne_no' => $order_code,
                    'reftype' => 2,
                    'gstype' => $gstype,

                );
                Service_GsNotifyProcess::addNotify( $notify );
            }

    		$params = array(
    				'product_id' => $product_id,
    				'quantity' => $quantity,
    				'operationType' => 6,
    				'warehouse_id' => $warehouse_id,
    				'reference_code' => '', //操作单号
    				'application_code' => '', //操作类型
    				'note' => '订单出货',
					'reference_code'=>$order_code,
    		);
    		$result = $piProccess->update($params);
    		if($result['state']==0) return '更新库存失败';
    	}
    	return true;
    }
    
    /**
     * 统计核销库存并减去批次库存
     * @author solar
     * @param string $order_code
     * @return array|string
     */
    public function statQuantity($order_code) {
    	$aQuantity = array();
    	$pkList = Service_PickingDetail::getByCondition(array('order_code'=>$order_code), 'ibo_id');
    	$ibo_ids = array();
    	foreach($pkList as $pkRow) $ibo_ids[] = $pkRow['ibo_id'];
    	if(empty($ibo_ids)) return '找不到库存批次';
    	$ibo_ids = array_unique($ibo_ids);
    	$iboList = Service_InventoryBatchOutbound::listInIboids($ibo_ids);
    	foreach($iboList as $iboRow) {
    		$ibRow = Service_InventoryBatch::getForUpdate($iboRow['ib_id']);
    		$product_id = $ibRow['product_id'];
    		if(!isset($aQuantity[$product_id])) $aQuantity[$product_id] = 0;
    		$aQuantity[$ibRow['product_id']] += $iboRow['ibo_quantity'];
    		$iboRet = Service_InventoryBatchOutbound::delete($iboRow['ibo_id']);
    		$ibolRet = Service_InventoryBatchOutboundLog::log($iboRow, '订单出货');
    		if(!$iboRet || !$ibolRet) return '数据库异常，删除核销库存失败';
    		$ib_quantity = $ibRow['ib_quantity']-$iboRow['ibo_quantity'];
    		if($ib_quantity==0) {
    			$ibRet = Service_InventoryBatch::delete($ibRow['ib_id']);
    			$note = '订单出货删除批次';
    		} else {
    			$updateRow['ib_quantity'] = $ib_quantity;
    			$updateRow['ib_update_time'] = date('Y-m-d H:i:s');
    			$ibRet = Service_InventoryBatch::update($updateRow, $ibRow['ib_id']);
    			$note = '订单出货修改批次库存';
    		}
    		$iblRet = Service_InventoryBatchLog::log($ibRow, $ibRow['ib_quantity'], $ib_quantity, $note);
            if($ibRow['from_product_id']!=0){
                $fromProduct = Service_Product::getByField($ibRow['from_product_id'],"product_id","*");
            }else{
                $fromProduct = Service_Product::getByField($ibRow['product_id'],"product_id","*");
            }
            $exSwp = Service_SwapProduct::getByCondition(array('product_id'=>$ibRow['product_id'],'from_goods_id'=>$fromProduct['goods_id']),"*");
            if(!empty($exSwp)){
                $updateSwp = array(
                    'sp_quantity'=>$exSwp[0]['sp_quantity']-$iboRow['ibo_quantity'],
                );
                Service_SwapProduct::update($updateSwp,$exSwp[0]['sp_id'],"sp_id");
            }
    		if(!$iboRet || !$ibolRet) return '数据库异常，更新批次库存失败';
    	}
        $ibsoList = Service_InventoryBatchSerialOutbound::getByCondition(array('reference_no'=>$order_code),"*");
        if(!empty($ibsoList)){
            foreach($ibsoList as $ibso){
                $inventoryBatchSerial = Service_InventoryBatchSerial::getByField($ibso['ibs_id'],'ibs_id',"*");
                $ibsQuantiy = $inventoryBatchSerial['ibs_quantity'] - $ibso['ibso_quantity'];
                if($ibsQuantiy==0){
                    Service_InventoryBatchSerial::delete($ibso['ibs_id']);
                }else{
                    $ibsUpdateRow = array(
                        'ibs_quantity'=>$ibsQuantiy,
                    );
                    Service_InventoryBatchSerial::update($ibsUpdateRow,$ibso['ibs_id'],'ibs_id');
                }
                Service_InventoryBatchSerialOutbound::delete($ibso['ibso_id'],'ibso_id');
            }
        }

    	return $aQuantity;
    }
    
    /**
     * 创建包袋订单
     * @author solar
     * @param int $order_id
     * @param string $order_code
     * @param string $ob_no
     * @param string $so_code
     * @param number $weight
     * @return boolean
     */
    public function addBagDetail($order_id, $order_code, $ob_no, $so_code, $weight) {
    	$row['ob_no'] = $ob_no;
    	$row['order_id'] = $order_id;
    	$row['order_code'] = $order_code;
    	$row['so_code'] = $so_code;
    	$row['so_weight'] = $weight;
    	$row['creater_id'] = Service_User::getUserId();
    	$row['obd_add_time'] = date('Y-m-d H:i:s');
    	return Service_OutboundBagDetail::add($row);
    }
    
    /**
     * 完成装袋
     * @author solar
     * @param array $aOutboundBag
     * @param float $total_weight
     * @return string|boolean 成功返回true
     */
    public function finishBag($aOutboundBag, $total_weight,$sm_channel='0') {
    	$obdList = Service_OutboundBagDetail::getByCondition(array('ob_no'=>$aOutboundBag['ob_no']));
    	if(empty($obdList)) return '包袋中没有订单，无法完成装袋';
    	//事务
    	$db = Common_Common::getAdapter();
    	$db->beginTransaction();
    	try {
	    	$order_weight = 0;
	    	foreach($obdList as $obdRow) {
	    		$order_weight += $obdRow['so_weight'];
	    		//订单
	    		
	    		$aOrder = Service_Orders::getByField($obdRow['order_code'], 'order_code');
	    		if(intval($aOrder['order_status'])!==8) throw new Exception('状态异常：订单['.$obdRow['order_code'].']不是已装袋状态');
	    		$uOrder['update_time'] = date('Y-m-d H:i:s');
	    		$uOrder['order_status'] = 9;
	    		Service_Orders::update($uOrder, $obdRow['order_code'], 'order_code');
	    		Service_OrderLog::log($aOrder['order_id'], $aOrder['order_code'], 8, 9, 0, '完成装袋');
	    		//物流订单
	    		$aShipOrder = Service_ShipOrder::getByField($obdRow['so_code'], 'so_code');
	    		if(intval($aShipOrder['so_status'])!==1) throw new Exception('状态异常：物流订单['.$obdRow['so_status'].']不是已装袋状态');
                //记录当前sm_code
                $sm_code = $aShipOrder['sm_code'];

	    		$uOrderShip['so_update_time'] = date('Y-m-d H:i:s');
	    		$uOrderShip['so_status'] = 2;
	    		Service_ShipOrder::update($uOrderShip, $obdRow['so_code'], 'so_code');
	    		
	    		//记录装袋时间
                $uopt = array(
                    'finishbag_time'=>date("Y-m-d H:i:s"),
                    'finishbag_user_id'=>Service_User::getUserId(),
                );
                Service_OrderOperationTime::update($uopt,$aOrder['order_code'],"order_code");
	    		//$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');
	    	}
            if($sm_code == 'TWPG' || $sm_code == 'TWPP'){
                $app = Service_Application::getByField('OutboundBag','application_code');
                if($app){
                    $timestamp = strtotime($app['app_add_time']);
                    if(date('Ymd', $timestamp) != date('Ymd')) {
                        Service_Application::delete($app['application_id']);
                    }
                }
                $obNum = 'GBE'.date('ymd').Common_GetNumbers::getOnlyNumberCode('OutboundBag','','4');
                $updateRow['ob_num'] =  $obNum;
            }
            
	    	//$updateRow['ob_weight'] = $sm_channel=='1' ? $total_weight : $order_weight;
            $updateRow['ob_weight'] =  $order_weight;
	    	$updateRow['ob_status'] = 1;
	    	$updateRow['ob_update_time'] = date('Y-m-d H:i:s');
	    	Service_OutboundBag::update($updateRow, $aOutboundBag['ob_id']);
	    	//提交
	    	$db->commit();
    	} catch (Exception $e) {
    		$db->rollback();
    		return $e->getMessage();
    	}  	
    	return true;
    }

    /**
     * 完成装袋（用于订单整进整出，参照finishBag，稍作修改）
     */
    public function finishBagForOrderInOut($aOutboundBag, $total_weight) {
      $obdList = Service_OutboundBagDetail::getByCondition(array('ob_no' => $aOutboundBag['ob_no']));

      if (empty($obdList)) {
        throw new Exception('包袋【' . $aOutboundBag['ob_no'] . '】中没有订单，无法完成装袋');
      }

      foreach($obdList as $obdRow) {
        $aOrder = Service_Orders::getByField($obdRow['order_code'], 'order_code');

        if (empty($aOrder)) {
          throw new Exception('订单【' . $obdRow['order_code'] . '】不存在');
        }

        if (8 !== intval($aOrder['order_status'])) {
          throw new Exception('订单【' . $obdRow['order_code'] . '】不是已装袋状态');
        }

        // 订单状态更新、日志添加
        $uOrder['update_time']  = date('Y-m-d H:i:s');
        $uOrder['order_status'] = 9;
        Service_Orders::update($uOrder, $obdRow['order_code'], 'order_code');
        Service_OrderLog::log($aOrder['order_id'], $aOrder['order_code'], 8, 9, 0, '完成装袋');

        // 物流订单更新
        $aShipOrder = Service_ShipOrder::getByField($obdRow['so_code'], 'so_code');

        if (1 !== intval($aShipOrder['so_status'])) {
          throw new Exception('物流单【' . $obdRow['so_code'] . '】不是已装袋状态');
        }

        $uOrderShip['so_update_time'] = date('Y-m-d H:i:s');
        $uOrderShip['so_status']      = 2;
        Service_ShipOrder::update($uOrderShip, $obdRow['so_code'], 'so_code');

        // 记录装袋时间
        $uopt = array(
          'finishbag_time'    => date("Y-m-d H:i:s"),
          'finishbag_user_id' => Service_User::getUserId(),
        );
        Service_OrderOperationTime::update($uopt,$aOrder['order_code'], 'order_code');
      }

      $updateRow['ob_weight']      = $total_weight;
      $updateRow['ob_status']      = 1;
      $updateRow['ob_update_time'] = date('Y-m-d H:i:s');
      Service_OutboundBag::update($updateRow, $aOutboundBag['ob_id']);
    }
    /**
     * 取消加挂
     * @param string $ob_no
     */
    public function cancelMount($ob_no){
      //事务
      $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'] = 9;
          Service_Orders::update($uOrder, $obdRow['order_code'], 'order_code');
          Service_OrderLog::log($aOrder['order_id'], $aOrder['order_code'], 10, 9, 0, '取消加挂');
          //物流订单
          $uOrderShip['so_status'] = 2;
          $uOrderShip['so_update_time'] = date('Y-m-d H:i:s');
          Service_ShipOrder::update($uOrderShip, $obdRow['so_code'], 'so_code');
        //更新包袋状态
        $updateRow['ob_status'] = 1;
        $updateRow['ob_update_time'] = date('Y-m-d H:i:s');
        Service_OutboundBag::update($updateRow, $ob_no, 'ob_no');
        $shipOrderTracking=array(
          'order_code'=>$aOrder['order_code'],
          'status_desc'=>'已加挂'
          );
         $sot=Service_ShipOrderTracking::getByCondition($shipOrderTracking);
         Service_ShipOrderTracking::delete($sot[0]['sot_id']);
        $oonRow=array(
          'order_id'=>$obdRow['order_id'],
          'oot_code'=>'ship'
          );
          $updateOrderGoods = array(
              'sb_code'=>'',
          );
          Service_OrderGoods::update($updateOrderGoods,$obdRow['order_code'], 'order_code');
        $oon=Service_OrderOperationNode::getByCondition($oonRow);
        Service_OrderOperationNode::delete($oon[0]['oon_id']);
        Service_ShipBatchDetail::delete($ob_no,'ob_no');
          Service_ShipBatchGoods::delete($ob_no,'ob_no');

        }
    
        //提交
        $db->commit();
        }  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) {
                //判断HS_CODE
                /*$hscodeNum = Service_ShipBatchDetail::countHscodeNum($sb_code);
                $obhscodeNum=Service_OutboundBagDetail::countHscodeNum($ob_no);
                if($hscodeNum+$obhscodeNum>20) {
                    throw new Exception('此出货总单已有20个hs_code，请创建新的总单加挂');
                }*/
	    		//订单
	    		$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, '加挂');

                $w = Service_Warehouse::getByField($aOrder['warehouse_id'],'warehouse_id','*');
                if($aOrder['order_mode_type']=="1"){
                    $sotDescription = "集货订单出货车辆确认完毕";
                }else{
                    $sotDescription = "备货订单出货车辆确认完毕";
                }
                $shipOrderTracking = array(
                    'order_code'=>$aOrder['order_code'],
                    'sot_location'=>$w['warehouse_desc'],
                    'sot_add_time'=>date("Y-m-d H:i:s"),
                    'warehouse_id'=>$aOrder['warehouse_id'],
                    'sot_description'=>$sotDescription,
                    'sot_type'=>'0',
                    'sot_time_offset'=>'',
                    'tracking_number'=>$aOrder['order_code'],
                    'ref_tracking_number'=>'',
                    'status_desc'=>'已加挂',
                    'user_id'=>Service_User::getUserId(),
                );
                Service_ShipOrderTracking::add($shipOrderTracking);

	    		//物流订单
	    		$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['mount_time'] = date('Y-m-d H:i:s');
                $ootRow['mount_user_id'] = Service_User::getUserId();
                $ootRow['update_time'] = date('Y-m-d H:i:s');
                Service_OrderOperationTime::update($ootRow, $obdRow['order_id'], 'order_id');

	    		//记录时间
	    		/*$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');*/
                $orderGoods = Service_OrderGoods::getByCondition(array('order_code'=>$obdRow['order_code']),"*");
                if(!empty($orderGoods)){
                    foreach($orderGoods as $og){
                        $existSbg = Service_ShipBatchGoods::getByCondition(array('sb_code'=>$sb_code,'from_product_id'=>$og['from_product_id'],'order_code'=>$obdRow['order_code'],'ob_no'=>$ob_no,'hs_serial_no'=>$og['hs_serial_no'],'batch_goods_id'=>$og['batch_goods_id']),"*");
                        if(!empty($existSbg)){
                            $updateSbg = array(
                                'good_quantity'=>$existSbg[0]['good_quantity']+$og['good_quantity'],
                            );
                            Service_ShipBatchGoods::update($updateSbg,$existSbg[0]['sbg_id'],'sbg_id');
                        }else{
                            $addSbg = array(
                                'sb_code'=>$sb_code,
                                'product_id'=>$og['product_id'],
                                'goods_id'=>$og['goods_id'],
                                'good_quantity'=>$og['good_quantity'],
                                'from_product_id'=>$og['from_product_id'],
                                'order_code'=>$obdRow['order_code'],
                                'ob_no'=>$ob_no,
                                'hs_serial_no'=>$og['hs_serial_no'],
                                'batch_goods_id'=>$og['batch_goods_id'],
                            );
                            Service_ShipBatchGoods::add($addSbg);
                        }
                    }
                }else{
                    $orderProduct = Service_OrderProduct::getByCondition(array('order_code'=>$obdRow['order_code']),"*");
                    foreach($orderProduct as $op){
                        $existSbg = Service_ShipBatchGoods::getByCondition(array('sb_code'=>$sb_code,'from_product_id'=>$op['product_id'],'order_code'=>$obdRow['order_code'],'ob_no'=>$ob_no,),"*");
                        if(!empty($existSbg)){
                            $updateSbg = array(
                                'good_quantity'=>$existSbg[0]['good_quantity']+$op['op_quantity'],
                            );
                            Service_ShipBatchGoods::update($updateSbg,$existSbg[0]['sbg_id'],'sbg_id');
                        }else{
                            $p = Service_Product::getByField($op['product_id'],'product_id',"*");
                            $addSbg = array(
                                'sb_code'=>$sb_code,
                                'product_id'=>$op['product_id'],
                                'goods_id'=>$p['goods_id'],
                                'good_quantity'=>$op['op_quantity'],
                                'from_product_id'=>$op['product_id'],
                                'order_code'=>$obdRow['order_code'],
                                'ob_no'=>$ob_no,
                                'hs_serial_no'=>'',
                                'batch_goods_id'=>'',
                            );
                            Service_ShipBatchGoods::add($addSbg);
                        }
                    }
                }
	    	}
	    	//更新包袋状态
	    	$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;
    }

    /**
     * 加挂（用于订单整进整出，参照mount，稍作修改）
     */
    public function mountForOrderInOut($ob_no, $sb_code, $ob_weight) {
      $obdList = Service_OutboundBagDetail::getByCondition(array('ob_no' => (string)$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, '加挂');

        $w                 = Service_Warehouse::getByField($aOrder['warehouse_id'], 'warehouse_id');
        $shipOrderTracking = array(
          'order_code'          => $aOrder['order_code'],
          'sot_location'        => $w['warehouse_desc'],
          'sot_add_time'        => date("Y-m-d H:i:s"),
          'warehouse_id'        => $aOrder['warehouse_id'],
          'sot_description'     => '集货订单出货车辆确认完毕',
          'sot_type'            => '0',
          'sot_time_offset'     => '',
          'tracking_number'     => $aOrder['order_code'],
          'ref_tracking_number' => '',
          'status_desc'         => '已加挂',
          'user_id'             => Service_User::getUserId(),
        );
        Service_ShipOrderTracking::add($shipOrderTracking);

        // 物流订单
        $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['mount_time']    = date('Y-m-d H:i:s');
        $ootRow['mount_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);

      // 判断HS_CODE
      //$hscodeNum = Service_ShipBatchDetail::countHscodeNum($sb_code);

      /*if ($hscodeNum >= 20) {
        throw new Exception('此出货总单已有20个hs_code，请创建新的总单加挂');
      }*/
    }

    /**
     * 完成加挂
     * @author solar
     * @param string $sb_code
     * @return boolean|string
     */
    public function finishMount($sb_code, $pack_no) {
        $userAuth = new Zend_Session_Namespace('userAuthorization');
        $user_id = $userAuth->userId;
    	$aShipBatch = Service_ShipBatch::getByField($sb_code, 'sb_code');
        
        //账户冻结
        $package = Service_ShipBatchDetail::getByCondition(array('sb_code'=>$sb_code),"*");
        $obNoArr = array();
        foreach($package as $key=>$value){
            if(!in_array($value['ob_no'],$obNoArr))
                $obNoArr[] = $value['ob_no'];
        }
        foreach($obNoArr as $v){
            $outbound_bag_detail = Service_OutboundBagDetail::getByCondition(array('ob_no'=>$v), "*");
            foreach($outbound_bag_detail as $key=>$outbound_bag_detail_row){
                $orderRow = Service_Orders::getByField($outbound_bag_detail_row['order_code'], 'order_code', array('customer_code'));
                $customerData = Service_Customer::getByField($orderRow['customer_code'], 'customer_code', array('is_frozen', 'frozen_reason'));
                if($customerData['is_frozen'] == 1){
                    return '总单号['.$sb_code.']-订单号['.$outbound_bag_detail_row['order_code'].']-客户['.$orderRow['customer_code'].']已冻结，冻结原因：'.$customerData['frozen_reason'];
                }
            }
        }

    	if(intval($aShipBatch['sb_status'])!==0) return '出货总单不在草稿状态，无法完成加挂';
    	$count = Service_ShipBatchDetail::getByCondition(array('sb_code'=>$sb_code), 'count(*)');
    	if(!$count) return '出货总单还没有包袋，无法完成加挂';

        $shipBatchAttribute = Service_ShipBatchAttribute::getByField($sb_code,'sb_code');
        if(!($shipBatchAttribute['gross_wt']>0 && $shipBatchAttribute['net_wt']>0)){
            $gross_weight = Service_ShipBatchDetail::sumGrossWeight($sb_code);
            $net_weight = Service_ShipBatchDetail::sumNetWeight($sb_code);
            $shipBatchAttributeRow = array(
                'gross_wt'=>$gross_weight,
                'net_wt'=>$net_weight
            );
            Service_ShipBatchAttribute::update($shipBatchAttributeRow,$sb_code,'sb_code');
            if($net_weight > $gross_weight) {
                return "净重({$net_weight})大于毛重({$gross_weight})，无法完成加挂";
            }
            $law_weight = Service_ShipBatchDetail::sumLawWeight($sb_code);
            if($law_weight > $gross_weight) {
                return "法定单位重量({$law_weight})大于毛重({$gross_weight})，无法完成加挂";
            }
            if($law_weight > $net_weight) {
                return "法定单位重量({$law_weight})大于净重({$net_weight})，无法完成加挂";
            }
        }else{
            $gross_weight = $shipBatchAttribute['gross_wt'];
            $net_weight = $shipBatchAttribute['net_wt'];
            $law_weight = Service_ShipBatchDetail::sumLawWeight($sb_code);
            if($net_weight > $gross_weight) {
                return "净重({$net_weight})大于毛重({$gross_weight})，无法完成加挂";
            }
            if($law_weight > $gross_weight) {
                return "法定单位重量({$law_weight})大于毛重({$gross_weight})，无法完成加挂";
            }
            if($law_weight > $net_weight) {
                return "法定单位重量({$law_weight})大于净重({$net_weight})，无法完成加挂";
            }
        }

        if (!preg_match('/^[1-9][0-9]*$/', $pack_no)) {
          return '总件数必需是正整数';
        }

        $fileName = '520678_'.date("YmdHis")."_PPS.txt";
        //$fileName2 = '520678_'.date("YmdHis")."_PLT.txt";
        //$filePath = APPLICATION_PATH . '/../data/Efile2015/'.$fileName;
        //$filePath2 = APPLICATION_PATH . '/../data/Efile2015/'.$fileName2;
        /*if(!file_exists($filePath)){
            $fp= fopen($filePath,"w");
            fclose($fp);
        }*/
        /*if(!file_exists($filePath2)){
            $fp= fopen($filePath2,"w");
            fclose($fp);
        }*/
    	//事务
    	$db = Common_Common::getAdapter();
    	$db->beginTransaction();
    	try {
	        $ShipBatchDetail = Service_ShipBatchDetail::getByCondition(array('sb_code'=>$sb_code),"*");
	        $tag = 0;
            $tag2 = 0;
            $tag3 = 0;
            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);

                    //记录时间
                    $ootRow['shipment_time'] = date('Y-m-d H:i:s');
                    $ootRow['shipment_user_id'] = Service_User::getUserId();
                    $ootRow['update_time'] = date('Y-m-d H:i:s');
                    Service_OrderOperationTime::update($ootRow, $orderRow['order_id'], 'order_id');

                    //$orderRow = Service_Orders::getByField($v['order_code'],"order_code","*");
                    $w = Service_Warehouse::getByField($orderRow['warehouse_id'],'warehouse_id','*');
                    if($orderRow['order_mode_type']=="1"){
                        $sotDescription = "集货订单仓库出货";
                    }else{
                        $sotDescription = "备货订单仓库出货";
                        $tag3++;
                    }
                    $shipOrderTracking = array(
                        'order_code'=>$orderRow['order_code'],
                        'sot_location'=>$w['warehouse_desc'],
                        'sot_add_time'=>date("Y-m-d H:i:s"),
                        'warehouse_id'=>$orderRow['warehouse_id'],
                        'sot_description'=>$sotDescription,
                        'sot_type'=>'0',
                        'sot_time_offset'=>'',
                        'tracking_number'=>$orderRow['order_code'],
                        'ref_tracking_number'=>'',
                        'status_desc'=>'物流完成',
                        'user_id'=>Service_User::getUserId(),
                    );
                    Service_ShipOrderTracking::add($shipOrderTracking);
                    if($shipBatchAttribute['trade_mode']=="1210"&&$shipBatchAttribute['form_type']!="E2F"){
                        $shipOrder = Service_ShipOrder::getByField($orderRow['order_code'],"order_code","*");
                        Service_EportLogisticsXml::insert(array(
                            'order_code'         => $orderRow['order_code'],
                            'tracking_number'    => $shipOrder['tracking_number'],
                            'sm_code'            => $orderRow['sm_code'],
                            'warehouse_id'       => $orderRow['warehouse_id'],
                            'order_mode'         => '0',
                            'customer_code'      => $orderRow['customer_code'],
                            'created_time'       => date("Y-m-d H:i:s"),
                            'signed_time'        => date("Y-m-d H:i:s"),
                            'updated_time'       => date("Y-m-d H:i:s"),
                            'xml_type'           => 0,
                            'xml_status'         => 0,
                        ));
                        Service_EportLogisticsXml::insert(array(
                            'order_code'         => $orderRow['order_code'],
                            'tracking_number'    => $shipOrder['tracking_number'],
                            'sm_code'            => $orderRow['sm_code'],
                            'warehouse_id'       => $orderRow['warehouse_id'],
                            'order_mode'         => '0',
                            'customer_code'      => $orderRow['customer_code'],
                            'created_time'       => date("Y-m-d H:i:s"),
                            'signed_time'        => date("Y-m-d H:i:s"),
                            'updated_time'       => date("Y-m-d H:i:s"),
                            'xml_type'           => 2,
                            'xml_status'         => 0,
                        ));
                        Service_EportLogisticsXml::insert(array(
                            'order_code'         => $orderRow['order_code'],
                            'tracking_number'    => $shipOrder['tracking_number'],
                            'sm_code'            => $orderRow['sm_code'],
                            'warehouse_id'       => $orderRow['warehouse_id'],
                            'order_mode'         => '0',
                            'customer_code'      => $orderRow['customer_code'],
                            'created_time'       => date("Y-m-d H:i:s"),
                            'signed_time'        => date("Y-m-d H:i:s"),
                            'updated_time'       => date("Y-m-d H:i:s"),
                            'xml_type'           => 3,
                            'xml_status'         => 0,
                        ));
                        $orderCustomerInfo = array(
                            'order_code'=>$orderRow['order_code'],
                            'pay_no'=>str_replace("SOE","PAY",$orderRow['order_code']),
                            'logistics_no'=>$shipOrder['tracking_number'],
                            'qd_cop_no'=>str_replace("SO","DL",$orderRow['order_code']),
                            'zfd_cop_no'=>str_replace("SO","WA",$orderRow['order_code']),
                            'l_cop_no'=>str_replace("SOE","DPL",$orderRow['order_code']),
                        );
                        Service_OrderCustomInfo::add($orderCustomerInfo);
                        $row303 = array(
                            'order_code'=>$orderRow['order_code'],
                            'send_type'=>303,
                            'send_status'=>1,
                            'add_time'=>date("Y-m-d H:i:s"),
                        );
                        Service_OrderSendList::add($row303);
                    }
                    $existOG = Service_OrderGoods::getByCondition(array('order_code'=>$orderRow['order_code']),"count(*)");
                    if($existOG){
                        $orderGoodsRow = array(
                            'sb_code'=>$sb_code,
                        );
                        Service_OrderGoods::update($orderGoodsRow,$orderRow['order_code'],'order_code');
                    }else{
                        $orderProduct = Service_OrderProduct::getByCondition(array('order_code'=>$orderRow['order_code']),"*");
                        foreach($orderProduct as $opk=>$opv){
                            $product = Service_Product::getByField($opv['product_id'],"product_id","*");
                            $orderGoods = array(
                                'order_code'=>$orderRow['order_code'],
                                'product_id'=>$product['product_id'],
                                'goods_id'=>$product['goods_id'],
                                'good_quantity'=>$opv['op_quantity'],
                                'hs_code'=>$product['hs_code'],
                                'sb_code'=>$sb_code,
                                'from_product_id'=>$product['product_id'],
                                'hs_serial_no'=>'',
                                'batch_goods_id'=>'',
                            );
                            Service_OrderGoods::add($orderGoods);
                            $addSbg = array(
                                'sb_code'=>$sb_code,
                                'product_id'=>$product['product_id'],
                                'goods_id'=>$product['goods_id'],
                                'good_quantity'=>$opv['op_quantity'],
                                'from_product_id'=>$product['product_id'],
                                'order_code'=>$orderRow['order_code'],
                                'ob_no'=>$v['ob_no'],
                                'hs_serial_no'=>'',
                                'batch_goods_id'=>'',
                            );
                            Service_ShipBatchGoods::add($addSbg);
                        }
                    }

                    /* if($orderRow['sm_code']=="CJ-DGMG"){
                        $orderReceiptAddress = Service_OrderAddressBook::getByCondition(array("order_code"=>$orderRow['order_code'],'oab_type'=>'0'),"*");
                        $shipOrder = Service_ShipOrder::getByField($orderRow['order_code'],"order_code","*");
                        $country = Service_Country::getByField($orderReceiptAddress[0]['oab_country_id'],'country_id',"*");
                        $ParcelContent = "";
                        $orderProduct = Service_OrderProduct::getByCondition(array('order_code'=>$orderRow['order_code']),"*");
                        //$op_declared_value = 0;
                        $address1 = str_replace(PHP_EOL, '',$orderReceiptAddress[0]['oab_street_address1']);
                        $address2 = str_replace(PHP_EOL, '',$orderReceiptAddress[0]['oab_street_address2']);
                        $totalDeclareValue = 0;
                        foreach($orderProduct as $op){
                            $totalDeclareValue+=$op['op_purpose_declared_value']*$op['op_quantity'];
                        }
                        foreach($orderProduct as $opk=>$opv){
                            //$ParcelContent=" ".trim($opv['product_title_en']);
                            //$op_declared_value=$opv['op_purpose_declared_value']*$opv['op_quantity'];

                            $ParcelContent=trim($opv['product_title_en']);
                            //$op_declared_value=$opv['op_purpose_declared_value']*$opv['op_quantity'];
                            $product = Service_Product::getByField($opv['product_id'],"product_id","*");

                            $content = "520678|".$shipOrder['tracking_number']."|".$orderReceiptAddress[0]['oab_firstname']."|".$address1."|".$address2."||".$orderReceiptAddress[0]['oab_city']."|".$orderReceiptAddress[0]['oab_state']."|".$orderReceiptAddress[0]['oab_postcode']."|".$orderReceiptAddress[0]['oab_cell_phone']."|".$orderReceiptAddress[0]['oab_email']."|".$country['country_code']."|".$country['country_name_en']."|CN|".$ParcelContent."|".$totalDeclareValue."|".($shipOrder['so_weight']*1000)."||".$opv['op_quantity']."|".$product['product_sku']."|".$ParcelContent."|".$opv['op_purpose_declared_value']."|||||USD||||PPS|||DDU||||".$shipOrder['tracking_number']."||\n";
                            file_put_contents($filePath,$content,FILE_APPEND);
                        }
                        //$dmgProductCode = $orderRow['sm_code']=="CJ-DGMG"?'PPS':'PKD';
                        $tag++;
                    } *///add Notes by @Felix
                    /*if($orderRow['sm_code']=="CJ-DGMP"){
                        $orderReceiptAddress = Service_OrderAddressBook::getByCondition(array("order_code"=>$orderRow['order_code'],'oab_type'=>'0'),"*");
                        $shipOrder = Service_ShipOrder::getByField($orderRow['order_code'],"order_code","*");
                        $country = Service_Country::getByField($orderReceiptAddress[0]['oab_country_id'],'country_id',"*");
                        $ParcelContent = "";
                        $orderProduct = Service_OrderProduct::getByCondition(array('order_code'=>$orderRow['order_code']),"*");
                        $op_declared_value = 0;
                        foreach($orderProduct as $opk=>$opv){
                            $ParcelContent.=" ".trim($opv['product_title_en']);
                            $op_declared_value+=$opv['op_purpose_declared_value']*$opv['op_quantity'];
                        }
                        //$dmgProductCode = $orderRow['sm_code']=="CJ-DGMG"?'PPS':'PKD';
                        $address1 = str_replace(PHP_EOL, '',$orderReceiptAddress[0]['oab_street_address1']);
                        $address2 = str_replace(PHP_EOL, '',$orderReceiptAddress[0]['oab_street_address2']);
                        $content = "520678|".$shipOrder['tracking_number']."|".$orderReceiptAddress[0]['oab_firstname']."|".$address1."|".$address2."||".$orderReceiptAddress[0]['oab_city']."|".$orderReceiptAddress[0]['oab_state']."|".$orderReceiptAddress[0]['oab_postcode']."|".$orderReceiptAddress[0]['oab_cell_phone']."|".$orderReceiptAddress[0]['oab_email']."|".$country['country_code']."|".$country['country_name_en']."|CN|".$ParcelContent."|".$op_declared_value."|".$orderRow['grossWt']."||PKW|PKW|PKW|PKW|||||".$orderRow['currency_code']."||||PKW|||||||".$shipOrder['tracking_number']."||\n";
                        file_put_contents($filePath,$content,FILE_APPEND);
                        $tag++;
                    }*/
                    /*if($orderRow['sm_code']=="DHL-PDUK"){
                        $orderReceiptAddress = Service_OrderAddressBook::getByCondition(array("order_code"=>$orderRow['order_code'],'oab_type'=>'0'),"*");
                        $shipOrder = Service_ShipOrder::getByField($orderRow['order_code'],"order_code","*");
                        $country = Service_Country::getByField($orderReceiptAddress[0]['oab_country_id'],'country_id',"*");
                        $ParcelContent = "";
                        $orderProduct = Service_OrderProduct::getByCondition(array('order_code'=>$orderRow['order_code']),"*");
                        //$op_declared_value = 0;
                        $address1 = str_replace(PHP_EOL, '',$orderReceiptAddress[0]['oab_street_address1']);
                        $address2 = str_replace(PHP_EOL, '',$orderReceiptAddress[0]['oab_street_address2']);
                        $totalDeclareValue = 0;
                        foreach($orderProduct as $op){
                            $totalDeclareValue+=$op['op_purpose_declared_value']*$op['op_quantity'];
                        }
                        foreach($orderProduct as $opk=>$opv){
                            //$ParcelContent=" ".trim($opv['product_title_en']);
                            //$op_declared_value=$opv['op_purpose_declared_value']*$opv['op_quantity'];

                            $ParcelContent=trim($opv['product_title_en']);
                            //$op_declared_value=$opv['op_purpose_declared_value']*$opv['op_quantity'];
                            $product = Service_Product::getByField($opv['product_id'],"product_id","*");

                            $content = "520678|".$shipOrder['tracking_number']."|".$orderReceiptAddress[0]['oab_firstname']."|".$address1."|".$address2."||".$orderReceiptAddress[0]['oab_city']."|".$orderReceiptAddress[0]['oab_state']."|".$orderReceiptAddress[0]['oab_postcode']."|".$orderReceiptAddress[0]['oab_cell_phone']."|".$orderReceiptAddress[0]['oab_email']."|".$country['country_code']."|".$country['country_name_en']."|CN|".$ParcelContent."|".$totalDeclareValue."|".($shipOrder['so_weight']*1000)."||".$opv['op_quantity']."|".$product['product_sku']."|".$ParcelContent."|".$opv['op_purpose_declared_value']."|||||USD||||PLT|||||DDU||||\n";
                            file_put_contents($filePath2,$content,FILE_APPEND);
                        }
                        //$dmgProductCode = $orderRow['sm_code']=="CJ-DGMG"?'PPS':'PKD';
                        $tag2++;
                    }*/
	            }
	        }

            /* if($tag){
                $aMessage['fmt_code'] = 'CRG';
                $aMessage['fmt_type'] = 'EFILE';
                $aMessage['refercence_no'] = $sb_code;
                $aMessage['fml_add_time'] = date('Y-m-d H:i:s');
                $aMessage['fml_path'] = $fileName;
                $aMessage['fml_status'] = "0";
                Service_FtpMessageSendlist::add($aMessage);
            }else{
                @unlink($filePath);
            } *///add Notes by @Felix
            /*if($tag2){
                $aMessage['fmt_code'] = 'CRG';
                $aMessage['fmt_type'] = 'EFILE';
                $aMessage['refercence_no'] = $sb_code;
                $aMessage['fml_add_time'] = date('Y-m-d H:i:s');
                $aMessage['fml_path'] = $fileName2;
                $aMessage['fml_status'] = "0";
                Service_FtpMessageSendlist::add($aMessage);
            }else{
                @unlink($filePath2);
            }*/

            //添加海关产品信息查询队列
            if($tag3){
                $aMessage['fmt_code'] = 'PS';
                $aMessage['fmt_type'] = '';
                $aMessage['refercence_no'] = $sb_code;
                $aMessage['fml_add_time'] = date('Y-m-d H:i:s');
                $aMessage['fml_status'] = "0";
                $aMessage['fml_path'] = '';
                Service_FtpMessageSendlist::add($aMessage);
            }

			$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'] = $pack_no;
	    	$sbaUpdate['wrap_type'] = '2';//固定是纸箱
            $sbaRet = Service_ShipBatchAttribute::update($sbaUpdate, $sb_code, 'sb_code');
			$shipBatchAttribute = Service_ShipBatchAttribute::getByField($sb_code, 'sb_code');
			if(!empty($shipBatchAttribute) && '1210' == $shipBatchAttribute['trade_mode']){
				self::splitShipBatch50($sb_code);
			}else{
				self::splitShipBatch($sb_code);
			}
            
	    	//提交
	    	$db->commit();
    	} catch (Exception $e) {
    		$db->rollback();
    		//return '内部错误';
            return $e->getMessage();
    	}
    	return true;
    }
    
    /**
     * 检查订单重量和出货称重
     * @author solar
     * @param string $order_code
     * @param string $pp_barcode
     * @param number $weighing
     * @return boolean
     */
    public static function checkWeight($order_code, $pp_barcode, $weighing) {
    	$limit = 0.05;
    	$result = array('state'=>0, 'limit'=>$limit, 'order_weight'=>0, 'deffer'=>0);
    	$productsWeight = floatval(Service_Orders::calculateWeight($order_code));
    	$aPackage = Service_ProductPackage::getByField($pp_barcode ,'pp_barcode', 'pp_weight');
    	$orderWeight = $productsWeight + floatval($aPackage['pp_weight']);
    	$deffer = abs(floatval($weighing) - $orderWeight);
    	if($deffer > $limit) {
    		$result['order_weight'] = $orderWeight;
    		$result['deffer'] = $deffer;
    	} else $result['state'] = 1;
    	return $result;
    }

    /**
     * @desc 区外仓扣运费  目前两个地方使用此方法,区外仓收货、重新计费
     * @param $order_code
     * @param array $customer_id
     * @param int $weight
     * @param int $country
     * @param int $readjustment //是否为重新计费 1：重新计费
     * @return bool|string
     */
    public function shipLogisticsFee($order_code, $customer_id,$weight,$country, $readjustment=0,$otherPara=array()){
        $sDate          = date('Y-m-d H:i:s');
        $addTime=isset($otherPara['receiving_date'])?$otherPara['receiving_date']:$sDate;
    
        $customerRow    = Service_Customer::getByField($customer_id);
        $currencyRow    = Service_Currency::getByField($customerRow['customer_currency'], 'currency_code');

        $orderRow       = Service_LogisticsOrder::getByField($order_code, 'logistics_code');
        $addressRow     = Service_LogisticsOrderAddress::getByField($order_code, 'logistics_code');
        $orderHsRow     = Service_LogisticsOrderHs::getByField($order_code, 'logistics_code');
        $orderDetailRow = Service_ReceivingBatchOrder::getByField($order_code, 'logistics_code');

        //国家简码
        $countryArr     = Service_Country::getByField($addressRow['loa_country'],'country_id');
        //业务员
        $customerArr    = Service_Customer::getByField($orderRow['customer_code'],'customer_code',array('customer_saler_user_id','customer_currency'));
        //运输方式
        $shippingMethodArr = Service_ShippingMethod::getByField($orderRow['sm_code'],'sm_code',array('sm_vol_rate'));

        //应收
        $incomeArr      = array();
        //应付
        $paymentArr     = array();
        
        //写入业务表
        $businessArr    = array(
            'ds_code'                   => 'lo',
            'customer_code'             => $orderRow['customer_code'],
            'warehouse_id'              => $orderRow['warehouse_id'],
            'sm_code'                   => $orderRow['sm_code'],
            'bb_volume_weight'          => 0, //体积重以下重新计算
            'bb_charge_weight'          => $weight,
            'bb_delivered_weight'       => $weight,
            'bb_pieces'                 => $orderHsRow['loh_quantity'],
            'bb_declared_value'         => $orderHsRow['loh_total_price'],
            'bb_declared_currency_code' => 'USD',
            'country_code'              => $countryArr['country_code'],
            'bb_postcode'               => $addressRow['loa_zipcode'],
            'bb_charge_time'            => $orderRow['lo_create_time'],
            'bb_declared_time'          => $sDate, //发货时间 此时间与服务商对接
            'bb_sales_id'               => $customerArr['customer_saler_user_id'],
            'bb_refer_code'             => $orderRow['logistics_code'],
            'bb_service_number'         => $orderRow['ref_tracking_number'],//ref_tracking_number
            'bb_reference_no'           => $orderRow['reference_no'],
            'bb_add_time'   =>$addTime,
        );
        if($shippingMethodArr['sm_vol_rate'] > 0){
            $businessArr['bb_volume_weight'] = ($orderDetailRow['length'] * $orderDetailRow['width'] * $orderDetailRow['height']) / $shippingMethodArr['sm_vol_rate'];
        } else {
            $businessArr['bb_volume_weight'] = 0;
        }

        $spArr = array();
        if($country=="") $country = $addressRow['loa_country'];

        if(0 == $readjustment){
            //非重新计算运费的情况
            $objCalculate   = new Common_CalculateShipping();
            $keys = array(
                'warehouseId'   => $orderRow['warehouse_id'],
                'countryId'     => $addressRow['loa_country'],
                'smCode'        => $orderRow['sm_code'],
                'weight'        => $weight,
                'customerCode'  => $orderRow['customer_code'],
            );
        } else if(1 == $readjustment) {
            //重新计算运费的情况 被 Process_BusinessIncome 所调用
            $objCalculate   = new Common_ReCalculateShipping(); /* 重新计费的方法差异很大，另写新类 */
            $logisticsCostRow = Service_LogisticsCost::getByField($order_code, 'order_code', array('currency_code', 'currency_rate', 'smc_discount', 'price_batch_number', 'sm_baf', 'customer_currency_code', 'customer_currency_rate'));
            $costRecordingRow = Service_CostRecording::getByField($order_code, 'order_code', array('currency_code', 'currency_rate', 'price_batch_number','currency_batch_number', 'sm_baf', 'provider_currency_code', 'provider_currency_rate'));
              $currency_batch_number  = $costRecordingRow['currency_batch_number'];
            $currencyLogRows        = Service_CurrencyLog::getByBatchnumber($currency_batch_number);
            $keys = array(
                'warehouseId'               => $orderRow['warehouse_id'],
                'countryId'                 => $addressRow['loa_country'],
                'smCode'                    => $orderRow['sm_code'],
                'weight'                    => $weight,
                'customerCode'              => $orderRow['customer_code'],
                'price_currency_code'       => $logisticsCostRow['currency_code'],          //运输价格币种
                'price_currency_rate'       => $logisticsCostRow['currency_rate'],          //运输价格币种汇率
                'smc_discount'              => $logisticsCostRow['smc_discount'],           //客户运输折扣
                'customer_currency_code'    => $logisticsCostRow['customer_currency_code'], //客户币种
                'customer_currency_rate'    => $logisticsCostRow['customer_currency_rate'], //客户币种汇率
                'provider_currency_code'    => $costRecordingRow['provider_currency_code'], //服务商币种 - costRecording
                'provider_currency_rate'    => $costRecordingRow['provider_currency_rate'], //服务商币种汇率 - costRecording
                'sm_baf'                    => $costRecordingRow['sm_baf'],                 //燃油费率，只对 CRE起作用 - costRecording
                'price_batch_number'        => $costRecordingRow['price_batch_number'],     //运输价格编号 - costRecording 或 logisticsCost
            );
        } else {
            //暂不存在第三种情况
        }
        if($addressRow['loa_country']=='253'){
           //美国的要加入城市
            $conditionCity = array(
                'country_id'=>$addressRow['loa_country'],
                'city_name'=>$addressRow['loa_city']
            );
            $citys = Service_City::getByCondition($conditionCity,'*');
            if(!empty($citys)){
                $keys['cityId'] = $citys[0]['city_id'];
            }
        }
        if($addressRow['loa_country']=='106'){
           //香港的要加入城市
            $conditionCity = array(
                'country_id'=>$addressRow['loa_country'],
                'city_name'=>$addressRow['loa_city']
            );
            $citys = Service_City::getByCondition($conditionCity,'*');
            if(!empty($citys)){
                $keys['cityId'] = $citys[0]['city_id'];
            }
        }
        $objCalculate->setParams($keys);
        $aCalculate = $objCalculate->getRate();
        if($aCalculate['state'] == 0) {
            return is_array($aCalculate['error']) ? implode(',', $aCalculate['error']) : $aCalculate['error'];
        }
        $fee = $aCalculate['data']['cost']['totalCost'];

        //生成一条成本费用的记录
        $sm             = $aCalculate['data']['sm'];
        //服务商货币及汇率
        $providerRow            = Service_ServiceProvider::getByField($sm['sp_code'], 'sp_code', array('currency_code'));
        if(empty($providerRow)){
            throw new Exception('运输方式'.$sm['sm_code'].'服务商未设置！');
        }
        $providerCurrencyRow    = Service_Currency::getByField( $providerRow['currency_code'], 'currency_code', array('currency_code','currency_rate'));
        //成本货币及汇率
        $costCurrencyRow        = Service_Currency::getByField($aCalculate['data']['cost']['cost_currency_code'], 'currency_code', array('currency_code','currency_rate'));
        //成本费
        $costFee        = $aCalculate['data']['cost']['cost'];
        //单票成本
        $ticket_cbcost  = isset($aCalculate['data']['cost']['one_ticket_cbcost'])?$aCalculate['data']['cost']['one_ticket_cbcost']:0;
        //燃油附加费
        //$fuel_addons = $aCalculate['data']['cost']['cost']*$sm['sm_baf'];
        $fuel_addons    = $aCalculate['data']['cost']['cost_baf'];
        if($sm['sm_class_code']=="CRP"||$sm['sm_class_code']=="CPS"){
            $total = $aCalculate['data']['cost']['cost'] + $ticket_cbcost ;
            $fuel_addons = 0;
        }else{
            $total = $aCalculate['data']['cost']['cost']  + $fuel_addons;
        }
        $costRecording = array(
            'order_code'                => $order_code,
            'customer_code'             => $orderRow['customer_code'],
            'reference_no'              => $orderRow['reference_no'],
            'tracking_number'           => $orderRow['ref_tracking_number'],
            'sm_code'                   => $orderRow['sm_code'],
            'country_id'                => $country,
            'weight'                    => $weight,
            'cost_fee'                  => $costFee,
            'ticket_fare'               => $ticket_cbcost,
            'fuel_addons'               => $fuel_addons,
            'total_fee'                 => $total,
            'price_batch_number'        => $aCalculate['data']['cost']['price_batch_number'],   //价格编号,用于重算
            'sm_baf'                    => $aCalculate['data']['sm']['sm_baf'],                 //燃油附加费率,用于重算
            'currency_code'             => $costCurrencyRow['currency_code'],       //成本币种
            'currency_rate'             => $costCurrencyRow['currency_rate'],       //成本币种汇率
            'provider_currency_code'    => $providerCurrencyRow['currency_code'],   //服务商币种
            'provider_currency_rate'    => $providerCurrencyRow['currency_rate'],   //服务商币种汇率
            'add_time'                  => $addTime,
            'update_time'               => $sDate,
        );
        //重新计费的情况
        $cRow = Service_CostRecording::getByField($order_code, 'order_code');
        if (empty($cRow)) {
            unset($costRecording['update_time']);
            Service_CostRecording::add($costRecording);
        } else {
            unset($costRecording['currency_code']);
            unset($costRecording['price_batch_number']);
            unset($costRecording['sm_baf']);
            unset($costRecording['currency_rate']);
            unset($costRecording['provider_currency_code']);
            unset($costRecording['provider_currency_rate']);
            unset($costRecording['add_time']);
            Service_CostRecording::update($costRecording, $cRow['cr_id'], 'cr_id');
        }
        
        //区外仓理论上不存在自有运输方式，都将进入这个非自有逻辑判断
        if('0' == $aCalculate['data']['sm']['sm_channel']){
            /**
            * 1、应付
            */
            //运费（未包括其它费用项）
            if ($costFee > 0) {
                if (!isset($spArr[$sm['sp_code']])) {
                    $spRow = Service_ServiceProvider::getByField($sm['sp_code'], 'sp_code');
                    $spArr[$sm['sp_code']] = $spRow['currency_code'];
                }
                $convert_fee = Service_Currency::converByCode($aCalculate['data']['cost']['cost_currency_code'], $spArr[$sm['sp_code']], $costFee);
                $paymentArr[] = array(
                    'sp_code'               => $sm['sp_code'], //服务商代码
                    'ft_code'               => 'shipping',
                    'ut_code'               => 'KG',
                    'sm_code'               => $orderRow['sm_code'],
                    'bp_amount'             => $convert_fee,
                    'bp_org_amount'         => $costFee, //原金额
                    'currency_code'         => $aCalculate['data']['cost']['cost_currency_code'],
                    'currency_rate'         => $aCalculate['data']['cost']['currency_rate'],
                    'bp_chargeable_time'    => $sDate,
                      'bp_add_time'             =>$addTime,
                    'bp_verify_time'          =>$addTime,
                );
            }

            //单票
            if($ticket_cbcost > 0){
                if (!isset($spArr[$sm['sp_code']])) {
                    $spRow = Service_ServiceProvider::getByField($sm['sp_code'], 'sp_code');
                    $spArr[$sm['sp_code']] = $spRow['currency_code'];
                }
                $convert_fee = Service_Currency::converByCode($aCalculate['data']['cost']['cost_currency_code'], $spArr[$sm['sp_code']], $ticket_cbcost);
                $paymentArr[]=array(
                    'sp_code'               => $sm['sp_code'],//服务商代码
                    'ft_code'               => 'one_ticket_fee',
                    'ut_code'               => 'PCE',
                    'sm_code'               => $orderRow['sm_code'],
                    'bp_amount'             => $convert_fee,
                    'bp_org_amount'         => $ticket_cbcost, //原金额
                    'currency_code'         => $aCalculate['data']['cost']['cost_currency_code'],
                    'currency_rate'         => $aCalculate['data']['cost']['currency_rate'],
                    'bp_chargeable_time'    => $sDate,
                      'bp_add_time'             =>$addTime,
                              'bp_verify_time'          =>$addTime,
                );
            }

            //燃油附加费用
            if($fuel_addons>0){
                if (!isset($spArr[$sm['sp_code']])) {
                    $spRow = Service_ServiceProvider::getByField($sm['sp_code'], 'sp_code');
                    $spArr[$sm['sp_code']] = $spRow['currency_code'];
                }
                $convert_fee = Service_Currency::converByCode($aCalculate['data']['cost']['cost_currency_code'], $spArr[$sm['sp_code']], $fuel_addons);
                $paymentArr[]=array(
                    'sp_code'               => $sm['sp_code'],//服务商代码
                    'ft_code'               => 'additional_fee',
                    'ut_code'               => 'PCE',
                    'sm_code'               => $orderRow['sm_code'],
                    'bp_amount'             => $convert_fee,
                    'bp_org_amount'         => $fuel_addons,//原金额
                    'currency_code'         => $aCalculate['data']['cost']['cost_currency_code'],
                    'currency_rate'         => $aCalculate['data']['cost']['currency_rate'],
                    'bp_chargeable_time'    => $sDate,
                      'bp_add_time'             =>$addTime,
                              'bp_verify_time'          =>$addTime,
                );
            }
            /**
             * End 应付
             */
             
            //生成一条运费记录
            //运费
            $transport_fee = $aCalculate['data']['cost']['baseCost']+$aCalculate['data']['cost']['addCost']+$aCalculate['data']['cost']['pCost'];
            if($sm['sm_class_code']=="CRP"){
                $transport_fee = $transport_fee + $aCalculate['data']['cost']['regCost'];
            }
            $fuel_addons = $aCalculate['data']['cost']['baseBaf'];
            if($sm['sm_class_code']=="CRP"||$sm['sm_class_code']=="CPS"){
                $fuel_addons = 0;
            }
            //单票费用
            $ticket_fare    = isset($aCalculate['data']['cost']['baseTicketFee'])?$aCalculate['data']['cost']['baseTicketFee']:0;
            if($sm['sm_class_code']=="CRP"||$sm['sm_class_code']=="CPS"){
                $totalFee   = $transport_fee + $ticket_fare + $fuel_addons;
            }else{
                $totalFee   = $transport_fee + $fuel_addons;
            }
            $logisticsCost = array(
                'order_code'                => $order_code,
                'customer_code'             => $orderRow['customer_code'],
                'reference_no'              => $orderRow['reference_no'],
                'tracking_number'           => $orderRow['ref_tracking_number'],
                'sm_code'                   => $orderRow['sm_code'],
                'country_id'                => $country,
                'weight'                    => $weight,
                'transport_fee'             => $transport_fee,
                'ticket_fare'               => $ticket_fare,
                'fuel_addons'               => $fuel_addons,
                'total_fee'                 => $totalFee,
                'currency_code'             => $aCalculate['data']['cost']['currency_code'],    //运输（费用）销售币种
                'currency_rate'             => $aCalculate['data']['cost']['currency_rate'],    //运输（费用）销售币种汇率
                'smc_discount'              => $aCalculate['data']['sm']['customer_discount'],        //客户运输方式折扣
                'price_batch_number'        => $aCalculate['data']['cost']['price_batch_number'], //价格编号,用于重算
                'sm_baf'                    => $aCalculate['data']['sm']['sm_baf'],             //燃油附加费率,用于重算
                'customer_currency_code'    => $currencyRow['currency_code'],           //客户币种
                'customer_currency_rate'    => $currencyRow['currency_rate'],           //客户币种汇率
                'add_time'                  => $addTime,
                'update_time'               => $sDate,
            );
            //无则新增，已存在则更新
            $lRow=Service_LogisticsCost::getByField($order_code,'order_code');
            if(empty($lRow)){
                unset($logisticsCost['update_time']);
                Service_LogisticsCost::add($logisticsCost);
            }else{
                unset($logisticsCost['currency_code']);
                unset($logisticsCost['currency_rate']);
                unset($logisticsCost['smc_discount']);
                unset($logisticsCost['price_batch_number']);
                unset($logisticsCost['sm_baf']);
                unset($logisticsCost['customer_currency_code']);
                unset($logisticsCost['customer_currency_rate']);
                unset($logisticsCost['add_time']);
                Service_LogisticsCost::update($logisticsCost,$lRow['lc_id'],'lc_id');
            }

            $feeArr = array(
                'currency_code' => $aCalculate['data']['cost']['currency_code'],
                'price'         => $fee,
            );
            if(1 == $readjustment){
                //重新计费的情况下，转换的金额也应该是根据原始汇率运算的结果
                $feeArr['convert_fee'] = sprintf('%.2f', $fee * $logisticsCostRow['currency_rate'] / $logisticsCostRow['customer_currency_rate']);
            }
            //扣运费
            $result = Service_CustomerBalanceProcess::deductFee($customer_id, $feeArr, '区外仓订单收货，扣运费', $order_code,'','',array('add_time'=>$addTime));
            if($result['ask'] == 0) return $result['error'];
            //hkdhl计算偏远费
            if( in_array( $orderRow['sm_code'], array( 'HKDHL', 'CNDHL', 'DHL-TH','WWDHLP','WWDHLU') ) ){
                
                $objOtherCalculte = new Service_CalculateLogisticOtherFee();
                $param = array(
                    'logistics_code' => $orderRow['logistics_code'],
                );
                $objOtherCalculte->setParams($param);
                $otherfeeArr = $objOtherCalculte->getOtherFee();
                $currencyCacheRows = Common_DataCache::getCurrency();
                $_otherfee_mix_arr = Process_BillConfig::getOtherFeeArr();
                $logisticShipOrder=  Service_OutsideShipOrder::getByField($orderRow['logistics_code'], 'logistics_code');
                foreach ($otherfeeArr['data']['otherFee'] as $otherfee_name => $otherFee) {
                    if (empty($otherFee['cost_currency_code'])) {
                        $otherFee['cost_currency_code'] = $otherFee['currency_code'];
                    }
                     if($otherFee&&$otherFee['price']>0){
                           if(1 == $readjustment){
                            if(empty($currencyLogRows)){
                                //若为空的情况下
                                $currencyLogRows = $currencyCacheRows;
                            }
                          //重新计费的情况下，转换的金额也应该是根据原始汇率运算的结果
                              $otherFee['convert_fee']   = Service_CurrencyLog::converByCode($otherFee['currency_code'],$customerArr['customer_currency'],$otherFee['price'],$currency_batch_number);
                              $convert_fee                    = $otherFee['convert_fee'];
                              $otherfee_rate                  = $currencyLogRows[$otherFee['currency_code']]['currency_rate'];
                          } else {
                              $convert_fee                    = Service_Currency::converByCode($otherFee['currency_code'], $customerArr['customer_currency'], $otherFee['price']);
                              $otherfee_rate                  = $currencyCacheRows[$otherFee['currency_code']]['currency_rate'];
                          }


                        $result = Service_CustomerBalanceProcess::deductFee($orderRow['customer_id'], $otherFee, $_cbl_note . '，' . $_otherfee_mix_arr[$otherfee_name]['binote'], $order_code, $_otherfee_mix_arr['pianyuan']['ftcode'], $otherFee['fee_id'], array('add_time' => $addTime));
                        if (0 == $result['ask'])
                            return $result['error'];

                        //应收记录
                        $incomeArr[] = array(
                            'customer_code' => $orderRow['customer_code'],
                            'ft_code' => $_otherfee_mix_arr['pianyuan']['ftcode'],
                            'ut_code' => $_otherfee_mix_arr['pianyuan']['utcode'],
                              'sm_code'               => $orderRow['sm_code'],
                              'bi_amount'             => $convert_fee,
                              'bi_org_amount'         => $otherFee['price'],
                              'currency_code'         => $otherFee['currency_code'],
                              'currency_rate'         => $otherfee_rate,
                              'bi_chargeable_time'    => $addTime,
                              'bi_note'               => $_otherfee_mix_arr['pianyuan']['binote'],
                              'bi_add_time'             =>$addTime,
                              'bi_verify_time'          =>$addTime,
                          );
                        $fee_detail = array(
                            'fee_amount_customer' => $convert_fee, //费用金额（客户）
                            'fee_currency_code_customer' => $customerArr['customer_currency'], //费用币种（客户）
                            'discount_customer' => $otherFee['discount'], //折扣率（客户）（1=100%）
                        );
                    }
                    if (isset($otherFee['cost']) && $otherFee['cost'] > 0 && $otherFee['sp_code'] != '') {
                        if (!isset($spArr[$otherFee['sp_code']])) {
                            $spRow = Service_ServiceProvider::getByField($otherFee['sp_code'], 'sp_code');
                            $spArr[$otherFee['sp_code']] = $spRow['currency_code'];
                        }
                        if (1 == $readjustment) {
                            $convert_fee = Service_CurrencyLog::converByCode($otherFee['cost_currency_code'], $spArr[$otherFee['sp_code']], $otherFee['cost'], $currency_batch_number);
                            $otherfee_rate = $currencyLogRows[$otherFee['cost_currency_code']]['currency_rate'];
                        } else {
                            $convert_fee = Service_Currency::converByCode($otherFee['cost_currency_code'], $spArr[$otherFee['sp_code']], $otherFee['cost']);
                            $otherfee_rate = $currencyCacheRows[$otherFee['cost_currency_code']]['currency_rate'];
                        }
                        //应付记录
                        $paymentArr[] = array(
                            'sp_code' => $otherFee['sp_code'], //服务商代码
                            'ft_code' => $_otherfee_mix_arr[$otherfee_name]['ftcode'],
                            'ut_code' => $_otherfee_mix_arr[$otherfee_name]['utcode'],
                            'sm_code' => $orderRow['sm_code'],
                            'bp_amount' => $otherFee['cost'], //服务商结算金额
                            'bp_org_amount' => $otherFee['cost'], //原金额
                            'currency_code' => $otherFee['cost_currency_code'], //原币种
                            'currency_rate' => $otherfee_rate,
                            'bp_chargeable_time' => $addTime,
                            'bp_note' => $_otherfee_mix_arr[$otherfee_name]['binote'],
                        );
                        $cost_detail = array(
                            'cost_amount_org' => $otherFee['cost'], //成本金额（原始）
                            'cost_currency_code_org' => $otherFee['cost_currency_code'], //成本币种（原始）
                            'cost_amount_sp' => $otherFee['cost'], //成本金额（服务商）
                            'cost_currency_code_sp' => $otherFee['cost_currency_code'], //成本币种（服务商）
                            'sp_code' => $otherFee['sp_code'], //服务商代码
                        );
                    }
                     if (!empty($fee_detail) || !empty($cost_detail)) {
                        $fee_cost_common = array(
                            'code_number' => $order_code, //单号
                            'code_type' => 2, //单号类型（1:区内单 2：区外单 3：ASN单）
                            'customer_code' => $orderRow['customer_code'], //客户代码
                            'reference_no' => $orderRow['reference_no'], //客户参考号
                            'tracking_number' => $logisticShipOrder['tracking_number'], //服务商单号（跟踪号）
                            'sm_code' => $orderRow['sm_code'], //运输方式代码
                            'country_code' => $countryArr['country_code'], //国际简称（二字码）
                            'fee_code' => $_otherfee_mix_arr[$otherfee_name]['ftcode'], //费用编号
                            'fee_name' => $_otherfee_mix_arr[$otherfee_name]['binote'], //费用名称
                            'fee_amount_org' => $otherFee['price'], //费用金额（原始）
                            'fee_currency_code_org' => $otherFee['currency_code'], //费用币种（原始）
                            'price_batch_number' => $aCalculate['data']['cost']['price_batch_number'], //运输价格编号
                            'currency_batch_number' => $currency_batch_number, //货币汇率编号
                            'fee_time' => $addTime, //扣费时间
                            'fee_time_recalculate' => $addTime, //重新扣费时间
                            'ip' => $remote_ip, //扣费操作IP
                            'ip_recalculate' => $remote_ip, //重新扣费操作IP
                            'operator' => $userAuth->user['user_name'], //扣费操作人
                            'operator_recalculate' => $userAuth->user['user_name'], //重新扣费操作人
                        );
                        $fee_cost_detail[] = array_merge($fee_detail, $cost_detail, $fee_cost_common);
                    }
                }
            }
           
            /**
             * 2、应收
             */
            //运费
            $convert_fee = Service_Currency::converByCode($aCalculate['data']['cost']['currency_code'], $customerArr['customer_currency'], $transport_fee);
            $incomeArr[] = array(
                'customer_code'         => $orderRow['customer_code'],
                'ft_code'               => 'shipping',
                'ut_code'               => 'KG',
                'sm_code'               => $orderRow['sm_code'],
                'bi_amount'             => $convert_fee,
                'bi_org_amount'         => $transport_fee,
                'currency_code'         => $aCalculate['data']['cost']['currency_code'],//原币种
                'currency_rate'         => $aCalculate['data']['cost']['currency_rate'],
                'bi_chargeable_time'    => $sDate,
                'bi_note'               => '运费',
                 'bi_add_time'             =>$addTime,
                'bi_verify_time'          =>$addTime,
            );
            //单票费用
            if($ticket_fare>0){
                $convert_fee = Service_Currency::converByCode($aCalculate['data']['cost']['currency_code'], $customerArr['customer_currency'], $ticket_fare);
                $incomeArr[] = array(
                    'customer_code'         => $orderRow['customer_code'],
                    'ft_code'               => 'one_ticket_fee',
                    'ut_code'               => 'KG',
                    'sm_code'               => $orderRow['sm_code'],
                    'bi_amount'             => $convert_fee,
                    'bi_org_amount'         => $ticket_fare,
                    'currency_code'         => $aCalculate['data']['cost']['currency_code'],//原币种
                    'currency_rate'         => $aCalculate['data']['cost']['currency_rate'],
                    'bi_chargeable_time'    => $sDate,
                    'bi_note'               => '单票费用',
                      'bi_add_time'             =>$addTime,
                     'bi_verify_time'          =>$addTime,
                );
            }
            //燃油附加费用
            if($fuel_addons>0){
                $convert_fee = Service_Currency::converByCode($aCalculate['data']['cost']['currency_code'], $customerArr['customer_currency'], $fuel_addons);
                $incomeArr[] = array(
                    'customer_code'         => $orderRow['customer_code'],
                    'ft_code'               => 'additional_fee',
                    'ut_code'               => 'KG',
                    'sm_code'               => $orderRow['sm_code'],
                    'bi_amount'             => $convert_fee,
                    'bi_org_amount'         => $fuel_addons,
                    'currency_code'         => $aCalculate['data']['cost']['currency_code'],//原币种
                    'currency_rate'         => $aCalculate['data']['cost']['currency_rate'],
                    'bi_chargeable_time'    => $sDate,
                    'bi_note'               => '燃油附加费用',
                    'bi_add_time'             =>$addTime,
                     'bi_verify_time'          =>$addTime,
                );
            }
            
            /**
             * End 应收
             */
             
             //业务数据
            $bsObj = new Process_Business();
            //判断是否需要处理应付
            //$paymentArr = $rpType == '0' ? array() : $paymentArr;
          
            $businessResult=$bsObj->businessFee($businessArr,$incomeArr,$paymentArr);
       
            if($businessResult['state']!='1'){
                return $businessResult['message'];
            }
             Service_FeeCostDetail::delete($order_code, 'code_number'); /* 清除同一订单号的杂费 */
             $feecostdetailResult = Service_FeeCostDetail::addMultiRows($fee_cost_detail);
        }

        return true;
    }
     public static function getXLSData($uploadFile,$field){        
        
        $path = APPLICATION_PATH.'/../data/upload/shiporder';
        if(!file_exists($path)){
            if(!mkdir($path,0700,true)){
                $result = array("ask"=>0,"message"=>"上传文件失败失败",'error'=>array('上传目录不存在创建文件目录失败'));
                return $result;
            }
        }
        $config = array();
        $config['upload_path']		= $path;
        $config['allowed_types']	= 'xls|xlsx|csv';
        $config['max_size']			= '10000';
        $config['encrypt_name']		= true;
        $upload	= new Common_UploadFile($config);
        $upload->set_upload_path($path);
        if (!$upload->do_upload($_FILES,$field) ){
            $result['ask'] = '0';
            $result['message'] = '上传文件失败';
            $result['error'] =  $upload->display_errors();
            return $result;
            exit;
        }

        $resultArray = $upload->data();
        $full_path = $resultArray['full_path'];
        if(empty($resultArray) || empty($full_path)){
            $result = array("ask"=>0,"message"=>"上传文件失败失败",'error'=>array('数据不存在'));
            return $result;
            exit;
        }
        switch($resultArray['file_ext']){
            case ".xls":
            case ".xlsx":
                $resultArray = Common_Upload::readEXCEL($full_path,true);
                break;
            case ".csv":
                $resultArray = Common_Upload::readCSV($full_path);
                break;
            default:
                $resultArray = array();
                break;
        }
        if(empty($resultArray) || !is_array($resultArray)){
            $result = array("ask"=>0,"message"=>"文件内容不符合格式或数据为空.",'error'=>array());
            //echo json_encode($result);
            //exit;
        }
        @unlink($full_path);
        return $resultArray;
    }
    /**
     * [getArea 获取收费分区]
     * @param  [type]  $sm_id        [description]
     * @param  [type]  $warehouseId  [description]
     * @param  [type]  $sm_calc_type [description]
     * @param  [type]  $sm_fee_type  [description]
     * @param  [type]  $countryId    [description]
     * @param  integer $provinceId   [description]
     * @param  integer $cityId       [description]
     * @return [type]                [description]
     */
    private function getArea($sm_id,$warehouseId,$sm_calc_type,$sm_fee_type,$countryId,$provinceId = 0,$cityId = 0){
        $areaArr[] = 0;
        $condition = array(
            'warehouse_id_arr' => array(0, $warehouseId),
            'country_id_arr' => array(0, $countryId),
            'province_id_arr' => array(0, $provinceId),
            'city_id_arr' => array(0, $cityId),
            'sm_id' => $sm_id
        );
        $condition['smcm_type'] = $sm_calc_type;
        $condition['smcm_calc_type'] = $sm_fee_type;
        $mapRows = Service_SmCountryMap::getByInCondition($condition, 'area', 0, 0, array('warehouse_id desc', 'country_id desc', 'province_id desc', 'city_id desc'));
        if (empty($mapRows)) {
            return $areaArr;
        }
        foreach ($mapRows as $val) {
            $areaArr[] = $val['area'];
        }
        return $areaArr;     
    }
    /**
     * [interval 区间重量]
     * @param  array  $areaArr      [description]
     * @param  [type] $sm_id        [description]
     * @param  [type] $warehouseId  [description]
     * @param  [type] $sp_fee_type  [description]
     * @param  [type] $sp_weight_gt [description]
     * @return [type]               [description]
     */
    private function interval($areaArr = array(),$sm_id,$warehouseId,$sp_fee_type,$sp_weight_gt){
        $condition = array(
              'sm_id' => $sm_id,
              'area_arr' => $areaArr,
              'warehouse_id_arr' => array(0, $warehouseId),
              'sp_fee_type' => $sm_fee_type,
              'sp_weight_gt' => $sp_weight_gt,
        );
        $spObj = new Table_ShipPrice();
        $smPriceRows = $spObj->getByInCondition($condition, '*', array('sp_weight', 'date_start desc', 'sp_id desc', 'warehouse_id desc', 'sp_price'));
        //获取有效报价，取第一条，其余的报价有效截止日期设置成当前日期
        if(is_array($smPriceRows) && !empty($smPriceRows)){
          foreach ($smPriceRows as $smKey=>$smVal){
            if($smKey == 0){
              //取第一条
              $smPriceRow = $smVal;
              break;
            }
          }
        }
        if (empty($smPriceRow)) {
            $this->_errorArray[] = '5'; //没有找到费用
            return $sp_weight_gt;
        }
        return $smPriceRow['sp_weight'];      
    }
    /**
     * [firstWeight 首续重]
     * @param  array  $areaArr      [description]
     * @param  [type] $sm_id        [description]
     * @param  [type] $warehouseId  [description]
     * @param  [type] $swp_fee_type [description]
     * @param  [type] $maxWeight    [description]
     * @return [type]               [description]
     */
    private function firstWeight($areaArr = array(),$sm_id,$warehouseId,$swp_fee_type,$maxWeight){
        $condition = array(
            'sm_id' => $sm_id,
            'area_arr' => $areaArr,
            'warehouse_id_arr' => array(0, $warehouseId),
            'swp_fee_type' => $swp_fee_type,
        );
        
        $spObj = new Table_ShipWeightPrice();
        $smPriceRows = $spObj->getByInCondition($condition, '*', array('date_start desc', 'swp_id desc','warehouse_id desc'));
        //$date_end = date('Y-m-d', strtotime("-1 days"));
        //获取有效报价，取第一条，其余的报价有效截止日期设置成当前日期
        if(is_array($smPriceRows) && !empty($smPriceRows)){
          foreach ($smPriceRows as $smKey=>$smVal){
            if($smKey == 0){
              //取第一条
              $smPriceRow = $smVal;
              break;
            }
          }
        }
        
        if (empty($smPriceRow)) {
            $this->_errorArray[] = '5'; //没有找到费用
            return $maxWeight;
        }

        $fee_weight = $maxWeight;
        $costNumber = ($maxWeight - $smPriceRow["swp_weight"]) / $smPriceRow["swp_exces_weight"];
        $fee_weight = $smPriceRow['swp_weight']+ceil($costNumber)*$smPriceRow["swp_exces_weight"];
        return $fee_weight;
    }

    public static function splitShipBatch($sb_code){
        $shipBatchAttribute = Service_ShipBatchAttribute::getByField($sb_code,'sb_code',"*");
        $hscodeArr = Service_ShipBatch::getSplit20($sb_code);
        $sphscodeArr = array_chunk($hscodeArr,20);
        $index = 65;
        $gross_weight = Service_ShipBatchDetail::sumGrossWeight($sb_code);
        //$net_weight = number_format(Service_ShipBatchDetail::sumNetWeight($sb_code),2,'.','');
        $totalSX = count($sphscodeArr);
        //$gtReduceNt = $gross_weight-$net_weight;
        //$gtSp = $gtReduceNt/$totalSX;
        //$packNoSp = floor($shipBatchAttribute['pack_no']/$totalSX);
        $totalNetWeight = 0;
        $kvCurrency = Service_Currency::getKeyVal();
        foreach($sphscodeArr as $key=>$codeArr){
            $subSbCode = $sb_code.chr($index);
            $shipBatchXml = array(
                'sb_code'=>$sb_code,
                'sub_sb_code'=>$subSbCode,
                'gross_wt'=>0,
                'net_wt'=>'0',
                'pack_no'=>'',
                'ship_batch_xml_status'=>'1',
                'sbx_add_time'=>date("Y-m-d H:i:s"),
                'sbx_update_time'=>date("Y-m-d H:i:s"),
                'total_price'=>'',
            );
            $sbxid = Service_ShipBatchXml::add($shipBatchXml);
            //$sbxid = 0;
            $no = 1;
            $allTotalPrice = 0;
            $ntw = 0;
            foreach($codeArr as $conditionArrStr){
                $conditionArr = explode("|",$conditionArrStr);
                $condition = array(
                    'sb_code'=>$sb_code,
                    'hs_code'=>$conditionArr[0],
                    'pu_code'=>$conditionArr[1],
                    'pu_code_law'=>$conditionArr[2],
                    'pu_code_second'=>$conditionArr[3],
                    'currency_code'=>$conditionArr[4],
                );
                $OrderProductList = Service_ShipBatch::getProductByCondition($condition);
                unset($OrderProductList['total']);
                foreach($OrderProductList as $op){
                    $hemList = Service_HsElementMap::getByCondition(array('product_id'=>$op['product_id']), 'hem_detail');;
                    $ntw+=$op['net_weight'];
                    $elements = array();
                    foreach($hemList as $hemRow) {
                        $hem_detail = trim($hemRow['hem_detail']);
                        if($hem_detail===""){
                            $elements[] = "";
                        }else{
                            $elements[] = $hem_detail ;
                        }
                        //$elements[] = $hem_detail ? $hem_detail : '';
                    }
                    $QTY = $op['hum_quantity_law'];
                    $total_price = sprintf("%.2f", $op['total_price']);
                    $allTotalPrice+=$total_price;
                    $DECL_PRICE = sprintf("%.4f", $total_price/$op['quantity']);
                    $hum_quantity_second =  $op['pu_code_second'] ? $op['hum_quantity_second'] : '';
                    $getTradeCountry = Service_ShipBatch::getTradeCountry($sb_code,$op['goods_id']);
                    /*$origin_country = "";
                    if(!empty($getTradeCountry)){
                        $origin_country = $getTradeCountry[0]['trade_country'];
                    }else{
                        $origin_country = "110";
                    }*/
                    $shipBatchXmlDetail = array(
                        'sbx_id'=>$sbxid,
                        'sb_code'=>$sb_code,
                        'sub_sb_code'=>$subSbCode,
                        'g_no'=>$no,
                        'goods_id'=>$op['goods_id'],
                        'merger_g_no'=>$no,
                        'merger_mode'=>'1',
                        'code_ts'=>$op['hs_code'],
                        'g_name_cn'=>$op['hs_goods_name'],
                        'g_model'=>implode('|',$elements),
                        'g_name_en'=>'',
                        'g_qty'=>$op['quantity'],
                        'g_unit'=>$op['pu_code'],
                        'decl_price'=>$DECL_PRICE,
                        'curr'=>$kvCurrency[$op['currency_code']],
                        'qty_1'=>$QTY,
                        'unit_1'=>$op['pu_code_law'],
                        'qty_2'=>$hum_quantity_second,
                        'unit_2'=>$op['pu_code_second'],
                        'origin_country'=>'110',
                        'decl_total'=>$total_price,
                    );
                    Service_ShipBatchXmlDetail::add($shipBatchXmlDetail);
                    $no++;
                }
            }
            /*$gwt = 0;
            $pn = 0;
            if($key==($totalSX-1)){
                $gwt = $ntw+($gtReduceNt-($gtSp*($totalSX-1)));
                if($packNoSp>=1){
                    $pn = $shipBatchAttribute['pack_no']-(($totalSX-1)*$packNoSp);
                }else{
                    $pn = 1;
                }
            }else{
                $gwt = $ntw+$gtSp;
                $pn = $packNoSp>1?$packNoSp:"1";
            }*/
            $totalNetWeight+=$ntw;
            $updateShipBatchXml = array(
                //'gross_wt'=>$gwt,
                'net_wt'=>$ntw<1?1:$ntw,
                //'pack_no'=>$pn,
                'total_price'=>$allTotalPrice,
            );
            Service_ShipBatchXml::update($updateShipBatchXml,$sbxid,'sbx_id');
            if($shipBatchAttribute['trade_mode']!="0110"){
                if ($shipBatchAttribute['form_type']=='E2F') {
                    $aMessage['fmt_code'] = 'ZCCQ';
                    $aMessage['fml_status'] = 1;
                }else{
                    $aMessage['fmt_code'] = 'MCK';
                    $aMessage['fml_status'] = 0;
                }
                $aMessage['fmt_type'] = 'BSG011';
                $aMessage['refercence_no'] = $subSbCode;
                $aMessage['fml_add_time'] = date('Y-m-d H:i:s');
                Service_FtpMessageSendlist::add($aMessage);
            }
            $index++;
        }
        $shipBatchXml = Service_ShipBatchXml::getByCondition(array('sb_code'=>$sb_code),"*");
        $divPackNo = $shipBatchAttribute['pack_no'];
        foreach($shipBatchXml as $kk=>$sbx){
            $gwt = round($sbx['net_wt']/$totalNetWeight*$gross_weight,2);
            $pack_no = round($sbx['net_wt']/$totalNetWeight*$shipBatchAttribute['pack_no'],2);
            if($gwt<=1) {
                $gwt = 1.1;
            }
            if($kk==count($shipBatchXml)-1){
                $pack_no=$divPackNo;
            }else{
                if($pack_no<=1){
                    $pack_no = 1;
                }else{
                    $pack_no = floor($pack_no);
                }
                $divPackNo=$divPackNo-$pack_no;
            }
            if($pack_no<=0) $pack_no=1;
            $updateSbx = array(
                'gross_wt'=>$gwt,
                //'net_wt'=>$ntw,
                'pack_no'=>$pack_no,
                //'total_price'=>$allTotalPrice,
            );
            Service_ShipBatchXml::update($updateSbx,$sbx['sbx_id'],'sbx_id');
        }
    }

    /* @todo:判断是否能装在同一个袋子里
     * @param string $obNo 袋子号
     * @param string $code 订单号或袋子号
     * @param string $type 根据何种类型来判断是否能装在同一个袋子，比如运输方式，客户
     * @param mixed  $allowValue 允许的值
     * @return boolean
     */
    public static function allowPutIntoBag( $obNo, $code, $type, $allowValue = '' ) {

        $flag = false;

        if( empty( $obNo ) || empty( $code ) || empty( $type ) )
            return $flag;

        switch( $type ) {
            case 'gsPlateFormAtBag':
                $order = Service_Orders::getByField( $code, 'order_code');
                if( $order ) {
                    $obRows = Service_OutboundBagDetail::getByCondition( array( 'ob_no' => $obNo ), '*', 1, 1 );
                    $orderInBag = empty( $obRows ) ? array() : Service_Orders::getByField( $obRows[0]['order_code'], 'order_code');
                    if( $orderInBag ) {
                        if( ( $order['platform'] == 2 && $orderInBag['platform'] == 2 ) || ( $order['platform'] != 2 && $orderInBag['platform'] != 2 ) ) {
                            $flag = true;
                        }
                    } else {
                        //袋子里还没有订单的情况
                        $flag = true;
                    }
                }
                break;
            case 'gsPlateFormAtMount':
                $obRows = Service_OutboundBagDetail::getByCondition( array( 'ob_no' => $obNo ), '*', 1, 1 );
                $shipBatchDetail = Service_ShipBatchDetail::getByCondition( array( 'sb_code' => $code ), '*', 1, 1 );
                if( $obRows && $shipBatchDetail ) {
                    $bagInShipBatch = Service_OutboundBagDetail::getByCondition( array( 'ob_no' => $shipBatchDetail[0]['ob_no'] ), '*', 1, 1 );

                    $orderInBag = Service_Orders::getByField( $obRows[0]['order_code'], 'order_code');
                    $orderInShipBatch = empty( $bagInShipBatch ) ? array() : Service_Orders::getByField( $bagInShipBatch[0]['order_code'], 'order_code');
                    if( $orderInShipBatch ) {
                        if( ( $orderInBag['platform'] == 2 && $orderInShipBatch['platform'] == 2 ) || ( $orderInBag['platform'] != 2 && $orderInShipBatch['platform'] != 2 ) ) {
                            $flag = true;
                        }
                    } else {
                        $flag = true;
                    }
                } else {
                    $flag = true;
                }

                break;
            default:
                $flag = true;
                break;
        }
        return $flag;
    }

    public function splitShipBatch50($sbCode){
        $db = Common_Common::getAdapter();
        $maxItem = 50;
        $sql = <<<SQL
SELECT b.order_code,d.goods_id
FROM ship_batch_detail AS a
INNER JOIN outbound_bag_detail AS b ON b.ob_no=a.ob_no
INNER JOIN order_product AS c ON c.order_code=b.order_code
INNER JOIN product AS d ON d.product_id=c.product_id
WHERE a.sb_code='{$sbCode}'
SQL;

        $resultSet = $db->fetchAll($sql);
        $mapSet = array();
        $splitSet = array();

        if (!empty($resultSet)) {
            foreach ($resultSet as $item) {
                $mapSet[$item['order_code']][$item['goods_id']] = 1;
            }
        }

        while (!empty($mapSet)) {
            $unionSet = array();
            $orderSet = array();

            foreach ($mapSet as $orderCode => $goodsSet) {
                if (count($goodsSet) > $maxItem) { // 避免死循环
                    throw new Exception('订单[' . $orderCode . ']料件超过' . $maxItem . '项');
                }

                $itemCount = count($unionSet);
                $itemEstimate = self::interpretUnionSet($unionSet, $goodsSet);

                if ($itemCount + $itemEstimate['for_plus_qty'] > $maxItem) {
                    continue ;
                }

                $unionSet = array_merge($unionSet, $goodsSet);
                $orderSet[] = $orderCode;
                unset($mapSet[$orderCode]);
            }

            $splitSet[] = $orderSet;
        }
        //var_dump($splitSet);
        $shipBatchAttribute = Service_ShipBatchAttribute::getByField($sbCode,'sb_code',"*");
        $gross_weight = Service_ShipBatchDetail::sumGrossWeight($sbCode);
        $totalNetWeight = 0;
        $index = 65;
        $kvCurrency = Service_Currency::getKeyVal();
        foreach($splitSet as $k=>$v){

            $subSbCode = $sbCode.chr($index);
            $shipBatchXml = array(
                'sb_code'=>$sbCode,
                'sub_sb_code'=>$subSbCode,
                'gross_wt'=>0,
                'net_wt'=>'0',
                'pack_no'=>'',
                'ship_batch_xml_status'=>'1',
                'sbx_add_time'=>date("Y-m-d H:i:s"),
                'sbx_update_time'=>date("Y-m-d H:i:s"),
                'total_price'=>'',
            );
            $sbxid = Service_ShipBatchXml::add($shipBatchXml);
            foreach($v as $order_code){
                $orderCustomInfo = Service_OrderCustomInfo::getByField($order_code,'order_code',"*");
                $updateRow = array(
                    'sub_sb_code'=>$subSbCode,
                );
                Service_OrderCustomInfo::update($updateRow,$orderCustomInfo['oci_id'],'oci_id');
            }
            $no = 1;
            $allTotalPrice = 0;
            $ntw = 0;

            $condition = array(
                'sb_code'=>$sbCode,
                'order_code_arr'=>$v,
            );
            //throw new Exception("getProductByCondition1");
            $OrderProductList = Service_ShipBatch::getProductByCondition($condition);
            //throw new Exception("getProductByCondition2");
            unset($OrderProductList['total']);
            foreach($OrderProductList as $op){
                $hemList = Service_HsElementMap::getByCondition(array('product_id'=>$op['product_id']), 'hem_detail');
                $product = Service_Product::getByField($op['product_id'],'product_id',"*");
                $ntw+=$op['net_weight'];
                $elements = array();
                foreach($hemList as $hemRow) {
                    $hem_detail = trim($hemRow['hem_detail']);
                    if($hem_detail===""){
                        $elements[] = "";
                    }else{
                        $elements[] = $hem_detail ;
                    }
                }
                $QTY = $op['hum_quantity_law'];
                $total_price = sprintf("%.2f", $op['total_price']);
                $allTotalPrice+=$total_price;
                $DECL_PRICE = sprintf("%.4f", $total_price/$op['quantity']);
                $hum_quantity_second =  $op['pu_code_second'] ? $op['hum_quantity_second'] : '';
                $shipBatchXmlDetail = array(
                    'sbx_id'=>$sbxid,
                    'sb_code'=>$sbCode,
                    'sub_sb_code'=>$subSbCode,
                    'g_no'=>$no,
                    'goods_id'=>$op['goods_id'],
                    'merger_g_no'=>$no,
                    'merger_mode'=>'1',
                    'code_ts'=>$op['hs_code'],
                    'g_name_cn'=>$op['hs_goods_name'],
                    'g_model'=>implode('|',$elements),
                    'g_name_en'=>'',
                    'g_qty'=>$op['quantity'],
                    'g_unit'=>$op['pu_code'],
                    'decl_price'=>$DECL_PRICE,
                    'curr'=>$kvCurrency[$op['currency_code']],
                    'qty_1'=>$QTY,
                    'unit_1'=>$op['pu_code_law'],
                    'qty_2'=>$hum_quantity_second,
                    'unit_2'=>$op['pu_code_second'],
                    'origin_country'=>'110',
                    'decl_total'=>$total_price,
                    'putrec_seqno'=>$product['putrec_seqno'],
                );
                Service_ShipBatchXmlDetail::add($shipBatchXmlDetail);
                $no++;
            }
            $totalNetWeight+=$ntw;
            $updateShipBatchXml = array(
                'net_wt'=>$ntw<1?1:$ntw,
                'total_price'=>$allTotalPrice,
            );
            Service_ShipBatchXml::update($updateShipBatchXml,$sbxid,'sbx_id');
            if($shipBatchAttribute['trade_mode']!="0110"){
                if ($shipBatchAttribute['form_type']=='E2F') {
                    $aMessage['fmt_code'] = 'ZCCQ';
                    $aMessage['fml_status'] = 1;
                }else{
                    $aMessage['fmt_code'] = 'MCK';
                    $aMessage['fml_status'] = 0;
                }
                $aMessage['fmt_type'] = 'BSG011';
                $aMessage['refercence_no'] = $subSbCode;
                $aMessage['fml_add_time'] = date('Y-m-d H:i:s');
                Service_FtpMessageSendlist::add($aMessage);
            }
            $index++;
        }
        $shipBatchXml = Service_ShipBatchXml::getByCondition(array('sb_code'=>$sbCode),"*");
        $divPackNo = $shipBatchAttribute['pack_no'];
        foreach($shipBatchXml as $kk=>$sbx){
            $gwt = round($sbx['net_wt']/$totalNetWeight*$gross_weight,2);
            $pack_no = round($sbx['net_wt']/$totalNetWeight*$shipBatchAttribute['pack_no'],2);
            if($gwt<=1) {
                $gwt = 1.1;
            }
            if($kk==count($shipBatchXml)-1){
                $pack_no=$divPackNo;
            }else{
                if($pack_no<=1){
                    $pack_no = 1;
                }else{
                    $pack_no = floor($pack_no);
                }
                $divPackNo=$divPackNo-$pack_no;
            }
            if($pack_no<=0) $pack_no=1;
            $updateSbx = array(
                'gross_wt'=>$gwt,
                'pack_no'=>$pack_no,
            );
            Service_ShipBatchXml::update($updateSbx,$sbx['sbx_id'],'sbx_id');
        }
    }

    static private function interpretUnionSet(&$unionSet, &$goodsSet)
    {
        $hasPlusQty = 0;
        $forPlusQty = 0;

        foreach ($goodsSet as $goodsId => $tag) {
            if (isset($unionSet[$goodsId])) {
                ++$hasPlusQty;
            } else {
                ++$forPlusQty;
            }
        }

        return array('has_plus_qty' => $hasPlusQty, 'for_plus_qty' => $forPlusQty);
    }
}