<?php
class Service_ReceivingProcess
{
    protected $_asnCode = null;
    protected $_receiving = array();
    protected $_receivingDetail = array();
    protected $_errorArr = array();
    protected $_params = array();
    protected $_date = '';

    //收货类型
    public static function getAsnType()
    {
        return Common_Type::receivingType('auto');
    }

    //asn状态
    public static function getStatus()
    {
        return Common_Status::receivingStatus('auto');
    }

    //asnDetail状态
    public static function getDetailStatus()
    {
        return Common_Status::receivingDetailStatus('auto');
    }


    public function __construct()
    {
        $this->_date = date('Y-m-d H:i:s');
    }

    /*
     * @收货
     * @return array('state','error','message')
     */
    public function submitReceived($params = array(),$weight='0')
    {
        $result = array(
            'state' => 0,
            'error' => array(),
            'code' => array(),
            'message' => '',
            'qcParam'=>array(),
        );
       
 
        $db = Service_ReceivingDetail::getModelInstance()->getAdapter();
        $db->beginTransaction();
        try {
            $asnDetail = Service_ReceivingDetail::getByCondition(array('rd_id_arr' => $params), '*');
            if (empty($asnDetail)) {
                $result['error'][] = array('errorCode' => '10002', 'errorMsg' => 'Not Data');
                return $result;
            }
            foreach ($asnDetail as $key => $val) {
                if ($val['rd_status'] > 0) {
                    $result['error'][] = array(
                        'errorCode' => '10001',
                        'errorMsg' => Ec::Lang('operationFail') . ' BarCode:' . $val['product_barcode'] . ' ' .'收货中,请刷新页面'
                    );
                }
            }
            $asnCode = $asnDetail[0]['receiving_code'];
            $asnObj = new Service_Receiving();
            $asnRow = $asnObj->getByField($asnDetail[0]['receiving_id'], 'receiving_id');
            $status=self::getStatus();
            if(!in_array($asnRow['receiving_status'],array('2','3','4','5','6'))){
                $result['error'][] = array(
                    'errorCode' => '10001',
                    'errorMsg' => '收货单状态为：'.$status[$asnRow['receiving_status']].' 不允许操作收货.',
                );
            }
           
            if (!empty($result['error'])) {
                return $result;
            }
             if(!($weight && $weight>0)){
          			throw new Exception("ASN需要填写重量,且重量是大于0的数字");
                }
            //假如是提货的情况
          	// 需要提货的ASN，在收货时，要填写总重，以实际总重进行实扣
            $receinvRow = array('receiving_status' =>6, 'receiving_update_time' => $this->_date,'netweight'=>$weight);
            //查看是否已经收过提货费
    		$biatt = Service_BilBusinessAttach::getByField($asnCode,'bb_refer_code');

            /*****************************************
             * [ 杂费解冻->扣款->写入财务数据 begin ]*
             *****************************************
             */
            $objOtherCalculte = new Common_CalculateOtherFee();
            $keys = array(
                'warehouseId' => $asnRow['warehouse_id'],
                'receiving_weight' => $weight,
                'receiving_code'=>$asnCode,
            );
            $objOtherCalculte->setParams($keys);
            //提货费
            if( $asnRow['is_delivery'] == '1' && empty($biatt) ){
          		$otherfeeArr = $objOtherCalculte->getOtherFee('TIHUO');
          		$otherfee_tihuo = $otherfeeArr['data']['otherFee']['tihuo'];
          		$asnOrder = $asnRow;
          		$asnOrder['order_code'] = $asnOrder['receiving_code'];
          	    if($otherfee_tihuo['price'] > 0 ) {
          	    	$tihuoOtherFee = Service_OtherFee::getByField('TIHUO','fee_code');
          	    	if(!empty($tihuoOtherFee)){
                        //解冻提货费
                        self::unfreezeFee($asnOrder, $objOtherCalculte, 'TIHUO');
          	    		//Service_CustomerBalanceProcess::unfreezeOtherFeeById($asnOrder,$tihuoOtherFee['fee_id'],'ASN收货，解冻入库费');
                    }else {
                        throw new Exception('杂费代码['.$otherFeeCode.']不存在');
                    }
                    //扣提货费
                    $deductResult = Service_CustomerBalanceProcess::deductFee($asnRow['customer_id'], $otherfee_tihuo, 'ASN收货，扣提货费', $asnCode,'TIHUO',$otherfee_tihuo['fee_id']);
                    if($deductResult['ask'] !=1 ){
                        throw new Exception($deductResult['error']);
                    }
                    //self::recodeBusinessAndIncome($asnRow,$otherfee_tihuo,$weight);
                    $tihuoBusinessIncom = self::getBusinessAndIncom($asnRow, $otherfee_tihuo, $tihuoOtherFee);
                }
            }

            //入库费
      		$otherfeeArr = $objOtherCalculte->getOtherFee('RUKU');
      		$otherfeeRuku = $otherfeeArr['data']['otherFee']['ruku'];
      		$asnOrder = $asnRow;
      		$asnOrder['order_code'] = $asnOrder['receiving_code'];
      	    if($otherfeeRuku['price'] > 0 ){
      	    	$rukuOtherFee = Service_OtherFee::getByField('ruku','fee_code');
      	    	if(!empty($rukuOtherFee)){
                    //解冻入库费
                    self::unfreezeFee($asnOrder, $objOtherCalculte, 'RUKU');
      	    		//Service_CustomerBalanceProcess::unfreezeOtherFeeById($asnOrder,$rukuOtherFee['fee_id'],'ASN收货，解冻入库费');
      	    	}else {
                    throw new Exception('杂费代码['.$otherFeeCode.']不存在');
                }
                //
                $deductResult = Service_CustomerBalanceProcess::deductFee($asnRow['customer_id'], $otherfeeRuku, 'ASN收货，扣入库费', $asnCode,'RUKU',$otherfeeRuku['fee_id']);
                if($deductResult['ask'] !=1 ){
                    throw new Exception($deductResult['error']);
                }
                //self::recodeBusinessAndIncome($asnRow,$otherfeeRuku,$weight);
                $rukuBusinessIncom = self::getBusinessAndIncom($asnRow, $otherfeeRuku, $rukuOtherFee);
            }

            //散租费
            $otherFeeCode = 'SANZU';
            $lowerOtherFeeCode = strtolower($otherFeeCode);
            $otherfeeArr = $objOtherCalculte->getOtherFee($otherFeeCode);
            $otherfee_sanzu = $otherfeeArr['data']['otherFee'][$lowerOtherFeeCode];
            $asnOrder = $asnRow;
            $asnOrder['order_code'] = $asnOrder['receiving_code'];
            //$asnRow['order_code'] = $asnRow['receiving_code'];
            if($otherfee_sanzu['price'] > 0){
                $sanzuOtherFee = Service_OtherFee::getByField($otherFeeCode, 'fee_code');
                //解冻费用
                if(!empty($sanzuOtherFee)){
                    //解冻散租
                    self::unfreezeFee($asnOrder, $objOtherCalculte, $otherFeeCode);
                    //Service_CustomerBalanceProcess::unfreezeOtherFeeById($asnRow,$sanzuOtherFee['fee_id']);
                }else {
                    throw new Exception('杂费代码['.$otherFeeCode.']不存在');
                }
                $deductResult = Service_CustomerBalanceProcess::deductFee($asnRow['customer_id'], $otherfee_sanzu, 'ASN收货，扣除'.$sanzuOtherFee['fee_name'], $asnCode, $otherFeeCode,$otherfee_sanzu['fee_id']);
                if($deductResult['ask'] !=1 ){
                    throw new Exception($deductResult['error']);
                }
                //self::recodeBusinessAndIncome($asnRow, $otherfee_sanzu, $weight);
                $sanzuBusinessIncom = self::getBusinessAndIncom($asnRow, $otherfee_sanzu, $sanzuOtherFee);
            }
            
            //操作费-M
            $otherFeeCode = 'CZF-M';
            $lowerOtherFeeCode = strtolower($otherFeeCode);
            $otherfeeArr = $objOtherCalculte->getOtherFee($otherFeeCode);
            $otherfee_czfm = $otherfeeArr['data']['otherFee'][$lowerOtherFeeCode];
            $asnOrder = $asnRow;
            $asnOrder['order_code'] = $asnOrder['receiving_code'];
            //$asnRow['order_code'] = $asnRow['receiving_code'];
            if($otherfee_czfm['price'] > 0){
                $czfmOtherFee = Service_OtherFee::getByField($otherFeeCode, 'fee_code');
                //解冻费用
                if(!empty($czfmOtherFee)){
                    //解冻散租
                    self::unfreezeFee($asnOrder, $objOtherCalculte, $otherFeeCode);
                    //Service_CustomerBalanceProcess::unfreezeOtherFeeById($asnRow,$sanzuOtherFee['fee_id']);
                }else {
                    throw new Exception('杂费代码['.$otherFeeCode.']不存在');
                }
                $deductResult = Service_CustomerBalanceProcess::deductFee($asnRow['customer_id'], $otherfee_czfm, 'ASN收货，扣除'.$czfmOtherFee['fee_name'], $asnCode, $otherFeeCode,$otherfee_czfm['fee_id']);
                if($deductResult['ask'] !=1 ){
                    throw new Exception($deductResult['error']);
                }
                //self::recodeBusinessAndIncome($asnRow, $otherfee_sanzu, $weight);
                $czfmBusinessIncom = self::getBusinessAndIncom($asnRow, $otherfee_czfm, $czfmOtherFee);
            }
            /**
            * return array(
                'income' => $incomeArr,
                'payment' => $paymentArr,
                'cost_detail' => $fee_cost_detail
            );
             */
            //处理收费业务数据
            $paymentArr = $incomeArr = $fee_cost_detail = array();
            // 提货费
            if($asnRow['is_delivery']=='1' && empty($biatt)){
                if(!empty($tihuoBusinessIncom)){
                    if(array_key_exists('income', $tihuoBusinessIncom) && $tihuoBusinessIncom['income']){
                        $incomeArr[] = $tihuoBusinessIncom['income'];
                    }
                    if(array_key_exists('payment', $tihuoBusinessIncom) && $tihuoBusinessIncom['payment']){
                        $paymentArr[] = $tihuoBusinessIncom['payment'];
                    }
                    if(array_key_exists('cost_detail', $tihuoBusinessIncom) && $tihuoBusinessIncom['cost_detail']){
                        $fee_cost_detail[] = $tihuoBusinessIncom['cost_detail'];
                    }
                }
            }
            // 入库费
            if(!empty($rukuBusinessIncom)){
                if(array_key_exists('income', $rukuBusinessIncom) && $rukuBusinessIncom['income']){
                    $incomeArr[] = $rukuBusinessIncom['income'];
                }
                if(array_key_exists('payment', $rukuBusinessIncom) && $rukuBusinessIncom['payment']){
                    $paymentArr[] = $rukuBusinessIncom['payment'];
                }
                if(array_key_exists('cost_detail', $rukuBusinessIncom) && $rukuBusinessIncom['cost_detail']){
                    $fee_cost_detail[] = $rukuBusinessIncom['cost_detail'];
                }
            }
            // 散租费
            if(!empty($sanzuBusinessIncom)){
                if(array_key_exists('income', $sanzuBusinessIncom) && $sanzuBusinessIncom['income']){
                    $incomeArr[] = $sanzuBusinessIncom['income'];
                }
                if(array_key_exists('payment', $sanzuBusinessIncom) && $sanzuBusinessIncom['payment']){
                    $paymentArr[] = $sanzuBusinessIncom['payment'];
                }
                if(array_key_exists('cost_detail', $sanzuBusinessIncom) && $sanzuBusinessIncom['cost_detail']){
                    $fee_cost_detail[] = $sanzuBusinessIncom['cost_detail'];
                }
            }
            //操作费-M
            if(!empty($czfmBusinessIncom)){
                if(array_key_exists('income', $czfmBusinessIncom) && $czfmBusinessIncom['income']){
                    $incomeArr[] = $czfmBusinessIncom['income'];
                }
                if(array_key_exists('payment', $czfmBusinessIncom) && $czfmBusinessIncom['payment']){
                    $paymentArr[] = $czfmBusinessIncom['payment'];
                }
                if(array_key_exists('cost_detail', $czfmBusinessIncom) && $czfmBusinessIncom['cost_detail']){
                    $fee_cost_detail[] = $czfmBusinessIncom['cost_detail'];
                }
            }
            //处理财务业务数据
            if(!empty($incomeArr) || !empty($paymentArr)){
                self::doBusinessPaymentIncome($asnRow, $incomeArr, $paymentArr, $fee_cost_detail, $weight);
            }

            /*****************************************
             * [ 杂费解冻->扣款->写入财务数据 end ]  *
             *****************************************
             */
            
            if($asnRow['receiving_status']=="5"){
                /*$session = new Zend_Session_Namespace('userAuthorization');
                $warehouseId = $session->warehouseId;
                $userId = $session->userId;
                $ASNLog = array(
                    'receiving_id'=>$asnRow['receiving_id'],
                    'receiving_code' => $asnRow['receiving_code'],
                    'user_id'=>$userId,
                    'customer_code' => $asnRow['customer_code'],
                    'rl_note' => "收货中",
                    'rl_status_from' => $asnRow['receiving_status'],
                    'rl_status_to' => "6",
                    'rl_add_time'=>date("Y-m-d H:i:s"),
                    'rl_ip'=>Common_Common::getIP()
                );
                //print_r($ASNLog);
                Service_ReceivingLog::add($ASNLog);*/

                $updateRa = array(
                    'receiving_time'=>date("Y-m-d H:i:s"),
                );
                Service_ReceivingAttribute::update($updateRa,$asnCode,"receiving_code");
            }
            
            $asnObj->update($receinvRow, $asnRow['receiving_id']);
            $putawayObj = new Service_Putaway();
            $putawayRow = $putawayObj->getByField($asnCode, 'receiving_code');
            if (empty($putawayRow)) {
                $code = Common_GetNumbers::getCode('putaway', $asnRow['warehouse_id'],'PA');
                $row = array(
                    'putaway_code' => $code,
                    'receiving_code' => $asnRow['receiving_code'],
                    'warehouse_id' => $asnRow['warehouse_id'],
                    'putaway_add_time' => $this->_date
                );
                $putawayObj->add($row);
            }
            $userId = Service_User::getUserId();
            $qcRow = array(
                'receiving_id' => $asnRow['receiving_id'],
                'warehouse_id' => $asnRow['warehouse_id'],
                'receiving_code' => $asnRow['receiving_code'],
                'customer_id' => $asnRow['customer_id'],
                'customer_code' => $asnRow['customer_code'],
                'receiving_user_id' => $userId,
                'qc_status' =>0,
            );
            $qcObj = new Service_QualityControl();
            $qcParam = array();
            foreach ($asnDetail as $key => $val) {
                $code = Common_GetNumbers::getCode('qualitycontrol', $asnRow['warehouse_id'], 'QC');
                $result['code'][] = $code;
                Service_ReceivingDetail::update(array('rd_status' => 1, 'rd_update_time' => $this->_date), $val['rd_id']);
                $qcRow['qc_code'] = $code;
                $qcRow['product_barcode'] = $val['product_barcode'];
                $qcRow['product_id'] = $val['product_id'];
                $qcRow['qc_quantity'] = $val['rd_receiving_qty'];
                $qcRow['rd_id'] = $val['rd_id'];
                $qcRow['qc_type'] = $val['is_qc'];//暂无特采
                $qcRow['hs_serial_no'] = $val['hs_serial_no'];
                $qcId = $qcObj->add($qcRow);
                $product = Service_Product::getByField($val['product_id'],'product_id',"*");
                //已经收过货的
                if($product['product_receive_status']=="1"){
                    $params = array(
                        'userId'=>Service_User::getUserId(),
                        'qcId'=>$qcId,
                        'productId'=>$product['product_id'],
                        'productBarcode'=>$product['product_barcode'],
                        'customerCode'=>$product['customer_code'],
                        'productCategoryId'=>0,
                        'firstReceived'=>0,
                        'productBarcodeType'=>$product['product_barcode_type'],
                        'productWeight'=>$product['product_weight'],
                        'receivedQty'=>$qcRow['qc_quantity'],
                        'problemQty'=>0,
                        'noLabelQty'=>0,
                        'shelf'=>'',
                        'product'=>array(
                            'category'=>'1',
                            'package'=>'1',
                            'declaredValue'=>$product['product_declared_value'],
                            'length'=>$product['product_length'],
                            'width'=>$product['product_width'],
                            'height'=>$product['product_height'],
                        ),
                        'remark'=>'',
                    );
                    $qcParam[] = $params;
                }
            }
            $db->commit();
            //$db->rollBack();
            $result = array('state' => 1, 'message' => Ec::Lang('operationSuccess'), 'code' => $result['code'],'qcParam'=>$qcParam);
            return $result;
        } catch (Exception $e) {
            $db->rollBack();
            $result['error'][] = array(
                'errorCode' => '50000',
                'errorMsg' => $e->getMessage()
            );
            return $result;
        }
    }

