<?php

class Merchant_LogisticsController extends Ec_Controller_Action
{

    public function preDispatch ()
    {
        $this->tplDirectory = "merchant/views/logistics/";
        $this->customerAuth = new Zend_Session_Namespace("customerAuth");
    }
    
    public function indexAction ()
    {
    	$this->listOrderAction();
    }
    
    private function getPostData()
    {
    	$postData = array();
    	//订单信息
    	$order = array();
    	$order['reference_no'] = trim($this->_request->getParam('reference_no',''));
    	$order['sm_code'] = trim($this->_request->getParam('sm_code',''));
    	$order['ref_tracking_number'] = trim($this->_request->getParam('ref_tracking_number',''));
		$order['lo_weight'] = trim($this->_request->getParam('lo_weight',''));
		$order['pack_number'] = trim($this->_request->getParam('pack_number',''));
		$order['size_width'] = trim($this->_request->getParam('size_width',''));
		$order['size_height'] = trim($this->_request->getParam('size_height',''));
		$order['size_length'] = trim($this->_request->getParam('size_length',''));
		$order['destination_tax'] = trim($this->_request->getParam('destination_tax',''));
		$order['warehouse_id'] = 3;	//仓库
    	//收件人信息
    	$receiver = array();
    	$receiver['loa_name'] = trim($this->_request->getParam('loa_name',''));
    	$receiver['loa_company'] = trim($this->_request->getParam('loa_company',''));
    	$receiver['loa_country'] = trim($this->_request->getParam('loa_country',''));
        $receiver['loa_province'] = trim($this->_request->getParam('loa_province',''));
        $receiver['loa_city'] = trim($this->_request->getParam('loa_city',''));
    	$receiver['loa_zipcode'] = trim($this->_request->getParam('loa_zipcode',''));
    	$receiver['loa_phone'] = trim($this->_request->getParam('loa_phone',''));
    	$receiver['loa_address'] = trim($this->_request->getParam('loa_address',''));
    	//发件人信息
    	$sender = array();
    	$sender['loa_name'] = trim($this->_request->getParam('sender_name',''));
    	$sender['loa_company'] = trim($this->_request->getParam('sender_company',''));
    	$sender['loa_province'] = trim($this->_request->getParam('sender_province',''));
    	$sender['loa_city'] = trim($this->_request->getParam('sender_city',''));
    	$sender['loa_phone'] = trim($this->_request->getParam('sender_phone',''));
    	$sender['loa_address'] = trim($this->_request->getParam('sender_address',''));
    	//海关申报信息
    	$hsList = array();
    	$loh_ids = $this->_request->getParam('loh_id','');
    	if(is_array($loh_ids) && count($loh_ids)>0 ) {
    		$loh_hs_names = $this->_request->getParam('loh_hs_name','');
    		$loh_units = $this->_request->getParam('loh_unit','');
    		$loh_prices = $this->_request->getParam('loh_price','');
    		$loh_quantitys = $this->_request->getParam('loh_quantity','');
    		$loh_hs_codes = $this->_request->getParam('loh_hs_code','');
    		$loh_names = $this->_request->getParam('loh_name','');
    		$loh_notes = $this->_request->getParam('loh_note','');
    		foreach($loh_ids as $key=>$loh_id) {
    			$row = array();
    			$row['loh_id'] = trim($loh_id);
    			$row['loh_hs_name'] = trim($loh_hs_names[$key]);
    			$row['loh_unit'] = trim($loh_units[$key]);
    			$row['loh_price'] = trim($loh_prices[$key]);
    			$row['loh_quantity'] = trim($loh_quantitys[$key]);
    			$row['loh_hs_code'] = trim($loh_hs_codes[$key]);
    			$row['loh_name'] = trim($loh_names[$key]);
    			$row['loh_note'] = trim($loh_notes[$key]);
    			$hsList[] = $row;
    		}
                
    	}
    	$postData['order'] = $order;
    	$postData['address'] = $receiver;
    	$postData['sender'] = $sender;
    	$postData['hs_list'] = $hsList;
    	return $postData;
    }
    
    /*建立订单*/
    public function createOrderAction() {
        if($this->_request->isPost()){
        	$result = array('ask'=>0, 'message'=>'');
        	$postData = $this->getPostData();	
        	$v = Service_LogisticsProcess::validator($postData);
        	if($v === true) {
        		$db = Common_Common::getAdapter();
        		$db->beginTransaction();
        		try{
                                 $postData['order']['is_remote_city']=0;
                                if($postData['order']['sm_code']=='HKDHL'){
                                    if(empty($postData['address']['loa_company'])){
                                        $postData['address']['loa_company']=$postData['address']['loa_name'];
                                    }
                                    $orderProcess=new Service_OrderProcess();
                                    $isRemote=$orderProcess->isRemoteCity($postData['address']['loa_country'],$postData['address']['loa_city'],$postData['address']['loa_zipcode']);
                                    if($isRemote){
                                          $postData['order']['is_remote_city']=1;
                                    }
                                }
        			$logistics_code = Service_LogisticsProcess::addLogisticsOrder($postData);
                                
        			$db->commit();
        			$result['ask'] = 1;
                    $result['message'] = '创建订单['.$logistics_code.']成功';
                    if(isset($isRemote)&&$isRemote){
                        $result['message'] .= '<br>订单属于偏远地区，如需修改，请在草稿状态下进行编辑修改';
                    }
                    if($postData['order']['sm_code']=='BH-DPD'){
                        $registry = Zend_Registry::getInstance();
                        if (isset($registry['loh_total_price'])) {
                            $totaldeclareEUR = Service_Currency::converByCode("USD", "EUR", $registry['loh_total_price']);
                            if($totaldeclareEUR >= 50){
                                $result['message'] .= '<br><span style="color:red;">订单号为'.$logistics_code.'有机会被征收关税</span>';
                            }
                        }
                        
                    }
                    
                    if($postData['order']['sm_code']=='CJ-DGMG' || $postData['order']['sm_code']=='CJ-DGMP'){
                        $search = array(" ","　","\n","\r","\t");
                        $loa_address = str_replace($search,"",$postData['address']['loa_address']);
                        $is_contain = false;
                        if(strstr(strtoupper($loa_address),'POSTOFFICE')){
                            $is_contain = true;
                        }
                        if(strstr(strtoupper($loa_address),'POSTBOX')){
                            $is_contain = true;                    
                        }
                        if($is_contain === true){
                            $result['message'] .= '<br><span style="color:red;">订单号为'.$logistics_code.'地址内包含POST OFFICE/POST BOX，派送不会另行通知</span>';                    
                        }                        
                    }                                
                                
        			$result['logistics_code'] = $logistics_code;
        		} catch(Exception $e) {
        			$db->rollback();
        			$result['message'] = $e->getMessage();
        		}
        	} else {
        		$result['message'] = implode('<br>', $v);
        	}        	
			echo json_encode($result);
        } else {        	
        	$hsunit = Service_ProductUom::getByCondition();
        	$this->view->hsunit = $hsunit;
        	$this->view->hsunitJson = json_encode($hsunit);
			/* $shipMethods = Service_ShippingMethod::getByCondition(array('method_code_arr'=>array('SWPT','BH-MMP')));
			$this->view->shipMethods = $shipMethods; */
			$this->view->shipMethods = Service_LogisticsProcess::getShipMethods();
        	echo Ec::renderTpl($this->tplDirectory.'order-create.tpl', 'noleftlayout');
        }
    }
    
