<?php
class Service_PackProcess
{
    protected $_errorArr = array();
    protected $_userId = 0;
    protected $_warehouseId = 0;
    protected $_order = array();
    protected $_pickingCode = '';
    protected $_pickingId = '';
    protected $_date = '';

    public function __construct()
    {
        $this->_date = date('Y-m-d H:i:s');
        $this->_warehouseId = Service_User::getUserWarehouseId();
        $this->_userId = Service_User::getUserId();
    }

    /**
     * @param string $orderCode
     * @param null $warehouseId
     * @param int $orderPickType
     * @return bool
     */
    private function setOrder($orderCode = '', $warehouseId = null, $orderPickType = 0)
    {
        if ($warehouseId != null) {
            $this->_warehouseId = $warehouseId;
        }
        $orderPickTypeArr=array('0');
        if($orderPickType=='1'){
            $orderPickTypeArr=array('1','2');
        }
        $orderRow = Service_Orders::getByCondition(array('warehouse_id' => $this->_warehouseId, 'order_code' => $orderCode), '*');

        if (empty($orderRow)) {
            $this->_errorArr[] = '订单: ' . $orderCode . ' 不存在.';
            return false;
        }
        if($orderRow[0]['order_mode_type']!="1"){
            if (!in_array($orderRow[0]['order_pick_type'],$orderPickTypeArr)) {
                $this->_errorArr[] = '订单: ' . $orderCode . ' 类型不是.' . ($orderPickType == '0' ? '一票一件' : '一票多件');
                return false;
            }
            if ($orderPickType == '0' && $orderRow[0]['order_status'] != '5') {
                $this->_errorArr[] = '订单: ' . $orderCode . ' 不是已打印状态.';
                return false;
            }
            if ($orderPickType != '0' && $orderRow[0]['order_status'] != '6') {
                $this->_errorArr[] = '订单: ' . $orderCode . ' 不是已下架状态.';
                return false;
            }
        }

        $orderTracking = Service_ServiceTrackingNumber::getByField($orderRow[0]['order_code'],'order_code');
        if(!empty($orderTracking)){
        	$orderRow[0]['tracking_number'] = $orderTracking['stn_code'];
        }else{
        	$orderRow[0]['tracking_number'] = '';
        }
        $this->_order['order'] = $orderRow[0];
        $this->_order['products'] = $this->getOrderProductUnique($orderCode);
    }

    /**
     * @desc 提取订单中的所有产品，主要是提取组合产品中的普通产品
     * @param $ordersCode
     * @return array
     */
    public function getOrderProductUnique($ordersCode)
    {
        $orderProduct = Service_OrderProduct::getByCondition(array("order_code" => $ordersCode));
        $orderProducts = array();
        foreach ($orderProduct as $v) { //提取所有产品（判断有无组合产品）
            $product = Service_Product::getByField($v['product_id'], 'product_id');
            if ($product['product_type'] == '1') { //组合产品
                $productCombine = Service_ProductCombineRelation::getByCondition(array('product_id' => $product['product_id']), "*");
                foreach ($productCombine as $sub) {
                    $subProduct = Service_Product::getByField($sub['pcr_product_id'], 'product_id');

                    if (isset($orderProducts[$sub['pcr_product_id']])) {
                        $orderProducts[$sub['pcr_product_id']]['op_quantity'] += $sub['pcr_quantity'] * $v['op_quantity'];
                    } else {
                        $orderProducts[$sub['pcr_product_id']] = array(
                            'order_code' => $ordersCode,
                            'op_id' => $v['op_id'],
                            'product_id' => $subProduct['product_id'],
                            'product_sku' => $subProduct['product_sku'],
                            'product_barcode' => $subProduct['product_barcode'],
                            'op_quantity' => $sub['pcr_quantity'] * $v['op_quantity'],
                            'op_category' => $v['op_category'],
                            'hs_code' => '',
                            'product_title' => $subProduct['product_title'],
                            'product_title_en' => $subProduct['product_title_en'],
                            'product_sales_value' => $subProduct['product_sales_value'],
                            'product_weight' => $subProduct['product_weight'],
                            'product_declared_value' => $subProduct['product_declared_value'],
                            'is_scan_imei' => $subProduct['is_scan_imei'],
                        );
                    }
                }
            } else {
                if (isset($orderProducts[$v['product_id']])) {
                    $orderProducts[$v['product_id']]['op_quantity'] += $v['op_quantity'];
                } else {
                    $orderProducts[$v['product_id']] = array(
                        'order_code' => $ordersCode,
                        'op_id' => $v['op_id'],
                        'product_id' => $product['product_id'],
                        'product_sku' => $product['product_sku'],
                        'product_barcode' => $product['product_barcode'],
                        'op_quantity' => $v['op_quantity'],
                        'op_category' => $v['op_category'],
                        'hs_code' => '',
                        'product_title' => $product['product_title'],
                        'product_title_en' => $product['product_title_en'],
                        'product_sales_value' => $product['product_sales_value'],
                        'product_weight' => $product['product_weight'],
                        'product_declared_value' => $product['product_declared_value'],
                        'is_scan_imei' => $product['is_scan_imei'],
                    );
                }
            }
        }
        return $orderProducts;
    }

    /**
     * @desc 获取推荐包材
     * @通过产品匹配最大的包材
     */
    private function setOrderPackage()
    {
        $packMapObj = new Service_ProductPackageMap();
        $packObj = new Service_ProductPackage();
        $pack = 0;
        $packName = '';
        foreach ($this->_order['products'] as $key => $val) {
            $packMapRows = $packMapObj->getByCondition(array('product_id' => $val['product_id'], 'warehouse_id_arr' => array(0, $this->_order['order']['warehouse_id'])), '*', 0, 0, array('warehouse_id desc'));
            if (!empty($packMapRows)) {
                $packRow = $packObj->getByField($packMapRows[0]['pp_id'], 'pp_id', array('pp_status', 'pp_quantity', 'pp_name', 'pp_length', 'pp_height', 'pp_width'));
                if (isset($packRow['pp_status']) && $packRow['pp_status'] == '1' && $packRow['pp_quantity'] > 0 && ($packRow['pp_length'] * $packRow['pp_width'] * $packRow['pp_height']) > $pack) {
                    $pack = $packRow['pp_length'] * $packRow['pp_width'] * $packRow['pp_height'];
                    $packName = $packRow['pp_name'];
                }
            }
        }
        $this->_order['order']['packName'] = $packName;
        $this->_order['order']['skuQty'] = count($this->_order['products']);
    }


    /**
     * @desc 获取打印订单信息
     * @param string $orderCode ，$warehouseId ,$orderPickType 订单下架类型
     * @return array
     */
    public function getOrderDetailByOrderCode($orderCode = '', $warehouseId = null, $orderPickType = 0)
    {
        $result = array('state' => 0, 'message' => '', 'error' => array(), 'data' => array(), 'orderCode' => $orderCode);
        $this->setOrder($orderCode, $warehouseId, $orderPickType);
        Service_OrderImei::delete($orderCode,'order_code');
        if (!empty($this->_errorArr)) {
            $result['error'] = $this->_errorArr;
        } else {
            $this->setOrderPackage();
            $result['state'] = 1;
            $result['data'] = $this->_order;
        }
        return $result;
    }