    /**
     * [getBusinessAndIncom 获取费用 应收 | 应付 | 成本数组]
     * @author [simple] <[<^^^^^^^>]>
     * @param  [type] $asnRow       [ASN]
     * @param  [type] $otherfeeRow  [收费数组]
     * @param  [type] $otherFeeInfo [费用基本数组]
     * @return [type]               [description]
     */
    private static function getBusinessAndIncom($asnRow, $otherfeeRow, $otherFeeInfo){
        //应收 / 应付 / 成本
        $incomeArr = $paymentArr = $fee_cost_detail = array();
        $_otherfee_mix_arr = Process_BillConfig::getOtherFeeArr();
        $tmpFee = str_replace('-', '', strtolower($otherFeeInfo['fee_code']));
        $billConfig = $_otherfee_mix_arr[$tmpFee];
        if(empty($billConfig)){
            throw new Exception('费用['.$otherFeeInfo['fee_code'].']配置错误');
        }
        $userAuth = new Zend_Session_Namespace('userAuthorization');
        $remote_ip = Common_Common::getIP();
        $customerArr = Service_Customer::getByField($asnRow['customer_code'], 'customer_code', array('customer_saler_user_id','customer_currency'));
        //转为客户币种
        $convert_fee = Service_Currency::converByCode($otherfeeRow['currency_code'], $customerArr['customer_currency'], $otherfeeRow['price']);
        $date = date("Y-m-d H:i:s");
        //应收
        $incomeArr = array(
            'customer_code' => $asnRow['customer_code'],
            'ft_code' => $billConfig['ftcode'],
            'ut_code' => $billConfig['utcode'],
            'sm_code' => '',
            'bi_amount' => $convert_fee,
            'bi_org_amount' => $otherfeeRow['price'],
            'currency_code' => $otherfeeRow['currency_code'],
            'currency_rate' => '',
            'bi_chargeable_time' => $date,
            'bi_note' => $otherFeeInfo['fee_name'],
        );
        $fee_detail = array(
            'fee_amount_customer' => $convert_fee,                                  //费用金额（客户）
            'fee_currency_code_customer' => $customerArr['customer_currency'],      //费用币种（客户）
            'discount_customer' => $otherFeeInfo['discount'],                       //折扣率（客户）（1=100%）
        );
        //应付费用  服务商不能为空
        $cost_detail = array();
        if (isset($otherfeeRow['cost']) && $otherfeeRow['cost'] > 0 && $otherFeeInfo['sp_code'] != '') {
            $spRow = Service_ServiceProvider::getByField($otherFeeInfo['sp_code'], 'sp_code');
            //$sp_currency_code = $spRow['currency_code'];
            //转为服务商币种
            $convert_fee = Service_Currency::converByCode($otherFeeInfo['fee_currency_code'], $spRow['currency_code'], $otherFeeInfo['cost']);
            $paymentArr = array(
                'sp_code' => $otherFeeInfo['sp_code'],                              //服务商代码
                'ft_code' => $billConfig['ftcode'],
                'ut_code' => $billConfig['utcode'],
                'sm_code' => '',
                'bp_amount' => $convert_fee,
                'bp_org_amount' => $otherfeeRow['cost'],
                'currency_code' => $otherFeeInfo['fee_currency_code'],
                'currency_rate' => '',
                'bp_chargeable_time' => $date,
            );
            $cost_detail = array(
                'cost_amount_org'           => $otherfeeRow['cost'],                //成本金额（原始）
                'cost_currency_code_org'    => $otherFeeInfo['fee_currency_code'],      //成本币种（原始）
                'cost_amount_sp'            => $convert_fee,                        //成本金额（服务商）
                'cost_currency_code_sp'     => $spRow['currency_code'],             //成本币种（服务商）
                'sp_code'                   => $otherFeeInfo['sp_code'],            //服务商代码
            );
        }
        if(!empty($fee_detail) || !empty($cost_detail)){
            $fee_cost_common = array(
                'code_number'                   => $asnRow['receiving_code'],           //单号
                'code_type'                     => 3,                                   //单号类型（1:区内单 2：区外单 3：ASN单）
                'customer_code'                 => $asnRow['customer_code'],            //客户代码
                'reference_no'                  => $asnRow['reference_no'],             //客户参考号
                'tracking_number'               => '',                                  //服务商单号（跟踪号）
                'sm_code'                       => '',                                  //运输方式代码
                'country_code'                  => '',                                  //国际简称（二字码）
                'fee_code'                      => $otherFeeInfo['fee_code'],           //费用编号
                'fee_name'                      => $billConfig['binote'],               //费用名称
                'fee_amount_org'                => $otherFeeInfo['price'],              //费用金额（原始）
                'fee_currency_code_org'         => $otherFeeInfo['fee_currency_code'],      //费用币种（原始）
                'price_batch_number'            => '',                                  //运输价格编号
                'currency_batch_number'         => '',                                  //货币汇率编号
                'fee_time'                      => $date,                               //扣费时间
                'fee_time_recalculate'          => $date,                               //重新扣费时间
                'ip'                            => $remote_ip,                          //扣费操作IP
                'ip_recalculate'                => $remote_ip,                          //重新扣费操作IP
                'operator'                      => $userAuth->user['user_name'],        //扣费操作人
                'operator_recalculate'          => $userAuth->user['user_name'],        //重新扣费操作人
            );
            $fee_cost_detail = array_merge($fee_detail, $cost_detail, $fee_cost_common);
        }
        return array(
            'income' => $incomeArr,
            'payment' => $paymentArr,
            'cost_detail' => $fee_cost_detail
        );
    }