     /*修改订单*/
    public function editOrderAction() {
    	$logistics_code = trim($this->_request->getParam('logistics_code',''));
    	if(empty($logistics_code)) exit('error parameter');
    	$aOrder = Service_LogisticsOrder::getByField($logistics_code, 'logistics_code');
    	if($this->_request->isPost()){
    		$result = array('ask'=>0, 'message'=>'');
    		$postData = $this->getPostData();
			$v = Service_LogisticsProcess::validator($postData,$logistics_code);
    		if($v === true) {
	    		$db = Common_Common::getAdapter();
	    		$db->beginTransaction();
	    		try{    		
                                     $postData['order']['is_remote_city']=0;
                                if($postData['order']['sm_code']=='HKDHL'){
                                    if(empty($postData['address']['loa_company'])){
                                        $postData['address']['loa_company']=$postData['address']['loa_name'];
                                    }
                                    $orderProcess=new Service_OrderProcess();
                                    $isRemote=$orderProcess->isRemoteCity($postData['address']['loa_country'],$postData['address']['loa_city'],$postData['address']['loa_zipcode']);
                                    if($isRemote){
                                          $postData['order']['is_remote_city']=1;
                                    }
                                }
	    			Service_LogisticsProcess::editLogisticsOrder($logistics_code, $postData);
	    			$db->commit();
	    			$result['ask'] = 1;
                    $result['message'] = '编辑订单['.$logistics_code.']成功';
                    if(isset($isRemote)&&$isRemote){
                         $result['message'].= '<br>订单属于偏远地区，如需修改，请在草稿状态下进行编辑修改';
                    }
                    $registry = Zend_Registry::getInstance();
                    if (isset($registry['loh_total_price'])) {
                        $totaldeclareEUR = Service_Currency::converByCode("USD", "EUR", $registry['loh_total_price']);
                        if($totaldeclareEUR >= 50){
                            $result['message'] .= '<br><span style="color:red;">订单号为'.$logistics_code.'有机会被征收关税</span>';
                        }
                    }
                    if($postData['order']['sm_code']=='CJ-DGMG' || $postData['order']['sm_code']=='CJ-DGMP'){
                        $search = array(" ","　","\n","\r","\t");
                        $loa_address = str_replace($search,"",$postData['address']['loa_address']);
                        $is_contain = false;
                        if(strstr(strtoupper($loa_address),'POSTOFFICE')){
                            $is_contain = true;
                        }
                        if(strstr(strtoupper($loa_address),'POSTBOX')){
                            $is_contain = true;                    
                        }
                        if($is_contain === true){
                            $result['message'] .= '<br><span style="color:red;">订单号为'.$logistics_code.'地址内包含POST OFFICE/POST BOX，派送不会另行通知</span>';                    
                        }                        
                    }                             
                            
	    			$result['logistics_code'] = $logistics_code;
	    		} catch(Exception $e) {
	    			$db->rollback();
	    			$result['message'] = $e->getMessage();
	    		}
    		} else {
    			$result['message'] = implode('<br>', $v);
    		}
    		echo json_encode($result);
    	} else {    		
    		if(empty($aOrder) || $aOrder['lo_status']!=0) exit('error parameter');
			$this->view->country = Common_DataCache::getShipTypeCountryMap();
    		$this->view->logistics_code = $logistics_code;
    		$this->view->aOrder = $aOrder;
    	 	$addressList = Service_LogisticsOrderAddress::getByCondition(array('logistics_code'=>$logistics_code));
    		foreach($addressList as $addressRow) {
    			if($addressRow['loa_type']==0) $this->view->aAddress = $addressRow;
    			else if($addressRow['loa_type']==1) $this->view->aSender = $addressRow;
    		}
    	 	//$this->view->aAddress = Service_LogisticsOrderAddress::getByField($logistics_code, 'logistics_code');
    		$this->view->hsList = Service_LogisticsOrderHs::getByCondition(array('logistics_code'=>$logistics_code));
    		$hsunit = Service_ProductUom::getByCondition();
    		$this->view->hsunit = $hsunit;
    		$this->view->hsunitJson = json_encode($hsunit);
			/* $shipMethods = Service_ShippingMethod::getByCondition(array('method_code_arr'=>array('SWPT','BH-MMP')));
			$this->view->shipMethods = $shipMethods; */			
			$this->view->shipMethods = Service_LogisticsProcess::getShipMethods();
			echo Ec::renderTpl($this->tplDirectory.'order-create.tpl', 'noleftlayout');
    	}
    }
    