    /**
     * @desc 获取下架单信息
     * @param string $orderCode,$productBarcode,$warehouseId ,$orderPickType 订单下架类型
     * @return array
     */
    public function getPickingByPickingCode($pickingCode = '', $productBarcode = '', $warehouseId = null, $orderPickType = 0)
    {
        if ($warehouseId != null) {
            $this->_warehouseId = $warehouseId;
        }
        $result = array('state' => 0, 'message' => '', 'error' => array(), 'data' => array(), 'pickingCode' => $pickingCode);
        $pickRow = Service_Picking::getByField($pickingCode, 'picking_code');
        if (empty($pickRow)) {
            $result['error'][] = ($orderPickType == '0' ? '下架单:' : '配货单:') . $pickingCode . ' 不存在.';
        } elseif ($pickRow['warehouse_id'] != $this->_warehouseId) {
            $result['error'][] = ($orderPickType == '0' ? '下架单:' : '配货单:') . $pickingCode . ' 不存在.';
        } elseif ($pickRow['picking_type'] != $orderPickType) {
            $result['error'][] = ($orderPickType == '0' ? '下架单:' : '配货单:') . $pickingCode . ' 类型不是' . ($orderPickType == '0' ? '一票一件' : '一票多件') . '!';
        } elseif ($pickRow['picking_status'] == '1') {
            $result['error'][] = ($orderPickType == '0' ? '下架单:' : '配货单:') . $pickingCode . ' 已完成.';
        }
        if (!empty($result['error'])) {
            $this->_errorArr = $result['error'];
            return $result;
        }
        $pickRow['packName'] = '';
        $pickRow['products'] = array();
        if (!empty($productBarcode)) {
            $pdRows = Service_PickingDetail::getByCondition(array('picking_id' => $pickRow['picking_id'], 'pd_status' => '0', 'product_barcode' => $productBarcode), '*');      
            if (empty($pdRows)) {
                $product=Service_Product::getByCondition(array('product_sku'=>$productBarcode),"*"); 
                $pdRows = array();
                if (!empty($product)) {
                    foreach ($product as $key => $value) {
                        $tempPdRows = Service_PickingDetail::getByCondition(array('picking_id' => $pickRow['picking_id'], 'pd_status' => '0', 'product_barcode' => $value['product_barcode']), '*');
                        if (!empty($tempPdRows)) {
                            $pdRows = array_merge($pdRows, $tempPdRows);
                        }
                    }
                    
              
                    if (empty($pdRows)) {
                         $this->_errorArr = $result['error'] = array('产品代码/SKU:' . $productBarcode . ' 未找到匹配未完成的订单.');
                return $result;
                    }
                }else{
                     $this->_errorArr = $result['error'] = array('产品代码/SKU:' . $productBarcode . ' 不存在.');
                         return $result;
                }
                
            } else {
                $packMapRows = Service_ProductPackageMap::getByCondition(array('product_id' => $pdRows[0]['product_id'], 'warehouse_id_arr' => array(0, $this->_warehouseId)), '*', 0, 0, array('warehouse_id desc'));
                if (!empty($packMapRows)) {
                    $packRow = Service_ProductPackage::getByField($packMapRows[0]['pp_id'], 'pp_id', array('pp_status', 'pp_quantity', 'pp_name', 'pp_length', 'pp_height', 'pp_width'));
                    $pickRow['packName'] = isset($packRow['pp_name']) ? $packRow['pp_name'] : '';
                }
            }
              //print_r($pdRows);
            $productRow = Service_Product::getByField($pdRows[0]['product_id'], 'product_id');
            $pickRow['products'] = array(
                'product_barcode' => $pdRows[0]['product_barcode'],
                'product_title' => isset($productRow['product_title']) ? $productRow['product_title'] : '',
                'is_scan_imei'=>$productRow['is_scan_imei'],
            );
        }
        //$order = Service_PickingDetail::getByCondition(array('picking_id' => $pickRow['picking_id']),"*");
        //Service_OrderImei::delete($order[0]['order_code'],"order_code");
        $pickRow['finish'] = Service_PickingDetail::getByCondition(array('picking_id' => $pickRow['picking_id'], 'pd_status' => 1), 'count(*)');
        $pickRow['scanQty'] = $pickRow['picking_order_cnt'] - $pickRow['finish'];
        $result['state'] = 1;
        $result['data'] = $pickRow;
        //print_r($result);exit;
        return $result;
    }

    /**
     * @打包贴标事务处理
     * @param array $orderCode,$packageCode,$orderPickType,$warehouseId
     * @return array
     */
    public function packTransaction($orderCode = '', $packageCode = '', $orderPickType = 0, $warehouseId = null)
    {
        $result = array('state' => 0, 'message' => '', 'error' => array(),'data'=>array(), 'orderCode' => $orderCode,'printLabel'=>1);

        $this->setOrder($orderCode, $warehouseId, $orderPickType);
        $orderRow = Service_Orders::getByField($orderCode,"order_code","*");
        if($orderRow['order_mode_type']!="1"){
            /*if (empty($packageCode)) {
                $this->_errorArr[] = '包材不能为空!';
            } else {
                $packageRow = Service_ProductPackage::getByField($packageCode, 'pp_barcode');
                if (empty($packageRow)) {
                    $this->_errorArr[] = '包材代码:' . $packageCode . ' 不存在.';
                } elseif ($packageRow['pp_status'] != '1' || $packageRow['pp_quantity'] < 1) {
                    $this->_errorArr[] = '包材代码:' . $packageCode . ' 不可用或已用完.';
                }
            }*/
        }

        if (!empty($this->_errorArr)) {
            $result['error'] = $this->_errorArr;
            return $result;
        }
        $this->_order['order']['packageCode'] = $packageCode;

        $shipMethod = Service_ShippingMethod::getByField($this->_order['order']['sm_code'],'sm_code');
        /*$serviceTracking = Service_ServiceTrackingNumber::getByField($this->_order['order']['order_code'],'order_code');
        if(!empty($serviceTracking)){
        	$error = $result['error'];
        	$error[] = "订单号{$this->_order['order']['order_code']}已经分配过服务商单号";
        	$result['error'] = $error;
        	return $result;
        }*/
        
        $track	= '';
        $db = Service_QualityControl::getModelInstance()->getAdapter();
        $db->beginTransaction();
        try {
        	 switch($shipMethod['sm_class_code']){
        		//CRE:快递;CRP:挂号;CPS:平邮'
        		case "CRE":
					//快递 直接把订单号设置为tracking_number
        			break;
        		case "CRP":
        			//挂号 直接在tracking_number分配一个给
        			if($this->_order['order']['change_order']=='1'){ 
                        // var_dump(in_array($this->_order['order']['sm_code'],array('UKTL','SZY-EUB','WG-EUB','SZY-ETK','BH-USPS')));
        				if(!in_array($this->_order['order']['sm_code'],array('UKTL','SZY-EUB','WG-EUB','SZY-ETK','BH-USPS','BH-SFEP','WG-EUB-EBAY' ,
						'BH-DPD','SF-RUPR','SF-RUPT', '4PX-LYT_GH', //A6
                            '4PX-EU_PACKET', //DS
                            '4PX-RU_POST-LINK_RMAIL', //BA
                            '4PX-HKDHL', //A1
                            '4PX-YX', //AI
                            '4PX-SG_ordinary_mail+',
                             '4PX-Singapo_SPack_IMAIR',
                            'LYT-SMTGH-X',
                             '4PX-OZXBTH',
                            'PNLG','PNLN','Rumall-RU-G','Rumall-RU-EP','CJ-DGMG','CJ-DGMP','DGM-US','BH-AZAT-G','BH-POST-NL',' BH-NLPOST-TH'
						))){
                            $conditionTrackinNumber = array(
                                'warehouse_id'=>$this->warehouse_id,
                                'sm_code'=>$this->_order['order']['sm_code'],
                                'stn_status'=>'0',
                            );
                            /* if ($this->_order['order']['sm_code']=='CJ-DGMG') {
                            $oab=Service_OrderAddressBook::getByField($orderCode,'order_code');
                                if (!empty($oab)) {
                                    if ($oab['oab_country_id']=='253') {
                                        $conditionTrackinNumber['stn_code_arr']=array('LX561450126DE','LX561480128DE');
                                    }
                                }
                            } */
                            $trackingNumber = Service_ServiceTrackingNumber::getByConditionLock($conditionTrackinNumber,'*',1,1);
                            if(!empty($trackingNumber)){
                                $trackingNumberDate = $trackingNumber[0];
                                $serviceTrackingNumberRow = array(
                                    'order_code'=>$this->_order['order']['order_code'],
                                    'stn_status'=>'1',
                                    'stn_update_time'=>date('Y-m-d H:i:s',time()),
                                );
                            
                                Service_ServiceTrackingNumber::update($serviceTrackingNumberRow, $trackingNumberDate['stn_id']);
                                //$change_tracking = Service_ServiceTrackingNumber::getTrackingNumber($this->_order['order']['sm_code'], $trackingNumberDate['stn_code']);
                                $updateOrder = array(
                                    'ref_tracking_number'=>$trackingNumberDate['stn_code'],
                                );
                                $this->_order['order']['ref_tracking_number'] = $trackingNumberDate['stn_code'];
                                $this->_order['order']['tracking_number'] = $trackingNumberDate['stn_code'];
                                Service_Orders::update($updateOrder,$this->_order['order']['order_code'],'order_code');
                                $orderRow['tracking_number'] = $trackingNumberDate['stn_code'];

                                $result['isPrint'] = '1';
                                $result['orderDate']['order'] = $orderRow;

                            }else{
                                //没有服务商单号
                                throw new Exception('没有该运输方式的服务商单号,无法分配');
                            }
                        }
        			}
                                if($this->_order['order']['sm_code']=='4PX-Singapo_SPack_IMAIR' || $this->_order['order']['sm_code']=='4PX-OZXBTH'){
                                    $track	= $orderRow['tracking_number'];
                                }else{
                                    $track	= $this->_order['order']['order_code'];
                                }
        			break;
        		case "CPS":
        			//平邮  直接把订单号 设置为tracking_number
        			break;
        		default:
        	}
            $warehouse = Common_DataCache::getWarehouse(0,$this->_order['order']['warehouse_id']);
            $updateOrder = array('order_status' => 7, 'print_quantity' => 1, 'update_time' => $this->_date);
            //环球不用再去录单，有自动任务录单
        	if( $this->_order['order']['customer_code'] == 'E0693' && $warehouse['warehouse_code'] == 'SZ01' && in_array($this->_order['order']['sm_code'], array('HKDHL','BH-HKDHL'))) {
                $updateOrder['order_status'] = 14;
                $result['printLabel'] = 0;
            }

            if (!Service_Orders::update($updateOrder, $this->_order['order']['order_code'], 'order_code')) {
                throw new Exception('更新订单状态失败.');
            }

            /*if($orderRow['order_mode_type']!="1"){
                if (!Service_ProductPackage::update(array('pp_quantity' => abs($packageRow['pp_quantity'] - 1), 'pp_update_time' => $this->_date), $packageCode, 'pp_barcode')) {
                    throw new Exception('更新包材使用数量失败.');
                }
            }*/

            if (!Service_OrderOperationTime::update(array('pack_time' => $this->_date, 'update_time' => $this->_date, 'pack_user_id' => $this->_userId), $this->_order['order']['order_code'], 'order_code')) {
                throw new Exception('更新订单操作时间失败.');
            }
            $node = array(
                'order_id' => $this->_order['order']['order_id'],
                'order_code' => $this->_order['order']['order_code'],
                'oot_code' => 'pack',
                'user_id' => $this->_userId
            );
            Service_OrderOperationNode::add($node);

            $w = Service_Warehouse::getByField($this->_order['order']['warehouse_id'],'warehouse_id','*');
            $shipOrderTracking = array(
                'order_code'=>$this->_order['order']['order_code'],
                'sot_location'=>$w['warehouse_desc'],
                'sot_add_time'=>date("Y-m-d H:i:s"),
                'warehouse_id'=>$this->_order['order']['warehouse_id'],
                'sot_description'=>'备货订单分拣打包,并打印快递面单完毕',
                'sot_type'=>'0',
                'sot_time_offset'=>'',
                'tracking_number'=>$this->_order['order']['order_code'],
                'ref_tracking_number'=>'',
                'status_desc'=>'已打包',
                'user_id'=>$this->_userId
            );
            Service_ShipOrderTracking::add($shipOrderTracking);
            $this->addOrderLog();
            $this->addShipOrder();
            //包材费屏蔽
            //$this->orderFee($packageCode,$this->_order['order']['order_code']);
            $db->commit();
            //$db->rollBack();
            $result['state'] = 1;
            $result['message'] = '操作成功.';
            $result['data'] = $this->_order;
			$orderProduct = Service_OrderProduct::getByCondition(array('order_code'=>$this->_order['order']['order_code']),"*");
            $op=0;  //订单的总目的海关申报价值
            foreach ($orderProduct as $key => $value) {
                $order = Service_Orders::getByField($value['order_id'],"order_id","*");
               if ($order['sm_code']=='BH-DPD') {
                    $op+=$value['op_purpose_declared_value']*$value['op_quantity'];
                }
            }
            $op=Service_Currency::converByCode('USD', 'EUR', $op);
            if ($op>300) {
                $result['op']=$op;
            }
			
/*            $orderAddressObj=new Table_OrderAddressBook();
            $result['data']['address'] =$orderAddressObj->getLeftJoinByField($this->_order['order']['order_id'],'order_id');
            $result['data']['address']['country'] = Service_Country::getByField($result['data']['address']['oab_country_id'], 'country_id',array('country_name','country_name_en','country_code'));
            $result['data']['sm']=Service_ShippingMethod::getByField($this->_order['order']['sm_code'],'sm_code',array('sm_code','sm_name_cn','sm_name','sm_logo','sm_return_address'));
            $shipRow=Service_ShipOrder::getByField($this->_order['order']['order_id'],'order_id',array('tracking_number'));
            $result['data']['ship']['tracking_number']=$orderCode;
            if(!empty($shipRow) && $shipRow['tracking_number']!=''){
                $result['data']['ship']=$shipRow;
            }*/

        } catch (Exception $e) {
            $db->rollBack();
            $result['error'][] = $e->getMessage();
        }
        $result2=Service_PackProcess::getOrderInfo($orderCode);
        $result['data']['date'] = $result2['data']['date'];
        $result['data']['address'] = $result2['data']['address'];
        $result['data']['sm'] = $result2['data']['sm'];
        $result['data']['pick_area'] = $result2['data']['pick_area'];
        $result['data']['area'] = $result2['data']['area'];
        $result['data']['orderOptionTime'] = $result2['data']['orderOptionTime'];
        $result['data']['ship'] = $result2['data']['ship'];
        $result['data']['battery_type'] = $result2['data']['battery_type'];
		if('' != $track){
			$result['data']['ship']['tracking_number']	= $track;
		}
        return $result;
    }