    /**
     * [unfreezeFeeSanZu 解冻杂费]
     * @param  [type] $receivingData [description]
     * @param  [type] $otherFeeObj   [description]
     * @param  [type] $otherFeeCode  [description]
     * @return [type]                [description]
     */
    public static function unfreezeFee($receivingData, $otherFeeObj, $otherFeeCode, $additionalLog = ''){
        $lowerOtherFeeCode = strtolower($otherFeeCode);
        $otherfeeArr = $otherFeeObj->getOtherFee($otherFeeCode);
        $otherfeeRow = $otherfeeArr['data']['otherFee'][$lowerOtherFeeCode];
        $additionalLog = $additionalLog ? $additionalLog : 'ASN退回草稿，解冻';
        if($otherfeeRow['price']>0){
            $otherFeeInfo = Service_OtherFee::getByField($otherFeeCode, 'fee_code');
            //解冻费用
            if(!empty($otherFeeInfo)){
                $asnOrder = $receivingData;
                $asnOrder['order_code'] = $receivingData['receiving_code'];
                $otherfeeArr = array(
                    'customer_id' => $receivingData['customer_id'],
                    'cbl_type' => '0',
                    'fee_id_gt' => '0',
                    'cbl_refer_code' => $receivingData['receiving_code'],
                    'fee_id' => $otherFeeInfo['fee_id'],
                );
                //查询是其它费用的情况
                $customerBalances = Service_CustomerBalanceLog::getByCondition($otherfeeArr);
                if(!empty($customerBalances)){
                    foreach ($customerBalances as $customerBalanceRow) {
                        if($customerBalanceRow['un_cbl_id'] > 0){
                            continue;
                        }
                        Service_CustomerBalanceProcess::unfreezeOtherFee($asnOrder, $customerBalanceRow, $additionalLog.$otherFeeInfo['fee_name']);
                    }
                }
            }
        }
    }