	/*物流订单*/
    public function listOrderAction ()
    {
	
    	//echo 'dddddddddd';exit;
        //set_time_limit(0);
    	$customer = $this->_customerAuth;
        $customerId = $customer['id'];
        $this->view->customer_code = $customer['code'];
        //if($this->_request->isPost()){
            $page = $this->_request->getParam('page', 1);
            $pageSize = $this->_request->getParam('pageSize', 20);
        
            $page = $page ? $page : 1;
            $pageSize = $pageSize ? $pageSize : 20;
            $pageSize = min($pageSize,1000);
            $condition = array();
            /* 以下为提交数据整理 */
        
            $orders_code_CustomerReference = trim($this->_request->getParam("orders_code_CustomerReference",""));
            $condition["orders_code_CustomerReference"] = $orders_code_CustomerReference;
        

            $condition["customer_id"] = $customerId;
        
        
            $warehouse_id = $this->_request->getParam("warehouse_id","");
            $condition["warehouse_id"] = $warehouse_id;
        

            $country_id = $this->_request->getParam("country_id","");
            $condition["country_id"] = $country_id;
            
            $orders_status = $this->_request->getParam("orders_status","0");
            
        
            $shipping_method = $this->_request->getParam("shipping_method","");
            $condition["sm_code"] = $shipping_method;                    

            //增加开始结束时间
            $add_time_start	= trim($this->_request->getParam('add_time_start',''));
            $condition["add_time_start"] = $add_time_start;
            
            $add_time_end	= trim($this->_request->getParam('add_time_end',''));
            $condition['add_time_end']	= $add_time_end;
            $orders_status_arr = explode(',',$orders_status);
			$condition['order_status_arr'] = $orders_status_arr;
			
            //print_r(array('1'));
			//print_r($orders_status_arr);     	
            $return = array(
                    "ask" => 0,
                    "message" => "No Data"
            );
            /* 以下为业务逻辑方法调用 */
            $count = Service_LogisticsOrder::getJoinOrderByCondition($condition, 'count(*)');
            $return['count'] = $count;
            $cacheProduct = array();
            $rows = '';
            if ($count) {
                $rows = Service_LogisticsOrder::getJoinOrderByCondition($condition, '*', $pageSize,$page,'lo_id desc');

                //$categories = Common_DataCache::getProductCategory();
                //$orderTypes = Service_OrderProcess::getOrderTypeArr();
                foreach($rows as $k=>$v){

                    $products = array();                    
                    $products= Service_LogisticsOrderHs::getByCondition(array('logistics_code'=>$v['logistics_code']));
                    
					 foreach($products as $kk=>$vv){
            			if($vv['loh_unit']){
							$productUom = Service_ProductUom::getByField($vv['loh_unit'],"pu_code","*");
            				$products[$kk]['pu_name'] = $productUom['pu_name'];	
						}  	
					 }				
					
					$v['order_product'] = $products;               
                    if($v['loa_country']){
						$countries= Service_Country::getByField($v['loa_country'],'country_id','*');
						 $v['country_name'] = $countries['country_name'];
					}
                              
                   
                    $rows[$k]=$v;
                }

                $return['data'] = $rows;
                $return['ask'] = 1;
                $return['message'] = "";
            }

			

            $allStatus = Service_LogisticsOrderProcess::getOrderStatus();
           //print_r($orderStatusArr);
            //处理数量问题
            if(!empty($allStatus)){
            	$numConditon = $condition;
            	foreach($allStatus as $keys=>$values){
            		$numConditon['order_status_arr'] = explode(',',$keys);
            		$countnum = Service_LogisticsOrder::getJoinOrderByCondition($numConditon, 'count(*)');
            		$allStatus[$keys] = $values."({$countnum})";
            	}
            }
			      
            
        $warehouse = Common_DataCache::getWarehouse();

        $this->view->warehouse = $warehouse;
        
        $this->view->result = $rows;
		
 		/*$countryArr = Common_DataCache::getShipTypeCountryMap();
		$this->view->country = $countryArr;*/
        
        $shipType = Common_DataCache::getShippingMethod();
        $smArray = array();
        foreach($shipType as $key=>$sm){
            if ($sm['warehouse_id']=='0' ||$sm['warehouse_id']=='3') {
                $smArray[$key]['sm_code'] = $sm['sm_code'];
                $smArray[$key]['sm_name_cn'] =$sm['sm_code'].'&nbsp;&nbsp;'.$sm['sm_name_cn'];
            }
            
        }
        sort($smArray);
        $this->view->shipType = $smArray;
       /* echo "<pre>";
        print_r($smArray);
        echo "</pre>";*/
        $this->view->count = $count;
        $this->view->page	  =	$page;
        $this->view->pageSize = $pageSize;

        $this->view->orderStatusArr = $allStatus;
        $this->view->orderType = Service_OrderProcess::getOrderTypeArr();
        $this->view->params = $condition;
        $this->view->orders_status=$orders_status;
        echo Ec::renderTpl($this->tplDirectory . "order-list.tpl",'noleftlayout');
	
	
    	
    }
	
   /*订单详细*/
    public function detailAction ()
    {
        $ordersCode = $this->_request->getParam('ordersCode','');
 
        $order = Service_LogisticsOrder::getByField($ordersCode,"logistics_code","*");
		if(empty($order)){ exit("没有找到订单.");}		
		if($order['warehouse_id']){      	
        	$warehouse = Service_Warehouse::getByField($order['warehouse_id'],"warehouse_id","*");
        	$order['warehouse_code'] = $warehouse['warehouse_code'];
		}
		$order['orderStatusText'] =  Service_LogisticsOrderProcess::getOrderStatusText($order['lo_status']);		
        $this->view->order = $order;
      
        /* $orderAddress = Service_LogisticsOrderAddress::getByField($ordersCode,'logistics_code',"*");
        $country = Service_Country::getByField($orderAddress['loa_country'],"country_id","*");
        $orderAddress['country_name'] = $country['country_name'];
        $this->view->orderAddress = $orderAddress; */        
        $addressList = Service_LogisticsOrderAddress::getByCondition(array('logistics_code'=>$ordersCode));
        foreach($addressList as $addressRow) {
            $country = Service_Country::getByField($addressRow['loa_country'],"country_id","*");
            $addressRow['country_name'] = $country['country_name'];
        	if($addressRow['loa_type']==0) {
        		$this->view->orderAddress = $addressRow;
        	}
        	else if($addressRow['loa_type']==1) {
        		$this->view->orderSender = $addressRow;
        	}
        }		
		
        $orderProducts = Service_LogisticsOrderHs::getByCondition(array('logistics_code'=>$ordersCode),"*");
        if($orderProducts){
			foreach($orderProducts as $k=>$v){
            	if($v['loh_unit']){
					$productUom = Service_ProductUom::getByField($v['loh_unit'],"pu_code","*");
            		$orderProducts[$k]['pu_name'] = $productUom['pu_name'];	
				}
				
        	}     
		}  
        $this->view->orderProduct = $orderProducts;
      
        $logs = Service_LogisticsOrderLog::getByCondition(array('logistics_code'=>$ordersCode),"*",0,0,array('lol_id DESC'));
		foreach($logs as $key=>$value){
            if($value['lol_operator']>0){
                $user = Service_User::getByField($value['lol_operator'],'user_id',"*");
                $logs[$key]['user_code'] = $user['user_code'];
            }
        }
		
		$apiDHLlogs = Service_ApiDhl::getByField($ordersCode,'order_code');
		$this->view->apiDHLlogs=$apiDHLlogs;
        $this->view->logs = $logs;
        $allStatus = Service_LogisticsOrderProcess::getOrderStatusAll();
        $this->view->orderStatusArr = $allStatus;

        echo Ec::renderTpl($this->tplDirectory . "order-detail.tpl", 'noleftlayout');
    }	
	
   	/*运输方式到国家*/
    public function getCountriesByShipMethodAction(){	
		$result = array('ask'=>0,'data'=>array());
		$sm_code = $this->_request->getParam('sm_code','SWPT');
		//$warehouse_id = $this->_request->getParam('warehouse_id',3);
		$countries = Service_SmCountryMap::getJoinCountryByGroupCondition(array('sm_code'=>$sm_code),'smcm_id');
		if($countries){
			$result['ask'] =  1;
			$result['data'] =  $countries;			
		}
		die(Zend_Json::encode($result));
		
	}	
	