    public function jhpack($orderCode = '', $packageCode = '', $orderPickType = 0, $warehouseId = null){
        $result = array('state' => 0, 'message' => '', 'error' => array(),'data'=>array(), 'orderCode' => $orderCode);
        $this->setOrder($orderCode, $warehouseId, $orderPickType);
        $this->_order['order']['packageCode'] = $packageCode;

        /*if (!Service_OrderOperationTime::update(array('pack_time' => $this->_date, 'update_time' => $this->_date, 'pack_user_id' => $this->_userId), $orderCode, 'order_code')) {
            throw new Exception('更新订单操作时间失败.');
        }*/
        $node = array(
            'order_id' => $this->_order['order']['order_id'],
            'order_code' => $this->_order['order']['order_code'],
            'oot_code' => 'pack',
            'user_id' => $this->_userId
        );
        Service_OrderOperationNode::add($node);
        //$this->addOrderLog();
        $this->addShipOrder();
        $result['state'] = 1;
        $result['message'] = '操作成功.';
        $result['data'] = $this->_order;
        return $result;
    }

    /**
     * @desc 分配服务商单号
     */
    protected function getServiceTrackingNumber()
    {
        /*$condition = array(
            'warehouse_id_in' => array(0, $this->_order['order']['warehouse_id']),
            'sm_code' => $this->_order['order']['sm_code'],
            'stn_status' => '0',
        );
        $trackingNumber = $this->_order['order']['order_code'];
        $stnObj = new Table_ServiceTrackingNumber();
        $trackingNumberRows = $stnObj->getByCondition($condition, array('stn_id', 'stn_code'), 2, 1, array('warehouse_id desc', 'order_code'));
        if (!empty($trackingNumberRows)) {
            $trackingNumber = $trackingNumberRows[0]['stn_code'];
            if (!$stnObj->update(array('order_code' => $this->_order['order']['order_code'], 'stn_status' => 1, 'stn_update_time' => $this->_date), $trackingNumberRows[0]['stn_id'], 'stn_id')) {
                throw new Exception('更新服务商单号失败.');
            }
        }*/
        //集货模式的订单 并且不换单 订单里面填写的服务商单号不为空 用订单的服务商单号 做此服务商单号
        $orderTracking = $this->_order['order']['ref_tracking_number'];
        $orderTracking = trim($orderTracking);
        if(!empty($orderTracking) && $this->_order['order']['order_mode_type']=='1'){
        	//集货并且参考号不为空
        	return $orderTracking;
        }else{
        	//参考号为空 的集货 和备货 
        	$stnObj = new Table_ServiceTrackingNumber();
        	$trackingNumberRows = $stnObj->getByField($this->_order['order']['order_code'],'order_code',"*");
        	if(!empty($trackingNumberRows)){
        		$updateOrder = array(
        				'ref_tracking_number'=>$trackingNumberRows['stn_code'],
        		);
        		Service_Orders::update($updateOrder,$this->_order['order']['order_code'],'order_code');
        		return $trackingNumberRows['stn_code'];
        	}else{
        		//空的话按下面操作 
        		
        		$shipMethod = Service_ShippingMethod::getByField($this->_order['order']['sm_code'],'sm_code');
        		
        		switch($shipMethod['sm_class_code']){
        			//CRE:快递;CRP:挂号;CPS:平邮'
        			case "CRE":
        				//快递 直接把订单号设置为tracking_number
        				return $this->_order['order']['order_code'];
        			case "CRP": 
        			    if(in_array($this->_order['order']['sm_code'], array('CJ-DGMG','CJ-DGMP','DGM-US','BH-POST-NL')))break;
        				//挂号 直接在tracking_number分配一个给  非自有渠道
        				$conditionTrackinNumber = array(
        						'warehouse_id'=>$this->warehouse_id,
        						'sm_code'=>$this->_order['order']['sm_code'],
        						'stn_status'=>'0',
        				);
                       /* if ($this->_order['order']['sm_code']=='CJ-DGMG') {
                            $oab=Service_OrderAddressBook::getByField($this->_order['order']['order_code'],'order_code');
                                if (!empty($oab)) {
                                    if ($oab['oab_country_id']=='253') {
                                        $conditionTrackinNumber['stn_code_arr']=array('LX561450126DE','LX561480128DE');
                                    }
                                }
                        } */
        				$trackingNumber = Service_ServiceTrackingNumber::getByConditionLock($conditionTrackinNumber,'*',1,1);
        				if(!empty($trackingNumber)){
        					$trackingNumberDate = $trackingNumber[0];
        					$serviceTrackingNumberRow = array(
        							'order_code'=>$this->_order['order']['order_code'],
        							'stn_status'=>'1',
        							'stn_update_time'=>date('Y-m-d H:i:s',time()),
        					);
        					Service_ServiceTrackingNumber::update($serviceTrackingNumberRow, $trackingNumberDate['stn_id']);
        					//$change_tracking = Service_ServiceTrackingNumber::getTrackingNumber($this->_order['order']['sm_code'], $trackingNumberDate['stn_code']);
        					$updateOrder = array(
        							'ref_tracking_number'=>$trackingNumberDate['stn_code'],
        					);
        					$this->_order['order']['ref_tracking_number'] = $trackingNumberDate['stn_code'];
        					Service_Orders::update($updateOrder,$this->_order['order']['order_code'],'order_code');
        					//}
        					return $trackingNumberDate['stn_code'];
        				}else{
        					//没有服务商单号
        					throw new Exception('没有该运输方式的服务商单号,无法分配');
        				}
        				break;
        			case "CPS":
        				//平邮  直接把订单号 设置为tracking_number
        				return $this->_order['order']['order_code'];
        				break;
        			default:
        				return $this->_order['order']['order_code'];
        		}
        		
        	}
        }
        /* if($this->_order['order']['order_mode_type']=='1' && $this->_order['order']['change_order']=='0'){
        	$trackingNumber = $orderTracking;
        	return $trackingNumber;
        } */
    }