    /**
     * [doBusinessPaymentIncome 处理财务业务数据]
     * @param  [type] $asnRow          [ASN]
     * @param  [type] $incomeArr       [应收]
     * @param  [type] $paymentArr      [应付]
     * @param  [type] $fee_cost_detail [成本]
     * @param  [type] $weight          [重量]
     * @return [type]                  [description]
     */
    private static function doBusinessPaymentIncome($asnRow, $incomeArr, $paymentArr, $fee_cost_detail, $weight){
        $customerArr = Service_Customer::getByField($asnRow['customer_code'], 'customer_code', array('customer_saler_user_id','customer_currency'));
        //判断是否存在应收、应付
        if(!empty($incomeArr) || !empty($paymentArr)){
            //写入业务表
            $businessArr = array(
                'ds_code' => 'asn',
                'customer_code' => $asnRow['customer_code'],
                'warehouse_id' => $asnRow['warehouse_id'],
                'sm_code' => '',
                'bb_volume_weight' => $weight,
                'bb_charge_weight' => $weight,
                'bb_delivered_weight' => $weight,
                'bb_pieces' => $asnRow['pack_no'],
                'bb_declared_value' =>0,
                'bb_declared_currency_code' => 'USD',
                'country_code' => '',
                'bb_postcode' => '',
                'bb_charge_time' => date("Y-m-d H:i:s"),
                'bb_declared_time' => date('Y-m-d H:i:s'), //发货时间 此时间与服务商对接
                'bb_sales_id' => $customerArr['customer_saler_user_id'],
                'bb_refer_code' => $asnRow['receiving_code'],
                'bb_service_number' => '', //ref_tracking_number
                'bb_reference_no' => '',
            );
            $bsObj = new Process_Business();
            $businessResult = $bsObj->businessFee($businessArr, $incomeArr, $paymentArr);
            if($businessResult['state']!='1'){
                throw new Exception($businessResult['message']);
            }
        }
        //插入成本数据
        if(!empty($fee_cost_detail)){
            if(Service_FeeCostDetail::addMultiRows($fee_cost_detail) === false){
                throw new Exception('成本写入异常');
            }
        }
    }

