<?php
class Service_CustomerBalanceProcess
{
        public $customerId;
        private $_customerBalance;
        protected $_customerRow;
        protected $_orderRow;
        protected $_currencyRow;
        protected $_error = array();
        protected $_date;
        protected $_income = array();//收入
        protected $_payment = array();//支付
        protected $_serviceProvider = array();//服务商
        protected $_currencyRate = array();

        public function __construct($customerId='') {
            $this->_date = date('Y-m-d H:i:s');
            if($customerId){
                $this->setCustomerRow( $customerId );
                $this->setCustomerBalance();
            }
        }
        public function setCustomerRow( $customerId ){
            if( empty( $customerId ) ){
                throw new Exception('客户ID为空');
            }

            $this->_customerRow=Service_Customer::getByField( $customerId );

            if( empty( $this->_customerRow ) ) {
                throw new Exception('客户不存在');
            }
            $this->customerId = $customerId;
        }

        protected function setOrder( $orderCode ) {
            if( $orderCode === '' || is_null( $orderCode ) ) {
                throw new Exception('订单号不能为空');
            }

            $order = Service_Orders::getByField( $orderCode, 'order_code', "*", "for update"  );
            if( empty( $order ) ) {
                throw new Exception('订单不存在');
            }

            $addressRow = Service_OrderAddressBook::getByField( $orderCode, 'order_code');
            if( empty( $addressRow ) ) {
                throw new Exception('订单地址信息不存在');
            }
            $country = Common_DataCache::getCountry( false,$addressRow['oab_country_id'] );
            $addressRow['country_code'] = $country['country_code'];

            if( $addressRow['oab_country_id']=='253'){
                //美国的要加入城市
                $conditionCity = array(
                    'country_id' => $addressRow['oab_country_id'],
                    'city_name'  => $addressRow['oab_city']
                );

                $cities = Service_City::getByCondition( $conditionCity, '*' );
                if( !empty( $cities ) ){
                    $addressRow['oab_city_id'] = $cities[0]['city_id'];
                }
            }
            if( $addressRow['oab_country_id']=='106'){
                //香港的要加入城市
                $conditionCity = array(
                    'country_id' => $addressRow['oab_country_id'],
                    'city_name'  => $addressRow['oab_city']
                );

                $cities = Service_City::getByCondition( $conditionCity, '*' );
                if( !empty( $cities ) ){
                    $addressRow['oab_city_id'] = $cities[0]['city_id'];
                }
            }
            $weight = Service_Orders::calculateWeight( $orderCode );
            $this->_orderRow = $order;
            $this->_orderRow['address'] = $addressRow;
            $this->_orderRow['weight'] = $weight;
        }

        protected function setCurrency( $currencyCode ) {
            if( $currencyCode === '' || is_null( $currencyCode ) ) {
                throw new Exception('币种不能为空');
            }

            $currency = Service_Currency::getByField( $currencyCode, 'currency_code' );
            if( empty( $currency ) ) {
                throw new Exception('币种不存在');
            }
            $this->_currencyRow = $currency;
            $this->_currencyRate[ $currencyCode ] = $currency;
        }