    /**
     * @desc 订单物流信息
     */
    protected function addShipOrder()
    {  
        //环球客户在建订单的时候已经添加ship_order信息
        $warehouse = Common_DataCache::getWarehouse(0,$this->_order['order']['warehouse_id']);
        if( $warehouse['warehouse_code'] == 'SZ01' && $this->_order['order']['customer_code'] == 'E0693' && in_array($this->_order['order']['sm_code'],array('HKDHL','BH-HKDHL')))
            return;

        $orderShipRow = Service_ShipOrder::getByField($this->_order['order']['order_code'], 'order_code');
        if (empty($orderShipRow)) {
            $soCode = Common_GetNumbers::getCode('shiporder', $this->_order['order']['customer_code'], 'SP');
            
            $shipMethodCondition = array(
            		'warehouse_id_arr'=>array($this->_warehouseId,"0"),
            		'sm_code'=>$this->_order['order']['sm_code'],
            		'sm_status'=>'1',
            );
            $shipMethodArr = Service_ShippingMethod::getByCondition($shipMethodCondition,'*',1,1);
            if(empty($shipMethodArr)){
            	throw new Exception('运输方式无效或禁用');
            }else{
            	$shipMethod = $shipMethodArr[0];
            }
            //是否换单情况(是否自有运输渠道是)
            /* if($this->_order['order']['order_mode_type']=='1' && $this->_order['order']['change_order']=='0'){
            	//是换单就不分派服务商单号
            	$trackingNumber = $this->getServiceTrackingNumber();
            }else{
            	switch($shipMethod['sm_class_code']){
            		//CRE:快递;CRP:挂号;CPS:平邮'
            		case "CRE":
            			//tracking_No为订单号
            			$trackingNumber = $this->_order['order']['order_code'];
            			break;
            		case "CRP":
            			$trackingNumber=$this->_order['order']['ref_tracking_number'];
            			if(empty($trackingNumber)){
            				$trackingNumber = $this->_order['order']['order_code'];
            			}
            			break;
            		case "CPS":
            			$trackingNumber = $this->_order['order']['order_code'];
            			break;
            		default:
            	}
            } */
                $noDistributionSmcode = array(
                           "SZY-EUB",'WG-EUB',"UKTL","SZY-ETK",'BH-USPS','BH-SFEP','WG-EUB-EBAY' , 'BH-DPD','SF-RUPR','SF-RUPT','PNLG','PNLN',
                            '4PX-LYT_GH', //A6
                            '4PX-EU_PACKET', //DS
                            '4PX-RU_POST-LINK_RMAIL', //BA
                            '4PX-HKDHL', //A1
                            '4PX-YX', //AI
                            '4PX-SG_ordinary_mail+',
                            '4PX-Singapo_SPack_IMAIR',
                            'LYT-SMTGH-X',
                            '4PX-OZXBTH',
                             'Rumall-RU-G','Rumall-RU-EP',
                            'CJ-DGMG','DGM-US',
                            'CJ-DGMP','BH-AZAT-G',
                            'DHL-BH03','BH-POST-NL'
                        );
            if(in_array($this->_order['order']['sm_code'],$noDistributionSmcode)){
                $trackingNumber = $this->_order['order']['ref_tracking_number'];
            }else{
                $trackingNumber = $this->getServiceTrackingNumber();
            }
            $packageRow=Service_ProductPackage::getByField($this->_order['order']['packageCode'],'pp_barcode');
            $orderRow = array(
                'so_code' => $soCode,
                'order_id' => $this->_order['order']['order_id'],
                'order_code' => $this->_order['order']['order_code'],
                'warehouse_id' => $this->_order['order']['warehouse_id'],
                'sm_code' => $this->_order['order']['sm_code'],
                'pp_barcode' => $this->_order['order']['packageCode'],
                //'pp_name'  =>$packageRow['pp_name'],
                'tracking_number' => $trackingNumber,
                'so_add_time' => $this->_date,
            );
            if (!$soId = Service_ShipOrder::add($orderRow)) {
                throw new Exception('添加物流信息失败.');
            }

            foreach ($this->_order['products'] as $key => $val) {
                $detailRow = array(
                    'so_id' => $soId,
                    'so_code' => $soCode,
                    'order_id' => $this->_order['order']['order_id'],
                    'order_code' => $this->_order['order']['order_code'],
                    'op_id' => $val['op_id'],
                    'sod_quantity' => $val['op_quantity'],
                    'op_description' => $val['product_title_en'],
                    'cn_description' => $val['product_title'],
                    'op_title' => $val['product_title'],
                    'hs_code' => isset($val['hs_code']) ? $val['hs_code'] : '',
                    'op_unit_price' => $val['product_sales_value'],
                    'op_subtotal' => round($val['op_quantity'] * $val['product_sales_value'], 4),
                    'op_origin' => '',
                    'op_declared_value' => $val['product_declared_value'],
                );
                if (!Service_ShipOrderDetail::add($detailRow)) {
                    throw new Exception ('添加物流详细失败. ' . $val['op_id']);
                }
            }
        } else {
            $orderRow = array(
                'pp_barcode' => $this->_order['order']['packageCode'],
                'so_update_time' => $this->_date,
            );
            if ($orderShipRow['tracking_number'] == '') {
                //$orderRow['tracking_number'] = $this->getServiceTrackingNumber();
                if(in_array($this->_order['order']['sm_code'],array("SZY-EUB",'WG-EUB',"SZY-ETK","UKTL",'WG-EUB-EBAY','4PX-LYT_GH', //A6
                            '4PX-EU_PACKET', //DS
                            '4PX-RU_POST-LINK_RMAIL', //BA
                            '4PX-HKDHL', //A1
                            '4PX-YX', //AI
                            '4PX-SG_ordinary_mail+',
							'PNLG','PNLN',
                    'Rumall-RU-G','Rumall-RU-EP','LYT-SMTGH-X','BH-AZAT-G'
						))){
                    $trackingNumber = $this->_order['order']['ref_tracking_number'];
                }else{
                    $trackingNumber = $this->getServiceTrackingNumber();
                }
            }
            if (!Service_ShipOrder::update($orderRow, $orderShipRow['so_id'], 'so_id')) {
                // 更新失败？重新获取该记录比较更新时间证实是否真的更新失败（解决整进整出创建ship_order又在这里更新ship_order引起的更新失败的BUG）
                $shipOrder = Service_ShipOrder::getByField($this->_order['order']['order_code'], 'order_code');
                if ($this->_date !== $shipOrder['so_update_time']) {
                  throw new Exception('更新物流信息失败.'.$this->_date);
                }
            }
        }
    }

    /**
     * @desc 订单操作日志
     */
    private function addOrderLog()
    {
        $orderLogObj = new Service_OrderLog();
        $log = array(
            'order_id' => $this->_order['order']['order_id'],
            'order_code' => $this->_order['order']['order_code'],
            'user_id' => $this->_userId,
            'ol_type' => '0',
            'ol_add_time' => $this->_date,
            'order_status_from' => $this->_order['order']['order_status'],
            'order_status_to' => 7,
            'ol_ip' => Common_Common::getIP(),
            'ol_add_time' => $this->_date,
            'ol_comments' => 'pack',
        );
        $orderLogObj->add($log);
    }

    /**
     * @desc 如果是一票一件 须要更新状态为已配货
     * @当下架单中的订单全部完成时，更新下架单状态
     * @return $state 0,完成部分 1,整个下架单完成
     */
    private function updatePicking()
    {
        $state = 0;
        if ($this->_order['order']['order_pick_type'] == '0') {
            Service_PickingDetail::update(array('pd_status' => 1), $this->_order['order']['order_id'], 'order_id');
            $total = Service_PickingDetail::getByCondition(array('picking_id' => $this->_pickingId, 'pd_status' => '0'), 'count(*)');
            if ($total == '0') {
                Service_Picking::update(array('picking_status' => 1, 'picking_update_time' => $this->_date), $this->_pickingId, 'picking_id');
                $state = 1;
            }
        }
        return $state;
    }