	/**
	 * 环球易购批量提交订单
	 * @author solar
	 */
	public function hqswghAction() {
		$return = array('ask' => 0, 'message' =>Ec_Lang::getInstance()->getTranslate('SubmitOrder').','.Ec_Lang::getInstance()->getTranslate('fail'));
		$orderArr	= $this->_request->getParam('orderArr','');
		if (!empty($orderArr)) {
			$success=0;
			$failse=0;
			$customer = $this->_customerAuth;
			$customerId = $customer['id'];
			$failsStr = '';
			foreach($orderArr as $key=>$logistics_code){
				$result = Service_LogisticsOrderProcess::hqswghOrder($logistics_code);
				
				if (!empty($result) && $result['ask']=='1') {
					$success++;
					$return['detailmessage'][] = '订单号'."[{$logistics_code}]成功.";
				}else{
					$return['detailmessage'][] = '订单号'."[{$logistics_code}]失败:".$result['message'];
					$failse++;
				}
			}
			if($success>0){
				$return['ask']=1;
			}
			$return['message']=Ec_Lang::getInstance()->getTranslate('SubmitOrder').','.Ec_Lang::getInstance()->getTranslate('success').':'.$success.Ec_Lang::getInstance()->getTranslate('fail').' :'.$failse.'<br/>'.$failsStr;
		}
		die(Zend_Json::encode($return));
	}
    
    /**
     * @todo 确认订单
     * @author solar
     */
    public function confirmAction(){
    	$return = array('ask' => 0, 'message' =>Ec_Lang::getInstance()->getTranslate('ConfirmOrder').','.Ec_Lang::getInstance()->getTranslate('fail'));
    	$orderArr	= $this->_request->getParam('orderArr','');
    	if (!empty($orderArr)) {
    		$success=0;
    		$failse=0;
    		$customer = $this->_customerAuth;
    		$customerId = $customer['id'];
    		$failsStr = '';
    		foreach($orderArr as $key=>$logistics_code){
    			$result = Service_LogisticsOrderProcess::confirmOrder($logistics_code);
    			if (!empty($result) && $result['ask']=='1') {
    				$success++;
                                $successMsg='订单号'."[{$logistics_code}]成功.";
                                if($result['is_remote_city']){
                                    $successMsg.='订单属于偏远地区';
                                }
    				$return['detailmessage'][] = $successMsg;
    			}else{
    				$return['detailmessage'][] = '订单号'."[{$logistics_code}]失败:".$result['message'];
    				$failse++;
    			}
    		}
    		if($success>0){
    			$return['ask']=1;
    		}
    		$return['message']=Ec_Lang::getInstance()->getTranslate('ConfirmOrder').','.Ec_Lang::getInstance()->getTranslate('success').':'.$success.Ec_Lang::getInstance()->getTranslate('fail').' :'.$failse.'<br/>'.$failsStr;
    	}
    	die(Zend_Json::encode($return));
    }
    
    /**
     * @todo 提交订单
     * @author solar
     */
    public function submitAction() {
    	$logisticsCode = $this->_request->getParam("logisticsCode","");
    	if(empty($logisticsCode)) exit('error parameter');
    	$aOrder = Service_LogisticsOrder::getByField($logisticsCode, 'logistics_code');
    	if(empty($aOrder) || $aOrder['lo_status']!=1) exit('error parameter');
		$customer = $this->_customerAuth;
    	$customerId = $customer['id'];
    	$result = Service_LogisticsOrderProcess::submitOrder($logisticsCode,$customerId);
    	if($result['ask']==0) exit($result['message']);
    	$this->printLabelAction();
    }
    
    /**
     * @author solar
     * @todo 打印标签
     */
    public function printLabelAction() {
    	$logisticsCode = $this->_request->getParam("logisticsCode","");
    	if(empty($logisticsCode)) exit('error parameter');
    	$aOrder = Service_LogisticsOrder::getByField($logisticsCode, 'logistics_code');
    	if(empty($aOrder)) exit('error parameter');
        $smInfo = Service_ShippingMethod::getByField($aOrder['sm_code'],"sm_code","*");
        //平邮
        //if($smInfo['sm_class_code']=="CPS") $aOrder['ref_tracking_number'] = "";
        //$aOrder['tracking_number'] = Service_ServiceTrackingNumber::getTrackingNumber($aOrder['sm_code'], $aOrder['ref_tracking_number']);
    	$aAddress = Service_LogisticsOrderAddress::getByWhere(array('logistics_code'=>$logisticsCode, 'loa_type'=>0));
    	$country = Service_Country::getByField($aAddress['loa_country'],'country_id',"*");
    	$aAddress['country_name_en'] = $country['country_name_en'];
    	$aAddress['country_name'] = $country['country_name'];
    	$hsList = Service_LogisticsOrderHs::getByCondition(array('logistics_code'=>$logisticsCode));
    	$total_price = 0.00;
    	foreach($hsList as $hsRow) $total_price += $hsRow['loh_total_price'];
        $aOrder['counthsList'] = count($hsList)>5?5:count($hsList);
    	$this->view->totalPrice = $total_price;
    	$this->view->aOrder = $aOrder;
    	$this->view->aAddress = $aAddress;
        if ($aOrder['sm_code']=="SF-RUPR"||$aOrder['sm_code']=="SF-RUPT") {
           $hsList = Service_LogisticsOrderHs::getByCondition(array('logistics_code'=>$logisticsCode),"*",5,1);
        }
    	$this->view->hsList = $hsList;
    	$this->view->smInfo = $smInfo;
      $this->view->country = $country;
      $this->view->area = '';
      $this->view->packNo = '';

      if ('HKPG' == $aOrder['sm_code']) {
        // 获取国家映射区域代码
        $smCountryMap = Service_SmCountryMap::getByInCondition(array(
          'warehouse_id_arr' => array(0, $aOrder['warehouse_id']),
          'sm_code' => $aOrder['sm_code'],
          'country_code' => $country['country_code']
        ));
        if ($smCountryMap) {
          $this->view->area = $smCountryMap[0]['area'];
        }
      }
      elseif ('HKPP' == $aOrder['sm_code']) {
        // 获取包袋号
        $this->view->packNo = Service_ChangePack::getPackNo($country['country_code'], $aAddress['loa_zipcode']);
         // 获取国家映射区域代码
        $smCountryMap = Service_SmCountryMap::getByInCondition(array(
          'warehouse_id_arr' => array(0, $aOrder['warehouse_id']),
          'sm_code' => $aOrder['sm_code'],
          'country_code' => $country['country_code']
        ));
        if ($smCountryMap) {
          $this->view->area = $smCountryMap[0]['area'];
        }
      }
    	if($aOrder['sm_code']=='HKDHL' || 'SZY-EMS' == $aOrder['sm_code'] || 'AUP' == $aOrder['sm_code'])
    		echo $this->view->render($this->tplDirectory . "/label/F4.tpl");
    	elseif($aOrder['sm_code']=='BH-SGG' || $aOrder['sm_code']=='BH-SGP'){
    		echo $this->view->render($this->tplDirectory . "/label/sg.tpl");
    	}
	elseif($aOrder['sm_code']=="BZAM"){
            echo $this->view->render($this->tplDirectory."/label/bzam.tpl");
        }
      elseif ('BH-MPPG' == $aOrder['sm_code']) {
        echo $this->view->render($this->tplDirectory . '/label/bh-mppg.tpl');
      }
      elseif ('HKPG' == $aOrder['sm_code']) {
        echo $this->view->render($this->tplDirectory . '/label/hkpg.tpl');
      }
      elseif ('HKPP' == $aOrder['sm_code']) {
        echo $this->view->render($this->tplDirectory . '/label/hkpp.tpl');
      }
      elseif ('CJ-DGMG' == $aOrder['sm_code']) {
        echo $this->view->render($this->tplDirectory . '/label/cj-dgmg.tpl');
      }
      elseif ('CJ-DGMP' == $aOrder['sm_code']) {
        echo $this->view->render($this->tplDirectory . '/label/cj-dgmp.tpl');
      }
       elseif ('SF-RUPR' == $aOrder['sm_code']) {
        echo $this->view->render($this->tplDirectory . '/label/rupr.tpl');
      }
       elseif ('SF-RUPT' == $aOrder['sm_code']) {
        echo $this->view->render($this->tplDirectory . '/label/rupt.tpl');
      }else{
    		echo $this->view->render($this->tplDirectory . "/label/sw.tpl");
    	}
    }
	