        public function setCustomerBalance(){
           if(empty($this->customerId)){
                throw new Exception('客户ID为空');
            }
            $this->_customerBalance = Service_CustomerBalance::getByField( $this->customerId, 'customer_id',"*","for update" );
            if( empty( $this->_customerBalance ) ) {
                throw new Exception('客户账户信息异常');
            }
            $this->_customerBalance['old_cb_value'] = $this->_customerBalance['cb_value'];
        }
	/**
	 * 订单预扣费
	 * @author solar
	 * @param string $order_code
	 * @param int $customer_id
	 * @return true|string
	 */
    public function freezeFee($order_code, $customer_id) { 
    	$customerRow = Service_Customer::getByField($customer_id);
    	$currencyRow = Service_Currency::getByField($customerRow['customer_currency'], 'currency_code');
        $orderRow = Service_Orders::getByField($order_code, 'order_code');
    	//if($customerRow['cash_type']==2) return true;	//月结，不用冻结
        //集货转运类的订单在确认到提交时，无须冻结金额，在日本仓出货的时候也无须扣款，只在目的仓出货的时候发生扣款动作
        //if($orderRow['warehouse_id']=="1"&&$orderRow['order_mode_type']=="1") return true;
    	$addressRow = Service_OrderAddressBook::getByField($order_code, 'order_code');
    	$weight = Service_Orders::calculateWeight($order_code);
    	//$orderProducts = Service_OrderProduct::getByCondition();
    	//$orderProducts = Service_OrderProduct::getByField($order_code,'order_code');
    	$objCalculate = new Common_CalculateShipping();
    	$keys = array(
    		'warehouseId' => $orderRow['warehouse_id'],
    		'countryId' => $addressRow['oab_country_id'],
    		'smCode' => $orderRow['sm_code'],
    		'weight' => $weight,
    		'order_code'=>$order_code,
            'customerCode' => $orderRow['customer_code'],
            'postcode'=>$addressRow['oab_postcode'],
    	);
    	if($addressRow['oab_country_id']=='253'){
    	    //美国的要加入城市
    	    $citys = Service_City::getByCondition(array('country_id' => $addressRow['oab_country_id'],'city_name'=>$addressRow['oab_city'],'sm_code' => $orderRow['sm_code']));
    	    if(empty($citys)){
    	        $conditionCity = array(
    	            'country_id'=>$addressRow['oab_country_id'],
    	            'city_name'=>$addressRow['oab_city'],
    	            'sm_code' =>'0'
    	        );
    	        $citys = Service_City::getByCondition($conditionCity,'*');
    	    }
    	    if(!empty($citys)){
    	        $keys['cityId'] = $citys[0]['city_id'];
    	    }
    	}
    	if($addressRow['oab_country_id']=='106'){
    	    //香港的要加入城市
    	    $citys = Service_City::getByCondition(array('country_id' => $addressRow['oab_country_id'],'city_name'=>$addressRow['oab_city'],'sm_code' => $orderRow['sm_code']));
    	    if(empty($citys)){
    	        $conditionCity = array(
    	            'country_id'=>$addressRow['oab_country_id'],
    	            'city_name'=>$addressRow['oab_city'],
    	            'sm_code' =>'0'
    	        );
    	        $citys = Service_City::getByCondition($conditionCity,'*');
    	    }
    	    if(!empty($citys)){
    	        $keys['cityId'] = $citys[0]['city_id'];
    	    }
    	}
        if($orderRow['sm_code']=='DGF-CARGO'){
            //获取空运相关的信息
            $orderShiping = Service_OrderShipping::getByField($order_code,'order_code');
            $keys['aircode'] = $orderShiping['destination'];
        }
    	$objCalculate->setParams($keys);
    	$result = $objCalculate->getRate();
    	if($result['state'] == 0)
    		return is_array($result['error']) ? implode(',', $result['error']) : $result['error'];
        $doresert = true;
        if(isset($result['data']['cost']['sm_channel']) && ($result['data']['cost']['sm_channel']=='1')){
            //只有渠道
           $doresert = false;
        }
    	$fee = $result['data']['cost']['totalCost'];
    	//$convert_fee = round($fee / $currencyRow['currency_rate'], 2);
        $convert_fee=sprintf('%.2f',$fee / $currencyRow['currency_rate']);
    	//转成客户的币种
    	$convert_fee = Service_Currency::converByCode($result['data']['cost']['currency_code'], $customerRow['customer_currency'], $fee);

    	//冻结金额
    	//$balanceRow = Service_CustomerBalance::getByField($customer_id, 'customer_id');
        $balanceRow = Service_CustomerBalance::getByField($customer_id, 'customer_id',"*","for update");
        /* print_r($balanceRow);
        echo $convert_fee; */
    	//$able_fee = floatval($balanceRow['cb_value'] - $convert_fee);
        $able_fee = sprintf('%.2f',$balanceRow['cb_value'] - $convert_fee);
    	//echo $able_fee;
        if($customerRow['cash_type']==1){
            if($able_fee < 0) return '账户余额不足，无法冻结金额';
        }
    	$hold_fee = $balanceRow['cb_hold_value'] + $convert_fee;
        $hold_fee = sprintf('%.2f',$hold_fee);

    	//if(!$uResult) return '更新余额数据失败';
    	//记录余额日记
    	$aBalanceLog['customer_code'] = $customerRow['customer_code'];
    	$aBalanceLog['customer_id'] = $customer_id;
    	$aBalanceLog['cbl_type'] = 0;
    	$aBalanceLog['cbl_transaction_value'] = $convert_fee;
    	$aBalanceLog['cbl_value'] = $fee;
    	$aBalanceLog['currency_rate'] = $currencyRow['currency_rate'];
    	$aBalanceLog['currency_code'] = $result['data']['cost']['currency_code'];

    	$aBalanceLog['cbl_note'] = '提交订单，冻结余额';
    	$aBalanceLog['user_id'] = -1;
    	$aBalanceLog['cbl_current_value'] = $able_fee;
    	$aBalanceLog['cbl_current_hold_value'] = $hold_fee;
    	$aBalanceLog['application_code'] = 1;
    	$aBalanceLog['cbl_refer_code'] = $order_code;
    	$aBalanceLog['cbl_add_time'] = date('Y-m-d H:i:s');
        if($doresert){
            if($convert_fee>0){
                $aResult = Service_CustomerBalanceLog::add($aBalanceLog);
                if(!$aResult) return '记录余额日志失败';
            }
        }

    	$uOrder['shipping_fee_estimate'] = $convert_fee;
    	$uOrder['update_time'] = date('Y-m-d H:i:s');

    	//扣其它费用
    	$objOtherFeeCalculate = new Common_CalculateOtherFee();
    	$keys = array(
    			'warehouseId' => $orderRow['warehouse_id'],
    			'countryId' => $addressRow['oab_country_id'],
    			'smCode' => $orderRow['sm_code'],
    			'weight' => $weight,
    			'order_code'=>$order_code,
    	);
    	$objOtherFeeCalculate->setParams($keys);
        $costFeeCode=array(
            'CAOZUO','BAOGUAN', 'YUNSHU', 'RUKU', 'WULIUCAOZUO',
            'WULIAO','GUANLI','JIANGUANYUNSHU','CZBGF',
            'BHDPDRemoteFee','GFX','SXZ','POD','4PX-DUTY','4PXPYDQ'
        );
		if( $orderRow['sm_code'] == 'DHL-TH') {
            $costFeeCode[] = 'THPIANYUAN';//偏远费
            $costFeeCode[] = 'THFBATAX';//关税预付金
        } else {
            $costFeeCode[] = 'PIANYUAN';//偏远费
            $costFeeCode[] = 'FBATAX';//关税预付金
        }
        if($orderRow['dispatch_notice'] == '1'){
            array_push($costFeeCode, 'PAISONG');
        }
        if($orderRow['guarantee'] == '1'){
            array_push($costFeeCode, 'BAOZHANG');
        }
        if($orderRow['order_mode_type'] == '0'){
            array_push($costFeeCode, 'CZF-B');
        }
        foreach($costFeeCode as $code){
            $otherfeeResult = $objOtherFeeCalculate->getOtherFee($code);
        }
    	$caozuofee = $otherfeeResult['data']['otherFee']['caozuo']['price'];
    	$baoguanfee = $otherfeeResult['data']['otherFee']['baoguan']['price'];
    	$yunshufee = $otherfeeResult['data']['otherFee']['yunshu']['price'];
        $rukuFee = isset($otherfeeResult['data']['otherFee']['ruku']['price'])?$otherfeeResult['data']['otherFee']['ruku']['price']:'0';
        $wuliucaozuoFee = $otherfeeResult['data']['otherFee']['wuliucaozuo']['price'];
        $pianyuanFee = isset($otherfeeResult['data']['otherFee']['pianyuan']['price'])?$otherfeeResult['data']['otherFee']['pianyuan']['price']:'0';
        $pydqfjfFee = isset($otherfeeResult['data']['otherFee']['4pxpydq']['price'])?$otherfeeResult['data']['otherFee']['4pxpydq']['price']:'0';
        $wuliaoFee = isset($otherfeeResult['data']['otherFee']['wuliao']['price'])?$otherfeeResult['data']['otherFee']['wuliao']['price']:'0';
        $guanliFee = isset($otherfeeResult['data']['otherFee']['guanli']['price'])?$otherfeeResult['data']['otherFee']['guanli']['price']:'0';
        $jgysFee = isset($otherfeeResult['data']['otherFee']['jianguanyunshu']['price'])?$otherfeeResult['data']['otherFee']['jianguanyunshu']['price']:'0';
        $chaozhiFee=isset($otherfeeResult['data']['otherFee']['chaozhibaoguan']['price'])?$otherfeeResult['data']['otherFee']['chaozhibaoguan']['price']:'0';
        $BHDPDRemoteFee = isset($otherfeeResult['data']['otherFee']['BHDPDRemoteFee']['price'])?$otherfeeResult['data']['otherFee']['BHDPDRemoteFee']['price']:"0";
        $kongyunFee=isset($otherfeeResult['data']['otherFee']['kongyun']['cost'])?$otherfeeResult['data']['otherFee']['kongyun']['cost']:'0';
        $gfxFee=isset($otherfeeResult['data']['otherFee']['gfx']['price'])?$otherfeeResult['data']['otherFee']['gfx']['price']:'0';
        $sxzFee=isset($otherfeeResult['data']['otherFee']['sxz']['price'])?$otherfeeResult['data']['otherFee']['sxz']['price']:'0';
        $fbataxFee = isset($otherfeeResult['data']['otherFee']['fbatax']['price']) ? $otherfeeResult['data']['otherFee']['fbatax']['price'] : '0';
        $podFee = isset($otherfeeResult['data']['otherFee']['pod']['price']) ? $otherfeeResult['data']['otherFee']['pod']['price'] : '0';
        $taxFee = isset($otherfeeResult['data']['otherFee']['4pxduty']['price']) ? $otherfeeResult['data']['otherFee']['4pxduty']['price'] : '0';
 		$thRemoteFee = isset($otherfeeResult['data']['otherFee']['thRemote']['price'])?$otherfeeResult['data']['otherFee']['thRemote']['price']:'0';//郑梦偏远费
        $thFbaTaxFee = isset($otherfeeResult['data']['otherFee']['thFbaTax']['price'])?$otherfeeResult['data']['otherFee']['thFbaTax']['price']:'0';//关税预付金
        $dispatchNoticeFee = isset($otherfeeResult['data']['otherFee']['dispatchNotice']['price']) ? $otherfeeResult['data']['otherFee']['dispatchNotice']['price'] : '0';
        $guaranteeFee = isset($otherfeeResult['data']['otherFee']['guarantee']['price']) ? $otherfeeResult['data']['otherFee']['guarantee']['price'] : '0';
        $caozuofeeB = isset($otherfeeResult['data']['otherFee']['czf-b']['price']) ? $otherfeeResult['data']['otherFee']['czf-b']['price'] : '0';
        if($orderRow['sm_code']=="BH-DPD"&&$BHDPDRemoteFee>0&&$orderRow['is_remote_city']=="1"){
            //$convert_caozuo_fee = round($caozuofee / $currencyRow['currency_rate'], 2);
            $convert_remote_fee = Service_Currency::converByCode($otherfeeResult['data']['otherFee']['BHDPDRemoteFee']['currency_code'], $customerRow['customer_currency'], $BHDPDRemoteFee);
            $able_fee = $able_fee-$convert_remote_fee;
            $able_fee=sprintf('%.2f',$able_fee);

            $hold_fee+=$convert_remote_fee;
            $hold_fee=sprintf('%.2f',$hold_fee);

            $aBalanceLog['customer_code'] = $customerRow['customer_code'];
            $aBalanceLog['customer_id'] = $customer_id;
            $aBalanceLog['cbl_type'] = 0;
            $aBalanceLog['cbl_transaction_value'] = $convert_remote_fee;
            $aBalanceLog['cbl_value'] = $BHDPDRemoteFee;
            $aBalanceLog['currency_rate'] = $currencyRow['currency_rate'];
            $aBalanceLog['currency_code'] = $otherfeeResult['data']['otherFee']['BHDPDRemoteFee']['currency_code'];
            $aBalanceLog['cbl_note'] = '提交订单扣操作费，冻结余额';
            $aBalanceLog['user_id'] = -1;
            $aBalanceLog['cbl_current_value'] = $able_fee;
            $aBalanceLog['cbl_current_hold_value'] = $hold_fee;
            $aBalanceLog['application_code'] = 1;
            $aBalanceLog['cbl_refer_code'] = $order_code;
            $aBalanceLog['cbl_add_time'] = date('Y-m-d H:i:s');
            $otherfee_remote=Service_OtherFee::getByField('BHDPDRemoteFee','fee_code');
            if(!empty($otherfee_remote)){
                $aBalanceLog['fee_id'] = $otherfee_remote['fee_id'];
            }

            //print_r($aBalanceLog);
            $aResult = Service_CustomerBalanceLog::add($aBalanceLog);
        }

    	if($caozuofee>0){
    		//$convert_caozuo_fee = round($caozuofee / $currencyRow['currency_rate'], 2);
    		$convert_caozuo_fee = Service_Currency::converByCode($otherfeeResult['data']['otherFee']['caozuo']['currency_code'], $customerRow['customer_currency'], $caozuofee);
    		$able_fee = $able_fee-$convert_caozuo_fee;
            $able_fee=sprintf('%.2f',$able_fee);
    			
    		$hold_fee+=$convert_caozuo_fee;
            $hold_fee=sprintf('%.2f',$hold_fee);
    		
    		$aBalanceLog['customer_code'] = $customerRow['customer_code'];
    		$aBalanceLog['customer_id'] = $customer_id;
    		$aBalanceLog['cbl_type'] = 0;
    		$aBalanceLog['cbl_transaction_value'] = $convert_caozuo_fee;
    		$aBalanceLog['cbl_value'] = $caozuofee;
    		$aBalanceLog['currency_rate'] = $currencyRow['currency_rate'];
    		$aBalanceLog['currency_code'] = $otherfeeResult['data']['otherFee']['caozuo']['currency_code'];
    		$aBalanceLog['cbl_note'] = '提交订单扣操作费，冻结余额';
    		$aBalanceLog['user_id'] = -1;
    		$aBalanceLog['cbl_current_value'] = $able_fee;
    		$aBalanceLog['cbl_current_hold_value'] = $hold_fee;
    		$aBalanceLog['application_code'] = 1;
    		$aBalanceLog['cbl_refer_code'] = $order_code;
    		$aBalanceLog['cbl_add_time'] = date('Y-m-d H:i:s');
    		$otherfee_caozuo=Service_OtherFee::getByField('caozuo','fee_code');
    		if(!empty($otherfee_caozuo)){
    			$aBalanceLog['fee_id'] = $otherfee_caozuo['fee_id'];
    		}
    		
    		//print_r($aBalanceLog);
    		$aResult = Service_CustomerBalanceLog::add($aBalanceLog);
    	}
    	if($baoguanfee>0){
    		//$convert_caozuo_fee = round($caozuofee / $currencyRow['currency_rate'], 2);
    		$convert_baoguan_fee = Service_Currency::converByCode($otherfeeResult['data']['otherFee']['baoguan']['currency_code'], $customerRow['customer_currency'], $baoguanfee);
    		$able_fee = $able_fee-$convert_baoguan_fee;
            $able_fee=sprintf('%.2f',$able_fee);

    		$hold_fee+=$convert_baoguan_fee;
            $hold_fee=sprintf('%.2f',$hold_fee);

    		$aBalanceLog['customer_code'] = $customerRow['customer_code'];
    		$aBalanceLog['customer_id'] = $customer_id;
    		$aBalanceLog['cbl_type'] = 0;
    		$aBalanceLog['cbl_transaction_value'] = $convert_baoguan_fee;
    		$aBalanceLog['cbl_value'] = $baoguanfee;
    		$aBalanceLog['currency_rate'] = $currencyRow['currency_rate'];
    		$aBalanceLog['currency_code'] = $otherfeeResult['data']['otherFee']['baoguan']['currency_code'];
    		$aBalanceLog['cbl_note'] = '提交订单扣报关费，冻结余额';
    		$aBalanceLog['user_id'] = -1;
    		$aBalanceLog['cbl_current_value'] = $able_fee;
    		$aBalanceLog['cbl_current_hold_value'] = $hold_fee;
    		$aBalanceLog['application_code'] = 1;
    		$aBalanceLog['cbl_refer_code'] = $order_code;
    		$aBalanceLog['cbl_add_time'] = date('Y-m-d H:i:s');
    		//$otherfee_caozuo=Service_OtherFee::getByField('caozuo','fee_code');
    		if($otherfeeResult['data']['otherFee']['baoguan']['fee_id']>0){
    			$aBalanceLog['fee_id'] = $otherfeeResult['data']['otherFee']['baoguan']['fee_id'];
    		}
    	
    		//print_r($aBalanceLog);
    		$aResult = Service_CustomerBalanceLog::add($aBalanceLog);
    	}
    	if($yunshufee>0){
    		//$convert_caozuo_fee = round($caozuofee / $currencyRow['currency_rate'], 2);
    		$convert_yunshu_fee = Service_Currency::converByCode($otherfeeResult['data']['otherFee']['yunshu']['currency_code'], $customerRow['customer_currency'], $yunshufee);
    		$able_fee = $able_fee-$convert_yunshu_fee;
            $able_fee=sprintf('%.2f',$able_fee);
    		 
    		$hold_fee+=$convert_yunshu_fee;
            $hold_fee=sprintf('%.2f',$hold_fee);

    		$aBalanceLog['customer_code'] = $customerRow['customer_code'];
    		$aBalanceLog['customer_id'] = $customer_id;
    		$aBalanceLog['cbl_type'] = 0;
    		$aBalanceLog['cbl_transaction_value'] = $convert_yunshu_fee;
    		$aBalanceLog['cbl_value'] = $yunshufee;
    		$aBalanceLog['currency_rate'] = $currencyRow['currency_rate'];
    		$aBalanceLog['currency_code'] = $otherfeeResult['data']['otherFee']['yunshu']['currency_code'];
    		$aBalanceLog['cbl_note'] = '提交订单扣中港运输费，冻结余额';
    		$aBalanceLog['user_id'] = -1;
    		$aBalanceLog['cbl_current_value'] = $able_fee;
    		$aBalanceLog['cbl_current_hold_value'] = $hold_fee;
    		$aBalanceLog['application_code'] = 1;
    		$aBalanceLog['cbl_refer_code'] = $order_code;
    		$aBalanceLog['cbl_add_time'] = date('Y-m-d H:i:s');
    		//$otherfee_caozuo=Service_OtherFee::getByField('caozuo','fee_code');
    		if($otherfeeResult['data']['otherFee']['yunshu']['fee_id']>0){
    			$aBalanceLog['fee_id'] = $otherfeeResult['data']['otherFee']['yunshu']['fee_id'];
    		}
    		 
    		//print_r($aBalanceLog);
    		$aResult = Service_CustomerBalanceLog::add($aBalanceLog);
    	}
        if($rukuFee>0){
            $convert_ruku_fee = Service_Currency::converByCode($otherfeeResult['data']['otherFee']['ruku']['currency_code'], $customerRow['customer_currency'], $rukuFee);
            $able_fee = $able_fee-$convert_ruku_fee;
            $able_fee=sprintf('%.2f',$able_fee);

            $hold_fee+=$convert_ruku_fee;
            $hold_fee=sprintf('%.2f',$hold_fee);

            $aBalanceLog['customer_code'] = $customerRow['customer_code'];
            $aBalanceLog['customer_id'] = $customer_id;
            $aBalanceLog['cbl_type'] = 0;
            $aBalanceLog['cbl_transaction_value'] = $convert_ruku_fee;
            $aBalanceLog['cbl_value'] = $rukuFee;
            $aBalanceLog['currency_rate'] = $currencyRow['currency_rate'];
            $aBalanceLog['currency_code'] = $otherfeeResult['data']['otherFee']['ruku']['currency_code'];
            $aBalanceLog['cbl_note'] = '提交订单扣入库费，冻结余额';
            $aBalanceLog['user_id'] = -1;
            $aBalanceLog['cbl_current_value'] = $able_fee;
            $aBalanceLog['cbl_current_hold_value'] = $hold_fee;
            $aBalanceLog['application_code'] = 1;
            $aBalanceLog['cbl_refer_code'] = $order_code;
            $aBalanceLog['cbl_add_time'] = date('Y-m-d H:i:s');
            //$otherfee_caozuo=Service_OtherFee::getByField('caozuo','fee_code');
            if($otherfeeResult['data']['otherFee']['ruku']['fee_id']>0){
                $aBalanceLog['fee_id'] = $otherfeeResult['data']['otherFee']['ruku']['fee_id'];
            }

            //print_r($aBalanceLog);
            $aResult = Service_CustomerBalanceLog::add($aBalanceLog);
        }
        if($wuliucaozuoFee>0){
            $convert_wuliucaozuo_fee = Service_Currency::converByCode($otherfeeResult['data']['otherFee']['wuliucaozuo']['currency_code'], $customerRow['customer_currency'], $wuliucaozuoFee);
            $able_fee = $able_fee-$convert_wuliucaozuo_fee;
            $able_fee=sprintf('%.2f',$able_fee);

            $hold_fee+=$convert_wuliucaozuo_fee;
            $hold_fee=sprintf('%.2f',$hold_fee);

            $aBalanceLog['customer_code'] = $customerRow['customer_code'];
            $aBalanceLog['customer_id'] = $customer_id;
            $aBalanceLog['cbl_type'] = 0;
            $aBalanceLog['cbl_transaction_value'] = $convert_wuliucaozuo_fee;
            $aBalanceLog['cbl_value'] = $wuliucaozuoFee;
            $aBalanceLog['currency_rate'] = $currencyRow['currency_rate'];
            $aBalanceLog['currency_code'] = $otherfeeResult['data']['otherFee']['wuliucaozuo']['currency_code'];
            $aBalanceLog['cbl_note'] = '提交订单扣入库费，冻结余额';
            $aBalanceLog['user_id'] = -1;
            $aBalanceLog['cbl_current_value'] = $able_fee;
            $aBalanceLog['cbl_current_hold_value'] = $hold_fee;
            $aBalanceLog['application_code'] = 1;
            $aBalanceLog['cbl_refer_code'] = $order_code;
            $aBalanceLog['cbl_add_time'] = date('Y-m-d H:i:s');
            //$otherfee_caozuo=Service_OtherFee::getByField('caozuo','fee_code');
            if($otherfeeResult['data']['otherFee']['wuliucaozuo']['fee_id']>0){
                $aBalanceLog['fee_id'] = $otherfeeResult['data']['otherFee']['wuliucaozuo']['fee_id'];
            }

            //print_r($aBalanceLog);
            $aResult = Service_CustomerBalanceLog::add($aBalanceLog);
        }
        //扣偏远费
        if($pianyuanFee>0&&$orderRow['sm_code']!="BH-DPD"){
            $convert_pianyuan_fee = Service_Currency::converByCode($otherfeeResult['data']['otherFee']['pianyuan']['currency_code'], $customerRow['customer_currency'], $pianyuanFee);
            $able_fee = $able_fee-$convert_pianyuan_fee;
            $able_fee=sprintf('%.2f',$able_fee);

            $hold_fee+=$convert_pianyuan_fee;
            $hold_fee=sprintf('%.2f',$hold_fee);

            $aBalanceLog['customer_code'] = $customerRow['customer_code'];
            $aBalanceLog['customer_id'] = $customer_id;
            $aBalanceLog['cbl_type'] = 0;
            $aBalanceLog['cbl_transaction_value'] = $convert_pianyuan_fee;
            $aBalanceLog['cbl_value'] = $pianyuanFee;
            $aBalanceLog['currency_rate'] = $currencyRow['currency_rate'];
            $aBalanceLog['currency_code'] = $otherfeeResult['data']['otherFee']['pianyuan']['currency_code'];
            $aBalanceLog['cbl_note'] = '提交订单扣偏远费，冻结余额';
            $aBalanceLog['user_id'] = -1;
            $aBalanceLog['cbl_current_value'] = $able_fee;
            $aBalanceLog['cbl_current_hold_value'] = $hold_fee;
            $aBalanceLog['application_code'] = 1;
            $aBalanceLog['cbl_refer_code'] = $order_code;
            $aBalanceLog['cbl_add_time'] = date('Y-m-d H:i:s');
            //$otherfee_caozuo=Service_OtherFee::getByField('caozuo','fee_code');
            if($otherfeeResult['data']['otherFee']['pianyuan']['fee_id']>0){
                $aBalanceLog['fee_id'] = $otherfeeResult['data']['otherFee']['pianyuan']['fee_id'];
            }

            //print_r($aBalanceLog);
            $aResult = Service_CustomerBalanceLog::add($aBalanceLog);
        }

        //扣偏远地区附加费
        if($pydqfjfFee>0&&$orderRow['sm_code']=="4PX-HKDHL"){
            $convert_pydqfjf_fee = Service_Currency::converByCode($otherfeeResult['data']['otherFee']['4pxpydq']['currency_code'], $customerRow['customer_currency'], $pydqfjfFee);
            $able_fee = $able_fee-$convert_pydqfjf_fee;
            $able_fee=sprintf('%.2f',$able_fee);

            $hold_fee+=$convert_pydqfjf_fee;
            $hold_fee=sprintf('%.2f',$hold_fee);

            $aBalanceLog['customer_code'] = $customerRow['customer_code'];
            $aBalanceLog['customer_id'] = $customer_id;
            $aBalanceLog['cbl_type'] = 0;
            $aBalanceLog['cbl_transaction_value'] = $convert_pydqfjf_fee;
            $aBalanceLog['cbl_value'] = $pydqfjfFee;
            $aBalanceLog['currency_rate'] = $currencyRow['currency_rate'];
            $aBalanceLog['currency_code'] = $otherfeeResult['data']['otherFee']['4pxpydq']['currency_code'];
            $aBalanceLog['cbl_note'] = '提交订单扣偏远地区附加费，冻结余额';
            $aBalanceLog['user_id'] = -1;
            $aBalanceLog['cbl_current_value'] = $able_fee;
            $aBalanceLog['cbl_current_hold_value'] = $hold_fee;
            $aBalanceLog['application_code'] = 1;
            $aBalanceLog['cbl_refer_code'] = $order_code;
            $aBalanceLog['cbl_add_time'] = date('Y-m-d H:i:s');
            //$otherfee_caozuo=Service_OtherFee::getByField('caozuo','fee_code');
            if($otherfeeResult['data']['otherFee']['4pxpydq']['fee_id']>0){
                $aBalanceLog['fee_id'] = $otherfeeResult['data']['otherFee']['4pxpydq']['fee_id'];
            }

            //print_r($aBalanceLog);
            $aResult = Service_CustomerBalanceLog::add($aBalanceLog);
        }

        //扣物料费
        if($wuliaoFee>0){
            $convert_wuliao_fee = Service_Currency::converByCode($otherfeeResult['data']['otherFee']['wuliao']['currency_code'], $customerRow['customer_currency'], $wuliaoFee);
            $able_fee = $able_fee-$convert_wuliao_fee;
            $able_fee=sprintf('%.2f',$able_fee);

            $hold_fee+=$convert_wuliao_fee;
            $hold_fee=sprintf('%.2f',$hold_fee);

            $aBalanceLog['customer_code'] = $customerRow['customer_code'];
            $aBalanceLog['customer_id'] = $customer_id;
            $aBalanceLog['cbl_type'] = 0;
            $aBalanceLog['cbl_transaction_value'] = $convert_wuliao_fee;
            $aBalanceLog['cbl_value'] = $wuliaoFee;
            $aBalanceLog['currency_rate'] = $currencyRow['currency_rate'];
            $aBalanceLog['currency_code'] = $otherfeeResult['data']['otherFee']['wuliao']['currency_code'];
            $aBalanceLog['cbl_note'] = '提交订单扣物料费，冻结余额';
            $aBalanceLog['user_id'] = -1;
            $aBalanceLog['cbl_current_value'] = $able_fee;
            $aBalanceLog['cbl_current_hold_value'] = $hold_fee;
            $aBalanceLog['application_code'] = 1;
            $aBalanceLog['cbl_refer_code'] = $order_code;
            $aBalanceLog['cbl_add_time'] = date('Y-m-d H:i:s');
            //$otherfee_caozuo=Service_OtherFee::getByField('caozuo','fee_code');
            if($otherfeeResult['data']['otherFee']['wuliao']['fee_id']>0){
                $aBalanceLog['fee_id'] = $otherfeeResult['data']['otherFee']['wuliao']['fee_id'];
            }

            //print_r($aBalanceLog);
            $aResult = Service_CustomerBalanceLog::add($aBalanceLog);
        }
        //扣管理费
        if($guanliFee>0){
            $convert_guanli_fee = Service_Currency::converByCode($otherfeeResult['data']['otherFee']['guanli']['currency_code'], $customerRow['customer_currency'], $guanliFee);
            $able_fee = $able_fee-$convert_guanli_fee;
            $able_fee=sprintf('%.2f',$able_fee);

            $hold_fee+=$convert_guanli_fee;
            $hold_fee=sprintf('%.2f',$hold_fee);

            $aBalanceLog['customer_code'] = $customerRow['customer_code'];
            $aBalanceLog['customer_id'] = $customer_id;
            $aBalanceLog['cbl_type'] = 0;
            $aBalanceLog['cbl_transaction_value'] = $convert_guanli_fee;
            $aBalanceLog['cbl_value'] = $guanliFee;
            $aBalanceLog['currency_rate'] = $currencyRow['currency_rate'];
            $aBalanceLog['currency_code'] = $otherfeeResult['data']['otherFee']['guanli']['currency_code'];
            $aBalanceLog['cbl_note'] = '提交订单扣管理费，冻结余额';
            $aBalanceLog['user_id'] = -1;
            $aBalanceLog['cbl_current_value'] = $able_fee;
            $aBalanceLog['cbl_current_hold_value'] = $hold_fee;
            $aBalanceLog['application_code'] = 1;
            $aBalanceLog['cbl_refer_code'] = $order_code;
            $aBalanceLog['cbl_add_time'] = date('Y-m-d H:i:s');
            //$otherfee_caozuo=Service_OtherFee::getByField('caozuo','fee_code');
            if($otherfeeResult['data']['otherFee']['guanli']['fee_id']>0){
                $aBalanceLog['fee_id'] = $otherfeeResult['data']['otherFee']['guanli']['fee_id'];
            }

            //print_r($aBalanceLog);
            $aResult = Service_CustomerBalanceLog::add($aBalanceLog);
        }
        if($jgysFee>0){
            $convert_jgys_fee = Service_Currency::converByCode($otherfeeResult['data']['otherFee']['jianguanyunshu']['currency_code'], $customerRow['customer_currency'], $jgysFee);
            $able_fee = $able_fee-$convert_jgys_fee;
            $able_fee=sprintf('%.2f',$able_fee);

            $hold_fee+=$convert_jgys_fee;
            $hold_fee=sprintf('%.2f',$hold_fee);

            $aBalanceLog['customer_code'] = $customerRow['customer_code'];
            $aBalanceLog['customer_id'] = $customer_id;
            $aBalanceLog['cbl_type'] = 0;
            $aBalanceLog['cbl_transaction_value'] = $convert_jgys_fee;
            $aBalanceLog['cbl_value'] = $jgysFee;
            $aBalanceLog['currency_rate'] = $currencyRow['currency_rate'];
            $aBalanceLog['currency_code'] = $otherfeeResult['data']['otherFee']['jianguanyunshu']['currency_code'];
            $aBalanceLog['cbl_note'] = '提交订单扣监管运输费，冻结余额';
            $aBalanceLog['user_id'] = -1;
            $aBalanceLog['cbl_current_value'] = $able_fee;
            $aBalanceLog['cbl_current_hold_value'] = $hold_fee;
            $aBalanceLog['application_code'] = 1;
            $aBalanceLog['cbl_refer_code'] = $order_code;
            $aBalanceLog['cbl_add_time'] = date('Y-m-d H:i:s');
            //$otherfee_caozuo=Service_OtherFee::getByField('caozuo','fee_code');
            if($otherfeeResult['data']['otherFee']['jianguanyunshu']['fee_id']>0){
                $aBalanceLog['fee_id'] = $otherfeeResult['data']['otherFee']['jianguanyunshu']['fee_id'];
            }
            $aResult = Service_CustomerBalanceLog::add($aBalanceLog);
        }

        if($orderRow['is_fba_tax']==1 && $fbataxFee > 0){
            $convert_fbatax_fee = Service_Currency::converByCode($otherfeeResult['data']['otherFee']['fbatax']['currency_code'], $customerRow['customer_currency'], $fbataxFee);
            $able_fee = $able_fee-$convert_fbatax_fee;
            $able_fee=sprintf('%.2f',$able_fee);

            $hold_fee+=$convert_fbatax_fee;
            $hold_fee=sprintf('%.2f',$hold_fee);

            $aBalanceLog['customer_code'] = $customerRow['customer_code'];
            $aBalanceLog['customer_id'] = $customer_id;
            $aBalanceLog['cbl_type'] = 0;
            $aBalanceLog['cbl_transaction_value'] = $convert_fbatax_fee;
            $aBalanceLog['cbl_value'] = $fbataxFee;
            $aBalanceLog['currency_rate'] = $currencyRow['currency_rate'];
            $aBalanceLog['currency_code'] = $otherfeeResult['data']['otherFee']['fbatax']['currency_code'];
            $aBalanceLog['cbl_note'] = '提交订单扣关税预付操作费，冻结余额';
            $aBalanceLog['user_id'] = -1;
            $aBalanceLog['cbl_current_value'] = $able_fee;
            $aBalanceLog['cbl_current_hold_value'] = $hold_fee;
            $aBalanceLog['application_code'] = 1;
            $aBalanceLog['cbl_refer_code'] = $order_code;
            $aBalanceLog['cbl_add_time'] = date('Y-m-d H:i:s');
            //$otherfee_caozuo=Service_OtherFee::getByField('caozuo','fee_code');
            if($otherfeeResult['data']['otherFee']['fbatax']['fee_id']>0){
                $aBalanceLog['fee_id'] = $otherfeeResult['data']['otherFee']['fbatax']['fee_id'];
            }
            $aResult = Service_CustomerBalanceLog::add($aBalanceLog);            
        }	
        // 扣POD服务费
        if($orderRow['sm_code']=="4PX-LYT_GH" && $orderRow['is_pod'] == '1' && $podFee > 0){
            $convert_fbatax_fee = Service_Currency::converByCode($otherfeeResult['data']['otherFee']['pod']['currency_code'], $customerRow['customer_currency'], $podFee);
            $able_fee = $able_fee-$convert_fbatax_fee;
            $able_fee=sprintf('%.2f',$able_fee);

            $hold_fee+=$convert_fbatax_fee;
            $hold_fee=sprintf('%.2f',$hold_fee);

            $aBalanceLog['customer_code'] = $customerRow['customer_code'];
            $aBalanceLog['customer_id'] = $customer_id;
            $aBalanceLog['cbl_type'] = 0;
            $aBalanceLog['cbl_transaction_value'] = $convert_fbatax_fee;
            $aBalanceLog['cbl_value'] = $podFee;
            $aBalanceLog['currency_rate'] = $currencyRow['currency_rate'];
            $aBalanceLog['currency_code'] = $otherfeeResult['data']['otherFee']['pod']['currency_code'];
            $aBalanceLog['cbl_note'] = '提交订单扣POD服务费，冻结余额';
            $aBalanceLog['user_id'] = -1;
            $aBalanceLog['cbl_current_value'] = $able_fee;
            $aBalanceLog['cbl_current_hold_value'] = $hold_fee;
            $aBalanceLog['application_code'] = 1;
            $aBalanceLog['cbl_refer_code'] = $order_code;
            $aBalanceLog['cbl_add_time'] = date('Y-m-d H:i:s');
            //$otherfee_caozuo=Service_OtherFee::getByField('caozuo','fee_code');
            if($otherfeeResult['data']['otherFee']['pod']['fee_id']>0){
                $aBalanceLog['fee_id'] = $otherfeeResult['data']['otherFee']['pod']['fee_id'];
            }
            $aResult = Service_CustomerBalanceLog::add($aBalanceLog);
        }


        //扣超值报关费
        if($chaozhiFee>0){
            $convert_caozhi_fee = Service_Currency::converByCode($otherfeeResult['data']['otherFee']['chaozhibaoguan']['currency_code'], $customerRow['customer_currency'], $chaozhiFee);
            $able_fee = $able_fee-$convert_caozhi_fee;
            $able_fee=sprintf('%.2f',$able_fee);
                
            $hold_fee+=$convert_caozhi_fee;
            $hold_fee=sprintf('%.2f',$hold_fee);
            
            $aBalanceLog['customer_code'] = $customerRow['customer_code'];
            $aBalanceLog['customer_id'] = $customer_id;
            $aBalanceLog['cbl_type'] = 0;
            $aBalanceLog['cbl_transaction_value'] = $convert_caozhi_fee;
            $aBalanceLog['cbl_value'] = $chaozhiFee;
            $aBalanceLog['currency_rate'] = $currencyRow['currency_rate'];
            $aBalanceLog['currency_code'] = $otherfeeResult['data']['otherFee']['chaozhibaoguan']['currency_code'];
            $aBalanceLog['cbl_note'] = '提交订单扣超值报关费，冻结余额';
            $aBalanceLog['user_id'] = -1;
            $aBalanceLog['cbl_current_value'] = $able_fee;
            $aBalanceLog['cbl_current_hold_value'] = $hold_fee;
            $aBalanceLog['application_code'] = "CZBGF";
            $aBalanceLog['cbl_refer_code'] = $order_code;
            $aBalanceLog['cbl_add_time'] = date('Y-m-d H:i:s');
            $otherfee_chaozhi=Service_OtherFee::getByField('CZBGF','fee_code');
            if(!empty($otherfee_chaozhi)){
                $aBalanceLog['fee_id'] = $otherfee_chaozhi['fee_id'];
            }
            
            //print_r($aBalanceLog);
            $aResult = Service_CustomerBalanceLog::add($aBalanceLog);
        }
        //扣空运费
        if($kongyunFee>0){
            $convert_kongyun_fee = Service_Currency::converByCode($otherfeeResult['data']['otherFee']['kongyun']['currency_code'], $customerRow['customer_currency'], $caozuofee);
            $able_fee = $able_fee-$convert_kongyun_fee;
            $able_fee=sprintf('%.2f',$able_fee);
                
            $hold_fee+=$convert_kongyun_fee;
            $hold_fee=sprintf('%.2f',$hold_fee);
            
            $aBalanceLog['customer_code'] = $customerRow['customer_code'];
            $aBalanceLog['customer_id'] = $customer_id;
            $aBalanceLog['cbl_type'] = 0;
            $aBalanceLog['cbl_transaction_value'] = $convert_kongyun_fee;
            $aBalanceLog['cbl_value'] = $kongyunFee;
            $aBalanceLog['currency_rate'] = $currencyRow['currency_rate'];
            $aBalanceLog['currency_code'] = $otherfeeResult['data']['otherFee']['kongyun']['currency_code'];
            $aBalanceLog['cbl_note'] = '提交订单扣空运费，冻结余额';
            $aBalanceLog['user_id'] = -1;
            $aBalanceLog['cbl_current_value'] = $able_fee;
            $aBalanceLog['cbl_current_hold_value'] = $hold_fee;
            $aBalanceLog['application_code'] = "KYF";
            $aBalanceLog['cbl_refer_code'] = $order_code;
            $aBalanceLog['cbl_add_time'] = date('Y-m-d H:i:s');
            $otherfee_kongyun=Service_OtherFee::getByField('KYF','fee_code');
            if(!empty($otherfee_kongyun)){
                $aBalanceLog['fee_id'] = $otherfee_kongyun['fee_id'];
            }
            
            //print_r($aBalanceLog);
            $aResult = Service_CustomerBalanceLog::add($aBalanceLog);
        }

        //扣高风险附加费
        if ($gfxFee>0) {
           $convert_gfx_fee = Service_Currency::converByCode($otherfeeResult['data']['otherFee']['gfx']['currency_code'], $customerRow['customer_currency'], $gfxFee);
            $able_fee = $able_fee-$convert_gfx_fee;
            $able_fee=sprintf('%.2f',$able_fee);
                
            $hold_fee+=$convert_gfx_fee;
            $hold_fee=sprintf('%.2f',$hold_fee);
            
            $aBalanceLog['customer_code'] = $customerRow['customer_code'];
            $aBalanceLog['customer_id'] = $customer_id;
            $aBalanceLog['cbl_type'] = 0;
            $aBalanceLog['cbl_transaction_value'] = $convert_gfx_fee;
            $aBalanceLog['cbl_value'] = $gfxFee;
            $aBalanceLog['currency_rate'] = $currencyRow['currency_rate'];
            $aBalanceLog['currency_code'] = $otherfeeResult['data']['otherFee']['gfx']['currency_code'];
            $aBalanceLog['cbl_note'] = '提交订单扣高风险附加费，冻结余额';
            $aBalanceLog['user_id'] = -1;
            $aBalanceLog['cbl_current_value'] = $able_fee;
            $aBalanceLog['cbl_current_hold_value'] = $hold_fee;
            $aBalanceLog['application_code'] = "Elevated Risk";
            $aBalanceLog['cbl_refer_code'] = $order_code;
            $aBalanceLog['cbl_add_time'] = date('Y-m-d H:i:s');
            $otherfee_gfx=Service_OtherFee::getByField('Elevated Risk','fee_code');
            if(!empty($otherfee_gfx)){
                $aBalanceLog['fee_id'] = $otherfee_gfx['fee_id'];
            }
            //print_r($aBalanceLog);
            $aResult = Service_CustomerBalanceLog::add($aBalanceLog);
        }
        //扣受限制附加费
        if ($sxzFee>0) {
            $convert_sxz_fee = Service_Currency::converByCode($otherfeeResult['data']['otherFee']['sxz']['currency_code'], $customerRow['customer_currency'], $sxzFee);
            $able_fee = $able_fee-$convert_sxz_fee;
            $able_fee=sprintf('%.2f',$able_fee);
                
            $hold_fee+=$convert_sxz_fee;
            $hold_fee=sprintf('%.2f',$hold_fee);
            
            $aBalanceLog['customer_code'] = $customerRow['customer_code'];
            $aBalanceLog['customer_id'] = $customer_id;
            $aBalanceLog['cbl_type'] = 0;
            $aBalanceLog['cbl_transaction_value'] = $convert_sxz_fee;
            $aBalanceLog['cbl_value'] = $sxzFee;
            $aBalanceLog['currency_rate'] = $currencyRow['currency_rate'];
            $aBalanceLog['currency_code'] = $otherfeeResult['data']['otherFee']['sxz']['currency_code'];
            $aBalanceLog['cbl_note'] = '提交订单扣受限制附加费，冻结余额';
            $aBalanceLog['user_id'] = -1;
            $aBalanceLog['cbl_current_value'] = $able_fee;
            $aBalanceLog['cbl_current_hold_value'] = $hold_fee;
            $aBalanceLog['application_code'] = "Restricted Destination";
            $aBalanceLog['cbl_refer_code'] = $order_code;
            $aBalanceLog['cbl_add_time'] = date('Y-m-d H:i:s');
            $otherfee_sxz=Service_OtherFee::getByField('Restricted Destination','fee_code');
            if(!empty($otherfee_sxz)){
                $aBalanceLog['fee_id'] = $otherfee_sxz['fee_id'];
            }   
            //print_r($aBalanceLog);
            $aResult = Service_CustomerBalanceLog::add($aBalanceLog);
        }
        if($taxFee>0){
              $convert_tax_fee = Service_Currency::converByCode($otherfeeResult['data']['otherFee']['4pxduty']['currency_code'], $customerRow['customer_currency'], $taxFee);
            $able_fee = $able_fee-$convert_sxz_fee;
            $able_fee=sprintf('%.2f',$able_fee);
            $hold_fee+=$convert_tax_fee;
            $hold_fee=sprintf('%.2f',$hold_fee);
            
            $aBalanceLog['customer_code'] = $customerRow['customer_code'];
            $aBalanceLog['customer_id'] = $customer_id;
            $aBalanceLog['cbl_type'] = 0;
            $aBalanceLog['cbl_transaction_value'] = $convert_tax_fee;
            $aBalanceLog['cbl_value'] = $taxFee;
            $aBalanceLog['currency_rate'] = $currencyRow['currency_rate'];
            $aBalanceLog['currency_code'] = $otherfeeResult['data']['otherFee']['4pxduty']['currency_code'];
            $aBalanceLog['cbl_note'] = '提交订单扣4PX英国超额税金，冻结余额';
            $aBalanceLog['user_id'] = -1;
            $aBalanceLog['cbl_current_value'] = $able_fee;
            $aBalanceLog['cbl_current_hold_value'] = $hold_fee;
            $aBalanceLog['application_code'] = "4PX-DUTY";
            $aBalanceLog['cbl_refer_code'] = $order_code;
            $aBalanceLog['cbl_add_time'] = date('Y-m-d H:i:s');
            $otherfee_duty=Service_OtherFee::getByField('4PX-DUTY','fee_code');
            if(!empty($otherfee_duty)){
                $aBalanceLog['fee_id'] = $otherfee_duty['fee_id'];
            }   
            //print_r($aBalanceLog);
            $aResult = Service_CustomerBalanceLog::add($aBalanceLog);
            
        }

        if( $thRemoteFee > 0 ){
            $convert_thRemoteFee = Service_Currency::converByCode($otherfeeResult['data']['otherFee']['thRemote']['currency_code'], $customerRow['customer_currency'], $thRemoteFee);
            $able_fee = $able_fee - $convert_thRemoteFee;
            $able_fee = sprintf('%.2f',$able_fee);
            $hold_fee += $convert_thRemoteFee;
            $hold_fee=sprintf('%.2f',$hold_fee);

            $aBalanceLog['customer_code'] = $customerRow['customer_code'];
            $aBalanceLog['customer_id'] = $customer_id;
            $aBalanceLog['cbl_type'] = 0;
            $aBalanceLog['cbl_transaction_value'] = $convert_thRemoteFee;
            $aBalanceLog['cbl_value'] = $thRemoteFee;
            $aBalanceLog['currency_rate'] = $currencyRow['currency_rate'];
            $aBalanceLog['currency_code'] = $otherfeeResult['data']['otherFee']['thRemote']['currency_code'];
            $aBalanceLog['cbl_note'] = '提交订单扣偏远费，冻结余额';
            $aBalanceLog['user_id'] = -1;
            $aBalanceLog['cbl_current_value'] = $able_fee;
            $aBalanceLog['cbl_current_hold_value'] = $hold_fee;
            $aBalanceLog['application_code'] = "4PX-DUTY";
            $aBalanceLog['cbl_refer_code'] = $order_code;
            $aBalanceLog['cbl_add_time'] = date('Y-m-d H:i:s');
            $aBalanceLog['fee_id'] = $otherfeeResult['data']['otherFee']['thRemote']['fee_id'];
            //print_r($aBalanceLog);
            $aResult = Service_CustomerBalanceLog::add($aBalanceLog);

        }

        if( $thFbaTaxFee > 0 ){
            $convert_thFbaTaxFee = Service_Currency::converByCode($otherfeeResult['data']['otherFee']['thFbaTax']['currency_code'], $customerRow['customer_currency'], $thFbaTaxFee);
            $able_fee = $able_fee - $convert_thFbaTaxFee;
            $able_fee=sprintf('%.2f',$able_fee);
            $hold_fee += $convert_thFbaTaxFee;
            $hold_fee=sprintf('%.2f',$hold_fee);

            $aBalanceLog['customer_code'] = $customerRow['customer_code'];
            $aBalanceLog['customer_id'] = $customer_id;
            $aBalanceLog['cbl_type'] = 0;
            $aBalanceLog['cbl_transaction_value'] = $convert_thFbaTaxFee;
            $aBalanceLog['cbl_value'] = $thFbaTaxFee;
            $aBalanceLog['currency_rate'] = $currencyRow['currency_rate'];
            $aBalanceLog['currency_code'] = $otherfeeResult['data']['otherFee']['thFbaTax']['currency_code'];
            $aBalanceLog['cbl_note'] = '提交订单扣关税预付金，冻结余额';
            $aBalanceLog['user_id'] = -1;
            $aBalanceLog['cbl_current_value'] = $able_fee;
            $aBalanceLog['cbl_current_hold_value'] = $hold_fee;
            $aBalanceLog['application_code'] = "4PX-DUTY";
            $aBalanceLog['cbl_refer_code'] = $order_code;
            $aBalanceLog['cbl_add_time'] = date('Y-m-d H:i:s');
            $aBalanceLog['fee_id'] = $otherfeeResult['data']['otherFee']['thFbaTax']['fee_id'];
            //print_r($aBalanceLog);
            $aResult = Service_CustomerBalanceLog::add($aBalanceLog);

        }
	
	//扣保险费
        if( $orderRow['insurance'] == 1) {
            $pObj = new Service_OtherFeeProcess();
            $address = Service_OrderAddressBook::getByField($orderRow['order_code'],'order_code');
            //获取保险费,返回的费用最多只有2位小数
            $param = array(
                'insuranceRate'=>$orderRow['insurance_rate'],
                'country'=>$address['oab_country_id'],
                'dealPrice'=>$orderRow['charge'],
                'dealCurrency'=>$orderRow['currency_code'],
            );
            $insurance = $pObj->getAmount($orderRow['warehouse_id'],$orderRow['insurance_code'],$param);
            if( $insurance === false )
                return implode(',',$pObj->getError());

            if( $insurance['amount'] > 0 ){
                foreach( $insurance['detail'] as $code=>$value) {

                    if( $value['amount'] == 0 )
                        continue;

                    $tmpFee = Service_Currency::converByCode($insurance['currency'], $customerRow['customer_currency'], $value['amount']);
                    $able_fee = $able_fee - $tmpFee;
                    //$able_fee = sprintf('%.2f',$able_fee); $able_fee系统里本来就是2位了，上面转换时也保留2位，没必要再四舍五入

                    $hold_fee += $tmpFee;
                    //$hold_fee = sprintf('%.2f',$hold_fee);
                    $aBalanceLog = array();
                    $aBalanceLog['customer_code'] = $customerRow['customer_code'];
                    $aBalanceLog['customer_id'] = $customer_id;
                    $aBalanceLog['cbl_type'] = 0;
                    $aBalanceLog['cbl_transaction_value'] = $tmpFee;
                    $aBalanceLog['cbl_value'] = $value['amount'];
                    $aBalanceLog['currency_rate'] = $currencyRow['currency_rate'];
                    $aBalanceLog['currency_code'] = $insurance['currency'];
                    $aBalanceLog['cbl_note'] = '提交订单扣保险('.$value['name'].')，冻结余额';
                    $aBalanceLog['user_id'] = -1;
                    $aBalanceLog['cbl_current_value'] = $able_fee;
                    $aBalanceLog['cbl_current_hold_value'] = $hold_fee;
                    $aBalanceLog['application_code'] = 1;
                    $aBalanceLog['cbl_refer_code'] = $order_code;
                    $aBalanceLog['cbl_add_time'] = date('Y-m-d H:i:s');
                    $tmpFeeRow = Service_OtherFee::getByField( $value['code'], 'fee_code');
                    $aBalanceLog['fee_id'] = $tmpFeeRow['fee_id'];

                    $aResult = Service_CustomerBalanceLog::add($aBalanceLog);
                }
            }
        }
       //派送通知服务费
       if($dispatchNoticeFee > 0){
           $convert_dispatchNoticeFee = Service_Currency::converByCode($otherfeeResult['data']['otherFee']['dispatchNotice']['currency_code'], $customerRow['customer_currency'], $dispatchNoticeFee);
           $able_fee = $able_fee-$convert_dispatchNoticeFee;
           $able_fee=sprintf('%.2f',$able_fee);
            
           $hold_fee+=$convert_dispatchNoticeFee;
           $hold_fee=sprintf('%.2f',$hold_fee);
           
           $aBalanceLog['customer_code'] = $customerRow['customer_code'];
           $aBalanceLog['customer_id'] = $customer_id;
           $aBalanceLog['cbl_type'] = 0;
           $aBalanceLog['cbl_transaction_value'] = $convert_dispatchNoticeFee;
           $aBalanceLog['cbl_value'] = $dispatchNoticeFee;
           $aBalanceLog['currency_rate'] = $currencyRow['currency_rate'];
           $aBalanceLog['currency_code'] = $otherfeeResult['data']['otherFee']['dispatchNotice']['currency_code'];
           $aBalanceLog['cbl_note'] = '提交订单扣派送通知服务费，冻结余额';
           $aBalanceLog['user_id'] = -1;
           $aBalanceLog['cbl_current_value'] = $able_fee;
           $aBalanceLog['cbl_current_hold_value'] = $hold_fee;
           $aBalanceLog['application_code'] = 1;
           $aBalanceLog['cbl_refer_code'] = $order_code;
           $aBalanceLog['cbl_add_time'] = date('Y-m-d H:i:s');
           $otherfee_dispatchNotice=Service_OtherFee::getByField('PAISONG','fee_code');
           if(!empty($otherfee_dispatchNotice)){
               $aBalanceLog['fee_id'] = $otherfee_dispatchNotice['fee_id'];
           }
           //print_r($aBalanceLog);
           $aResult = Service_CustomerBalanceLog::add($aBalanceLog);
            
       }
       
       //保障服务费
       if($guaranteeFee > 0){
           $convert_guaranteeFee = Service_Currency::converByCode($otherfeeResult['data']['otherFee']['guarantee']['currency_code'], $customerRow['customer_currency'], $guaranteeFee);
           $able_fee = $able_fee-$convert_guaranteeFee;
           $able_fee=sprintf('%.2f',$able_fee);
       
           $hold_fee+=$convert_guaranteeFee;
           $hold_fee=sprintf('%.2f',$hold_fee);
            
           $aBalanceLog['customer_code'] = $customerRow['customer_code'];
           $aBalanceLog['customer_id'] = $customer_id;
           $aBalanceLog['cbl_type'] = 0;
           $aBalanceLog['cbl_transaction_value'] = $convert_guaranteeFee;
           $aBalanceLog['cbl_value'] = $guaranteeFee;
           $aBalanceLog['currency_rate'] = $currencyRow['currency_rate'];
           $aBalanceLog['currency_code'] = $otherfeeResult['data']['otherFee']['guarantee']['currency_code'];
           $aBalanceLog['cbl_note'] = '提交订单扣保障服务费，冻结余额';
           $aBalanceLog['user_id'] = -1;
           $aBalanceLog['cbl_current_value'] = $able_fee;
           $aBalanceLog['cbl_current_hold_value'] = $hold_fee;
           $aBalanceLog['application_code'] = 1;
           $aBalanceLog['cbl_refer_code'] = $order_code;
           $aBalanceLog['cbl_add_time'] = date('Y-m-d H:i:s');
           $otherfee_guarantee=Service_OtherFee::getByField('BAOZHANG','fee_code');
           if(!empty($otherfee_guarantee)){
               $aBalanceLog['fee_id'] = $otherfee_guarantee['fee_id'];
           }
           //print_r($aBalanceLog);
           $aResult = Service_CustomerBalanceLog::add($aBalanceLog);
       
       }
       //操作费-B
       if($caozuofeeB > 0){
           $convert_caozuofeeB = Service_Currency::converByCode($otherfeeResult['data']['otherFee']['czf-b']['currency_code'], $customerRow['customer_currency'], $caozuofeeB);
           $able_fee = $able_fee-$convert_caozuofeeB;
           $able_fee=sprintf('%.2f',$able_fee);
            
           $hold_fee+=$convert_caozuofeeB;
           $hold_fee=sprintf('%.2f',$hold_fee);
       
           $aBalanceLog['customer_code'] = $customerRow['customer_code'];
           $aBalanceLog['customer_id'] = $customer_id;
           $aBalanceLog['cbl_type'] = 0;
           $aBalanceLog['cbl_transaction_value'] = $convert_caozuofeeB;
           $aBalanceLog['cbl_value'] = $caozuofeeB;
           $aBalanceLog['currency_rate'] = $currencyRow['currency_rate'];
           $aBalanceLog['currency_code'] = $otherfeeResult['data']['otherFee']['czf-b']['currency_code'];
           $aBalanceLog['cbl_note'] = '提交订单扣操作费-B，冻结余额';
           $aBalanceLog['user_id'] = -1;
           $aBalanceLog['cbl_current_value'] = $able_fee;
           $aBalanceLog['cbl_current_hold_value'] = $hold_fee;
           $aBalanceLog['application_code'] = 1;
           $aBalanceLog['cbl_refer_code'] = $order_code;
           $aBalanceLog['cbl_add_time'] = date('Y-m-d H:i:s');
           $otherfee_caozuofeeB=Service_OtherFee::getByField('CZF-B','fee_code');
           if(!empty($otherfee_caozuofeeB)){
               $aBalanceLog['fee_id'] = $otherfee_caozuofeeB['fee_id'];
           }
           //print_r($aBalanceLog);
           $aResult = Service_CustomerBalanceLog::add($aBalanceLog);
            
       }
        
    	$uBalance['cb_value'] = $able_fee;
    	$uBalance['cb_hold_value'] = $hold_fee;
    	$uBalance['cb_update_time'] = date('Y-m-d H:i:s');
        //print_r($uBalance);
    	$uResult = Service_CustomerBalance::update($uBalance, $balanceRow['cb_id']);
        if($doresert){
            Service_Orders::update($uOrder, $order_code, 'order_code');
        }
    	return true;
    }