    /**
     * [recodeBusinessAndIncome 此方法只适用于一种费用，多种费用需调用上面两个方法组合]
     * @param  [type] $asnRow   [description]
     * @param  [type] $otherfee [description]
     * @param  [type] $weight   [description]
     * @return [type]           [description]
     */
    private static function recodeBusinessAndIncome($asnRow, $otherfee, $weight){
        $remote_ip          = Common_Common::getIP();
        $userAuth           = new Zend_Session_Namespace('userAuthorization');
        $_otherfee_mix_arr  = Process_BillConfig::getOtherFeeArr();
        $date               = date('Y-m-d H:i:s');
        $otherFeeInfo = Service_OtherFee::getByField($otherfee['fee_id']);
        $tmpFee = str_replace('-', '', strtolower($otherFeeInfo['fee_code']));
        $billConfig = $_otherfee_mix_arr[$tmpFee];
        if(empty($billConfig)){
            throw new Exception('费用配置错误');
        }
        $customerArr = Service_Customer::getByField($asnRow['customer_code'], 'customer_code', array('customer_saler_user_id', 'customer_currency'));
        //转为客户币种
        $convert_fee = Service_Currency::converByCode($otherfee['currency_code'], $customerArr['customer_currency'], $otherfee['price']);
        //应收
        $incomeArr[] = array(
            'customer_code' => $asnRow['customer_code'],
            'ft_code' => $billConfig['ftcode'],
            'ut_code' =>$billConfig['utcode'],
            'sm_code' => '',
            'bi_amount' => $convert_fee,
            'bi_org_amount' => $otherfee['price'],
            'currency_code' => $otherfee['currency_code'],
            'currency_rate' => '',
            'bi_chargeable_time' =>date("Y-m-d H:i:s"),
            'bi_note' => $otherFeeInfo['fee_name'],
        );

        $fee_detail = array(
            'fee_amount_customer'           => $convert_fee,                        //费用金额（客户）
            'fee_currency_code_customer'    => $customerArr['customer_currency'],   //费用币种（客户）
            'discount_customer'             => $otherfee['discount'],         //折扣率（客户）（1=100%）
        );

        //应付费用  服务商不能为空
        $cost_detail = array();
        if (isset($otherfee['cost']) && $otherfee['sp_code'] != '' && $otherfee['cost'] > 0) {
            $spRow=Service_ServiceProvider::getByField($otherfee['sp_code'],'sp_code');
            $sp_currency_code=$spRow['currency_code'];
            //转为服务商币种
            $convert_fee = Service_Currency::converByCode($otherfee['currency_code'], $sp_currency_code, $otherfee['cost']);
            $paymentArr[] = array(
                'sp_code' => $otherfee['sp_code'], //服务商代码
                'ft_code' =>$billConfig['ftcode'],
                'ut_code' => $billConfig['utcode'],
                'sm_code' => '',
                'bp_amount' => $convert_fee,
                'bp_org_amount' => $otherfee['cost'],
                'currency_code' => $otherfee['currency_code'],
                'currency_rate' => '',
                'bp_chargeable_time' => date("Y-m-d H:i:s"),
            );

            $cost_detail = array(
                'cost_amount_org'           => $otherfee['cost'],             //成本金额（原始）
                'cost_currency_code_org'    => $otherfee['currency_code'],    //成本币种（原始）
                'cost_amount_sp'            => $convert_fee,                        //成本金额（服务商）
                'cost_currency_code_sp'     => $sp_currency_code,                   //成本币种（服务商）
                'sp_code'                   => $otherfee['sp_code'],           //服务商代码
            );
        }

        //判断是否存在应收、应付
        if(!empty($incomeArr) || !empty($paymentArr)){
            //写入业务表
            $businessArr = array(
                'ds_code' => 'asn',
                'customer_code' => $asnRow['customer_code'],
                'warehouse_id' => $asnRow['warehouse_id'],
                'sm_code' => '',
                'bb_volume_weight' => $weight,
                'bb_charge_weight' => $weight,
                'bb_delivered_weight' => $weight,
                'bb_pieces' => $asnRow['pack_no'],
                'bb_declared_value' =>0,
                'bb_declared_currency_code' => 'USD',
                'country_code' => '',
                'bb_postcode' => '',
                'bb_charge_time' => date("Y-m-d H:i:s"),
                'bb_declared_time' => date('Y-m-d H:i:s'), //发货时间 此时间与服务商对接
                'bb_sales_id' => $customerArr['customer_saler_user_id'],
                //单个入库单，多种费用收费时追踪号重复
                'bb_refer_code' => $asnRow['receiving_code'],
                'bb_service_number' => '',//ref_tracking_number
                'bb_reference_no' => '',
            );
            $bsObj = new Process_Business();
            $businessResult=$bsObj->businessFee($businessArr,$incomeArr,$paymentArr);
            if($businessResult['state']!='1'){
                throw new Exception($businessResult['message']);
            }
        }
        if(!empty($fee_detail) || !empty($cost_detail)){
            $fee_cost_common    = array(
                'code_number'                   => $asnRow['receiving_code'],           //单号
                'code_type'                     => 3,                                   //单号类型（1:区内单 2：区外单 3：ASN单）
                'customer_code'                 => $asnRow['customer_code'],            //客户代码
                'reference_no'                  => $asnRow['reference_no'],             //客户参考号
                'tracking_number'               => '',                                      //服务商单号（跟踪号）
                'sm_code'                       => '',                                      //运输方式代码
                'country_code'                  => '',                                      //国际简称（二字码）
                'fee_code'                      => $otherFeeInfo['fee_code'],                                 //费用编号
                'fee_name'                      => $billConfig['binote'],   //费用名称
                'fee_amount_org'                => $otherfee['price'],                //费用金额（原始）
                'fee_currency_code_org'         => $otherfee['currency_code'],        //费用币种（原始）
                'price_batch_number'            => '',                                      //运输价格编号
                'currency_batch_number'         => '',                                      //货币汇率编号
                'fee_time'                      => $date,                                   //扣费时间
                'fee_time_recalculate'          => $date,                                   //重新扣费时间
                'ip'                            => $remote_ip,                              //扣费操作IP
                'ip_recalculate'                => $remote_ip,                              //重新扣费操作IP
                'operator'                      => $userAuth->user['user_name'],            //扣费操作人
                'operator_recalculate'          => $userAuth->user['user_name'],            //重新扣费操作人
            );
            $fee_cost_detail        = array_merge($fee_detail, $cost_detail, $fee_cost_common);
            $feecostdetailResult    = Service_FeeCostDetail::add($fee_cost_detail);
        }
    }