	/*批量提交打印标签*/
    public function submitOrdersAction() {
		
		$return = array('ask' => 0, 'orderCodeList'=>array(),'message' =>Ec_Lang::getInstance()->getTranslate('ConfirmOrder').','.Ec_Lang::getInstance()->getTranslate('fail'));
		$orderArr = $this->_request->getParam("orderArr","");
		
		
		if (!empty($orderArr)){
    		$success=0;
    		$failse=0;
    		$customer = $this->_customerAuth;
    		$customerId = $customer['id'];
    		$failsStr = '';
    		foreach($orderArr as $logisticsCode){							
				$customer = $this->_customerAuth;
    			$customerId = $customer['id'];
				$result = Service_LogisticsOrderProcess::submitOrder($logisticsCode,$customerId);
				if($result['ask']=='1'){
					$success++;
    				$return['detailmessage'][] = '订单号'."[{$logisticsCode}]成功.";
					$return['orderCodeList'][] = $logisticsCode;
                    $return['orderinfo'][] = array('order_code'=>$logisticsCode,'ref_tracking_number'=>$result['ref_tracking_number']);
				}else{
    				$return['detailmessage'][] = '订单号'."[{$logisticsCode}]失败:".$result['message'];
    				$failse++;
				}
						
			
			
			}// 
			
    		if($success>0){
    			$return['ask']=1;
    		}			
			$return['message']='提交订单,'.Ec_Lang::getInstance()->getTranslate('success').':'.$success.Ec_Lang::getInstance()->getTranslate('fail').' :'.$failse.'<br/>'.$failsStr;						
			 	
		}
    	die(Zend_Json::encode($return));
    }//submitOrdersAction() {
	
	
   /**
     * @author solar
     * @todo 批量打印标签
     */
    public function batchPrintLabelAction() {
		$orderCodes = $this->_request->getParam("orderCodes","");		
		if(!$orderCodes){ echo "没有参数.";exit;}
		$orderArr = explode(',',$orderCodes);		
		$orders = array();
		
		foreach($orderArr as $logisticsCode){
			if(empty($logisticsCode)){continue;}
			$aOrder = Service_LogisticsOrder::getByField($logisticsCode, 'logistics_code');
			if(empty($aOrder)) {
				 continue;//exit('error parameter');
			}
            $smInfo = Service_ShippingMethod::getByField($aOrder['sm_code'],"sm_code","*");
            //if($smInfo['sm_class_code']=="CPS") $aOrder['ref_tracking_number'] = "";
            //$aAddress = Service_LogisticsOrderAddress::getByField($logisticsCode, 'logistics_code');
            $aAddress = Service_LogisticsOrderAddress::getByWhere(array('logistics_code'=>$logisticsCode, 'loa_type'=>0));
    		$country = Service_Country::getByField($aAddress['loa_country'],'country_id',"*");
    		$aAddress['country_name_en'] = $country['country_name_en'];
    		$aAddress['country_name'] = $country['country_name'];
    		$hsList = Service_LogisticsOrderHs::getByCondition(array('logistics_code'=>$logisticsCode));
			$total_price = 0.00;
      $area = '';
      $packNo = '';
      if ('HKPG' == $aOrder['sm_code']) {
        // 获取国家映射区域代码
        $smCountryMap = Service_SmCountryMap::getByInCondition(array(
          'warehouse_id_arr' => array(0, $aOrder['warehouse_id']),
          'sm_code' => $aOrder['sm_code'],
          'country_code' => $country['country_code']
        ));
        if ($smCountryMap) {
          $area = $smCountryMap[0]['area'];
        }
      }
      elseif ('HKPP' == $aOrder['sm_code']) {
        $packNo = Service_ChangePack::getPackNo($country['country_code'], $aAddress['loa_zipcode']);
      }
    		foreach($hsList as $hsRow){ $total_price += $hsRow['loh_total_price'];}  
				
			$orders[] = array(
				'smInfo'=>$smInfo,
				'aOrder'=>$aOrder,
				'aAddress'=>$aAddress,
				'hsList'=>$hsList,
				'totalPrice'=>$total_price,
        'country'=>$country,
        'area' => $area,
        'packNo' => $packNo
			);		
		}    	
    	
    	//$this->view->aOrder = $aOrder;
    	//$this->view->aAddress = $aAddress;
    	//$this->view->hsList = $hsList;
		//$this->view->totalPrice = $total_price;	
    	/* $result = Service_LogisticsOrderProcess::submitOrder($logisticsCode);
    	if($result['ask']==0) exit('inner error'); */
		$this->view->orders = $orders;
    	echo $this->view->render($this->tplDirectory . "batchsw.tpl");    	
    }