    public static function unfreezeFee($order_code,$note='') {
        $aOrder = Service_Orders::getByField($order_code, 'order_code');
        if(empty($aOrder)) return '找不到订单'.$order_code;
        //if($aOrder['shipping_fee_estimate'] == 0) return true;
        $aCustomer = Service_Customer::getByField($aOrder['customer_id']);
        $aBalance = Service_CustomerBalance::getByField($aOrder['customer_id'], 'customer_id');
        if(empty($aBalance)) return '找不到客户账户余额记录';
        //处理
        $balanceRow = Service_CustomerBalance::getForUpdate($aBalance['cb_id']);
        //$hold_value = $balanceRow['cb_hold_value'] - $aOrder['shipping_fee_estimate'];
        //if($hold_value < 0) return '账户金额异常，冻结余额不足';
        //$uBalance['cb_value'] = $balanceRow['cb_value'] + $aOrder['shipping_fee_estimate'];
        //$uResult = Service_CustomerBalance::update($uBalance, $balanceRow['cb_id']);

        $balanceShipCondition = array(
            'customer_id'=>$aOrder['customer_id'],
            'cbl_type'=>'0',
            //'fee_id' => '0',
            'cbl_refer_code'=>$aOrder['order_code']
        );
        $feeTotal = 0;
        $shipfees = Service_CustomerBalanceLog::getByCondition($balanceShipCondition,'*',0,0,'cbl_id desc');
        if(empty($shipfees)){
            return '不存在冻结运费记录';
        }
        $cbl_current_value = $balanceRow['cb_value'];
        $cbl_current_hold_value = $balanceRow['cb_hold_value'];
        foreach($shipfees as $k=>$v){
            if($v['un_cbl_id']>0){
                //存在解冻记录，不要在解冻了
                continue;
            }
            $cbl_current_value = sprintf('%.2f',$cbl_current_value+$v['cbl_transaction_value']);
            $cbl_current_hold_value = sprintf('%.2f',$cbl_current_hold_value-$v['cbl_transaction_value']);
            $aBalanceLog['customer_code'] = $v['customer_code'];
            $aBalanceLog['customer_id'] = $v['customer_id'];
            $aBalanceLog['cbl_transaction_value'] = $v['cbl_transaction_value'];
            $aBalanceLog['cbl_value'] = $v['cbl_value'];
            $aBalanceLog['cbl_current_value'] = $cbl_current_value;
            $aBalanceLog['cbl_current_hold_value'] = $cbl_current_hold_value;
            $aBalanceLog['currency_code'] = $v['currency_code'];
            $aBalanceLog['fee_id'] = $v['fee_id'];
            $aBalanceLog['application_code'] = 1;
            $aBalanceLog['cbl_refer_code'] = $order_code;
            $aBalanceLog['cbl_type'] = 1;
            if(!empty($note)){
                $cbl_note = $note;
            }else{
               $cbl_note =  "订单拦截,解冻余额";
            }
            $aBalanceLog['cbl_note'] = $cbl_note;
            $aBalanceLog['user_id'] = '0';
            $aBalanceLog['cbl_add_time'] = date("Y-m-d H:i:s");
            $feeTotal = sprintf('%.2f',$feeTotal + $v['cbl_transaction_value']);
            if($v['cbl_transaction_value']>0){
                $aResult = Service_CustomerBalanceLog::add($aBalanceLog);
                if($aResult){
                    $uLogRow = array(
                        'un_cbl_id'=>$aResult
                    );
                    Service_CustomerBalanceLog::update($uLogRow,$v['cbl_id']);
                }
                if(!$aResult) return '记录余额日志失败';
            }
        }
        $currencyRow = Service_Currency::getByField($aCustomer['customer_currency'],'currency_code',"*");
        $hold_value  = sprintf('%.2f',$balanceRow['cb_hold_value'] - $feeTotal);
        //if($hold_value < 0) return '账户金额异常，冻结余额不足';
        $uBalance['cb_hold_value'] = sprintf('%.2f',$hold_value);
        $uBalance['cb_update_time'] = date('Y-m-d H:i:s');
        $uBalance['cb_value'] = sprintf('%.2f',$balanceRow['cb_value'] + $feeTotal);
        $uResult = Service_CustomerBalance::update($uBalance, $balanceRow['cb_id']);
        //$shipfee = $shipfees[0];
        //解冻日志
        //$currencyRow= Service_Currency::getByField($aCustomer['customer_currency'],"currency_code","*");
        //$aBalanceLog['customer_code'] = $aCustomer['customer_code'];
        //$aBalanceLog['customer_id'] = $aCustomer['customer_id'];
        //$aBalanceLog['cbl_type'] = 1;
        //$aBalanceLog['cbl_transaction_value'] = $aOrder['shipping_fee_estimate'];
        //$aBalanceLog['cbl_value'] = $shipfee['cbl_value'];
        //$aBalanceLog['currency_rate'] = $currencyRow['currency_rate'];
        //$aBalanceLog['currency_code'] = $shipfee['currency_code'];
        //$aBalanceLog['cbl_note'] = '订单出货，解冻余额';
        //$aBalanceLog['user_id'] = '0';
        //$aBalanceLog['cbl_current_value'] = $uBalance['cb_value'];
        //$aBalanceLog['cbl_current_hold_value'] = $uBalance['cb_hold_value'];
        //$aBalanceLog['application_code'] = 1;
        //$aBalanceLog['cbl_refer_code'] = $order_code;
        //$aBalanceLog['cbl_add_time'] = date('Y-m-d H:i:s');
        //$aResult = Service_CustomerBalanceLog::add($aBalanceLog);
        //self::unfreezeAllOtherFee($aOrder);
        return true;
    }
	