    public static function getAsnDetail($asnCode = '')
    {
        $result = array(
            'state' => 0,
            'data' => array(),
            'message' => ''
        );
        $asnRow = Service_Receiving::getByField($asnCode, 'receiving_code');
        if (!empty($asnRow)) {
            $result['state'] = 1;
            $lang = Ec::getLang(1);
            $asnItem = Service_ReceivingDetail::getByCondition(array('receiving_id' => $asnRow['receiving_id']), '*');
            foreach ($asnItem as $key => $val) {
                $asnItem[$key]['product'] = Service_Product::getByProduct($val['product_id'], 'product_id');
            }
            $result['data'] = array(
                'order' => $asnRow,
                'item' => $asnItem
            );
        }
        return $result;
    }
	/**
	 * @author william-fan
	 * @todo 用于审核asn
	 */
    public static function shenhe($paragram){
    	$result = array(
    			'state' => 0,
    			'error' => array(),
    			'code' => array(),
    			'message' => ''
    	);
    	$db = Service_ReceivingDetail::getModelInstance()->getAdapter();
    	$db->beginTransaction();
    	try {
    		$receiving_code = $paragram['receiving_code'];
    		$receivingInfo = Service_Receiving::getByField($receiving_code,'receiving_code');
    		if(empty($receiving_code)||empty($receivingInfo)){
    			$result['message'] = "ASN不存在";
    			$db->rollBack();
    			return $result;
    		}
    		/*$expected = $paragram['expected'];
    		$expected = trim($expected);
    		if(empty($expected)){
    			$result['message'] = "参数错误";
    			$db->rollBack();
    			return $result;
    		}*/
    		if($receivingInfo['receiving_status']!='3'){
    			$result['message'] = "ASN状态不为未审核,不能进行审核操作";
    			$db->rollBack();
    			return $result;
    		}
            /*if($receivingInfo['trade_mode']=="0110"&&$receivingInfo['import_hsserialno']=="0"&&$receivingInfo['receive_model_type']=="0"){
                $result['message'] = "一般贸易入区单尚未导入海关备案号,不能进行审核操作!";
                $db->rollBack();
                return $result;
            }*/
    		$receivingRow = array(
    			'receiving_status'=>'4',
    			//'expected_date'=>$expected
    		);
    		Service_Receiving::update($receivingRow, $receiving_code,'receiving_code');
            /*if($receivingInfo['trade_mode']=="0110"){
                $aMessage['fmt_code'] = 'ASNSH-TO-FX';//ASN审核推送分销
                $aMessage['fmt_type'] = 'FXSYS';
                $aMessage['refercence_no'] = $receiving_code;
                $aMessage['fml_status'] = 1;
                $aMessage['fml_add_time'] = date('Y-m-d H:i:s');
                Service_FtpMessageSendlist::add($aMessage);
            }*/
    		
    		//$db->rollBack();
    		$db->commit();
    		$result = array('state' => 1, 'message' => Ec::Lang('operationSuccess'), 'code' => $result['code']);
    		return $result;
    	} catch (Exception $e) {
            $db->rollBack();
            $result['error'][] = array(
                'errorCode' => '50000',
                'errorMsg' => $e->getMessage()
            );
            return $result;
        }
    }
    /* @desc 获取ASN的收货状态
     * @param string $receivingCode
     * @return mixed 1：未收货 2：首次收货 3：收货中 4：收货完成 false:异常
     */
    public static function getReceivedStatus($receivingCode) {
        if($receivingCode==='' || false==is_string($receivingCode)){
            return false;
        }

    }

}