    public function deleteAction(){
        $return = array('ask' => 0, 'message' => Ec_Lang::getInstance()->getTranslate('delete').','.Ec_Lang::getInstance()->getTranslate('fail'),'error'=>'');
        $orderArr	= $this->_request->getParam('orderArr','');
        $error = array();
        if (!empty($orderArr)){
            $success=0;
            $failse=0;
            $customer = $this->_customerAuth;
            $customerId = $customer['id'];
            foreach($orderArr as $key=>$orderCode){
                //$result = Service_OrderProcess::confirm($orderCode,$customerId);
                $result = Service_LogisticsOrderProcess::deleteTranslate($orderCode,$customerId);
                if (!empty($result) && $result['ask']=='1') {
                    $return['detailmessage'][] = '订单号'."[{$orderCode}]成功.";
                    $success++;
                }else{
                    $failse++;
                    $return['detailmessage'][] = '订单号'."[{$orderCode}]失败：".$result['message'];
                    //$error[] = $orderCode.Ec_Lang::getInstance()->getTranslate('delete').Ec_Lang::getInstance()->getTranslate('fail').",".Ec_Lang::getInstance()->getTranslate('Reason').':'.$result['message'];
                }
            }
            if($success>0){
                $return['ask']=1;
            }
            if(!empty($error)){
                $return['error'] = $error;
            }
            $return['message']=Ec_Lang::getInstance()->getTranslate('DeletedSuccessfully').':'.$success.' '.Ec_Lang::getInstance()->getTranslate('fail').':'.$failse;
        }
        die(Zend_Json::encode($return));
    }
    
    /**
     * @todo 下载模板
     * @author solar
     */
    public function downloadAction() {
    	header("Content-Type: APPLICATION/OCTET-STREAM");
    	header("Content-Disposition: attachment; filename=upload-order-template.xls;");
    	echo file_get_contents(APPLICATION_PATH."/../data/file".'/upload-order-template.xls');
    	exit;
    }
	
	/**
     * @todo 批量上传订单
     * @author solar
     */
    public function uploadAction() {
    	echo Ec::renderTpl($this->tplDirectory . "upload.tpl", 'noleftlayout');
    }
	
    /**
     * @todo 批量上传订单
     * @author solar
     */
    public function uploadSubmitAction() {
    	/* $uploadSession = new Zend_Session_Namespace('upload');
    	$uploadSession->elementExcel = ''; */
		set_time_limit(300);
		ini_set('memory_limit','1024M');		
    	$path = APPLICATION_PATH.'/../data/upload/'.$this->_customerAuth['id'];
    	if(!file_exists($path)){
    		if(!mkdir($path,0777,true)){
    			$this->view->message = '上传失败：内部错误';
    			echo Ec::renderTpl($this->tplDirectory . "upload.tpl",'noleftlayout');
    			exit;
    		}
    	}
    	$config = array();
    	$config['upload_path']		= $path;
    	$config['allowed_types']	= 'xls|xlsx';
    	$config['max_size']			= '2048000';
    	$config['encrypt_name']		= true;
    	$upload	= new Common_UploadFile($config);
    	$upload->set_upload_path($path);
    	if (!$upload->do_upload($_FILES,'XMLForInput')){
    		$this->view->message = '上传文件失败：'.$upload->display_errors();
    		echo Ec::renderTpl($this->tplDirectory . "upload.tpl",'noleftlayout');
    		exit;
    	}
    	$uploadData = $upload->data();
    	if(empty($uploadData) || empty($uploadData['full_path'])){
    		$this->view->message = '上传失败：内部错误';
    		echo Ec::renderTpl($this->tplDirectory . "upload.tpl",'noleftlayout');
    		exit;
    	}
    	$excelData = Common_Upload::readEXCEL($uploadData['full_path']);
    	if(!is_array($excelData) || empty($excelData) || count($excelData)<2) {
    		$this->view->message = '文件数据为空，请编辑好数据后再上传';
    		@unlink($uploadData['full_path']);
    		echo Ec::renderTpl($this->tplDirectory . "upload.tpl",'noleftlayout');
    		exit;
    	}
    	$result = Service_LogisticsProcess::validateExcel($excelData);
        $messageTip = '';
    	if($result['ask']==0) {
    		$this->view->message = implode('<br>', $result['error']);
    	} else {
    		$db = Common_Common::getAdapter();
    		$db->beginTransaction();
    		try{
    			$aCode = array();
                         $orderProcess=new Service_OrderProcess();
    			foreach($result['body'] as $data) {
                              $data['order']['is_remote_city']=0;
                                if($data['order']['sm_code']=='HKDHL'){
                                        if(empty($data['address']['loa_company'])){
                                        $data['address']['loa_company']=$data['address']['loa_name'];
                                     }
                                    $isRemote=$orderProcess->isRemoteCity($data['address']['loa_country'],$data['address']['loa_city'],$data['address']['loa_zipcode']);
                                    if($isRemote){
                                          $data['order']['is_remote_city']=1;
                                    }
                            }
                    $order_code = Service_LogisticsProcess::addLogisticsOrder($data);
    				$aCode[] = $order_code;
                    
                    if($data['order']['sm_code']=='BH-DPD'){
                        $registry = Zend_Registry::getInstance();
                        if (isset($registry['loh_total_price'])) {
                            $totaldeclareEUR = Service_Currency::converByCode("USD", "EUR", $registry['loh_total_price']);
                            if($totaldeclareEUR >= 50){
                                $messageTip .= '<br><span style="color:red;">订单号为'.$order_code.'有机会被征收关税</span>';
                            }
                        }
                        
                    }
                    if($data['order']['sm_code']=='CJ-DGMG' || $data['order']['sm_code']=='CJ-DGMP'){
                        $search = array(" ","　","\n","\r","\t");
                        $loa_address = str_replace($search,"",$data['address']['loa_address']);
                        $is_contain = false;
                        if(strstr(strtoupper($loa_address),'POSTOFFICE')){
                            $is_contain = true;
                        }
                        if(strstr(strtoupper($loa_address),'POSTBOX')){
                            $is_contain = true;                    
                        }
                        if($is_contain === true){
                            $messageTip .= '<br><span style="color:red;">订单号为'.$order_code.'地址内包含POST OFFICE/POST BOX，派送不会另行通知</span>';                    
                        }                        
                    }                     
                    
    			}
    			$db->commit();
                $result = '批量上传订单成功，总共上传'.count($aCode).'个订单，订单号是：'.implode(', ', $aCode);
                $result.= $messageTip;
    			$this->view->message = $result;
    		} catch(Exception $e) {
    			$db->rollback();
    			$this->view->message = '批量上传订单出现异常，请稍后重新上传';
    		}
    		/*$this->view->excelHead = $result['header'];
    		$this->view->excelData = $result['body'];
    		$uploadSession->elementExcel = $uploadData['full_path'];
    		echo Ec::renderTpl($this->tplDirectory . "element-preview.tpl",'noleftlayout');*/
    	}
    	echo Ec::renderTpl($this->tplDirectory . "upload.tpl", 'noleftlayout');
    	@unlink($uploadData['full_path']);
    }