    /**
     * @desc 一票一件打包 自动分配 订单并返回订单号
     * @params $pickingCode 下架单，$packageCode 包材代码
     * @return array
     */
    public function assignOrderTransaction($pickingCode = '', $packageCode = '', $productBarcode = '', $warehouseId = null)
    {
        $result = array('state' => 0, 'message' => '', 'error' => array(), 'isFocus' => 0, 'orderCode' => '','printLabel'=>1);
        $orderCode = '';
        if ($warehouseId != null) {
            $this->_warehouseId = $warehouseId;
        }
        if (empty($productBarcode)) {
            $this->_errorArr[] = '产品代码不能为空!';
        }
        if (empty($pickingCode)) {
            $this->_errorArr[] = '下架单不能为空!';
        } else {
            $pickRow = Service_Picking::getByField($pickingCode, 'picking_code');
            if (empty($pickRow)) {
                $this->_errorArr[] = '下架单:' . $pickingCode . ' 不存在.';
                $result['isFocus'] = 1;
            } elseif ($pickRow['warehouse_id'] != $this->_warehouseId) {
                $this->_errorArr[] = '下架单:' . $pickingCode . ' 不匹配当前操作员仓库.';
            } elseif ($pickRow['picking_status'] == '1') {
                $this->_errorArr[] = '下架单:' . $pickingCode . ' 已完成,不允许操作.';
            } else {
                $pdRows = Service_PickingDetail::getByCondition(array('picking_id' => $pickRow['picking_id'], 'product_barcode' => trim($productBarcode), 'pd_status' => '0'), '*');
                if (empty($pdRows)) {
                     $product=Service_Product::getByCondition(array('product_sku'=>trim($productBarcode)),"*");
                     if (!empty($product)) {
                        foreach ($product as $key => $value) {
                            $pdRows = Service_PickingDetail::getByCondition(array('picking_id' => $pickRow['picking_id'], 'pd_status' => '0', 'product_barcode' => $value['product_barcode']), '*');
                            if (!empty($pdRows)) {
                               break;
                            }
                        }
                         $productBarcode=$pdRows[0]['product_barcode'];
                         
                         if (empty($pdRows)) {
                    $this->_errorArr[] = '没有找到匹配 ' . $productBarcode . ' 未完成打包的订单.';
                    $result['isFocus'] = 2;
                }
            }
                   
        }
            }
        }

       /* if (empty($packageCode)) {
            $this->_errorArr[] = '包材不能为空!';
        } else {
            $packageRow = Service_ProductPackage::getByField($packageCode, 'pp_barcode');
            if (empty($packageRow)) {
                $this->_errorArr[] = '包材代码:' . $packageCode . ' 不存在.';
                $result['isFocus'] = 3;
            } elseif ($packageRow['pp_status'] != '1') {
                $this->_errorArr[] = '包材代码:' . $packageCode . ' 不可用.';
                $result['isFocus'] = 3;
            }
        }*/
        if (!empty($this->_errorArr)) {
            $result['error'] = $this->_errorArr;
            return $result;
        }
        $orderCode = isset($pdRows[0]['order_code']) ? $pdRows[0]['order_code'] : '';

        $this->setOrder($orderCode, null, 0);

        if (!empty($this->_errorArr)) {
            $result['error'] = $this->_errorArr;
            return $result;
        }
        
        $shipMethod = Service_ShippingMethod::getByField($this->_order['order']['sm_code'],'sm_code');
        /*$serviceTracking = Service_ServiceTrackingNumber::getByField($this->_order['order']['order_code'],'order_code');
        if(!empty($serviceTracking)){
			$error = $result['error'];
			$error[] = "订单号{$this->_order['order']['order_code']}已经分配过服务商单号";
        	$result['error'] = $error;
        	return $result;
        }*/
		$track	= '';
        $this->_pickingCode = $pickingCode;
        $this->_pickingId = $pickRow['picking_id'];
        $this->_order['order']['packageCode'] = $packageCode;

        $db = Service_QualityControl::getModelInstance()->getAdapter();
        $db->beginTransaction();
        try {
        	if($shipMethod['sm_class_code']=='CRP'){
        		//挂号 换单情况下 分配一个服务商单号
        		if($this->_order['order']['change_order']=='1'){
                            $noDistributionSmcode = array(
                            "UKTL", "SZY-EUB", 'WG-EUB',
                            "SZY-ETK", 'BH-USPS','BH-SFEP',
                            "WG-EUB-EBAY",
                            'BH-DPD',
                            'SF-RUPR',
                            'SF-RUPT',
                            'PNLG',
                            'PNLN',
                            '4PX-LYT_GH', //A6
                            '4PX-EU_PACKET', //DS
                            '4PX-RU_POST-LINK_RMAIL', //BA
                            '4PX-HKDHL', //A1
                            '4PX-YX', //AI
                            '4PX-SG_ordinary_mail+',
                            '4PX-OZXBTH',
                            'Rumall-RU-G','Rumall-RU-EP',
                             '4PX-Singapo_SPack_IMAIR',
                             'LYT-SMTGH-X',
                            '4PX-Singapo_SPack_IMAIR',
                            'LYT-SMTGH-X',
                            'CJ-DGMG','DGM-US',
                            'CJ-DGMP','BH-AZAT-G','BH-POST-NL',' BH-NLPOST-TH'
                                );
                    if(!in_array($this->_order['order']['sm_code'],$noDistributionSmcode)){
                        $conditionTrackinNumber = array(
                            'warehouse_id'=>$this->warehouse_id,
                            'sm_code'=>$this->_order['order']['sm_code'],
                            'stn_status'=>'0',
                        );
                         /* if ($this->_order['order']['sm_code']=='CJ-DGMG') {
                            $oab=Service_OrderAddressBook::getByField($this->_order['order']['order_code'],'order_code');
                                if (!empty($oab)) {
                                    if ($oab['oab_country_id']=='253') {
                                        $conditionTrackinNumber['stn_code_arr']=array('LX561450126DE','LX561480128DE');
                                    }
                                }
                            } */
                        $trackingNumber = Service_ServiceTrackingNumber::getByConditionLock($conditionTrackinNumber,'*',1,1);
                        if(!empty($trackingNumber)){
                            $trackingNumberDate = $trackingNumber[0];
                            $serviceTrackingNumberRow = array(
                                'order_code'=>$this->_order['order']['order_code'],
                                'stn_status'=>'1',
                                'stn_update_time'=>date('Y-m-d H:i:s',time()),
                            );
                            Service_ServiceTrackingNumber::update($serviceTrackingNumberRow, $trackingNumberDate['stn_id']);
                            //$change_tracking = Service_ServiceTrackingNumber::getTrackingNumber($this->_order['order']['sm_code'], $trackingNumberDate['stn_code']);

                            $updateOrder = array(
                                'ref_tracking_number'=>$trackingNumberDate['stn_code'],
                            );
                            $this->_order['order']['ref_tracking_number'] = $trackingNumberDate['stn_code'];
                            $this->_order['order']['tracking_number'] = $trackingNumberDate['stn_code'];
                            Service_Orders::update($updateOrder,$this->_order['order']['order_code'],'order_code');

                            $orderRow['tracking_number'] = $trackingNumberDate['stn_code'];
                            $result['isPrint'] = '1';
                            $result['orderDate']['order'] = $orderRow;
                        }else{
                            //没有服务商单号
                            $result['isFocus'] = 2;
                            throw new Exception('没有该运输方式的服务商单号,无法分配');
                        }
                    }
        		}
                if($this->_order['order']['sm_code']=='4PX-Singapo_SPack_IMAIR' || $this->_order['order']['sm_code']=='4PX-OZXBTH'){
                    $track	= $orderRow['tracking_number'];
                }else{
                    $track	= $this->_order['order']['order_code'];
                }

        	}
            $o = Service_Orders::getByField($this->_order['order']['order_code'], 'order_code',"*");

            if($o['order_status']!= '5') throw new Exception( '订单: ' . $orderCode . ' 不是已打印状态.');

            //账户冻结
            $customerData = Service_Customer::getByField($o['customer_code'], 'customer_code', array('is_frozen', 'frozen_reason'));
            if($customerData['is_frozen']){
                throw new Exception('订单:['. $this->_order['order']['order_code'] .']，客户['.$o['customer_code'].']已冻结，冻结原因：'.$customerData['frozen_reason']);
            }

            $warehouse = Common_DataCache::getWarehouse(0,$this->_order['order']['warehouse_id']);
            $updateOrder = array('order_status' => 7, 'print_quantity' => 1, 'update_time' => $this->_date);
            //环球不用再去录单，有自动任务录单,且不用打标签，环球是直接打好包贴好标签送到仓库的
            if( $this->_order['order']['customer_code'] == 'E0693' && $warehouse['warehouse_code'] == 'SZ01' && in_array($this->_order['order']['sm_code'], array('HKDHL','BH-HKDHL'))) {
                $updateOrder['order_status'] = 14;
                $result['printLabel'] = 0;
            }

            if (!Service_Orders::update($updateOrder, $this->_order['order']['order_code'], 'order_code')) {
                $result['isFocus'] = 2;
                throw new Exception('更新订单状态失败.');
            }

            /*if (!Service_ProductPackage::update(array('pp_quantity' => abs($packageRow['pp_quantity'] - 1), 'pp_update_time' => $this->_date), $packageCode, 'pp_barcode')) {
                throw new Exception('更新包材使用数量失败.');
            }*/
            if (!Service_OrderOperationTime::update(array('pack_time' => $this->_date, 'update_time' => $this->_date, 'pack_user_id' => $this->_userId), $this->_order['order']['order_code'], 'order_code')) {
                $result['isFocus'] = 2;
                throw new Exception('更新订单操作时间失败.');
            }
            $node = array(
                'order_id' => $this->_order['order']['order_id'],
                'order_code' => $this->_order['order']['order_code'],
                'oot_code' => 'pack',
                'user_id' => $this->_userId
            );
            Service_OrderOperationNode::add($node);
            $this->addOrderLog();
            $this->addShipOrder();

            $orderRow = Service_Orders::getByField($this->_order['order']['order_code'],"order_code","*");
            $w = Service_Warehouse::getByField($orderRow['warehouse_id'],'warehouse_id','*');
            $shipOrderTracking = array(
                'order_code'=>$this->_order['order']['order_code'],
                'sot_location'=>$w['warehouse_desc'],
                'sot_add_time'=>date("Y-m-d H:i:s"),
                'warehouse_id'=>$orderRow['warehouse_id'],
                'sot_description'=>'备货订单分拣打包,并打印快递面单完毕',
                'sot_type'=>'0',
                'sot_time_offset'=>'',
                'tracking_number'=>$this->_order['order']['order_code'],
                'ref_tracking_number'=>'',
                'status_desc'=>'已打包',
                'user_id'=>Service_User::getUserId()
            );
            Service_ShipOrderTracking::add($shipOrderTracking);
            $pickStatus = $this->updatePicking();
            //屏蔽包材费
            //$this->orderFee($packageCode,$this->_order['order']['order_code']);
            $db->commit();
           	//$db->rollBack();
            $orderProduct = Service_OrderProduct::getByCondition(array('order_code'=>$this->_order['order']['order_code']),"*");
            $op=0;  //订单的总目的海关申报价值
            foreach ($orderProduct as $key => $value) {
                $order = Service_Orders::getByField($value['order_id'],"order_id","*");
               if ($order['sm_code']=='BH-DPD') {
                    $op+=$value['op_purpose_declared_value']*$value['op_quantity'];
                }
            }
            $op=Service_Currency::converByCode('USD', 'EUR', $op);
            if ($op>300) {
                $result['op']=$op;
            }
            $result['isFocus'] = $pickStatus ? '1' : '2';
            $result['state'] = 1;
            $result['message'] = '操作成功.';
            $result['orderCode'] = $orderCode;
            $result['pickingCode'] = $pickingCode;
            $result['data'] = $this->_order;
		
/*            $result['data']['address'] =Service_OrderAddressBook::getByField($this->_order['order']['order_id'],'order_id');
            $result['data']['address']['country'] = Service_Country::getByField($result['data']['address']['oab_country_id'], 'country_id',array('country_name','country_name_en','country_code'));
            $result['data']['sm']=Service_ShippingMethod::getByField($this->_order['order']['sm_code'],'sm_code',array('sm_code','sm_name_cn','sm_name','sm_logo','sm_return_address'));
            $shipRow=Service_ShipOrder::getByField($this->_order['order']['order_id'],'order_id',array('tracking_number'));
            $result['data']['ship']['tracking_number']=$orderCode;
            if(!empty($shipRow) && $shipRow['tracking_number']!=''){
                $result['data']['ship']=$shipRow;
            }*/
        } catch (Exception $e) {
            $db->rollBack();
            $result['error'][] = $e->getMessage();
        }
        $result2=Service_PackProcess::getOrderInfo($orderCode);
        $result['data']['date'] = $result2['data']['date'];
        $result['data']['address'] = $result2['data']['address'];
        $result['data']['sm'] = $result2['data']['sm'];
        $result['data']['pick_area'] = $result2['data']['pick_area'];
        $result['data']['area'] = $result2['data']['area'];
        $result['data']['orderOptionTime'] = $result2['data']['orderOptionTime'];
        $result['data']['ship'] = $result2['data']['ship'];
        $result['data']['battery_type'] = $result2['data']['battery_type'];
		if('' != $track){
			$result['data']['ship']['tracking_number']	= $track;
		}
        return $result;
    }