	/**
	 * 订单预扣费
	 * @author colin
	 * @param string $order_code
	 * @param int $customer_id
	 * @return true|string
	 */
   public function logisticsFreezeFee($order_code, $customer_id) {
   		//print_r($order_code);exit;
		
    	$customerRow = Service_Customer::getByField($customer_id);
    	$currencyRow = Service_Currency::getByField($customerRow['customer_currency'], 'currency_code');
		
        $orderRow = Service_LogisticsOrder::getByField($order_code, 'logistics_code');
		
    	//if($customerRow['cash_type']==2) return true;	//月结，不用冻结
        //集货转运类的订单在确认到提交时，无须冻结金额，在日本仓出货的时候也无须扣款，只在目的仓出货的时候发生扣款动作
        //if($orderRow['warehouse_id']=="1"&&$orderRow['order_mode_type']=="1") return true;
    	$addressRow = Service_LogisticsOrderAddress::getByField($order_code, 'logistics_code');

    	$objCalculate = new Common_CalculateShipping();
    	$keys = array(
    		'warehouseId' => $orderRow['warehouse_id'],
    		'countryId' => $addressRow['loa_country'],
    		'smCode' => $orderRow['sm_code'],
    		'weight' => $orderRow['lo_weight'],
        'customerCode' => $orderRow['customer_code'],
             'postcode'=>$addressRow['oab_postcode'],
    	);
        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);
    	$result = $objCalculate->getRate();
    	if($result['state'] == 0)
    		return is_array($result['error']) ? implode(',', $result['error']) : $result['error'];
       if($orderRow['sm_code']=='HKDHL'){
        $orderProcess=new Service_OrderProcess();
        $isRemote=$orderProcess->isRemoteCity($addressRow['loa_country'],$addressRow['loa_city'],$addressRow['loa_zipcode']);
        //是偏远的订单
        if($isRemote){
            $pianyuanFee=0;
            //偏远城市，计算偏远费
             if(!in_array($orderRow['sm_code'],array('ZCCQ'))){
                    $pianyuan = Service_OtherFee::getByField ( "PIANYUAN", "fee_code", "*" );
                if (! empty ( $pianyuan )) {
                    $customerFeeCondition = array (
                        'customer_code' => $orderRow['customer_code'] ,
                        'fee_id' => $pianyuan ['fee_id']
                    );
                    $customerOtherFee = Service_CustomerOtherFee::getByCondition ( $customerFeeCondition, '*' );
                    $pianyuanFee = $pianyuan ['fee_value'] ;
                    $cost = $pianyuan ['fee_amount'];
                    $discount = 1;

                    if ('1' == $pianyuan ['status']) {
                        // 杂费状态：可用
                        if (! empty ( $customerOtherFee )) {
                            if ($customerOtherFee [0] ['status'] == '1') {
                                // 客户杂费可用，则参与打折计算
                                $pianyuanFee = $customerOtherFee [0] ['discount'] * $pianyuanFee;
                                $discount = $customerOtherFee [0] ['discount'];
                            }
                        } else {
                            // 非默认费用且该客户无此项杂费设置，则此项费用不收
                            if ('0' == $pianyuan ['is_default_fee']) {
                                $pianyuanFee = 0;
                                $cost = 0;
                            }
                        }
                    } else {
                        // 杂费状态：不可用
                        $pianyuanFee = 0;
                        $cost = 0;
                    }
                    $pianyuanFee = sprintf('%.2f',$pianyuanFee);
                    $otherFee= array (
                        'currency_code' => $pianyuan ['fee_currency_code'],
                        'price' => $pianyuanFee,
                        'discount' => $discount,
                        'cost' => $cost,
                        'sp_code' => $pianyuan ['sp_code'],
                        'fee_id' => $pianyuan ['fee_id']
                    );
                }
             }
          

        }
       }
    	$fee = $result['data']['cost']['totalCost'];
        $cureencyCode = $result['data']['cost']['currency_code'];
    	$convert_fee = round($fee / $currencyRow['currency_rate'], 2);
		$smArray = array("BH-HKECM","BH-JE-POST","BH-US");
		if(in_array($orderRow['sm_code'],$smArray)){
			$weight = $result['data']['cost']['weight'];
			Service_LogisticsOrder::update(array('fee_weight'=>$weight),$orderRow['lo_id']);
		}
		