    public function exportAction(){

        set_time_limit(0);

        $customer = $this->_customerAuth;
        $customerId = $customer['id'];
        $orderArr = $this->_request->getParam('orderArr','');
        $exportType = $this->_request->getParam("exportType","");
        if($exportType=="1"){
            $htmlTitle = '<tr>';
            $htmlTitle  = '<td>客户代码</td>';
            $htmlTitle .= '<td>客户参考号</td>';
            $htmlTitle .= '<td>订单号</td>';
            $htmlTitle .= '<td>跟踪号</td>';
            $htmlTitle .= '<td>运输方式</td>';
            $htmlTitle .= '<td>发件人姓名</td>';
            $htmlTitle .= '<td>发件人公司名</td>';
            $htmlTitle .= '<td>发件人省份</td>';
            $htmlTitle .= '<td>发件人城市</td>';
            $htmlTitle .= '<td>发件人电话</td>';
            $htmlTitle .= '<td>发件人地址</td>';

            $htmlTitle .= '<td>收件人姓名</td>';
            $htmlTitle .= '<td>收件人地址</td>';
            $htmlTitle .= '<td>收件人州\区域</td>';
            $htmlTitle .= '<td>收件人城市</td>';
            $htmlTitle .= '<td>收件人邮编</td>';
            $htmlTitle .= '<td>收件人电话</td>';
            $htmlTitle .= '<td>重量（KG）</td>';
            $htmlTitle .= '<td>收件国家（CN）</td>';
            $htmlTitle .= '<td>国家简称</td>';
            $maxHs = 1;
            $orderContent = "";
            foreach($orderArr as $logisticsCode){
                if($logisticsCode=="") continue;
                $logisticsRow = Service_LogisticsOrder::getByField($logisticsCode,'logistics_code',"*");
                $logisticsOrderHs = Service_LogisticsOrderHs::getByCondition(array('logistics_code'=>$logisticsCode),"*",0,0);
                if(count($logisticsOrderHs)>$maxHs) $maxHs = count($logisticsOrderHs);
                $orderContent.="<tr>";
                $orderContent.="<td>".$logisticsRow['customer_code']."</td>";
                $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>".$logisticsRow['reference_no']."</td>";
                $orderContent.="<td>".$logisticsRow['logistics_code']."</td>";
                $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>".$logisticsRow['ref_tracking_number']."</td>";
                $orderContent.="<td>".$logisticsRow['sm_code']."</td>";
                //$orderContent.="<td>".$logisticsRow['customer_code']."</td>";
                //$orderContent.="<td>".$logisticsRow['customer_code']."</td>";
                $loSenderAddress = Service_LogisticsOrderAddress::getByCondition(array('logistics_code'=>$logisticsCode,'loa_type'=>1),"*",0,0);
                if(!empty($loSenderAddress)){
                    $orderContent.="<td>".$loSenderAddress[0]['loa_name']."</td>";
                    $orderContent.="<td>".$loSenderAddress[0]['loa_company']."</td>";
                    //$senderCountry = Service_Country::getByField($loSenderAddress[0]['loa_country'],'country_id',"*");
                    //$orderContent.="<td>".$senderCountry['country_name']."</td>";
                    $orderContent.="<td>".$loSenderAddress[0]['loa_province']."</td>";
                    $orderContent.="<td>".$loSenderAddress[0]['loa_city']."</td>";
                    $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>".$loSenderAddress[0]['loa_phone']."</td>";
                    $orderContent.="<td>".$loSenderAddress[0]['loa_address']."</td>";
                }else{
                    $orderContent.="<td></td>";
                    $orderContent.="<td></td>";
                    $orderContent.="<td></td>";
                    $orderContent.="<td></td>";
                    $orderContent.="<td></td>";
                    $orderContent.="<td></td>";
                }

                $loReceiptAddress = Service_LogisticsOrderAddress::getByCondition(array('logistics_code'=>$logisticsCode,'loa_type'=>'0'),"*",0,0);
                $orderContent.="<td>".$loReceiptAddress[0]['loa_name']."</td>";
                $orderContent.="<td>".$loReceiptAddress[0]['loa_address']."</td>";
                $orderContent.="<td>".$loReceiptAddress[0]['loa_province']."</td>";
                $orderContent.="<td>".$loReceiptAddress[0]['loa_city']."</td>";
                $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>".$loReceiptAddress[0]['loa_zipcode']."</td>";
                $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>".$loReceiptAddress[0]['loa_phone']."</td>";
                $orderContent.="<td>".$logisticsRow['lo_weight']."</td>";

                $receiptCountry = Service_Country::getByField($loReceiptAddress[0]['loa_country'],'country_id',"*");
                $orderContent.="<td>".$receiptCountry['country_name']."</td>";
                $orderContent.="<td>".$receiptCountry['country_code']."</td>";
                foreach($logisticsOrderHs as $hs){
                    $orderContent.="<td>".$hs['loh_hs_name']."</td>";
                    $orderContent.="<td>".$hs['loh_total_price']."</td>";
                    $orderContent.="<td>".$hs['loh_quantity']."</td>";
                }
                $orderContent.="</tr>";
            }
            for($i=0;$i<$maxHs;$i++){
                $htmlTitle.="<td>英文品名".($i+1)."</td>";
                $htmlTitle.="<td>申报价值".($i+1)."（USD）</td>";
                $htmlTitle.="<td>数量".($i+1)."（个）</td>";
            }
            $htmlTitle."<tr>";

            header('Pragma:public');
            header('Content-Type:application/x-msexecl;name=logisticsOrderList.xls');
            header("Content-Disposition:inline;filename=logisticsOrderList.xls");
            //file_put_contents(APPLICATION_PATH . "/../data/{$fileName}",$html);
            echo "<table border='1'>".$htmlTitle.$orderContent."</table>";
            exit;

        }else{
            $orders_code_CustomerReference = trim($this->_request->getParam("orders_code_CustomerReference",""));
            $condition["orders_code_CustomerReference"] = $orders_code_CustomerReference;

            $condition["customer_id"] = $customerId;

            $warehouse_id = $this->_request->getParam("warehouse_id","");
            $condition["warehouse_id"] = $warehouse_id;

            $country_id = $this->_request->getParam("country_id","");
            $condition["country_id"] = $country_id;

            $orders_status = $this->_request->getParam("orders_status","");
            $shipping_method = $this->_request->getParam("shipping_method","");
            $condition["sm_code"] = $shipping_method;            //增加开始结束时间

            $add_time_start	= trim($this->_request->getParam('add_time_start',''));
            $condition["add_time_start"] = $add_time_start;

            $add_time_end	= trim($this->_request->getParam('add_time_end',''));
            $condition['add_time_end']	= $add_time_end;

            //$orders_status_arr = explode(',',$orders_status);
            $condition['lo_status'] = $orders_status;

            $htmlTitle = '<tr>';
            $htmlTitle  = '<td>客户代码</td>';
            $htmlTitle .= '<td>客户参考号</td>';
            $htmlTitle .= '<td>订单号</td>';
            $htmlTitle .= '<td>跟踪号</td>';
            $htmlTitle .= '<td>运输方式</td>';
            $htmlTitle .= '<td>发件人姓名</td>';
            $htmlTitle .= '<td>发件人公司名</td>';
            $htmlTitle .= '<td>发件人省份</td>';
            $htmlTitle .= '<td>发件人城市</td>';
            $htmlTitle .= '<td>发件人电话</td>';
            $htmlTitle .= '<td>发件人地址</td>';

            $htmlTitle .= '<td>收件人姓名</td>';
            $htmlTitle .= '<td>收件人地址</td>';
            $htmlTitle .= '<td>收件人州\区域</td>';
            $htmlTitle .= '<td>收件人城市</td>';
            $htmlTitle .= '<td>收件人邮编</td>';
            $htmlTitle .= '<td>收件人电话</td>';
            $htmlTitle .= '<td>重量（KG）</td>';
            $htmlTitle .= '<td>收件国家（CN）</td>';
            $htmlTitle .= '<td>国家简称</td>';
            $maxHs = 1;
            $orderContent = "";

            $rows = Service_LogisticsOrder::getByCondition($condition, '*', 0,0,'lo_id desc');

            foreach($rows as $logisticsRow){
                $logisticsOrderHs = Service_LogisticsOrderHs::getByCondition(array('logistics_code'=>$logisticsRow['logistics_code']),"*",0,0);
                if(count($logisticsOrderHs)>$maxHs) $maxHs = count($logisticsOrderHs);
                $orderContent.="<tr>";
                $orderContent.="<td>".$logisticsRow['customer_code']."</td>";
                $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>".$logisticsRow['reference_no']."</td>";
                $orderContent.="<td>".$logisticsRow['logistics_code']."</td>";
                $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>".$logisticsRow['ref_tracking_number']."</td>";
                $orderContent.="<td>".$logisticsRow['sm_code']."</td>";
                //$orderContent.="<td>".$logisticsRow['customer_code']."</td>";
                //$orderContent.="<td>".$logisticsRow['customer_code']."</td>";
                $loSenderAddress = Service_LogisticsOrderAddress::getByCondition(array('logistics_code'=>$logisticsRow['logistics_code'],'loa_type'=>1),"*",0,0);
                if(!empty($loSenderAddress)){
                    $orderContent.="<td>".$loSenderAddress[0]['loa_name']."</td>";
                    $orderContent.="<td>".$loSenderAddress[0]['loa_company']."</td>";
                    //$senderCountry = Service_Country::getByField($loSenderAddress[0]['loa_country'],'country_id',"*");
                    //$orderContent.="<td>".$senderCountry['country_name']."</td>";
                    $orderContent.="<td>".$loSenderAddress[0]['loa_province']."</td>";
                    $orderContent.="<td>".$loSenderAddress[0]['loa_city']."</td>";
                    $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>".$loSenderAddress[0]['loa_phone']."</td>";
                    $orderContent.="<td>".$loSenderAddress[0]['loa_address']."</td>";
                }else{
                    $orderContent.="<td></td>";
                    $orderContent.="<td></td>";
                    $orderContent.="<td></td>";
                    $orderContent.="<td></td>";
                    $orderContent.="<td></td>";
                    $orderContent.="<td></td>";
                }

                $loReceiptAddress = Service_LogisticsOrderAddress::getByCondition(array('logistics_code'=>$logisticsRow['logistics_code'],'loa_type'=>'0'),"*",0,0);
                $orderContent.="<td>".$loReceiptAddress[0]['loa_name']."</td>";
                $orderContent.="<td>".$loReceiptAddress[0]['loa_address']."</td>";
                $orderContent.="<td>".$loReceiptAddress[0]['loa_province']."</td>";
                $orderContent.="<td>".$loReceiptAddress[0]['loa_city']."</td>";
                $orderContent.="<td>".$loReceiptAddress[0]['loa_zipcode']."</td>";
                $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>".$loReceiptAddress[0]['loa_phone']."</td>";
                $orderContent.="<td>".$logisticsRow['lo_weight']."</td>";

                $receiptCountry = Service_Country::getByField($loReceiptAddress[0]['loa_country'],'country_id',"*");
                $orderContent.="<td>".$receiptCountry['country_name']."</td>";
                $orderContent.="<td>".$receiptCountry['country_code']."</td>";
                foreach($logisticsOrderHs as $hs){
                    $orderContent.="<td>".$hs['loh_hs_name']."</td>";
                    $orderContent.="<td>".$hs['loh_total_price']."</td>";
                    $orderContent.="<td>".$hs['loh_quantity']."</td>";
                }
                $orderContent.="</tr>";
            }
            for($i=0;$i<$maxHs;$i++){
                $htmlTitle.="<td>英文品名".($i+1)."</td>";
                $htmlTitle.="<td>申报价值".($i+1)."（USD）</td>";
                $htmlTitle.="<td>数量".($i+1)."（个）</td>";
            }
            $htmlTitle."<tr>";

            header('Pragma:public');
            header('Content-Type:application/x-msexecl;name=logisticsOrderList.xls');
            header("Content-Disposition:inline;filename=logisticsOrderList.xls");
            //file_put_contents(APPLICATION_PATH . "/../data/{$fileName}",$html);
            echo "<table border='1'>".$htmlTitle.$orderContent."</table>";
            exit;
        }
    }