    /**
     * @desc 确认完成下架单,将未完成的Item转移到新的下架中
     * @params $pickingCode,$warehouseId
     * @return array
     */
    public function  confirmPickOrderTransaction($pickingCode, $warehouseId = null)
    {
        $result = array('state' => 0, 'message' => '', 'error' => array(), 'pickingCode' => '');
        if ($warehouseId != null) {
            $this->_warehouseId = $warehouseId;
        }

        if (empty($pickingCode)) {
            $this->_errorArr[] = '下架单不能为空!';
        } else {
            $pickRow = Service_Picking::getByField($pickingCode, 'picking_code');
            if (empty($pickRow)) {
                $this->_errorArr[] = '下架单:' . $pickingCode . ' 不存在.';
            } elseif ($pickRow['warehouse_id'] != $this->_warehouseId) {
                $this->_errorArr[] = '下架单:' . $pickingCode . ' 不匹配当前操作员仓库.';
            } elseif ($pickRow['picking_status'] == '1') {
                $this->_errorArr[] = '下架单:' . $pickingCode . ' 已完成,不允许操作.';
            }
        }
        if (!empty($this->_errorArr)) {
            $result['error'] = $this->_errorArr;
            return $result;
        }

        $this->_pickingCode = $pickingCode;
        $this->_pickingId = $pickRow['picking_id'];

        $db = Service_QualityControl::getModelInstance()->getAdapter();
        try {
            $db->beginTransaction();
            $code = Common_GetNumbers::getCode('picking',$this->_warehouseId, 'PL');
            $shelfArr = array();
            $pdRows = Service_PickingDetail::getByCondition(array('picking_id' => $pickRow['picking_id'], 'pd_status' => '0'), '*');
            if (empty($pdRows)) {
                throw new Exception('没有找到未完成的订单.');
            } else {
                foreach ($pdRows as $key => $val) {
                    if (!in_array($val['lc_code'], $shelfArr)) {
                        $shelfArr[] = $val['lc_code'];
                    }
                }
            }
            $shelfTotal = count($shelfArr);
            $orderTotal = count($pdRows);
            if ($pickRow['picking_order_cnt'] == $orderTotal) {
                throw new Exception('下架单:' . $pickingCode . ' 没有找到已完成的订单.');
            }

            $row = array(
                'warehouse_id' => $pickRow['warehouse_id'],
                'picking_code' => $code,
                'picker_id' => $pickRow['picker_id'],
                'creater_id' => $this->_userId,
                'picking_order_cnt' => $orderTotal,
                'picking_lc_cnt' => $shelfTotal,
                'picking_item_cnt' => $orderTotal,
                'picking_status' => 0,
                'is_assign' => 1,
                'picking_type' => 0,
                'picking_add_time' => $this->_date
            );
            if (!$pickingId = Service_Picking::add($row)) {
                throw new Exception('创建新下架单失败.');
            }
            $pdObj = new Table_PickingDetail();
            if (!$pdObj->updateByPickingIdAndStatus(array('picking_id' => $pickingId, 'picking_code' => $code, 'pd_add_time' => $this->_date), $this->_pickingId, '0')) {
                throw new Exception('转移未完成订单失败.');
            }
            $lcCode = Service_PickingDetail::getGroupShelfByPickingId($this->_pickingId, array('lc_code'));
            $updateRow = array(
                'picking_order_cnt' => $pickRow['picking_order_cnt'] - $orderTotal,
                'picking_lc_cnt' => count($lcCode),
                'picking_item_cnt' => $pickRow['picking_item_cnt'] - $orderTotal,
                'picking_update_time' => $this->_date,
                'picking_status' => 1
            );
            if (!Service_Picking::update($updateRow, $this->_pickingId, 'picking_id')) {
                throw new Exception('下架单:' . $pickingCode . ' 更新失败.');
            }

            $db->commit();
            $result['state'] = 1;
            $result['message'] = 'Success.';
            $result['pickingCode'] = $code;
            $result['orderCnt'] = $orderTotal;
        } catch (Exception $e) {
            $db->rollBack();
            $result['error'][] = $e->getMessage();
        }

        return $result;
    }