    	//冻结金额
    	$balanceRow = Service_CustomerBalance::getByField($customer_id, 'customer_id');
    	/* print_r($balanceRow);
    	echo $convert_fee; */
    	$able_fee = floatval($balanceRow['cb_value'] - $convert_fee);
		
    	//echo $able_fee;
        if($customerRow['cash_type']==1){
            if($able_fee < 0) return '账户余额不足，无法冻结金额';
        }
    	$hold_fee = $balanceRow['cb_hold_value'] + $convert_fee;
    	$uBalance['cb_value'] = $able_fee;
    	$uBalance['cb_hold_value'] = $hold_fee;
    	$uBalance['cb_update_time'] = date('Y-m-d H:i:s');
    	$uResult = Service_CustomerBalance::update($uBalance, $balanceRow['cb_id']);
    	//if(!$uResult) return '更新余额数据失败';
    	//记录余额日记
    	$aBalanceLog['customer_code'] = $customerRow['customer_code'];
    	$aBalanceLog['customer_id'] = $customer_id;
    	$aBalanceLog['cbl_type'] = 0;
    	$aBalanceLog['cbl_transaction_value'] = $convert_fee;
    	$aBalanceLog['cbl_value'] = $fee;
    	$aBalanceLog['currency_rate'] = $currencyRow['currency_rate'];
    	$aBalanceLog['currency_code'] = $cureencyCode ;//$customerRow['customer_currency'];
    	$aBalanceLog['cbl_note'] = '提交订单，冻结余额';
    	$aBalanceLog['user_id'] = -1;
    	$aBalanceLog['cbl_current_value'] = $able_fee;
    	$aBalanceLog['cbl_current_hold_value'] = $hold_fee;
    	$aBalanceLog['application_code'] = 'logistics';
		//$aBalanceLog['fee_id'] = $order_code;
    	$aBalanceLog['cbl_refer_code'] = $order_code;
    	$aBalanceLog['cbl_add_time'] = date('Y-m-d H:i:s');
        $aResult = Service_CustomerBalanceLog::add($aBalanceLog);
        if(!$aResult) return '记录余额日志失败';
       if(isset($otherFee)&&$otherFee['price']>0){
           $convert_pianyuan_fee = Service_Currency::converByCode($otherFee['currency_code'], $customerRow['customer_currency'], $otherFee['price']);
           $able_fee = floatval($able_fee - $convert_pianyuan_fee);
           $hold_fee=  floatval($hold_fee+$convert_pianyuan_fee);
               	$aBalanceLog['customer_code'] = $customerRow['customer_code'];
                $aBalanceLog['customer_id'] = $customer_id;
                $aBalanceLog['cbl_type'] = 0;
                $aBalanceLog['cbl_transaction_value'] = $convert_pianyuan_fee;
                $aBalanceLog['cbl_value'] = $otherFee['price'];
                $aBalanceLog['currency_rate'] = $currencyRow['currency_rate'];
                $aBalanceLog['currency_code'] = $otherFee['currency_code'] ;//$customerRow['customer_currency'];
                $aBalanceLog['cbl_note'] = '提交订单，冻结余额';
                $aBalanceLog['user_id'] = -1;
                $aBalanceLog['cbl_current_value'] = $able_fee;
                $aBalanceLog['cbl_current_hold_value'] = $hold_fee;
                $aBalanceLog['application_code'] = 'logistics';
                 $aBalanceLog['fee_id'] = $otherFee['fee_id'];
                $aBalanceLog['cbl_refer_code'] = $order_code;
                $aBalanceLog['cbl_add_time'] = date('Y-m-d H:i:s');
                $aResult = Service_CustomerBalanceLog::add($aBalanceLog);
                if(!$aResult) return '记录余额日志失败';
   
       }
       	$uBalance['cb_value'] = $able_fee;
    	$uBalance['cb_hold_value'] = $hold_fee;
        $uBalance['cb_update_time'] = date('Y-m-d H:i:s');
    	$uResult = Service_CustomerBalance::update($uBalance, $balanceRow['cb_id']);
    	$uOrder['shipping_fee_estimate'] = $convert_fee;
    	$uOrder['update_time'] = date('Y-m-d H:i:s');
    	Service_Orders::update($uOrder, $order_code, 'order_code');
    	return true;
    }	
	
    /**
     * ASN预扣费
     * @author william-fan
     */
    public function freezeASNFee($receiving_code, $customer_id) {
    	$customerRow = Service_Customer::getByField($customer_id);
    	$currencyRow = Service_Currency::getByField($customerRow['customer_currency'], 'currency_code');
    	$asnRow = Service_Receiving::getByField($receiving_code,'receiving_code');
    	$objOtherFeeCalculate = new Common_CalculateOtherFee();
    	$keys = array(
    			'warehouseId' => $asnRow['warehouse_id'],
    			'receiving_code'=>$receiving_code,
    	);
    	$objOtherFeeCalculate->setParams($keys);
    	$otherfeeResult = $objOtherFeeCalculate->getOtherFee('TIHUO'); //预扣提货费
        //print_r($otherfeeResult);
    	$tihuofee = $otherfeeResult['data']['otherFee']['tihuo']['price'];
    	
    	//冻结金额
    	$balanceRow = Service_CustomerBalance::getByField($customer_id, 'customer_id');
    	/* print_r($balanceRow);
    	 echo $convert_fee; */
    	$able_fee = floatval($balanceRow['cb_value']);
    	//echo $able_fee;
    	if($customerRow['cash_type']==1){
    		if($able_fee < 0) return '账户余额不足，无法冻结金额';
    	}
    	$hold_fee = $balanceRow['cb_hold_value'];
    	if($tihuofee>0){
    		//$convert_caozuo_fee = round($caozuofee / $currencyRow['currency_rate'], 2);
    		$convert_tihuuo_fee = Service_Currency::converByCode($otherfeeResult['data']['otherFee']['tihuo']['currency_code'], $customerRow['customer_currency'], $tihuofee);
    		$able_fee = $able_fee-$convert_tihuuo_fee;
    		 
    		$hold_fee+=$convert_tihuuo_fee;
    		 
    		$aBalanceLog['customer_code'] = $customerRow['customer_code'];
    		$aBalanceLog['customer_id'] = $customer_id;
    		$aBalanceLog['cbl_type'] = 0;
    		$aBalanceLog['cbl_transaction_value'] = $convert_tihuuo_fee;
    		$aBalanceLog['cbl_value'] = $tihuofee;
    		$aBalanceLog['currency_rate'] = $currencyRow['currency_rate'];
    		$aBalanceLog['currency_code'] = $otherfeeResult['data']['otherFee']['tihuo']['currency_code'];
    		$aBalanceLog['cbl_note'] = 'ASN提交扣提货费，冻结余额';
    		$aBalanceLog['user_id'] = -1;
    		$aBalanceLog['cbl_current_value'] = $able_fee;
    		$aBalanceLog['cbl_current_hold_value'] = $hold_fee;
    		$aBalanceLog['application_code'] = 1;
    		$aBalanceLog['cbl_refer_code'] = $receiving_code;
    		$aBalanceLog['cbl_add_time'] = date('Y-m-d H:i:s');
    		//$otherfee_caozuo=Service_OtherFee::getByField('caozuo','fee_code');
    		if($otherfeeResult['data']['otherFee']['tihuo']['fee_id']>0){
    			$aBalanceLog['fee_id'] = $otherfeeResult['data']['otherFee']['tihuo']['fee_id'];
    		}
    		 
    		$aResult = Service_CustomerBalanceLog::add($aBalanceLog);
    	}
    	$uBalance['cb_value'] = $able_fee;
    	$uBalance['cb_hold_value'] = $hold_fee;
    	$uResult = Service_CustomerBalance::update($uBalance, $balanceRow['cb_id']);
    	return true;
    }
      /**
     * 预扣其他费用
     * @author yao
     */
    public function freezeOtherFee($money,$currencyCode,$referCode,$otherFeeId,$note) {
        if(empty($this->customerId)){
            throw new Exception('客户ID为空');
        }
    	$currencyRow = Service_Currency::getByField($this->_customerRow['customer_currency'], 'currency_code');
    	$able_fee = floatval($this->_customerBalance['cb_value']);
    	//echo $able_fee;
    	if($this->_customerRow['cash_type']==1){
                if($able_fee < 0) {
                      throw new Exception('账户余额不足，无法冻结金额');
                }
    	}
    	$hold_fee = $this->_customerBalance['cb_hold_value'];
    	if($money>0){
    		$convertMoney = Service_Currency::converByCode($currencyCode, $this->_customerRow['customer_currency'], $money);
    		$able_fee = $able_fee-$convertMoney;
    		$hold_fee+=$convertMoney;
    		$aBalanceLog['customer_code'] = $this->_customerRow['customer_code'];
    		$aBalanceLog['customer_id'] = $this->customerId;
    		$aBalanceLog['cbl_type'] = 0;
    		$aBalanceLog['cbl_transaction_value'] = $convertMoney;
    		$aBalanceLog['cbl_value'] = $money;
    		$aBalanceLog['currency_rate'] = $currencyRow['currency_rate'];
    		$aBalanceLog['currency_code'] =$currencyCode;
    		$aBalanceLog['cbl_note'] = $note;
    		$aBalanceLog['user_id'] = -1;
    		$aBalanceLog['cbl_current_value'] = $able_fee;
    		$aBalanceLog['cbl_current_hold_value'] = $hold_fee;
    		$aBalanceLog['application_code'] = 1;
    		$aBalanceLog['cbl_refer_code'] = $referCode;
    		$aBalanceLog['cbl_add_time'] = date('Y-m-d H:i:s');
    		//$otherfee_caozuo=Service_OtherFee::getByField('caozuo','fee_code');
    		if($otherFeeId>0){
    			$aBalanceLog['fee_id'] = $otherFeeId;
    		}
    		 
    		$aResult = Service_CustomerBalanceLog::add($aBalanceLog);
    	}
        $uBalance['cb_value'] = $able_fee;
    	$uBalance['cb_hold_value'] = $hold_fee;
        $this->updateCustomerBalance($uBalance);
    	return true;
    }
    public function updateCustomerBalance($uBalance){
    	$uResult = Service_CustomerBalance::update($uBalance, $this->_customerBalance['cb_id']);
        if(!$uResult){
            throw new Exception('冻结费用失败');
        }
        foreach($uBalance as $key=>$value){
            if(isset($this->_customerBalance[$key])){
                $this->_customerBalance[$key]=$value;
            }
        }
        return $this;
    }
    /**
     * @author william-fan
     * @todo 订单预付费检查
     */
    public function freezeFeeCheck($order_code, $customer_id) {
    	$customerRow = Service_Customer::getByField($customer_id);
    	$currencyRow = Service_Currency::getByField($customerRow['customer_currency'], 'currency_code');
    	$orderRow = Service_Orders::getByField($order_code, 'order_code');
    	$addressRow = Service_OrderAddressBook::getByField($order_code, 'order_code');
    	$weight = Service_Orders::calculateWeight($order_code);
    	$orderProductsCondition = array(
    		'order_code'=>$order_code,
    	);
    	$orderProducts = Service_OrderProduct::getByCondition($orderProductsCondition);
    	$objCalculate = new Common_CalculateShipping();
    	$keys = array(
    			'warehouseId' => $orderRow['warehouse_id'],
    			'countryId' => $addressRow['oab_country_id'],
    			'smCode' => $orderRow['sm_code'],
    			'weight' => $weight,
    			'orderProducts' =>$orderProducts,
    			'order_code'=>$order_code, 
            'postcode'=>$addressRow['oab_postcode'],
    	);
        if($addressRow['oab_country_id']=='253'){
           //美国的要加入城市
            $citys = Service_City::getByCondition(array('country_id' => $addressRow['oab_country_id'],'city_name'=>$addressRow['oab_city'],'sm_code' => $orderRow['sm_code']));
            if(empty($citys)){
                $conditionCity = array(
                    'country_id'=>$addressRow['oab_country_id'],
                    'city_name'=>$addressRow['oab_city'],
                    'sm_code' =>'0'
                );
                $citys = Service_City::getByCondition($conditionCity,'*');
            }
            if(!empty($citys)){
                $keys['cityId'] = $citys[0]['city_id'];
            }
        }
        if($addressRow['oab_country_id']=='106'){
           //香港的要加入城市
           $citys = Service_City::getByCondition(array('country_id' => $addressRow['oab_country_id'],'city_name'=>$addressRow['oab_city'],'sm_code' => $orderRow['sm_code']));
           if(empty($citys)){
               $conditionCity = array(
                   'country_id'=>$addressRow['oab_country_id'],
                   'city_name'=>$addressRow['oab_city'],
                   'sm_code' =>'0'
               );
               $citys = Service_City::getByCondition($conditionCity,'*');
           }
            if(!empty($citys)){
                $keys['cityId'] = $citys[0]['city_id'];
            }
        }
        if($orderRow['sm_code']=='DGF-CARGO'){
            //获取空运相关的信息
            $orderShiping = Service_OrderShipping::getByField($order_code,'order_code');
            $keys['aircode'] = $orderShiping['destination'];
        }
    	$objCalculate->setParams($keys);
    	$result = $objCalculate->getRate();
    	if($result['state'] == 0){
    		return is_array($result['error']) ? implode(',', $result['error']) : $result['error'];
    	}else{
    		return true;
    	}
    }

    public static function unfreezeOtherFee($aOrder,$balanceLog,$log=''){
        $aCustomer = Service_Customer::getByField($aOrder['customer_id']);
        //if($aCustomer['cash_type']==2) return true;	//月结
        $aBalance = Service_CustomerBalance::getByField($aOrder['customer_id'], 'customer_id');
        if(empty($aBalance)) return '找不到客户账户余额记录';
        //处理
        $balanceRow = Service_CustomerBalance::getForUpdate($aBalance['cb_id']);
        $hold_value = $balanceRow['cb_hold_value'] - $balanceLog['cbl_transaction_value'];
        //允许冻结金额小于0
        //if($hold_value < 0) return '账户金额异常，冻结余额不足';
        $uBalance['cb_value'] = $balanceRow['cb_value'] + $balanceLog['cbl_transaction_value'];
        $uBalance['cb_hold_value'] = $hold_value;
        $uBalance['cb_update_time'] = date('Y-m-d H:i:s');
        $uResult = Service_CustomerBalance::update($uBalance, $balanceRow['cb_id']);
        //if(!$uResult) return '更新余额数据失败';
        //解冻日志
        $currencyRow= Service_Currency::getByField($aCustomer['customer_currency'],"currency_code","*");
        $aBalanceLog['customer_code'] = $aCustomer['customer_code'];
        $aBalanceLog['customer_id'] = $aCustomer['customer_id'];
        $aBalanceLog['cbl_type'] = 1;
        $aBalanceLog['cbl_transaction_value'] = $balanceLog['cbl_transaction_value'];
        $aBalanceLog['cbl_value'] = $balanceLog['cbl_value'];
        $aBalanceLog['currency_rate'] = $currencyRow['currency_rate'];
        $aBalanceLog['currency_code'] = $balanceLog['currency_code'];
        $aBalanceLog['cbl_note'] = $log?$log:'订单出货，解冻其它费用余额';
        $aBalanceLog['user_id'] = 0;
        $aBalanceLog['cbl_current_value'] = $uBalance['cb_value'];
        $aBalanceLog['cbl_current_hold_value'] = $uBalance['cb_hold_value'];
        $aBalanceLog['application_code'] = 1;
        $aBalanceLog['cbl_refer_code'] = $aOrder['order_code'];
        $aBalanceLog['cbl_add_time'] = date('Y-m-d H:i:s');
        $aBalanceLog['fee_id'] = $balanceLog['fee_id'];
        if($balanceLog['cbl_transaction_value']>0){
            $aResult = Service_CustomerBalanceLog::add($aBalanceLog);
            if($aResult){
                $uLogRow = array(
                    'un_cbl_id'=>$aResult
                );
                Service_CustomerBalanceLog::update($uLogRow,$balanceLog['cbl_id']);
            }
            return $aResult ? true : '记录其它费用余额日志失败';
        }
        return true;
    }

    /* @desc:只能用于【环球】提交订单时扣费，另外要注意此时并没有ship_order的数据
     *
     */
    public function deductFee( $orderCode ) {
        try{
            $this->init( $orderCode );
            //扣取运费
            $this->deductShipFee();
            //扣取各种杂费
            $this->deductOtherFee();
            //写入业务信息
            $this->addBusiness();
            //如果扣运费了
            $update = array(
                'shipping_fee_estimate' => 0,
                'update_time' => $this->_date
            );
            if( $this->_orderRow['deduct_ship_fee'] ) {
                //更新订单运费
                $update['shipping_fee_estimate'] = $this->_orderRow['shipping_fee_estimate'];
            }

            $result = Service_Orders::update( $update, $this->_orderRow['order_id'], 'order_id' );
            if( !$result )
                throw new Exception('更新订单费用失败');

            //如果不等于开始时的金额，就更新
            if( $this->_customerBalance['cb_value'] != $this->_customerBalance['old_cb_value'] ) {
                $update = array(
                    'cb_update_time' => $this->_date,
                    'cb_value' => $this->_customerBalance['cb_value']
                );
                $result = Service_CustomerBalance::update( $update, $this->_customerBalance['cb_id'] );
                if( !$result )
                    throw new Exception('扣取费用失败');
            }
            return true;
        } catch( Exception $e ) {
            if( 999 != $e->getCode() ) {
                $this->_error[] = $e->getMessage();
            }
            return false;
        }
    }

    /* @desc 扣取运费
     *
     */
    protected function deductShipFee() {
        $objCalculate = new Common_CalculateShipping();
        $keys = array(
            'warehouseId'       => $this->_orderRow['warehouse_id'],
            'countryId'         => $this->_orderRow['address']['oab_country_id'],
            'smCode'            => $this->_orderRow['sm_code'],
            'weight'            => $this->_orderRow['weight'],
            'order_code'       => $this->_orderRow['order_code'],
            'customerCode'     => $this->_orderRow['customer_code'],
            'postcode'          => $this->_orderRow['address']['oab_postcode'],
            'cityId'            => $this->_orderRow['address']['oab_city_id'],
        );
        if( $this->_orderRow['sm_code'] == 'DGF-CARGO'){
            //获取空运相关的信息
            $orderShipping = Service_OrderShipping::getByField( $this->_orderRow['order_code'], 'order_code' );
            $keys['aircode'] = $orderShipping['destination'];
        }

        $objCalculate->setParams( $keys );
        //获取运费
        $shipFee = $objCalculate->getRate();
        if( $shipFee['state'] == 0 ) {
            if( is_array( $shipFee['error'] ) ) {
                $this->_error = array_merge( $this->_error, $shipFee['error'] );
            } else {
                $this->_error[] = $shipFee['error'];
            }
            throw new Exception('扣费失败',999);
        }
        $this->_orderRow['deduct_ship_fee'] = false;//是否需要扣费
        //写运费日志 (注意自有渠道不扣费 )
        if( isset( $shipFee['data']['sm']['sm_channel'] ) && $shipFee['data']['sm']['sm_channel'] != '1' ) {
            //设置服务商
            $spCode = $shipFee['data']['sm']['sp_code'];
            if( !isset( $this->_serviceProvider[$spCode] ) ){
                $serviceProvider = Service_ServiceProvider::getByField( $spCode, 'sp_code' );
                if( empty( $serviceProvider ) )
                    throw new Exception('服务商不存在');

                $this->_serviceProvider[$spCode] = $serviceProvider;
            }

            $totalPrice = $shipFee['data']['cost']['totalCost'];//客户需要付的总运费

            $this->_orderRow['deduct_ship_fee'] = true;

            //应收（费用）
            $currencyCode = $shipFee['data']['cost']['currency_code'];
            //运费
            $shipPrice = $shipFee['data']['cost']['baseCost'] + $shipFee['data']['cost']['addCost'] + $shipFee['data']['cost']['pCost'];
            if( $shipFee['data']['sm']['sm_class_code'] == "CRP" ){
                $shipPrice += $shipFee['data']['cost']['regCost'];
            }
            $singleTicketPrice = isset( $shipFee['data']['cost']['baseTicketFee']) ? $shipFee['data']['cost']['baseTicketFee'] : 0;//单票费
            $fuelPrice = $shipFee['data']['cost']['baseBaf'];//燃油费

            //应付（成本）
            $costCurrencyCode = $shipFee['data']['cost']['cost_currency_code'];
            $shipCost = $shipFee['data']['cost']['cost'];//运费成本
            $singleTicketCost = $shipFee['data']['cost']['one_ticket_cbcost'];//单票费
            $fuelCost = $shipFee['data']['cost']['cost_baf'];//燃油费

            //设置订单的运费，用于后面更新
            $this->_orderRow['shipping_fee_estimate'] = $totalPrice;

            $note = '提交订单，扣取运费';
            //写入扣费日志
            $this->addDeductBalanceLog( $totalPrice, $currencyCode, $note );
            $this->addCostRecording( $shipFee );
            $this->addLogisticsCost( $shipFee );

            //添加运费应收
            $this->addIncomeLog( $shipPrice, $currencyCode, 'shipping', '运费', 'KG' );
            //添加单票费应收
            $this->addIncomeLog( $singleTicketPrice, $currencyCode, 'one_ticket_fee', '单票费用', 'PCE' );
            //添加燃油费应收
            $this->addIncomeLog( $fuelPrice, $currencyCode, 'additional_fee', '燃油附加费用', 'PCE' );

            //添加运费应付
            $this->addPaymentLog( $shipCost, $costCurrencyCode, $spCode, 'shipping', '运费', 'KG' );
            //添加单票费应付
            $this->addPaymentLog( $singleTicketCost, $costCurrencyCode, $spCode, 'one_ticket_fee', '单票费用', 'PCE' );
            //添加燃油费应付
            $this->addPaymentLog( $fuelCost, $costCurrencyCode, $spCode, 'additional_fee', '燃油附加费用', 'PCE' );
        }

    }

    /* @desc 扣取杂费
     *
     */
    protected function deductOtherFee() {
        $objOtherFeeCalculate = new Common_CalculateOtherFee();
        $keys = array(
            'warehouseId'   => $this->_orderRow['warehouse_id'],
            'countryId'     => $this->_orderRow['address']['oab_country_id'],
            'smCode'        => $this->_orderRow['sm_code'],
            'weight'        => $this->_orderRow['weight'],
            'order_code'   => $this->_orderRow['order_code'],
        );
        $objOtherFeeCalculate->setParams($keys);
        $costFeeCode = array(
            'CAOZUO','BAOGUAN', 'YUNSHU', 'RUKU', 'WULIUCAOZUO',
            'WULIAO','GUANLI','JIANGUANYUNSHU','CZBGF',
            'BHDPDRemoteFee','GFX','SXZ','POD','4PX-DUTY','4PXPYDQ'
        );
        if( $this->_orderRow['sm_code'] == 'DHL-THL') {
            $costFeeCode[] = 'THPIANYUAN';//偏远费
            $costFeeCode[] = 'THFBATAX';//关税预付金
        } else {
            $costFeeCode[] = 'PIANYUAN';//偏远费
            $costFeeCode[] = 'FBATAX';//关税预付金
        }

        $utCodes = Service_OtherFeeProcess::getUtCode();

        foreach($costFeeCode as $code){
            if( !in_array( $code, array( 'GTI','ODI','GTI','GRI' ) ) ){
                $result = $objOtherFeeCalculate->getOtherFee( $code );
            }
            $otherFee = array();
            switch( $code ) {
                case 'CAOZUO':
                    $otherFee = $result['data']['otherFee']['caozuo'];
                    break;
                case 'BAOGUAN':
                    $otherFee = $result['data']['otherFee']['baoguan'];
                    break;
                case 'YUNSHU':
                    $otherFee = $result['data']['otherFee']['yunshu'];
                    break;
                case 'RUKU':
                    $otherFee = $result['data']['otherFee']['ruku'];
                    break;
                case 'WULIUCAOZUO':
                    $otherFee = $result['data']['otherFee']['wuliucaozuo'];
                    break;
                case 'PIANYUAN':
                    if( $this->_orderRow['sm_code'] != "BH-DPD" ) {
                        $otherFee = $result['data']['otherFee']['pianyuan'];
                    }
                    break;
                case 'WULIAO':
                    $otherFee = $result['data']['otherFee']['wuliao'];
                    break;
                case 'GUANLI':
                    $otherFee = $result['data']['otherFee']['guanli'];
                    break;
                case 'JIANGUANYUNSHU':
                    $otherFee = $result['data']['otherFee']['jianguanyunshu'];
                    break;
                case 'BHDPDRemoteFee':
                    if( $this->_orderRow['sm_code'] == "BH-DPD" && $this->_orderRow['is_remote_city'] == "1" ) {
                        $otherFee = $result['data']['otherFee']['BHDPDRemoteFee'];
                    }
                    break;
                case 'FBATAX':
                    if( $this->_orderRow['is_fba_tax'] == 1 ) {
                        $otherFee = $result['data']['otherFee']['fbatax'];
                    }
                    break;
                case 'GFX':
                    $otherFee = $result['data']['otherFee']['gfx'];
                    break;
                case 'SXZ':
                    $otherFee = $result['data']['otherFee']['sxz'];
                    break;
                case 'POD':
                    if( $this->_orderRow['sm_code'] == "4PX-LYT_GH" && $this->_orderRow['is_pod'] == '1' ) {
                        $otherFee = $result['data']['otherFee']['pod'];
                    }
                    break;
                case '4PX-DUTY':
                    $otherFee = $result['data']['otherFee']['4pxduty'];
                    break;
                case '4PXPYDQ':
                    if( $this->_orderRow['sm_code'] == "4PX-HKDHL" ) {
                        $otherFee = $result['data']['otherFee']['4pxpydq'];
                    }
                    break;
                case 'THFBATAX':
                    $otherFee = @$result['data']['otherFee']['thFbaTax'];
                    break;
                case 'THPIANYUAN':
                    $otherFee = @$result['data']['otherFee']['thRemote'];
                    break;
                default:
                    break;
            }
            if( $otherFee ) {
                if($otherFee['price'] > 0 ) {
                    $results[] = $otherFee;
                }
                if( false == $this->checkOtherFee( $otherFee ) ){
                    throw new Exception('扣取杂费失败');
                }
                $utCode = $utCodes[$code];
                $note = '提交订单，扣'.$otherFee['fee_name'];
                if( !$utCode ) {
                    throw new Exception($otherFee['fee_name'].'未配置UT_CODE');
                }
                if( $otherFee['price'] > 0 ){
                    //写入扣费日志
                    $this->addDeductBalanceLog( $otherFee['price'], $otherFee['currency_code'], $note, $otherFee['fee_id'], $otherFee['customer_ft_code'] );
                }
                //添加应收记录
                $this->addIncomeLog( $otherFee['price'], $otherFee['currency_code'], $otherFee['customer_ft_code'], $otherFee['fee_name'], $utCode );
                //添加应付记录
                $this->addPaymentLog( $otherFee['cost'], $otherFee['currency_code'], $otherFee['sp_code'], $otherFee['customer_ft_code'], $otherFee['fee_name'], $utCode );
                //添加成本费用明细
                $this->addFeeCostDetail( $otherFee );
            }
        }
        //var_dump(5555);
        // print_r($results);exit;

        //扣保险
        if( $this->_orderRow['insurance'] == 1 ) {
            $param = array(
                'insuranceRate' => $this->_orderRow['insurance_rate'],
                'country' => $this->_orderRow['address']['oab_country_id'],
                'dealPrice' => $this->_orderRow['charge'],
                'dealCurrency'=>$this->_orderRow['currency_code'],
                'returnCost'=>true
            );
            $pObj = new Service_OtherFeeProcess();
            $insurance = $pObj->getAmount( $this->_orderRow['warehouse_id'], $this->_orderRow['insurance_code'] ,$param );
            if( $insurance === false )
                throw new Exception('扣除保险费失败');

            foreach( $insurance['detail'] as $value ) {
                if( $value['amount'] == 0 )
                    continue;

                $feeItem = Service_OtherFee::getByField( $value['feeCode'],'fee_code');
                if( empty( $feeItem ) )
                    return '费用项目不存在';

                $note = '订单出货，扣'.$feeItem['fee_name'].'费';

                $otherFee = array(
                    'cost_currency_code'      => 'RMB',
                    'currency_code'            => 'RMB',
                    'price'                     => $value['amount'],
                    'discount'                  => 1,
                    'cost'                       => $value['cost'],
                    'sp_code'                   => $feeItem['sp_code'],
                    'fee_id'                    => $feeItem['fee_id'],
                    'fee_name'                  => $feeItem['fee_name'],
                    'ft_code'                   => $feeItem['ft_code']
                );

                //写入扣费日志
                $this->addDeductBalanceLog( $otherFee['amount'], 'RMB', $note, $otherFee['fee_id'], $otherFee['ft_code'] );
                //添加应收记录
                $this->addIncomeLog( $otherFee['amount'], 'RMB', $otherFee['ft_code'], $otherFee['fee_name'], 'PCE' );
                //添加应付记录
                $this->addPaymentLog( $otherFee['cost'], 'RMB', $otherFee['sp_code'], $otherFee['ft_code'], $otherFee['fee_name'], 'PCE' );
                //添加成本费用明细
                $this->addFeeCostDetail( $otherFee );
            }
        }
    }

    /* @检查杂费是否缺少字段
     *
     */
    protected function checkOtherFee( $otherFee ) {
        if( !isset( $otherFee['price'] ) || $otherFee['price'] === '')
            return false;
        if( !isset( $otherFee['currency_code'] ) || $otherFee['currency_code'] === '')
            return false;
        if( !isset( $otherFee['fee_id'] ) || $otherFee['fee_id'] === '')
            return false;
        if( !isset( $otherFee['fee_name'] ) || $otherFee['fee_name'] === '')
            return false;
        if( !isset( $otherFee['customer_ft_code'] ) || $otherFee['customer_ft_code'] === '')
            return false;

        return true;
    }

    public function getError() {
        return $this->_error;
    }

    protected function setError( $error ) {
        $this->_error[] = $error;
    }

    protected function init( $orderCode ) {
        $this->setOrder( $orderCode );
        $this->setCustomerRow( $this->_orderRow['customer_id'] );
        //设置客户币种
        $this->setCurrency( $this->_customerRow['customer_currency'] );
        $this->setCustomerBalance();
    }


    /* @desc 添加扣费日志
     * @param double $amount 金额
     * @param string $currencyCode 币种
     * @param int    $feeId 费用ID
     * @param string $applicationCode 代码
     * @param string $note 扣费备注
     * @return none;
     */
    protected function addDeductBalanceLog( $amount, $currencyCode, $note = '', $feeId = '', $applicationCode = '' ) {
        if( $amount < 0 ) {
            throw new Exception('费用必须是正整数');
        }
        //customer_balance表的币种是人民币，customer表的币种也是人民币
        $translatedAmount = $this->translate( $currencyCode, $this->_customerRow['customer_currency'], $amount );
        if( $translatedAmount === false ) {
            throw new Exception('币种转换失败');
        }

        $leftAmount = $this->_customerBalance['cb_value'] - $translatedAmount;
        //非月结客户需要判断余额是否足够
        if( $this->_customerRow['cash_type'] == 1 && $leftAmount < 0) {
            throw new Exception('账户余额不足，无法扣费');
        }
        //减少可用余额
        $this->_customerBalance['cb_value']             = $leftAmount;

        $aBalanceLog['customer_code']                  = $this->_customerRow['customer_code'];
        $aBalanceLog['customer_id']                    = $this->_customerRow['customer_id'];
        $aBalanceLog['cbl_type']                        = 2;
        $aBalanceLog['cbl_transaction_value']         = $translatedAmount;
        $aBalanceLog['cbl_value']                       = $amount;
        $aBalanceLog['currency_rate']                   = $this->_currencyRow['currency_rate'];
        $aBalanceLog['currency_code']                   = $currencyCode;
        $aBalanceLog['cbl_note']                         = $note;
        $aBalanceLog['user_id']                          = 0;
        $aBalanceLog['cbl_current_value']              = $leftAmount;
        $aBalanceLog['cbl_current_hold_value']        = $this->_customerBalance['cb_hold_value'];
        $aBalanceLog['fee_id']                           = $feeId;
        $aBalanceLog['application_code']               = $applicationCode;
        $aBalanceLog['cbl_refer_code']                 = $this->_orderRow['order_code'];
        $aBalanceLog['cbl_add_time']                    = $this->_date;

        $aResult = Service_CustomerBalanceLog::add($aBalanceLog);
        if( !$aResult )
            throw new Exception('添加费用日志出错');

    }

    /*
     * @desc 添加应收记录
     * @param numeric $amount 金额
     * @param string $currencyCode 币种
     * @param string  $ftCode 费用类型代码
     * @param string $utCode 计费单位代码 比如按千克计费
     * @return none;
     */
    protected function addIncomeLog( $amount, $currencyCode, $ftCode, $note, $utCode ) {
        if( $amount <= 0 )
            return;

        //customer_balance表的币种是人民币，customer表的币种也是人民币
        $translatedAmount = $this->translate( $currencyCode, $this->_customerRow['customer_currency'], $amount );
        if( $translatedAmount === false ) {
            throw new Exception('币种转换失败');
        }
        //应收记录
        $this->_income[] = array(
            'customer_code'         => $this->_orderRow['customer_code'],
            'ft_code'               => $ftCode,
            'ut_code'               => $utCode,
            'sm_code'               => $this->_orderRow['sm_code'],
            'bi_amount'             => $translatedAmount,//客户金额
            'bi_org_amount'        => $amount,//原金额
            'currency_code'        => $currencyCode,//原币种
            'currency_rate'        => $this->_currencyRate[ $currencyCode ],//原币种当前的汇率
            'bi_chargeable_time'  => $this->_date,
            'bi_note'               => $note,
        );
    }

    /*
     * @desc 添加应付记录
     * @param numeric $amount 金额
     * @param string $currencyCode 币种
     * @param string $spCode 服务商代码
     * @param numeric $rate 汇率
     * @param string  $ftCode 费用类型代码
     * @param string $utCode 计费单位代码 比如按千克计费
     * @return none;
     */
    protected function addPaymentLog( $amount, $currencyCode, $spCode, $ftCode, $note, $utCode ) {

        if( $amount <= 0 || $spCode === '' || $spCode === null )
            return;

        if( !isset( $this->_serviceProvider[$spCode] ) ){
            $serviceProvider = Service_ServiceProvider::getByField( $spCode, 'sp_code' );
            if( empty( $serviceProvider ) )
                throw new Exception('服务商不存在');

            $this->_serviceProvider[$spCode] = $serviceProvider;
        }
        //customer_balance表的币种是人民币
        $translatedAmount = $this->translate( $currencyCode, $this->_serviceProvider[$spCode]['currency_code'], $amount );
        if( $translatedAmount === false ) {
            throw new Exception('币种转换失败');
        }

        $this->_payment[] = array(
            'sp_code'               => $spCode,       //服务商代码
            'ft_code'               => $ftCode,
            'ut_code'               => $utCode,
            'sm_code'               => $this->_orderRow['sm_code'],
            'bp_amount'             => $translatedAmount,//服务商结算金额
            'bp_org_amount'        => $amount,          //原金额
            'currency_code'        => $currencyCode, //原币种
            'currency_rate'        => $this->_currencyRate[ $currencyCode ],//原币种当前的汇率
            'bp_chargeable_time'  => $this->_date,
            'bp_note'               => $note,
        );
    }

    /* @desc 添加费用成本明细表
     * @param array $fee 费用数组
     * @return none;
     */
    protected function addFeeCostDetail( $fee ) {
        $feeDetail = $costDetail = array();
        if( $fee['price'] > 0 ) {
            $translatedAmount = $this->translate( $fee['currency_code'], $this->_customerRow['customer_currency'], $fee['price'] );
            if( $translatedAmount === false )
                throw new Exception('币种转换失败');

            $feeDetail = array(
                'fee_amount_customer'           => $translatedAmount,                                        //费用金额（客户）
                'fee_currency_code_customer'   => $this->_customerRow['customer_currency'],              //费用币种（客户）
                'discount_customer'             => $fee['discount'],                       //折扣率（客户）（1=100%）
            );
        }
        if(  $fee['cost'] > 0 ) {
            if( !isset( $this->_serviceProvider[$fee['sp_code']] ) ) {
                $serviceProvider = Service_ServiceProvider::getByField( $fee['sp_code'], 'sp_code' );
                if( empty( $serviceProvider ) )
                    throw new Exception('服务商不存在');

                $this->_serviceProvider[ $fee['sp_code'] ] = $serviceProvider;
            }
            $spCurrencyCode = $this->_serviceProvider[$fee['sp_code']]['currency_code'];
            $translatedAmount = $this->translate( $fee['currency_code'], $spCurrencyCode, $fee['cost'] );
            if( $translatedAmount === false )
                throw new Exception('币种转换失败');

            $costDetail = array(
                'cost_amount_org'               => $fee['cost'],                              //成本金额（原始）
                'cost_currency_code_org'       => $fee['currency_code'],                     //成本币种（原始）
                'cost_amount_sp'                => $fee['cost'],                                        //成本金额（服务商）
                'cost_currency_code_sp'        => $spCurrencyCode,                   //成本币种（服务商）
                'sp_code'                        => $fee['sp_code'],                           //服务商代码
            );
        }
        //注意提交订单时，ship_order还没有数据
        if( !empty( $feeDetail ) || !empty( $costDetail ) ) {
            $fee_cost_common    = array(
                'code_number'                    => $this->_orderRow['order_code'],                    //单号
                'code_type'                      => 1,                                                   //单号类型（1:区内单 2：区外单 3：ASN单）
                'customer_code'                 => $this->_orderRow['customer_code'],                 //客户代码
                'reference_no'                  => $this->_orderRow['reference_no'],                  //客户参考号
                'tracking_number'               => '',                   //服务商单号（跟踪号）
                'sm_code'                        => $this->_orderRow['sm_code'],                        //运输方式代码
                'country_code'                  => $this->_orderRow['address']['country_code'],                        //国际简称（二字码）
                'fee_code'                       => $fee['customer_ft_code'],        //费用编号
                'fee_name'                       => $fee['fee_name'],        //费用名称
                'fee_amount_org'                => $fee['price'],                             //费用金额（原始）
                'fee_currency_code_org'        => $fee['currency_code'],                   //费用币种（原始）
                'price_batch_number'           => $fee['price_batch_number'],//运输价格编号
                'currency_batch_number'        => $this->_currencyRow['currency_batch_number'],           //货币汇率编号
                'fee_time'                       => $this->_date,                                               //扣费时间
                'fee_time_recalculate'          => $this->_date,                                              //重新扣费时间
                'ip'                               => Common_Common::getIP(),                                    //扣费操作IP
                'ip_recalculate'                 => Common_Common::getIP(),                                    //重新扣费操作IP
                'operator'                        => 0,                         //扣费操作人
                'operator_recalculate'          => '',                         //重新扣费操作人
            );
            $detail  = array_merge( $feeDetail, $costDetail, $fee_cost_common );
            $result = Service_FeeAndCostDetail::add( $detail );
            if( !$result ) {
                throw new Exception( '添加费用明细失败' );
            }
        }
    }

    protected  function addBusiness() {
        $businessArr = array(
            'ds_code'                    => 'so',
            'customer_code'             => $this->_customerRow['customer_code'],
            'warehouse_id'              => $this->_orderRow['warehouse_id'],
            'sm_code'                    => $this->_orderRow['sm_code'],
            'bb_volume_weight'          => $this->_orderRow['so_weight'],
            'bb_charge_weight'          => $this->_orderRow['so_weight'],
            'bb_delivered_weight'      => $this->_orderRow['so_weight'],
            'bb_pieces'                  => $this->_orderRow['parcel_quantity'],
            'bb_declared_value'         => $this->_orderRow['parcel_declared_value'],
            'bb_declared_currency_code' => 'USD',
            'country_code'               => $this->_orderRow['address']['country_code'],
            'bb_postcode'                => $this->_orderRow['address']['oab_postcode'],
            'bb_charge_time'             => $this->_orderRow['add_time'],
            'bb_declared_time'          => $this->_date, //发货时间 此时间与服务商对接
            'bb_sales_id'                => $this->_customerRow['customer_saler_user_id'],
            'bb_refer_code'              => $this->_orderRow['order_code'],
            'bb_service_number'         => $this->_orderRow['ref_tracking_number'],//ref_tracking_number
            'bb_reference_no'            => $this->_orderRow['reference_no'],
        );
        $bsObj          = new Service_BusinessProcess();
        $businessResult = $bsObj->businessFee( $businessArr, $this->_income, $this->_payment);
        if($businessResult['state'] !='1' ){
            throw new Exception( $businessResult['message'] );
        }
    }

    protected function addCostRecording( $shipFee ) {
        $costCurrencyCode = $shipFee['data']['cost']['cost_currency_code'];
        $spCode = $shipFee['data']['sm']['sp_code'];
        $providerCurrency = $this->_serviceProvider[$spCode]['currency_code'];
        //这里只是为了获取汇率而已
        $transAmount = $this->translate( $costCurrencyCode, 'CNY', 1);
        $transAmount = $this->translate( $providerCurrency, 'CNY', 1);

        //成本费
        $costFee        = $shipFee['data']['cost']['cost'];
        //单票成本
        $ticketCbCost  = isset( $shipFee['data']['cost']['one_ticket_cbcost']) ? $shipFee['data']['cost']['one_ticket_cbcost'] : 0;
        //燃油附加费
        $fuelSurcharge            = $shipFee['data']['cost']['cost_baf'];
        if( $shipFee['data']['sm']['sm_class_code']=="CRP" || $shipFee['data']['sm']['sm_class_code'] == "CPS" ){
            $total = $shipFee['data']['cost']['cost'] + $ticketCbCost ;
            $fuelSurcharge = 0;
        }else{
            $total = $shipFee['data']['cost']['cost']  + $fuelSurcharge;
        }

        $costRecording = array(
            'order_code'                  => $this->_orderRow['order_code'],
            'customer_code'              => $this->_orderRow['customer_code'],
            'reference_no'               => $this->_orderRow['reference_no'],
            'tracking_number'           => '',
            'sm_code'                    => $this->_orderRow['sm_code'],
            'country_id'                 => $this->_orderRow['address']['oab_country_id'],
            'weight'                     => $this->_orderRow['weight'],
            'cost_fee'                  => $costFee,
            'ticket_fare'               => $ticketCbCost,
            'fuel_addons'               => $fuelSurcharge,
            'total_fee'                 => $total,
            'price_batch_number'        => $shipFee['data']['cost']['price_batch_number'],   //价格编号,用于重算
            'currency_batch_number'     => $this->_currencyRate[$costCurrencyCode]['currency_batch_number'],                              //汇率编号，用于重算
            'sm_baf'                     => $shipFee['data']['sm']['sm_baf'],                 //燃油附加费率,用于重算
            'currency_code'             => $shipFee['data']['cost']['cost_currency_code'],   //成本币种
            'currency_rate'             => $costCurrencyCode == 'CNY' ? 1 : $this->_currencyRate[$costCurrencyCode]['currency_rate'] ,                   //成本币种汇率
            'provider_currency_code'    => $providerCurrency,               //服务商币种
            'provider_currency_rate'    => $providerCurrency == 'CNY' ? 1 : $this->_currencyRate[$providerCurrency]['currency_rate'],               //服务商币种汇率
            'add_time'                   => $this->_date,
            'update_time'                => $this->_date,
        );
        $result = Service_CostRecording::add( $costRecording );
        if( !$result )
            throw new Exception('扣取杂费失败1');
    }

    /* @desc 添加运费记录
     *
     */
    protected function addLogisticsCost( $shipFee ) {
        //运费
        $shipPrice = $shipFee['data']['cost']['baseCost'] + $shipFee['data']['cost']['addCost'] + $shipFee['data']['cost']['pCost'];
        if( $shipFee['data']['sm']['sm_class_code'] == "CRP" ){
            $shipPrice +=  $shipFee['data']['cost']['regCost'];
        }

        $ticketFare = isset( $shipFee['data']['cost']['baseTicketFee'] ) ? $shipFee['data']['cost']['baseTicketFee'] : 0;

        //燃油附加费
        $fuelFee = $shipFee['data']['cost']['baseBaf'];
        
        if( $shipFee['data']['sm']['sm_class_code']=="CRP" || $shipFee['data']['sm']['sm_class_code']=="CPS" ){
            //平邮挂号收单票费，不收燃油费
            $fuelFee = 0;
        } else {
            //快递收燃油费，不收单票费
            $ticketFare = 0;
        }

        $totalFee = $shipPrice + $ticketFare + $fuelFee;

        //仅是为了获取汇率
        $this->translate( $shipFee['data']['cost']['currency_code'], 'RMB', 1 );

        //生成一条运费记录
        $logisticsCost = array(
            'order_code'                => $this->_orderRow['order_code'],
            'customer_code'             => $this->_orderRow['customer_code'],
            'reference_no'              => $this->_orderRow['reference_no'],
            'tracking_number'           => '',
            'sm_code'                   => $this->_orderRow['sm_code'],
            'country_id'                => $this->_orderRow['address']['oab_country_id'],
            'weight'                    => $this->_orderRow['weight'],
            'transport_fee'             => $shipPrice,
            'ticket_fare'               => $ticketFare,
            'fuel_addons'               => $fuelFee,
            'total_fee'                 => $totalFee,
            'currency_code'             => $shipFee['data']['cost']['currency_code'],    //运输（费用）销售币种
            'currency_rate'             => $this->_currencyRate[$shipFee['data']['cost']['currency_code']]['currency_rate'],    //运输（费用）销售币种汇率
            'smc_discount'              => $shipFee['data']['sm']['customer_discount'],  //客户运输方式折扣
            'price_batch_number'        => $shipFee['data']['cost']['price_batch_number'], //价格编号,用于重算
            'sm_baf'                    => $shipFee['data']['sm']['sm_baf'],             //燃油附加费率,用于重算
            'customer_currency_code'    => $this->_currencyRow['currency_code'],           //客户币种
            'customer_currency_rate'    => $this->_currencyRow['currency_rate'],           //客户币种汇率
            'add_time'                  => $this->_date,
            'update_time'               => $this->_date,
        );
        $result = Service_LogisticsCost::add( $logisticsCost );
        if( !$result )
            throw new Exception('扣取运费失败');

    }

    /**
     * @todo 转换币种
     * @author gilbert
     * @param string $fromCurrencyCode 原币种
     * @param string $toCurrencyCode   目标币种
     * @param double $amount            金额
     */
    protected function translate( $fromCurrencyCode, $toCurrencyCode, $amount ){
        if($fromCurrencyCode == '' || $fromCurrencyCode == '' || !is_numeric( $amount )){
            return false;
        }
        if( $fromCurrencyCode == $toCurrencyCode){
            return $amount;
        }
        $fromRate = $toRate = 1;
        if( !isset( $this->_currencyRate[ $fromCurrencyCode ] ) ) {
            $row_start = Service_Currency::getByField( $fromCurrencyCode, 'currency_code' );
            if( empty( $row_start ) || empty( $row_start['currency_rate'] ) ){
                return false;
            }
            $fromRate = $row_start['currency_rate'];
            $this->_currencyRate[ $fromCurrencyCode ] = $row_start;
        } else {
            $fromRate = $this->_currencyRate[ $fromCurrencyCode ]['currency_rate'];
        }

        if( !isset( $this->_currencyRate[ $toCurrencyCode ] ) ) {
            $row_end = Service_Currency::getByField( $toCurrencyCode, 'currency_code' );
            if( empty( $row_end ) || empty( $row_end['currency_rate'] ) ){
                return false;
            }
            $toRate = $row_end['currency_rate'];
            $this->_currencyRate[ $toCurrencyCode ] = $row_end;
        } else {
            $toRate = $this->_currencyRate[ $toCurrencyCode ]['currency_rate'];
        }

        $transValue = ( $amount * $fromRate ) / $toRate;
        return sprintf( '%.2f', $transValue );
    }

    public function returnFee( $orderCode ) {
        try{
            $this->init( $orderCode );
            $logs = Service_CustomerBalanceLog::getByCondition( array( 'cbl_refer_code' => $orderCode, 'cbl_type' => 2 ) );
            if( $logs ) {
                foreach( $logs as $value ) {
                    $this->addReturnBalanceLog( $value );
                }
            }
            if( $this->_customerBalance['cb_value'] != $this->_customerBalance['old_cb_value']){
                $update = array(
                    'cb_update_time' => $this->_date,
                    'cb_value' => $this->_customerBalance['cb_value']
                );
                $result = Service_CustomerBalance::update( $update, $this->_customerBalance['cb_id'] );
                if( !$result )
                    throw new Exception('退费失败');
            }
            //删除应收应付
            $businessBill = Service_BilBusinessAttach::getByField( $this->_orderRow['order_code'], 'bb_refer_code' );
            if( $businessBill ) {
                Service_BilIncome::delete( $businessBill['bb_id'], 'bb_id' );

                Service_BilPayment::delete( $businessBill['bb_id'], 'bb_id' );

                $result = Service_BilBusinessAttach::delete( $businessBill['bb_id'], 'bb_id' );
                if( !$result )
                    throw new Exception('退费失败');

                $result = Service_BilBusiness::delete( $businessBill['bb_id'], 'bb_id' );
                if( !$result )
                    throw new Exception('退费失败');
            }
            //非自有渠道才会有
            Service_CostRecording::delete( $orderCode, 'order_code');
            Service_LogisticsCost::delete( $orderCode, 'order_code' );

            //有应收或应付才会有数据
            Service_FeeAndCostDetail::delete( $orderCode, 'code_number' );

            return true;
        } catch( Exception $e ) {
            if( 999 != $e->getCode() ) {
                $this->_error[] = $e->getMessage();
            }
            return false;
        }
    }

    /* @desc 添加扣费日志
     * @param array $log 原扣费日志
     * @return none;
     */
    protected function addReturnBalanceLog( $log ) {

        if( $log['cbl_note'] == '提交订单，扣取运费' ) {
            $note = '拦截订单，返还运费';
        } else {
            $feeItem = array();
            if( $log['fee_id'] )
                $feeItem = Service_OtherFee::getByField( $log['fee_id'] );

            $note = $feeItem ? '拦截订单，返还'.$feeItem['fee_name'] : '拦截订单，返还费用';
        }
        //减少可用余额
        $this->_customerBalance['cb_value']             = $this->_customerBalance['cb_value'] + $log['cbl_transaction_value'];

        $aBalanceLog['customer_code']                  = $this->_customerRow['customer_code'];
        $aBalanceLog['customer_id']                    = $this->_customerRow['customer_id'];
        $aBalanceLog['cbl_type']                        = 3;
        $aBalanceLog['cbl_transaction_value']         = $log['cbl_transaction_value'];
        $aBalanceLog['cbl_value']                       = $log['cbl_value'];
        $aBalanceLog['currency_rate']                   = $log['currency_rate'];
        $aBalanceLog['currency_code']                   = $log['currency_code'];
        $aBalanceLog['cbl_note']                         = $note;
        $aBalanceLog['user_id']                          = 0;
        $aBalanceLog['cbl_current_value']              = $this->_customerBalance['cb_value'];
        $aBalanceLog['cbl_current_hold_value']        = $this->_customerBalance['cb_hold_value'];
        $aBalanceLog['fee_id']                           = $log['fee_id'];
        $aBalanceLog['application_code']               = $log['application_code'];
        $aBalanceLog['cbl_refer_code']                 = $log['cbl_refer_code'];
        $aBalanceLog['cbl_add_time']                    = $this->_date;

        $aResult = Service_CustomerBalanceLog::add( $aBalanceLog );
        if( !$aResult )
            throw new Exception('添加费用日志出错');

    }

}