    public function recoveryAction(){
        $return = array('ask' => 0, 'message' => "恢复订单失败",'error'=>'');
        $orderArr	= $this->_request->getParam('orderArr','');
        $error = array();
        if (!empty($orderArr)) {
            $success=0;
            $failse=0;
            $customer = $this->_customerAuth;
            $customerId = $customer['id'];
            foreach($orderArr as $key=>$orderCode){
                //$result = Service_OrderProcess::confirm($orderCode,$customerId);
                $result = Service_LogisticsOrderProcess::recoveryTranslate($orderCode,$customerId);
                if (!empty($result) && $result['ask']=='1') {
                    $return['detailmessage'][] = '订单号'."[{$orderCode}]恢复成功.";
                    $success++;
                }else{
                    $failse++;
                    $return['detailmessage'][] = '订单号'."[{$orderCode}]恢复失败：".$result['message'];
                    //$error[] = $orderCode.Ec_Lang::getInstance()->getTranslate('delete').Ec_Lang::getInstance()->getTranslate('fail').",".Ec_Lang::getInstance()->getTranslate('Reason').':'.$result['message'];
                }
            }
            if($success>0){
                $return['ask']=1;
            }
            if(!empty($error)){
                $return['error'] = $error;
            }
            $return['message']="恢复订单成功".':'.$success.' '.Ec_Lang::getInstance()->getTranslate('fail').':'.$failse;
        }
        die(Zend_Json::encode($return));
    }
    
}