    /**
     * @desc 根据订单号获取订单物流信息
     * @param string $orderCode $orderStatus 状态限制
     * @return array
     */
    public static function getOrderInfo($orderCode = '',$orderStatus=array())
    {
        $result = array('state' => 0, 'message' => '', 'data' => array());
        $orderRow = Service_Orders::getByField($orderCode, 'order_code');
        if (empty($orderRow)) {
            $result['message'] = 'Not Data.';
            return $result;
        }
        $orderTraking=Service_ServiceTrackingNumber::getByField($orderRow['order_code'],'order_code');
        if(!empty($orderTraking)){
        	$change_tracking = Service_ServiceTrackingNumber::getTrackingNumber($orderRow['sm_code'], $orderTraking['stn_code']);
        	$orderRow['tracking_number'] = $change_tracking;
        }else{
        	$orderRow['tracking_number'] ='';
        }
        if(count($orderStatus)>0){
            if(!in_array($orderRow['order_status'],$orderStatus)){
                $result['message'] = '订单目前状态不允许操作.';
                return $result;
            }
        }
        //打印次数
        Service_Orders::update(array('print_quantity' => $orderRow['print_quantity'] + 1), $orderRow['order_id'], 'order_id');
        $dataArr=array();
        $result['state']=1;
        $dataArr['order']=$orderRow;
        $dataArr['date']=date('m/d H:i:s');
        $orderAddress = Service_OrderAddressBook::getByField($orderRow['order_id'], 'order_id');
        $dataArr['address'] = $orderAddress;
        $countryinfo=Service_Country::getByField($dataArr['address']['oab_country_id'], 'country_id',array('country_name','country_name_en','country_code'));
        $dataArr['address']['country'] = $countryinfo;
        $dataArr['address']['postcode']='';
        //邮编问题
        if ($dataArr['address']['oab_state'] == '' && $dataArr['address']['oab_city'] == '' && $dataArr['address']['oab_postcode'] != '') {
            $dataArr['address']['postcode'] = $dataArr['address']['oab_postcode'];
        }
        $dataArr['sm'] = Service_ShippingMethod::getByField($orderRow['sm_code'], 'sm_code', array('sm_code', 'sm_name_cn', 'sm_name', 'sm_logo', 'sm_return_address','sm_short_name','sm_return_recipient','sm_class_code','sm_is_volume'));
        $shipRow = Service_ShipOrder::getByField($orderRow['order_id'], 'order_id', array('tracking_number'));
        //运输方式标签分区
        $araeObj = new Table_TransportPickArea();
        $tpaRows = $araeObj->getByCondition(array('sm_code' => $orderRow['sm_code'], 'country' => $dataArr['address']['country']['country_code']), array('area_code'));
        $dataArr['pick_area'] = isset($tpaRows[0]['area_code'])?$tpaRows[0]['area_code']:'';
        //分区
        $smCondition = array(
        	'warehouse_id'=>$orderRow['warehouse_id'],
        	'sm_code'=>$orderRow['sm_code'],
        	'country_name'=>$orderAddress['country_name_en'],
        	'country_code'=>$countryinfo['country_code']	
        );
        if($orderRow['sm_code']=='4PX-Singapo_SPack_IMAIR' || $orderRow['sm_code']=='4PX-OZXBTH'){
            unset($smCondition['warehouse_id']);
            $smCondition['warehouse_id_arr']=array(0,$orderRow['warehouse_id']);
        }
        $smInfo = Service_SmCountryMap::getByCondition($smCondition,array('area'),1,1);
        $dataArr['area'] = isset($smInfo[0]['area'])?$smInfo[0]['area']:'';
       //订单产品
        $orderProducts = Service_OrderProduct::getByCondition(array('order_id'=>$orderRow['order_id']));
        $with_battery=0;
        $totalWeight=0;
        $totalValue=0;
        $batterType=0;
        if(!empty($orderProducts)){
        	foreach ($orderProducts as $keyp=>$product){
        		$productSku = Service_Product::getByField($product['product_id']);
        		$orderProducts[$keyp]['product_weight'] = $productSku['product_weight'];
        		$orderProducts[$keyp]['product_title_cn'] = $productSku['product_title'];
        		$orderProducts[$keyp]['customer_code'] = $productSku['customer_code'];
        		$orderProducts[$keyp]['hs_goods_name'] = $productSku['hs_goods_name'];
                if ($productSku['with_battery']=='1') {
                    $with_battery=1;
                }
                if($productSku['battery_type'] == '1'){
                    $batterType = '1';
                }
                $totalValue+=floatval($product['op_purpose_declared_value']*$product['op_quantity']);
                $totalWeight+=floatval($productSku['product_weight']*$product['op_quantity']);
        	}
            $op=array();
            foreach ($orderProducts as $key => $value) {
                $op[]=$value;
               if ($key==4) {
                   break;
               }
            }
        }
        
        $dataArr['orderProduct'] = $op;
        $dataArr['with_battery'] = $with_battery;
        $dataArr['battery_type'] = $batterType;
        $dataArr['totalWeight'] = $totalWeight;
        $dataArr['totalValue'] = $totalValue;
        $dataArr['ship']['tracking_number'] = $orderCode; 
        if (!empty($shipRow) && $shipRow['tracking_number'] != '') {
            $dataArr['ship'] = $shipRow;
        }
		$shipMethod = Service_ShippingMethod::getByField($orderRow['sm_code'],'sm_code');
        if($orderRow['sm_code']=='BH-AZAT-G'&&empty($shipRow)){
            $dataArr['ship']['tracking_number'] = $orderRow['ref_tracking_number'];
        }
        if($orderRow['sm_code']=='4PX-Singapo_SPack_IMAIR' || $orderRow['sm_code']=='4PX-OZXBTH'){
            if(empty($dataArr['ship']['tracking_number'])&&!empty($orderRow['ref_tracking_number'])){
                  $dataArr['ship']['tracking_number']=$orderRow['ref_tracking_number'];
            }
            $dataArr['returnSign'] = 'Y';
        }
        if(in_array($shipMethod['sm_class_code'], array('CRP','CRE'))){
            if(empty($shipRow)){
                if($orderRow['ref_tracking_number']!=''){
                    $dataArr['ship']['tracking_number'] = $orderRow['ref_tracking_number'];
                }
            }else{
                $dataArr['ship']['order_code']	= $orderRow['order_code'];
                $dataArr['ship']['tracking_number'] = $shipRow['tracking_number'];
            }
        }
        $result['data'] = $dataArr;
        return $result;
    }
    /**
     **扣包材费
     */
    public function orderFee($packageCode='',$order_code=''){
         //扣费
        $otherfee = Service_OtherFee::getByField('BAOCAI', 'fee_code');
        if (!empty($order_code)) {
            $orders=Service_Orders::getByField($order_code,'order_code');
        }
        $productPackage=Service_ProductPackage::getByField($packageCode,'pp_barcode');
        $baocaiFee     = sprintf('%.2f', $productPackage['pp_price']);
        $baocaiCost    = sprintf('%.2f', $productPackage['pp_cost']);

        $customerFeeCondition = array(
            'customer_code' => $orders['customer_code'],
            'fee_id'        => $otherfee['fee_id']
        );
        $customerOtherFee = Service_CustomerOtherFee::getByCondition($customerFeeCondition, '*');
        if ($otherfee['is_default_fee'] == '1') {
            //操作费可用
            if (!empty($customerOtherFee)) {
                if ($customerOtherFee[0]['status'] == 0 && 
                    $customerOtherFee[0]['discount']>0) {
                    $baocaiFee = 0;
                    $baocaiCost =0;
                } else { 
                    $baocaiFee = $customerOtherFee[0]['discount'] * $baocaiFee;
                    $discount   = $customerOtherFee[0]['discount'];
                }
            }
        } else {
            //操作费不可用
            if ($customerOtherFee[0]['discount']>0 && $customerOtherFee[0]['status'] == '1') {
                $baocaiFee = $customerOtherFee[0]['discount'] * $baocaiFee;
                $discount   = $customerOtherFee[0]['discount'];
            } else {
                $baocaiFee = 0;
                $baocaiCost =0;
            }
        }  
         $otherfee_data = array(
            'cost_currency_code'  => $productPackage['currency_code'],
            'currency_code' => $productPackage['currency_code'],
            'price'         => $baocaiFee,
            'discount'      => $discount,
            'cost'          => $baocaiCost,
            'sp_code'       => $otherfee['sp_code'],
            'fee_id'        => $otherfee['fee_id']
        );
         //print_r($otherfee_data);exit;
         //$order_code=$this->_order['order']['order_code'];
        $userAuth                   = new Zend_Session_Namespace('userAuthorization');
        $aOrder                     = Service_Orders::getByField($order_code, 'order_code');
        $aShipOrder                 = Service_ShipOrder::getByField($order_code, 'order_code');
        $aAddress                   = Service_OrderAddressBook::getByField($order_code, 'order_code');
        $countryArr                 = Service_Country::getByField($aAddress['oab_country_id'],'country_id');
        $customerArr                = Service_Customer::getByField($aOrder['customer_code'],'customer_code',array('customer_saler_user_id','customer_currency'));
        $customerCurrencyRow        = Service_Currency::getByField($customerArr['customer_currency'],'currency_code',array('currency_code','currency_rate','currency_batch_number'));
        $shippingMethodArr          = Service_ShippingMethod::getByField($aOrder['sm_code'],'sm_code',array('sm_vol_rate','sm_is_volume'));
        $currency_batch_number      = $customerCurrencyRow['currency_batch_number']; 
        $_cbl_note      = '订单打包，扣';
        $otherfee_name  =  'baocai';
        /* 当前汇率编号 */
        $_otherfee_mix_arr          = Process_BillConfig::getOtherFeeArr();
        $fee_cost_detail            = array(); /* 费用及成本明细 */
        $spArr                      = array();
        $incomeArr                  = array(); /* 客户费用 应收 */
        $paymentArr                 = array(); /* 应付费用 */
        $realWeight                 = 0;
        $date                       = date('Y-m-d H:i:s');
        $remote_ip                  = Common_Common::getIP();
        $currencyCacheRows          = Common_DataCache::getCurrency();
               // print_r($_otherfee_mix_arr);exit;
         if (empty($otherfee_data['cost_currency_code'])) {
                $otherfee_data['cost_currency_code']=$otherfee_data['currency_code'];
            }
            if($otherfee_data['price'] > 0){
                    $convert_fee                    = Service_Currency::converByCode($otherfee_data['currency_code'], $customerArr['customer_currency'], $otherfee_data['price']);
                    $otherfee_rate                  = $currencyCacheRows[$otherfee_data['currency_code']]['currency_rate'];

                $result = Service_CustomerBalanceProcess::deductFee($aOrder['customer_id'], $otherfee_data, $_cbl_note . $_otherfee_mix_arr[$otherfee_name]['binote'], $order_code, $_otherfee_mix_arr[$otherfee_name]['ftcode'], $otherfee_data['fee_id']);
                if(0 == $result['ask']) return $result['error'];

                //应收记录
                $incomeArr[] = array(
                    'customer_code'         => $aOrder['customer_code'],
                    'ft_code'               => $_otherfee_mix_arr[$otherfee_name]['ftcode'],
                    'ut_code'               => $_otherfee_mix_arr[$otherfee_name]['utcode'],
                    'sm_code'               => $aOrder['sm_code'],
                    'bi_amount'             => $convert_fee,
                    'bi_org_amount'         => $otherfee_data['price'],
                    'currency_code'         => $otherfee_data['currency_code'],
                    'currency_rate'         => $otherfee_rate,
                    'bi_chargeable_time'    => $date,
                    'bi_note'               => $_otherfee_mix_arr[$otherfee_name]['binote'],
                );
                $fee_detail = array(
                    'fee_amount_customer'           => $convert_fee,                                        //费用金额（客户）
                    'fee_currency_code_customer'    => $customerArr['customer_currency'],                   //费用币种（客户）
                    'discount_customer'             => $otherfee_data['discount'],                          //折扣率（客户）（1=100%）
                );
            }
            //print_r($fee_detail);exit;
            if(isset($otherfee_data['cost']) && $otherfee_data['cost'] > 0 && $otherfee_data['sp_code']!=''){
                if(!isset($spArr[$otherfee_data['sp_code']])){
                    $spRow = Service_ServiceProvider::getByField($otherfee_data['sp_code'],'sp_code');
                    $spArr[$otherfee_data['sp_code']] = $spRow['currency_code'];
                }

                    $convert_fee    = Service_Currency::converByCode($otherfee_data['cost_currency_code'], $spArr[$otherfee_data['sp_code']], $otherfee_data['cost']);
                    $otherfee_rate  = $currencyCacheRows[$otherfee_data['cost_currency_code']]['currency_rate'];

                //应付记录
                $paymentArr[] = array(
                    'sp_code'               => $otherfee_data['sp_code'],       //服务商代码
                    'ft_code'               => $_otherfee_mix_arr[$otherfee_name]['ftcode'],
                    'ut_code'               => $_otherfee_mix_arr[$otherfee_name]['utcode'],
                    'sm_code'               => $aOrder['sm_code'],
                    'bp_amount'             => $otherfee_data['cost'],                    //服务商结算金额
                    'bp_org_amount'         => $otherfee_data['cost'],          //原金额
                    'currency_code'         => $otherfee_data['cost_currency_code'], //原币种
                    'currency_rate'         => $otherfee_rate,
                    'bp_chargeable_time'    => $date,
                    'bp_note'               => $_otherfee_mix_arr[$otherfee_name]['binote'],
                );
                $cost_detail = array(
                    'cost_amount_org'               => $otherfee_data['cost'],                              //成本金额（原始）
                    'cost_currency_code_org'        => $otherfee_data['cost_currency_code'],                     //成本币种（原始）
                    'cost_amount_sp'                => $otherfee_data['cost'],                                        //成本金额（服务商）
                    'cost_currency_code_sp'         => $otherfee_data['cost_currency_code'],                   //成本币种（服务商）
                    'sp_code'                       => $otherfee_data['sp_code'],                           //服务商代码
                );
            }

            if(!empty($fee_detail) || !empty($cost_detail)){
                if (empty($fee_detail)) {$fee_detail=array();}
                if (empty($cost_detail)) {$cost_detail=array();}
                $fee_cost_common    = array(
                    'code_number'                   => $order_code,                                         //单号
                    'code_type'                     => 1,                                                   //单号类型（1:区内单 2：区外单 3：ASN单）
                    'customer_code'                 => $aOrder['customer_code'],                            //客户代码
                    'reference_no'                  => $aOrder['reference_no'],                             //客户参考号
                    'tracking_number'               => $aShipOrder['tracking_number'],                      //服务商单号（跟踪号）
                    'sm_code'                       => $aOrder['sm_code'],                                  //运输方式代码
                    'country_code'                  => $countryArr['country_code'],                         //国际简称（二字码）
                    'fee_code'                      => $_otherfee_mix_arr[$otherfee_name]['ftcode'],        //费用编号
                    'fee_name'                      => $_otherfee_mix_arr[$otherfee_name]['binote'],        //费用名称
                    'fee_amount_org'                => $otherfee_data['price'],                             //费用金额（原始）
                    'fee_currency_code_org'         => $otherfee_data['currency_code'],                     //费用币种（原始）
                    //'price_batch_number'            => $aCalculate['data']['cost']['price_batch_number'],   //运输价格编号
                     'price_batch_number'           => '',
                    'currency_batch_number'         => $currency_batch_number,                              //货币汇率编号
                    'fee_time'                      => $date,                                               //扣费时间
                    'fee_time_recalculate'          => $date,                                               //重新扣费时间
                    'ip'                            => $remote_ip,                                          //扣费操作IP
                    'ip_recalculate'                => $remote_ip,                                          //重新扣费操作IP
                    'operator'                      => $userAuth->user['user_name'],                         //扣费操作人
                    'operator_recalculate'          => $userAuth->user['user_name'],                         //重新扣费操作人
                );

                $fee_cost_detail[]  = array_merge($fee_detail, $cost_detail, $fee_cost_common);
            }
            //print_r($fee_cost_detail);exit;
        $_bb_volumne_weight = 0;
       
        $businessArr = array(
            'ds_code'                   => 'so',
            'customer_code'             => $aOrder['customer_code'],
            'warehouse_id'              => $aOrder['warehouse_id'],
            'sm_code'                   => $aOrder['sm_code'],
            'bb_volume_weight'          => $_bb_volumne_weight,
            'bb_charge_weight'          => $aShipOrder['so_weight'],
            'bb_delivered_weight'       => $aShipOrder['so_weight'],
            'bb_pieces'                 => $aOrder['parcel_quantity'],
            'bb_declared_value'         => $aOrder['parcel_declared_value'],
            'bb_declared_currency_code' => 'USD',
            'country_code'              => $countryArr['country_code'],
            'bb_postcode'               => $aAddress['oab_postcode'],
            'bb_charge_time'            => $aOrder['add_time'],
            'bb_declared_time'          => $date, //发货时间 此时间与服务商对接
            'bb_sales_id'               => $customerArr['customer_saler_user_id'],
            'bb_refer_code'             => $aOrder['order_code'],
            'bb_service_number'         => $aOrder['ref_tracking_number'],//
            'bb_reference_no'           => $aOrder['reference_no'],
        );
        $bsObj          = new Process_Business();
        /*$paymentArr     = ('0' == $rpType) ? array() : $paymentArr;*/
        $businessResult = $bsObj->businessFee($businessArr, $incomeArr, $paymentArr);
        if($businessResult['state']!='1'){
            return $businessResult['message'];
        }

        //更新 费用及成本明细表
       // Service_FeeCostDetail::delete($order_code, 'code_number'); /* 清除同一订单号的杂费 */
        $feecostdetailResult = Service_FeeCostDetail::addMultiRows($fee_cost_detail);
        return true;
    }
}