<?php

class Merchant_OrderController extends Ec_Controller_Action
{

    public function preDispatch ()
    {
        $this->tplDirectory = "merchant/views/order/";
        // $this->tplDirectory = "merchant/account_config/";
        $this->customerAuth = new Zend_Session_Namespace("customerAuth");
    }
    public function indexAction ()
    {
    	$this->listbhAction();
        //echo Ec::renderTpl($this->tplDirectory . "order-index.tpl",'noleftlayout');
    }
    /*生成订单*/
    public function createAction ()
    {
        //$customerId = Default_Service_Customer::getLoginInfo()->customer['customer_id'];
        $customer = $this->_customerAuth;
		$defaultOrderMode = trim($this->_request->getParam('defaultOrderMode','none'));		
		if(!in_array($defaultOrderMode,array('jihuo','beihuo','none'))){$defaultOrderMode ='none'; }
		$this->view->defaultOrderMode = $defaultOrderMode;
		//$currencyUSD = Service_Currency::getByField('USD','currency_code');
		//$this->view->currency_rate = $currencyUSD['currency_rate'];
        $customerId = $customer['id'];
        //exit('ss');
        if($this->_request->isPost()){
            $param = $this->_request->getParams();
            
            //print_r($param);
            
            
            $order_product = array();
            $opQty = $this->_request->getParam('sku',array());
            $declarePrice = $this->_request->getParam('declared_value',array());
            $productEnName = $this->_request->getParam('productEnName',array());
            $purposeDeclaredValue = $this->_request->getParam('purpose_declared_value',array());
            $ebayItemId = $this->_request->getParam("ebayItemId",array());
            $ebayTransactionId = $this->_request->getParam("ebayTransactionId",array());
            $ebayBuyerId = $this->_request->getParam("ebayBuyerId",array());
            foreach($opQty as $product_id=>$qty){
            	$price = '';
            	if(isset($declarePrice[$product_id])){
            		$price = $declarePrice[$product_id];
            	}
            	$product_title_en = ''; //英文品名
            	if(isset($productEnName[$product_id])){
            		$product_title_en = $productEnName[$product_id];
            	}
            	$purpose_declared_value = '';
            	if(isset($declarePrice[$product_id])){
            		$purpose_declared_value = $purposeDeclaredValue[$product_id];
            	}
                $ebay_item_id = "";
                if(isset($ebayItemId[$product_id])&&$ebayItemId[$product_id]!=""){
                    $ebay_item_id = $ebayItemId[$product_id];
                }
                $ebay_transaction_id = "";
                if(isset($ebayTransactionId[$product_id])&&$ebayTransactionId[$product_id]!=""){
                    $ebay_transaction_id = $ebayTransactionId[$product_id];
                }
                $ebay_buyer_id = "";
                if(isset($ebayBuyerId[$product_id])&&$ebayBuyerId[$product_id]!=""){
                    $ebay_buyer_id = $ebayBuyerId[$product_id];
                }
                $order_product[] = array('product_id'=>$product_id,'qty'=>$qty,'declare_price'=>$price,'op_declared_value'=>$purpose_declared_value,'product_title_en'=>$product_title_en,'ebay_item_id'=>$ebay_item_id,'ebay_transaction_id'=>$ebay_transaction_id,'ebay_buyer_id'=>$ebay_buyer_id);
            }
            //echo "<pre>";
            //var_dump($order_product);
            //echo "</pre>";
            //exit;
            $row = array(
                    'customer_id'=>$customerId,
                    'warehouse_id'=>$this->_request->getParam('warehouse_id',''),
                    'to_warehouse_id'=>$this->_request->getParam('to_warehouse_id',''),
                    'sm_code'=>$this->_request->getParam('shipping_method',''),
                    'reference_no'=>trim($this->_request->getParam('reference_no','')),
                    'remark'=>trim($this->_request->getParam('remark','')),
                    'order_type'=>$this->_request->getParam('order_type',''),
                    'oab_firstname'=>trim($this->_request->getParam('oab_firstname','')),
                    'oab_lastname'=>trim($this->_request->getParam('oab_lastname','')),
                    'oab_company'=>trim($this->_request->getParam('oab_company','')),
                    'oab_country_id'=>$this->_request->getParam('country_id',''),
                    'oab_postcode'=>trim($this->_request->getParam('oab_postcode','')),
                    'oab_state'=>$this->_request->getParam('oab_state',''),
                    'oab_city'=>trim($this->_request->getParam('oab_city','')),
                    'oab_street_address1'=>trim($this->_request->getParam('oab_street_address1','')),
                    'oab_street_address2'=>trim($this->_request->getParam('oab_street_address2','')),
                    'consignee_address3'=>trim($this->_request->getParam('consignee_address3','')),
                    'oab_phone'=>trim($this->_request->getParam('oab_phone','')),
                    'oab_email'=>trim($this->_request->getParam('oab_email','')),
                    'order_mode_type'=>$this->_request->getParam('ordermodel',''),//订单模型
                   	'change_order'=>$this->_request->getParam('change_single',''),
            		'ref_tracking_number'=>trim($this->_request->getParam('ref_tracking_number','')), 
                    'order_product'=>$order_product,
					'charge'=>trim($this->_request->getParam('charge','')),
    				        'currency_code'=>$this->_request->getParam('currency_code',''),
                                        'delivery_address'=>$this->_request->getParam("delivery_address",""),
                    'is_fba' => $this->_request->getParam('isFba', 0),
                    'is_fba_tax' => $this->_request->getParam('isFbaTax', 0),
		            'insurance' => $this->_request->getParam('buyInsurance', 0),
                    'insurance_rate' => $this->_request->getParam('insuranceRate', 1),
                    'insurance_code' => $this->_request->getParam('insuranceItem', ''),
                    'is_pod' => $this->_request->getParam('is_pod', 0),
                    'shippingInfo'=> array(
                        'notifyTel'          => $this->_request->getParam('notify_tel', ''),
                        'notifyContact'     => $this->_request->getParam('notify_contact', ''),
                        'notifyAddr'         => $this->_request->getParam('notify_addr', ''),
                        'destination'        => $this->_request->getParam('destination', ''),
                        'isDGD'               => $this->_request->getParam('is_dgd', 0),
                        'hsDescription'      => $this->_request->getParam('hs_description', ''),
                        'insuredAccount'     => $this->_request->getParam('insured_account', 0),
                    ),
                    'dispatch_notice'=>$this->_request->getParam('dispatch_notice',''),
                    'guarantee'=>$this->_request->getParam('guarantee','')
            );
            /* $addressSender = array(
            	'oab_firstname'=>$this->_request->getParam('osab_firstname',''),
            	'oab_lastname'=>$this->_request->getParam('osab_lastname',''),
            	'oab_company'=>	$this->_request->getParam('osab_company',''),		
				'oab_state'=>$this->_request->getParam('osab_province',''),
            	'oab_city'=>$this->_request->getParam('osab_city',''),
            	'oab_street_address1'=>$this->_request->getParam('osab_street_address1',''),
            	'oab_street_address2'=>$this->_request->getParam('osab_street_address2',''),
            	'oab_postcode'=>$this->_request->getParam('osab_postcode',''),	
            	'oab_phone'=>$this->_request->getParam('osab_phone',''),
            	'oab_email'=>$this->_request->getParam('osab_email',''),
            );
            $row['addressSender'] = $addressSender; */
            $ordersCode = $this->_request->getParam('ordersCode','');
            //var_dump($ordersCode);
            $process = new Service_OrderProcess();
            if($ordersCode){				
				$row['ordersCode'] = $ordersCode;
                $result = $process->updateOrderTransaction($row,$ordersCode,$customerId);
                //Common_DataCache::getOrderElseInfo($ordersCode,1);
            }else{
                $result = $process->createOrderTransaction($row);
                
            }
            //print_r($result);
            if(!empty($result['error'])){
                foreach($result['error'] as $k=>$v){
                    $result['error'][$k] = preg_replace('/^([0-9]+)/', '', $v);
                }
            }
            
            die(Zend_Json::encode($result));
        }
        $ordersCode = $this->_request->getParam('ordersCode','');
        $tpl = 'order-create.tpl';
        if($ordersCode){
            $orderInfo = Service_Orders::getOrderAllInfo($ordersCode,$customerId);
            //$orderSendAddress = $orderInfo['addressSender'];
            if($orderInfo){
            	/* if(!empty($orderSendAddress)){
            		$this->view->sender = $orderSendAddress;
            	} */
                $this->view->orderInfo = $orderInfo;
                $this->view->modify ='1';
            }
            $tpl = 'order-create.tpl';
        }
        $ordermodel = $this->_request->getParam('ordermodel','');
        $type = $this->_request->getParam('type','');


        $this->view->ordersCode = $ordersCode;
        
        $warehouse = Common_DataCache::getWarehouse();
        
        if(!empty($warehouse)){
        	foreach($warehouse as $keyw=>$wh){
        		if($wh['warehouse_scope']=='0'){
        			unset($warehouse[$keyw]);
        		}
        	}
        }
        $this->view->warehouse = $warehouse;
        $warehouseJs = array();
        $warehouseIds = array();
        foreach($warehouse as $w){
            $warehouseJs[$w['warehouse_id']] = array(
                'warehouse_id'=>$w['warehouse_id'],
                'warehouse_name'=>$w['warehouse_code'],
                'country_id'=>$w['country_id'],
            );
            $warehouseIds[] = $w['warehouse_id'];
        }
        $warehouseIds[] = '0';
        $this->view->warehouseJs = Zend_Json::encode($warehouseJs);
        
        $province_array = Service_Region::getByCondition(array('parent_id'=>1));
        $this->view->province_array = $province_array;
        
        
        /*$countryArr = Common_DataCache::getOrderShipTypeCountryMap();
		//print_r($countryArr);exit;
        foreach($countryArr as $key=>$value){
            foreach($value['ship_type'] as $k2=>$v2){
                if($v2['sm_code']!=""){
                    $smRow = Service_ShippingMethod::getByField($v2['sm_code'],'sm_code',array("sm_name_cn",'warehouse_id'));
                    if(!in_array($smRow['warehouse_id'], $warehouseIds)){
                    	unset($countryArr[$key]['ship_type'][$k2]);
                    }else{
                    	$countryArr[$key]['ship_type'][$k2]['sm_name_cn'] = $smRow['sm_name_cn'];
                    }
                }
            }
        }*/
        //$cityArr = Common_Service_DataCache::getShipTypeCityMap();

        $this->view->country = Service_Country::getAll();

        $currencyAll = Common_DataCache::getCurrency();
        $this->view->currencyAll = $currencyAll;
			
		
    	$actionLabel="add";
    	$action = Ec_Lang::getInstance()->getTranslate('OrderAdd');		
		if($ordersCode){
    		$actionLabel="add";
    		$action = Ec_Lang::getInstance()->getTranslate('OrderModify');;
		}
		$this->view->actionLabel = $actionLabel;
		$this->view->action = $action;
        /* echo '<pre>';
        print_r($countryArr);
        echo '</pre>'; */
		$this->view->city_array = array();
		if(isset($orderInfo)&&$orderInfo){
			//print_r(Service_Region::getByCondition(array('parent_id'=>$orderInfo['oab_state_id'])));
			if(isset($orderInfo['addressSender']['oab_state_id']) && $orderInfo['addressSender']['oab_state_id']>0){
				$this->view->city_array = Service_Region::getByCondition(array('parent_id'=>$orderInfo['addressSender']['oab_state_id']));;
			}
		}

        //$this->view->countryJs = Zend_Json::encode($countryArr);
        //$this->view->cityJs = Zend_Json::encode($cityArr);
        $ecg_category = Common_DataCache::getProductCategory();
        $this->view->ecg_category = $ecg_category;
        $this->view->orderType = Service_OrderProcess::getOrderTypeArr();
        //保险项目
        $this->view->insurance = Service_OtherFee::getByCondition( array('status'=>1,'ft_code'=>'SI') );
        $this->view->continent = json_encode(Service_ShippingMethod::getContinent());
        $this->view->date = date('Y-m-d');
        //-iframe
        if($type=='getTpl'){
        	if($ordermodel=='0'){
        		$tpl = 'beihuo.tpl';
        	}elseif($ordermodel=='1'){
        		$tpl = 'jihuo.tpl';
        	}else{
        		exit(Ec_Lang::getInstance()->getTranslate('DataError'));
        	}
        	echo $this->view->render($this->tplDirectory . $tpl);
        }else{
        	echo Ec::renderTpl($this->tplDirectory . $tpl,'noleftlayout');
        }
        
    }
    
	/*备货订单列表*/
    public function listbhAction ()
    {
    	//echo 'dddddddddd';exit;
        //set_time_limit(0);
    	$customer = $this->_customerAuth;
        $customerId = $customer['id'];
        //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 = trim($this->_request->getParam("orders_code",""));
			$condition['new_reference_no'] = $orders_code;
            //$condition["order_code"] = $orders_code;
        

            $condition["customer_id"] = $customerId;
        
        
            $warehouse_id = $this->_request->getParam("warehouse_id","");
            $condition["warehouse_id"] = $warehouse_id;
        

            $order_type = $this->_request->getParam("order_type","");
            $condition["order_type"] = $order_type;
            
            $orders_status = $this->_request->getParam("orders_status","1");
            
        
            $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;
			$condition['order_mode_type'] = '0'; //备货模式的订单
            $condition['ship_time_start'] = trim($this->_request->getParam('ship_time_start',''));
            $condition['ship_time_end'] = trim($this->_request->getParam('ship_time_end',''));
            $condition['insurance'] = trim($this->_request->getParam('buyInsurance',''));
            $serviceTracking=trim($this->_request->getParam('service_tracking'));
            if($serviceTracking!=''){
                 $shipOrderList=Service_ShipOrder::getByCondition(array('tracking_number'=>$serviceTracking),'order_code');
                 $orderCodeArray=array();
                 if(!empty($shipOrderList)){
                     foreach($shipOrderList as $so){
                         $orderCodeArray[]=$so['order_code'];
                     }
                     $condition['order_code']=$orderCodeArray;
                 }else{
                     $condition['ref_tracking_number']=$serviceTracking;
                 }
                 
             }
  	
            $return = array(
                    "ask" => 0,
                    "message" => "No Data"
            );
            /* 以下为业务逻辑方法调用 */
            $count = Service_Orders::getByCondition($condition, 'count(*)');
            $return['count'] = $count;
            $cacheProduct = array();
            $rows = '';
            if ($count) {
                $rows = Service_Orders::getByCondition($condition, '*', $pageSize,$page,'order_id desc');

                $categories = Common_DataCache::getProductCategory();
                $orderTypes = Service_OrderProcess::getOrderTypeArr();
                foreach($rows as $k=>$v){
                    //$orderElse = Common_Service_DataCache::getOrderElseInfo($v['orders_code']);
                    /* $address = Merchant_Service_OrdersAddress::getByField($v['orders_code'],'orders_code');

                    $country = Common_Service_DataCache::getCategory($address['oa_consignee_country_id']);
                    $address['oa_country_name'] = $country['en_name'];
                    $address['oa_country_code'] = $country['country_code'];
                   
                   
                    $v =  array_merge($v,$address);*/
                    $orderAddressBook = Service_OrderAddressBook::getByField($v['order_id'],'order_id');
					if(!empty($orderAddressBook)){
						$country = Service_Country::getByField($orderAddressBook['oab_country_id']);
						$v['country_name'] = $country['country_name'];
					}
                    //$v=array_merge($v,$orderAddressBook);
                    $products = array();                    
                    $products= Service_OrderProcess::getDeclaredValue($v['order_code']);
                    $v['order_product'] = $products;
                    $v['order_type_text'] = $orderTypes[$v['order_type']];
                    if($v['sm_code']!=""){
                        $sm = Service_ShippingMethod::getByField($v['sm_code'],"sm_code","*");
                        $v['sm_class_code'] = $sm['sm_class_code'];
                    }
                    $shipOrder = Service_ShipOrder::getByField($v['order_code'],"order_code","*");
                    if(isset($shipOrder['tracking_number'])){
                        $v['tracking_number'] = $shipOrder['tracking_number'];						
                    }else{
                        $v['tracking_number'] = $v['ref_tracking_number'];
                    }


                    if(!empty($shipOrder)){
                        if($shipOrder['so_fee_weight']>0){
                            $v['charged_weight'] = $shipOrder['so_fee_weight'];
                        }else{
                            $v['charged_weight'] = $shipOrder['so_weight']>=$shipOrder['so_vol_weight']?$shipOrder['so_weight']:$shipOrder['so_vol_weight'];
                        }
                    }				
					
                    
                    /* switch($v['underreview_status']){
                        case 1:
                            $v['underreview_status_txt'] = 'Inventory Insufficient';
                            break;
                        case 2:
                            $v['underreview_status_txt'] = 'Currency Insufficient';
                            break;
                        default:
                            $v['underreview_status_txt'] = '';
                    } */
                    //$v =  array_merge($orderElse,$v);
                    //是否偏远城市
                    $v['is_remote_city'] = $v['is_remote_city']==1 ? '是' : '否';
                    
                    $rows[$k]=$v;
                }

                $return['data'] = $rows;
                $return['ask'] = 1;
                $return['message'] = "";
            }

            $orderStatusArr = Service_Orders::getCustomerOrderStatusGroup($condition);
            $allStatus = Service_OrderProcess::getOrderStatus();
            
            //处理数量问题
            if(!empty($allStatus)){
            	$numConditon = $condition;
            	foreach($allStatus as $keys=>$values){
            		$numConditon['order_status_arr'] = explode(',',$keys);
            		$countnum = Service_Orders::getByCondition($numConditon, 'count(*)');
            		$allStatus[$keys] = $values."({$countnum})";
            	}
            }

            $statusTxt = array();
            $return['orderStatusArr'] = $statusTxt;
        $warehouse = Common_DataCache::getWarehouse();
        $warehouseId = array();
        if(!empty($warehouse)){
        	foreach($warehouse as $keyw=>$wh){
        		if($wh['warehouse_scope']=='0'){
        			unset($warehouse[$keyw]);
        		}else{
        			$warehouseId[] = $wh['warehouse_id'];
        		}
        	}
        }
        $warehouseId[] = '0';
        $this->view->warehouse = $warehouse;
        
        $this->view->result = $rows;
        
        $shipType = Common_DataCache::getShippingMethod();
        //print_r($shipType);
		foreach($shipType as $key=>$value){
            if($value['sm_status']!='1'){
                unset($shipType[$key]);
            }
			if(!in_array($value['warehouse_id'],$warehouseId)){
				unset($shipType[$key]);
			}
		}
        /*$smArray = array();
        foreach($shipType as $sm){
            $smArray[] = $sm['sm_code'];
        }
        sort($smArray);*/
        $condition['service_tracking']=$serviceTracking;
        $this->view->shipType = $shipType;
        $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 . "bh-order-list.tpl",'noleftlayout');
    }
    /***
     * @author william-fan
     * @todo 集货模式订单
     */
    public function listjhAction ()
    {
    	//echo 'dddddddddd';exit;
    	//set_time_limit(0);
    	$customer = $this->_customerAuth;
    	$customerId = $customer['id'];
    	//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 = trim($this->_request->getParam("orders_code",""));
        $condition['new_reference_no'] = $orders_code;
        //$condition["order_code"] = $orders_code;
    
    
    	$condition["customer_id"] = $customerId;
    
    
    	$warehouse_id = $this->_request->getParam("warehouse_id","");
    	$condition["warehouse_id"] = $warehouse_id;
    
    
    	$order_type = $this->_request->getParam("order_type","");
    	$condition["order_type"] = $order_type;
    
    	$orders_status = $this->_request->getParam("orders_status","1");
    
    
    	$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;
    	$condition['order_mode_type'] = '1'; //集货模式的订单
        $condition['ship_time_start'] = $this->_request->getParam('ship_time_start',"");
        $condition['ship_time_end'] = $this->_request->getParam('ship_time_end',"");
        $condition['insurance'] = $this->_request->getParam('buyInsurance',"");
        $serviceTracking=trim($this->_request->getParam('service_tracking'));
         if($serviceTracking!=''){
              $shipOrderList=Service_ShipOrder::getByCondition(array('tracking_number'=>$serviceTracking),'order_code');
               $orderCodeArray=array();
              if(!empty($shipOrderList)){
                 
                  foreach($shipOrderList as $so){
                      $orderCodeArray[]=$so['order_code'];
                  }
                  $condition['order_code']=$orderCodeArray;
              }else{
                    $condition['ref_tracking_number']=$serviceTracking;
              }
              
          }
    	//print_r(array('1'));
    	//print_r($orders_status_arr);
    	$return = array(
    			"ask" => 0,
    			"message" => "No Data"
    	);
    	/* 以下为业务逻辑方法调用 */
    	$count = Service_Orders::getByCondition($condition, 'count(*)');
    	$return['count'] = $count;
    	$cacheProduct = array();
    	$rows = '';
    	if ($count) {
    		$rows = Service_Orders::getByCondition($condition, '*', $pageSize,$page,'order_id desc');
    
    		$categories = Common_DataCache::getProductCategory();
    		$orderTypes = Service_OrderProcess::getOrderTypeArr();
    		foreach($rows as $k=>$v){
    			//$orderElse = Common_Service_DataCache::getOrderElseInfo($v['orders_code']);
    			/* $address = Merchant_Service_OrdersAddress::getByField($v['orders_code'],'orders_code');
    
    			$country = Common_Service_DataCache::getCategory($address['oa_consignee_country_id']);
    			$address['oa_country_name'] = $country['en_name'];
    			$address['oa_country_code'] = $country['country_code'];
    			 
    			 
    			$v =  array_merge($v,$address);*/
    			$orderAddressBook = Service_OrderAddressBook::getByField($v['order_id'],'order_id');
    			if(!empty($orderAddressBook)){
    				$country = Service_Country::getByField($orderAddressBook['oab_country_id']);
    				$v['country_name'] = $country['country_name'];
    			}
    			//$v=array_merge($v,$orderAddressBook);
    			$products = array();
    			$products= Service_OrderProcess::getDeclaredValue($v['order_code']);
    			$v['order_product'] = $products;
    			$v['order_type_text'] = $orderTypes[$v['order_type']];
                if($v['sm_code']!=""){
                    $sm = Service_ShippingMethod::getByField($v['sm_code'],"sm_code","*");
                    $v['sm_class_code'] = $sm['sm_class_code'];
                }
                $shipOrder = Service_ShipOrder::getByField($v['order_code'],"order_code","*");
                if(isset($shipOrder['tracking_number'])){
                    $v['tracking_number'] = $shipOrder['tracking_number'];
                }else{
                    $v['tracking_number'] = $v['ref_tracking_number'];
                }
    
				if(!empty($shipOrder)){
                    if($shipOrder['so_fee_weight']>0){
                        $v['charged_weight'] = $shipOrder['so_fee_weight'];
                    }else{
                        $v['charged_weight'] = $shipOrder['so_weight']>=$shipOrder['so_vol_weight']?$shipOrder['so_weight']:$shipOrder['so_vol_weight'];
                    }
				}
    			/* switch($v['underreview_status']){
    			 case 1:
    			$v['underreview_status_txt'] = 'Inventory Insufficient';
    			break;
    			case 2:
    			$v['underreview_status_txt'] = 'Currency Insufficient';
    			break;
    			default:
    			$v['underreview_status_txt'] = '';
    			} */
    			//$v =  array_merge($orderElse,$v);
    			//是否偏远城市
                $v['is_remote_city'] = $v['is_remote_city']==1 ? '是' : '否';
                
    			$rows[$k]=$v;
    		}
    
    		$return['data'] = $rows;
    		$return['ask'] = 1;
    		$return['message'] = "";
    	}
    
    	$orderStatusArr = Service_Orders::getCustomerOrderStatusGroup($condition);
    	$allStatus = Service_OrderProcess::getjiOrderStatus();
    
    	//处理数量问题
    	if(!empty($allStatus)){
    		$numConditon = $condition;
    		foreach($allStatus as $keys=>$values){
    			$numConditon['order_status_arr'] = explode(',',$keys);
    			$countnum = Service_Orders::getByCondition($numConditon, 'count(*)');
    			$allStatus[$keys] = $values."({$countnum})";
    		}
    	}
    
    	$statusTxt = array();
    	$return['orderStatusArr'] = $statusTxt;
    	$warehouse = Common_DataCache::getWarehouse();
    	if(!empty($warehouse)){
    		foreach($warehouse as $keyw=>$wh){
    			if($wh['warehouse_scope']=='0'){
    				unset($warehouse[$keyw]);
    			}else{
    				$warehouseId[] = $wh['warehouse_id'];
    			}
    		}
    	}
    	$warehouseId[] = '0';
    	$this->view->warehouse = $warehouse;
    
    	$this->view->result = $rows;
    
    	$shipType = Common_DataCache::getShippingMethod();
    	foreach($shipType as $key=>$value){
            if($value['sm_status']!='1'){
                unset($shipType[$key]);
            }
    		if(!in_array($value['warehouse_id'],$warehouseId)){
    			unset($shipType[$key]);
    		}
    	}
    	/*$smArray = array();
    	foreach($shipType as $sm){
    		$smArray[] = $sm['sm_code'];
    	}
    	sort($smArray);*/
        $condition['service_tracking']=$serviceTracking;
    	$province_array = Service_Region::getByCondition(array('parent_id'=>1));
    	$this->view->province_array = $province_array;
    	
    	
    	
    	$this->view->shipType = $shipType;
    	$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 . "jh-order-list.tpl",'noleftlayout');
    }

    public function changeStatusAction ()
    {
        $ordersCodes = $this->_request->getParam('ordersCodes','');
        $status = $this->_request->getParam('status','');
        $return = array();
        $process =  new Merchant_Service_OrderProcess();
        foreach($ordersCodes as $ordersCode){            
            $result = $process->submit($ordersCode, $status);
            if(!empty($result['error'])){
                foreach($result['error'] as $k=>$v){
                    $result['error'][$k] = preg_replace('/^([0-9]+)/', '', $v);
                }
            }
            $return[] = $result;
        }
        
        die(Zend_Json::encode($return));
    }
    /*订单详细*/
    public function detailAction ()
    {
        $ordersCode = $this->_request->getParam('ordersCode','');
        /*if($ordersCode){
            $customer_id = $this->customerAuth->customer['customer_id'];
            
            $orderInfo = Service_Orders::getOrderAllInfo($ordersCode,$customer_id);
            if($orderInfo){
                $this->view->orderInfo = $orderInfo;
                $orderFee=Service_OrderFee::getByCondition(array('orders_code'=>$ordersCode),'*');
                if($orderFee){
                    $this->view->orderFee=$orderFee;
                }
                
            }
        }*/
        $order = Service_Orders::getByField($ordersCode,"order_code","*");
		if(empty($order)){
            $this->_redirect("/merchant/logistics/detail?ordersCode=".$ordersCode);
            //exit("没有找到订单.");
        }
		
        if($order['currency_code']!="RMB"){
            $currency = Service_Currency::getByField($order['currency_code'],"currency_code","*");
            //$order['currency_code'] = "RMB";
            $order['parcel_declared_value'] = round($order['parcel_declared_value']*$currency['currency_rate'],2);
            $order['shipping_fee_estimate'] = round($order['shipping_fee_estimate']*$currency['currency_rate'],2);
        }
		
		$order['parcel_declared_value'] = $parcel_declared_value = Service_OrderProcess::getDeclaredValue2($ordersCode);
		$order['purpose_declared_value'] = $purpose_declared_value = Service_OrderProcess::getHSTotalPrice($ordersCode);
		
		
        $warehouse = Service_Warehouse::getByField($order['warehouse_id'],"warehouse_id","*");
        $order['warehouse_code'] = $warehouse['warehouse_code'];
        $user = Service_User::getByField($order['picker_id'],"user_id","*");
        $order['picker'] = $user['user_code'];
        if( $order['insurance'] == 1 ) {
            $feeItem = Service_OtherFee::getByField($order['insurance_code'],'fee_code');
            $order['insurance_name'] = $feeItem['fee_name'];
        } else {
            $order['insurance_name'] = '';
            $order['insurance_rate'] = '';
        }
        $this->view->order = $order;
        //0:删除;1:草稿;2:确认;3:异常;4:已提交;5:已打印;6:已下架;7:已打包;8:已装袋;9:装袋完成;10:已加挂;11:物流完成;12:物流发货;13:已签收
        $this->view->orderStatus = array(
            '0'=>Ec_Lang::getInstance()->getTranslate('delete'),//'删除',
            '1'=>Ec_Lang::getInstance()->getTranslate('Draft'),//'草稿',
            '2'=>Ec_Lang::getInstance()->getTranslate('Confirm'),//'确认',
            '3'=>Ec_Lang::getInstance()->getTranslate('Abnormal'),//'异常',
            '4'=>Ec_Lang::getInstance()->getTranslate('Submitted'),//'已提交',
            '5'=>Ec_Lang::getInstance()->getTranslate('Printed'),//'已打印',
            '6'=>Ec_Lang::getInstance()->getTranslate('OffTheShelf'),//'已下架',
            '7'=>Ec_Lang::getInstance()->getTranslate('Packaged'),//'已打包',
            '8'=>Ec_Lang::getInstance()->getTranslate('HasBeenBagging'),//'已装袋',
            '9'=>Ec_Lang::getInstance()->getTranslate('BaggingCompleted'),//'装袋完成',
            '10'=>Ec_Lang::getInstance()->getTranslate('HasBeenHang'),//'已加挂',
            '11'=>Ec_Lang::getInstance()->getTranslate('LogisticsCompleted'),//'物流完成',
            '12'=>Ec_Lang::getInstance()->getTranslate('LogisticsShipping'),//'物流发货',
            '13'=>Ec_Lang::getInstance()->getTranslate('Received'),//'已签收'
            '14'=>'已录单',
        );
        //0:一票一件;1:一票一件多个;2;一票多件
        $this->view->orderPickType = array(
            '0'=>Ec_Lang::getInstance()->getTranslate('OnePiece'),//'一票一件',
            '1'=>Ec_Lang::getInstance()->getTranslate('APluralityVote'),//'一票一件多个',
            '2'=>Ec_Lang::getInstance()->getTranslate('MoreThanAVote')//'一票多件'
        );

        $orderProducts = Service_OrderProduct::getByCondition(array('order_code'=>$ordersCode),"*");
        foreach($orderProducts as $k=>$v){
            $product = Service_Product::getByField($v['product_id'],"product_id","*");
            $orderProducts[$k]['product_sku'] = $product['product_sku'];
			$orderProducts[$k]['product_title'] = $product['product_title'];
            $orderProducts[$k]['product_title_en'] = $product['product_title_en'];
        }
        $this->view->orderProduct = $orderProducts;


		$orderAddressBook = Service_OrderAddressBook::getByField($ordersCode,'order_code');
		$this->view->orderAddressBook = $orderAddressBook;
        //$this->view->logs = Service_OrderLog::getByCondition(array('order_code'=>$ordersCode),"*",0,0,'ol_add_time desc');

        $logs = Service_OrderLog::getByCondition(array('order_code'=>$ordersCode),"*",0,0,array('ol_add_time DESC', 'ol_id DESC'));
        foreach($logs as $key=>$value){
            if($value['user_id']>0){
                //$user = Service_User::getByField($value['user_id'],'user_id',"*");
                $logs[$key]['user_code'] = '系统';//$user['user_code'];
            }
            else {
              $logs[$key]['user_code'] = $order['customer_code'];

              if ((int) $value['account_id']) {
                $user = Service_Account::getByCondition(array('account_id' => $value['account_id']));
                $logs[$key]['user_code'] = $user ? $user['account_name'] : $order['customer_code'];
              }
            }
        }
        $this->view->logs = $logs;

        $shipOrderTracking = Service_ShipOrderTracking::getByCondition(array('order_code'=>$ordersCode),"*",0,0,"sot_add_time desc");
        foreach($shipOrderTracking as $key=>$value){
            $warehouse = Service_Warehouse::getByField($value['warehouse_id'],"warehouse_id","*");
            $shipOrderTracking[$key]['warehouse_code'] = $warehouse['warehouse_code'];
        }
        $this->view->shipOrderTracking = $shipOrderTracking;

        echo Ec::renderTpl($this->tplDirectory . "order-detail.tpl", 'noleftlayout');
    }

    public function detailLogAction ()
    {
        if($this->_request->isPost()){
            $page = $this->_request->getParam('page', 1);
            $pageSize = $this->_request->getParam('pageSize', 20);
        
            $page = $page ? $page : 1;
            $pageSize = $pageSize ? $pageSize : 20;
            $condition = array();
            /* 以下为提交数据整理 */
        
            $ordersCode = $this->_request->getParam("ordersCode","");
            $condition["orders_code"] = $ordersCode;
        

            $customer_id = $this->customerAuth->customer['customer_id'];
            $condition["customer_id"] = $customer_id;
            
            $return = array(
                    "ask" => 0,
                    "message" => "No Data"
            );
        
            /* 以下为业务逻辑方法调用 */
            $count = Merchant_Service_OrderStatusHistory::getByCondition($condition, 'count(*)');
            $return['count'] = $count;
             
            if ($count) {
                $rows = Merchant_Service_OrderStatusHistory::getByCondition($condition, '*', $pageSize,$page);  
                $return['data'] = $rows;
                $return['ask'] = 1;
                $return['message'] = "";
            }
        
            die(Zend_Json::encode($return));
        }
    }
    
    
    public function holdAction ()
    {
        echo Ec::renderTpl($this->tplDirectory . "order-hold.tpl", 'customer-layout');
    }
    /**
     * @author william-fan
     * @todo 订单创建asn单
     */
    public function createAsnAction(){
    	$return = array(
    			"ask" => 0,
    			"message" => "Error"
    	);
    	$ordersCode = $this->_request->getParam('ordersCode','');
    	
    	if($this->_request->isPost()){
    		$customer_id = $this->customerAuth->customer['customer_id'];
    		if(!empty($ordersCode)){
    			$orderInfo = Merchant_Service_Orders::getOrderAllInfo($ordersCode,$customer_id);
    			if($orderInfo){
    				if(in_array($orderInfo['orders_status'], array('5','6','7'))){
    					//订单状态正确
    					$warehouseId ='';
    					$ASNObj = new Merchant_Service_AsnProccess();
    			
    					$order['warehouse_id'] 		= $orderInfo['warehouse_id'];
    					$order['tracking_number']	= '';
    					$order['order_type']		= '4';
    					$order['ref_id']			= $orderInfo['orders_code'];
    					$order['packing_status']	= 0;//暂时不开放装箱功能
    					$order['description']		= 'create return asn!';
    					if(empty($warehouseId)){
    						$warehouseId = $orderInfo['warehouse_id'];
    					}
    					$item = array();
    					foreach ($orderInfo['order_product'] as $kop=>$vop){
    						$item[$kop]['product_id'] 	= $vop['product_id'];
    						$item[$kop]['order_qty']	= $vop['op_quantity'];
    						$item[$kop]['attribute']	= '';
    						$item[$kop]['product_info']	= array(
    								'product_sku'=>$vop['product_sku'],
    								'product_title'=>$vop['product_title'],
    								'product_title_cn'=>$vop['product_title_cn'],
    								//'product_net_weight'=>,
    								//'category_id'=>
    						);
    			
    					}
    					$boxArr = array();
    			
    					$asnresult = $ASNObj->createTransaction($order, $item, $customer_id, $warehouseId, $boxArr);
    					if($asnresult['ask']=='1'){
    						$return['ask'] = 1;
    						$return['message'] = "create return ASNCode: {$asnresult['ASNCode']} Success";
    						//ASNCode: REC000041304010001 Success
    					} else{
    						$return['message'] = $asnresult['msg'];
    					}		
    					$return['ask'] = 1;
    			
    				}else{
    					$return['message']='order status error!';
    				}
    			}else{
    				$return['message']='order error!';
    			}
    		}else{
    			//订单号为空
    			$return['message']='order code must be input';
    		}
    	}
    	die(Zend_Json::encode($return));
    }
    /**
     * @author william-fan
     * @todo 用于确认订单
     */
    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=>$orderCode){
    			$orderRow = Service_Orders::getByField($orderCode,'order_code');
    			$result = Service_OrderProcess::confirm($orderCode,$customerId);
    			if (!empty($result) && $result['ask']=='1') {
    				$success++;
    				$detailMessage = '订单号['.$orderCode.']成功.';
    				if($orderRow['is_remote_city']==1) {
    					$detailMessage .= '订单属于偏远地区.';
    				}
                    if($orderRow['sm_code']=='HKDHL'||$orderRow['sm_code']=='CNDHL') {
                        $op=Service_OrderProduct::getByCondition(array('order_code'=>$orderCode));
                        if (!empty($op)) {
                            $purpose_totalDeclare = 0;
                            foreach ($op as $key => $value) {
                               $purpose_totalDeclare +=$value['op_purpose_declared_value']*$value['op_quantity']; 
                            }
                            if ($purpose_totalDeclare>120) {
                               $detailMessage .= '<br>该订单目的海关申报价大于120USD，将产生超值报关费.';
                            }     
                        }
                        
                    }
					$return['detailmessage'][] = $detailMessage;
    			}else{
					$return['detailmessage'][] = '订单号'."[{$orderCode}]失败:".$result['message'];
    				//$failsStr.=$orderCode.Ec_Lang::getInstance()->getTranslate('error').$result['message'].'<br/>';
    				$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));
    }
    /**
     * @author william-fan
     * @todo 提交订单
     */
    public function submitAction(){
    	
    	$return = array('ask' => 0, 'message' =>Ec_Lang::getInstance()->getTranslate('SubmitOrder').','.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'];
        $batchNumber = microtime(TRUE);
    		foreach($orderArr as $key=>$orderCode){
    			//$result = Service_OrderProcess::confirm($orderCode,$customerId);
    			$result = Service_OrderProcess::submit($orderCode,$customerId,$batchNumber);
                //echo "<pre>";
                //var_dump($result);
                //echo "</pre>";
    			if (!empty($result) && $result['ask']=='1') {
    				$success++;
					$return['detailmessage'][] = "[{$orderCode}]已提交成功";
    			}else{
    				$failse++;
					$return['detailmessage'][] = "[{$orderCode}]提交失败:".join('<br />', $result['error']);
    				//$error[] = $orderCode.Ec_Lang::getInstance()->getTranslate('SubmitOrder').",".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('SubmitOrder').':'.Ec_Lang::getInstance()->getTranslate('success').$success.' '.Ec_Lang::getInstance()->getTranslate('fail').':'.$failse;
    	}
    	die(Zend_Json::encode($return));
    }

    /**
     * @author william-fan
     * @todo 用于移至草稿状态
     */
    public function draftAction(){
    	$return = array('ask' => 0, 'message' => Ec_Lang::getInstance()->getTranslate('MoveDraft').','.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_OrderProcess::draftTranslate($orderCode,$customerId);
    			if (!empty($result) && $result['ask']=='1') {
    				$success++;
					$return['detailmessage'][] = '订单号'."[{$orderCode}]成功.";
    			}else{
    				$failse++;
					$return['detailmessage'][] = '订单号'."[{$orderCode}]失败:".$result['message'];
    				//$error[] = $orderCode.Ec_Lang::getInstance()->getTranslate('MoveDraft').",".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('MoveDraft').','.Ec_Lang::getInstance()->getTranslate('success').':'.$success.' '.Ec_Lang::getInstance()->getTranslate('fail').':'.$failse;
    	}
    	die(Zend_Json::encode($return));
    }
	
	
  /**
     * @author colin
     * @todo 用于移至草稿状态
     */
    public function draftFromAbnormalAction(){
    	$return = array('ask' => 0, 'message' => Ec_Lang::getInstance()->getTranslate('MoveDraft').','.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_OrderProcess::draftFromAbnormal($orderCode,$customerId);
    			if (!empty($result) && $result['ask']=='1') {
    				$success++;
					$return['detailmessage'][] = '订单号'."[{$orderCode}]成功.";
    			}else{
    				$failse++;
					$return['detailmessage'][] = '订单号'."[{$orderCode}]失败:".$result['message'];
    				//$error[] = $orderCode.Ec_Lang::getInstance()->getTranslate('MoveDraft').",".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('MoveDraft').','.Ec_Lang::getInstance()->getTranslate('success').':'.$success.' '.Ec_Lang::getInstance()->getTranslate('fail').':'.$failse;
    	}
    	die(Zend_Json::encode($return));
    }	
    /**
     * @author william-fan
     * @todo 加入删除功能
     */
    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_OrderProcess::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));
    }
    
    /**
     * @author william-fan
     * @todo 用户查询ASN新建的订单信息
     */
    public function listAsnOrderAction(){
    	$customer = $this->_customerAuth;
        $customerId = $customer['id'];
        //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 = $this->_request->getParam("orders_code","");
            $condition["order_code"] = $orders_code;

            $condition["customer_id"] = $customerId;

            $warehouse_id = $this->_request->getParam("warehouse_id","");
            $condition["warehouse_id"] = $warehouse_id;
        

            $order_type = $this->_request->getParam("order_type","");
            $condition["order_type"] = $order_type;

            $reference_no = $this->_request->getParam("reference_no","");
            $condition["reference_no"] = $reference_no;
            
            $orders_status = $this->_request->getParam("orders_status","1");
            
        
            $shipping_method = $this->_request->getParam("shipping_method","");
            $condition["sm_code"] = $shipping_method;                    

            //增加开始结束时间
            $add_time_start	= $this->_request->getParam('add_time_start','');
            $condition["add_time_start"] = $add_time_start;
            
            $add_time_end	= $this->_request->getParam('add_time_end','');
            $condition['add_time_end']	= $add_time_end;
            $orders_status_arr = explode(',',$orders_status);
			$condition['order_status'] = '2';
			$condition['order_mode_type'] = '1'; //备货模式的订单
            $return = array(
                    "ask" => 0,
                    "message" => "No Data"
            );
            /* 以下为业务逻辑方法调用 */
            $count = Service_Orders::getByCondition($condition, 'count(*)');
            $return['count'] = $count;
            $cacheProduct = array();
            $page = $page>ceil($count/$pageSize)?ceil($count/$pageSize):$page;
            $rows = '';
            if ($count) {
                $rows = Service_Orders::getByCondition($condition, '*', $pageSize,$page,'order_id desc');

                $categories = Common_DataCache::getProductCategory();
                $orderTypes = Service_OrderProcess::getOrderTypeArr();
                foreach($rows as $k=>$v){
                    $orderAddressBook = Service_OrderAddressBook::getByField($v['order_id'],'order_id');
					if(!empty($orderAddressBook)){
						$country = Service_Country::getByField($orderAddressBook['oab_country_id']);
						$v['country_name'] = $country['country_name'];
					}
                    //$v=array_merge($v,$orderAddressBook);
                    $products = array();
                    $products= Service_OrderProcess::getDeclaredValue($v['order_code']);
                  
                    $v['order_product'] = $products;
                    $v['order_type_text'] = $orderTypes[$v['order_type']];
                    
                    $rows[$k]=$v;
                }

                $return['data'] = $rows;
                $return['ask'] = 1;
                $return['message'] = "";
            }

            $orderStatusArr = Service_Orders::getCustomerOrderStatusGroup($condition);
            $allStatus = Service_OrderProcess::getOrderStatus();
            
            //处理数量问题
            if(!empty($allStatus)){
            	$numConditon = $condition;
            	foreach($allStatus as $keys=>$values){
            		$numConditon['order_status_arr'] = explode(',',$keys);
            		$countnum = Service_Orders::getByCondition($numConditon, 'count(*)');
            		$allStatus[$keys] = $values."({$countnum})";
            	}
            }

            $statusTxt = array();
            $return['orderStatusArr'] = $statusTxt;
        $warehouse = Common_DataCache::getWarehouse();

        $this->view->warehouse = $warehouse;
        
        $this->view->result = $rows;
        
        $shipType = Common_DataCache::getShippingMethod();
        $smArray = array();
        foreach($shipType as $sm){
            $smArray[] = $sm['sm_code'];
        }
        sort($smArray);
        $this->view->shipType = $smArray;
        $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 $this->view->render($this->tplDirectory . "asn-order-list.tpl");
        //echo Ec::renderTpl($this->tplDirectory . "asn-order-list.tpl",'noleftlayout');
    }
    
    /**
     * @author william-fan
     * @todo 用于恢复删除的订单
     */
    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_OrderProcess::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('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));
    }

    public function printLabelAction(){
        $orderCode = $this->_request->getParam("ordersCode","");
        $orderInfo = Service_Orders::getByField($orderCode,'order_code',"*");
        $orderAddress = Service_OrderAddressBook::getByField($orderInfo['order_code'],"order_code","*");
        $country = Service_Country::getByField($orderAddress['oab_country_id'],'country_id',"*");
        $orderAddress['country'] = $country;
        $orderInfo['address'] = $orderAddress;
        $products = Service_OrderProduct::getByCondition(array('order_code'=>$orderCode),"*");
        $orderInfo['orderProduct'] = $products;
		
        $serviceTracking=Service_ServiceTrackingNumber::getByField($orderCode,'order_code');
        //$trackingNumber = $orderCode;
        $trackingNumber = "";
        if(!empty($serviceTracking)){
        	$trackingNumber = $serviceTracking['stn_code'];
        	$trackingNumber=Service_ServiceTrackingNumber::getTrackingNumber($orderInfo['sm_code'], $trackingNumber);
        }
        $orderInfo['ship']['tracking_number'] = $trackingNumber;
        $tpaRows = Service_TransportPickArea::getByCondition(array('sm_code' => $orderInfo['sm_code'], 'country' => $orderInfo['address']['country']['country_code']), array('area_code'));
        $orderInfo['pick_area'] = isset($tpaRows[0]['area_code'])?$tpaRows[0]['area_code']:'';

        $smInfo = Service_ShippingMethod::getByField($orderInfo['sm_code'],"sm_code","*");
        $this->view->orderInfo = $orderInfo;
        $this->view->smInfo = $smInfo;
        if($orderInfo['sm_code']=="SWPT"||$orderInfo['sm_code']=="BH-MMP"){
            echo $this->view->render($this->tplDirectory . "sw.tpl");
        }elsE{
            echo $this->view->render($this->tplDirectory . "F4.tpl");
        }
    }

    public function batchPrintAction(){
        $return = array('ask' => 0, 'message' =>Ec_Lang::getInstance()->getTranslate('SubmitOrder').','.Ec_Lang::getInstance()->getTranslate('fail'),'error'=>'','orderCodeArr'=>array());
        $orderArr	= $this->_request->getParam('orderArr','');
        $error = array();
        if (!empty($orderArr)) {
            $success=0;
            $failse=0;
            $customer = $this->_customerAuth;
            $customerId = $customer['id'];
            $oca = array();
            foreach($orderArr as $key=>$orderCode){
                $result = Service_OrderProcess::submit($orderCode,$customerId);
                if (!empty($result) && $result['ask']=='1') {
                    $oca[] = $orderCode;
                    $success++;
                    $return['detailmessage'][] = '订单号'."[{$orderCode}]成功.";
                }else{
                    $failse++;
                    $return['detailmessage'][] = '订单号'."[{$orderCode}]失败：".$result['message'];
                }
            }
            if($success>0){
                $return['orderCodeArr'] = $oca;
                $return['ask']=1;
            }
            if(!empty($error)){
                $return['error'] = $error;
            }
            $return['message']=Ec_Lang::getInstance()->getTranslate('SubmitOrder').':'.Ec_Lang::getInstance()->getTranslate('success').$success.' '.Ec_Lang::getInstance()->getTranslate('fail').':'.$failse;
        }
        die(Zend_Json::encode($return));
    }

    public function batchPrintLabelAction(){
        $orderCodeStr = $this->_request->getParam("orderCodes","");
        $orderCodeArr = explode(",",$orderCodeStr);

        if(empty($orderCodeStr)){
            $receivingCode = $this->_request->getParam("receiving_code","");
            $receivingCodeArr = explode(",",$receivingCode);
            foreach ($receivingCodeArr as $value) {
                if($value == '')continue;
                $rod = Service_ReceivingOrderDetail::getByCondition(array('receiving_code'=>$value),array('order_code'));            
                if(!empty($rod)){              
                    foreach($rod AS $val){
                        $orderCodeArr[] =   $val['order_code'];
                    }
                }
            }            
        }
        
        $orderList = array();
         $pdfSmcode=array( '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',
                        'LYT-SMTGH-X',
                        'BH-SFEP',
                );
        foreach($orderCodeArr as $orderCode){
            if($orderCode=="") continue;
            $o = array();
            $totalWeight=0;
            $totalValue=0;
            $orderInfo = Service_Orders::getByField($orderCode,'order_code',"*");
            if(in_array($orderInfo['sm_code'],$pdfSmcode)&&$orderInfo['order_mode_type']==1){
                continue;
            }
            $orderAddress = Service_OrderAddressBook::getByField($orderInfo['order_code'],"order_code","*");
            $country = Service_Country::getByField($orderAddress['oab_country_id'],'country_id',"*");
            $orderAddress['country'] = $country;
            $orderInfo['address'] = $orderAddress;
            $products = Service_OrderProduct::getByCondition(array('order_code'=>$orderCode),"*");
            $with_battery=0;
            foreach($products as $keyp=>$valuep){
            	$product = Service_Product::getByField($valuep['product_id']);
            	$products[$keyp]['product_weight'] = $product['product_weight'];
                $products[$keyp]['hs_code'] = $product['hs_code'];
                $products[$keyp]['product_title_cn'] = $product['product_title'];
                $products[$keyp]['customer_code'] = $product['customer_code'];
                $products[$keyp]['hs_goods_name'] = $product['hs_goods_name'];
               if ($product['with_battery']=='1') {
                    $with_battery=1;
                }
              // PNLG PNLP运输方式，需要把目的海关申报价值转换为EUR欧元
              if ('PNLG' === trim($orderInfo['sm_code']) || 'PNLP' === trim($orderInfo['sm_code']) || 'PNLN' === trim($orderInfo['sm_code'])) {
                $revertToEur = Service_Currency::converByCode('USD', 'EUR', $valuep['op_purpose_declared_value']);
                $products[$keyp]['op_purpose_declared_value'] = $revertToEur;
              }
                 $totalValue+=floatval($valuep['op_purpose_declared_value']*$valuep['op_quantity']);
                $totalWeight+=floatval($product['product_weight']*$valuep['op_quantity']);
            }
            if($orderInfo['sm_code']=='4PX-Singapo_SPack_IMAIR' || $orderInfo['sm_code']=='4PX-OZXBTH'){
                $condition=array(
                        'country_id'=>$orderInfo['address']['oab_country_id'],
                        // 'sm_code'=>'4PX-Singapo_SPack_IMAIR',
                        'sm_code'=>$orderInfo['sm_code'],
                        );
                    $picupArea=  Service_SmCountryPickcode::getByCondition($condition,'*',0,1,'post_code_end desc');
                    if(!empty($picupArea)){
                        foreach($picupArea as $area){
                            if(is_numeric($area['post_code_start'])&&!empty($area['post_code_end']) && !empty($orderInfo['address']['oab_postcode'])){
                                //add by @Felix 1182
                                $postCodeLen = strlen($area['post_code_end']);
                                if(strlen($orderInfo['address']['oab_postcode']) >= $postCodeLen ){
                                    $tmpPostcode = substr($orderInfo['address']['oab_postcode'],0,$postCodeLen);
                                }else{ 
                                    $format = '%0'.$postCodeLen.'s'; 
                                    $tmpPostcode = sprintf($format, $orderInfo['address']['oab_postcode']);
                                }
                                
                                if((int)$tmpPostcode>=(int)$area['post_code_start']
                                  &&(int)$tmpPostcode<=(int)$area['post_code_end']){
                                    break;
                                }
                            }
                        }
                    }
                    $orderInfo['pick_up']=array(
                        'pick_code'=>$area['pick_code'],
                        'number_area'=>$area['area']
                    );
                    $orderInfo['returnSign'] = 'Y';
            }
            if($orderInfo['sm_code']=='BH-NLPOST-TH'){
                $filePath = APPLICATION_PATH . '/../data/file/BH-NLPOST-TH-PICKCODES.xlsx';
                $fileData = Common_Upload::readEXCEL($filePath);
                $res      = 0;
                foreach ($fileData as $k => $v) {
                    if ($k == 0) {
                        continue;
                    }
                    $str = strpos(strtolower( $country['country_code'] ), strtolower($v[0]));
                    if (is_numeric($str)) {
                        $res = 1;
                        $pick_code = $v[3];
                        break;
                    }
                }
                if ($res) {
                    $pick_code = $pick_code ? $pick_code : '';
                    $orderInfo['pick_up']=array(
                        'pick_code'=>$pick_code,
                    );
                 }
            }
            $orderInfo['with_battery']=$with_battery;
            $orderInfo['orderProduct'] = $products;
            $orderInfo['totalWeight']=$totalWeight;
            $orderInfo['totalValue']=$totalValue;
            if ('HKPP' === trim($orderInfo['sm_code'])) { // HKPP运输方式需要计算包袋号
              $orderInfo['pack_no'] = Service_ChangePack::getPackNo($country['country_code'], $orderAddress['oab_postcode']);
              $smCountryMap = Service_SmCountryMap::getByInCondition(array(
                'warehouse_id_arr' => array(0, $orderInfo['warehouse_id']),
                'sm_code' => $orderInfo['sm_code'],
                'country_code' => $country['country_code']
              ));
             
              if ($smCountryMap) {
                $orderInfo['country_area'] = $smCountryMap[0]['area'];
              }
              else {
                $orderInfo['country_area'] = '';
              }
            }
            elseif ('HKPG' == trim($orderInfo['sm_code'])||'4PX-Singapo_SPack_IMAIR' == trim($orderInfo['sm_code'])) { // 获取国家映射区域代码
              $smCountryMap = Service_SmCountryMap::getByInCondition(array(
                'warehouse_id_arr' => array(0, $orderInfo['warehouse_id']),
                'sm_code' => $orderInfo['sm_code'],
                'country_code' => $country['country_code']
              ));
             
              if ($smCountryMap) {
                $orderInfo['country_area'] = $smCountryMap[0]['area'];
              }
              else {
                $orderInfo['country_area'] = '';
              }
            }
            elseif ('PNLG' === trim($orderInfo['sm_code']) || 'PNLP' === trim($orderInfo['sm_code']) || 'PNLN' === trim($orderInfo['sm_code'])) {
              $currency = Service_Currency::getByField('EUR', 'currency_code');
              $orderInfo['currency_symbol'] = $currency ? $currency['currency_symbol_left'] : '';
            }
            if(in_array($orderInfo['sm_code'],array('TWPG','TWPP'))){
                $orderInfo['change_code']=  Service_HjtwApi::getCode($orderAddress['oab_country_id'], $orderAddress['oab_postcode'],$orderInfo['sm_code']);
                if(empty($orderInfo['print_no'])){
                      $printNo=Service_OrderProcess::getPrintNo();
                      $orderInfo['print_no']=$printNo;
                      $updateOrder=array(
                          'print_no'=>$printNo
                      );
                    Service_Orders::update($updateOrder,$orderInfo['order_id']);
                }
            }
            //$serviceTracking=Service_ServiceTrackingNumber::getByField($orderCode,'order_code');
            if(!in_array($orderInfo['sm_code'],array('SWPT','BH-MMP','BH-AZAT-G','BH-MMP1'))){
                $trackingNumber = $orderCode;
            }else{
                $trackingNumber = $orderInfo['ref_tracking_number'];
            }
            /*if(!empty($serviceTracking)){
                $trackingNumber = $serviceTracking['stn_code'];
                $trackingNumber=Service_ServiceTrackingNumber::getTrackingNumber($orderInfo['sm_code'], $trackingNumber);
            }*/
            $orderInfo['ship']['tracking_number'] = $trackingNumber;
            $tpaRows = Service_TransportPickArea::getByCondition(array('sm_code' => $orderInfo['sm_code'], 'country' => $orderInfo['address']['country']['country_code']), array('area_code'));
            $orderInfo['pick_area'] = isset($tpaRows[0]['area_code'])?$tpaRows[0]['area_code']:'';

            $smInfo = Service_ShippingMethod::getByField($orderInfo['sm_code'],"sm_code","*");
            if(in_array($smInfo['sm_class_code'], array('CRP','CRE'))){ 
            	if($orderInfo['ref_tracking_number']!=''){
            		$orderInfo['ship']['tracking_number'] = $orderInfo['ref_tracking_number'];
            	}
            }
            /*1.+ URL 中+号表示空格 %2B
            2.空格 URL中的空格可以用+号或者编码 %20
            3./ 分隔目录和子目录 %2F
            4.? 分隔实际的 URL 和参数 %3F
            5.% 指定特殊字符 %25
            6.# 表示书签 %23
            7.& URL 中指定的参数间的分隔符 %26
            8.= URL 中指定参数的值 %3D */
            $orderInfo['reference_no'] = str_replace('#','%23',$orderInfo['reference_no']);
            $o['orderInfo'] = $orderInfo;
            $o['smInfo'] = $smInfo;
            $orderList[] = $o;
            //$this->view->orderInfo = $orderInfo;
            //$this->view->smInfo = $smInfo;

        }
        $this->view->nowTime = date("Y-m-d");
        $this->view->nowTime2 = date("Y-m-d H:i:s");
        $this->view->orderList = $orderList;
        echo $this->view->render($this->tplDirectory . "print-label.tpl");
    }
    public function batchPrintPdfLabelAction(){
         $orderCodeStr = $this->_request->getParam("orderCodes","");
        $orderCodeArr = explode(",",$orderCodeStr);
        $sm_code=$this->_request->getParam('sm_code','');
        if(empty($orderCodeStr)){
            $receivingCode = $this->_request->getParam("receiving_code","");
            $receivingCodeArr = explode(",",$receivingCode);
            foreach ($receivingCodeArr as $value) {
                if($value == '')continue;
                $rod = Service_ReceivingOrderDetail::getByCondition(array('receiving_code'=>$value),array('order_code'));            
                if(!empty($rod)){              
                    foreach($rod AS $val){
                        $orderCodeArr[] =   $val['order_code'];
                    }
                }
            }            
        }
         $pdfSmcode=array( '4PX-LYT_GH', //A6
                        '4PX-EU_PACKET', //DS
                        '4PX-RU_POST-LINK_RMAIL', //BA
                        '4PX-HKDHL', //A1
                        '4PX-YX', //AI
                        '4PX-SG_ordinary_mail+' ,
                        'PNLN','PNLG',
                        'LYT-SMTGH-X',
                        'BH-SFEP',
             );
         if(!empty($sm_code)&&in_array($sm_code,$pdfSmcode)){
               $condition=array(
                                'order_code'=>$orderCodeArr,
                                'sm_code'=>$sm_code,
                                'order_mode_type'=>'1'
                    );
                    $hasPdfOrder=Service_Orders::getByCondition($condition,'distinct(order_code) as order_code');
                    $orderCodeArr=array();
                    foreach($hasPdfOrder as $order){
                        $orderCodeArr[]=$order['order_code'];
                    }
         }
  
            $pdfNew = new Zend_Pdf();
            $obj4px=new Service_FourpxWebService();
        foreach($orderCodeArr as $orderCode){
            if($orderCode=="") continue;
            $o = array();
            $totalWeight=0;
            $totalValue=0;
            $orderInfo = Service_Orders::getByField($orderCode,'order_code',"*");
            if(in_array($orderInfo['sm_code'],$pdfSmcode)&&
                    $orderInfo['order_mode_type']==1&&
                    !in_array($orderInfo['sm_code'],array('PNLN','PNLG','BH-SFEP'))){
                    $label=Service_OrdersLabel::getByField($orderInfo['order_code'],'order_code');
                    if(empty($label)){
                       $result= $obj4px->getPdfByOrderCode($orderCode);
                       if($result['lable_content']){
                           $label=$result['lable_content'];
                       }
                    }
                    if(!empty($label)){
                          $pdf = Zend_Pdf::parse(base64_decode($label['ol_content']));
                           $extractor = new Zend_Pdf_Resource_Extractor();
                          foreach ($pdf->pages as $page) {
                                $pdfExtract = $extractor->clonePage($page);
                                $pdfNew->pages[] = $pdfExtract;
                           }
                    }else{
                       $pdf=new Zend_pdf();
                       $newPage=$pdf->newPage('228:228:');///大概10*10
                        $font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA);
                          $newPage->setFont($font, 15)
                                 ->drawText($orderInfo['order_code'].' no label,', 1, 200)
                                ->drawText(' Please wait a while and', 1, 180)
                                ->drawText('try again', 3, 160);
                       $pdf->pages[0] = $newPage;
                       $labelContent=$pdf->render();
                       unset($pdf);
                       $pdf = Zend_Pdf::parse($labelContent);
                        $extractor = new Zend_Pdf_Resource_Extractor();
                        foreach ($pdf->pages as $page) {
                                $pdfExtract = $extractor->clonePage($page);
                                $pdfNew->pages[] = $pdfExtract;
                        }
                    }
                    
                }elseif(in_array($orderInfo['sm_code'],array('PNLG','PNLN','BH-SFEP'))&&$orderInfo['order_mode_type']==1&&$sm_code){
                    $pnOrder[]=$orderInfo['order_code'];
                }
		}
           if($pnOrder){
               try{
                  $UspsClass = new Service_UspsInterface();
                  $pdfPath=$UspsClass->getLabel(implode(",",$pnOrder));
                  if($pdfPath['pdfUrl']){
                        header('content-type:application/pdf');
                         echo file_get_contents($pdfPath['pdfUrl']);
                         die();
                  }
               }catch(Exception $e){
                   die('获取标签失败:'.$e->getMessage());
               } 
           }else{
                if(count($pdfNew->pages)<1){
                    die('ASN单没有pdf格式标签的订单');
                }
                 header('content-type:application/pdf');
              echo $pdfNew->render();
           }
        
	}

    /*城市*/
    public function cityInputAction(){
    	$province_id = $this->getRequest()->getParam('province_id', 0);
    	if(!$province_id){
    		echo "";
    		exit;
    	}  //if(!$province_id)
    	$city_array = Service_Region::getByCondition(array('parent_id'=>$province_id));
    	echo json_encode($city_array);
    	exit;
    
    }//function end
    /**
     * @author william-fan
     * @todo 用于获取收发件人信息
     */
    public function orderAddressAction(){
    	//if($this->_request->isPost()){
    		$param = $this->_request->getParams();
    			
    		$customer = $this->_customerAuth;
    		$customerId = $customer['id'];
    			
    		$page = $this->_request->getParam('page', 1);
    		$pageSize = $this->_request->getParam('pageSize', 20);
    			
    		$condition = array();
    		/* 以下为提交数据整理 */
    			
    		$cab_type = trim($this->_request->getParam("oab_type","1"));
    		$condition["cab_type"] = $cab_type;
    			
    			
    		$condition["customer_id"] = $customerId;
    			
    			
    		$cab_code = $this->_request->getParam("cab_code","");
    		$condition["cab_code"] = $cab_code;
    			
    			
    		$cab_lastname = $this->_request->getParam("cab_lastname","");
    			
    		$condition["cab_lastname"] = $cab_lastname;
    			
    		$count = Service_CustomerAddressBook::getByCondition($condition,'count(*)');
    			
    		$rows = Service_CustomerAddressBook::getByCondition($condition,'*');
    		foreach ($rows as $key=>$value){
    			$cab_country_name = '';
    			if(!empty($value) && $value['cab_country_id']>0){
    				$cabCountryInfo = Service_Country::getByField($value['cab_country_id']);
    				if($cabCountryInfo){
    					$cab_country_name = $cabCountryInfo['country_name'];
    				}
    			}
    			$rows[$key]['cab_country_name'] = $cab_country_name;
    		}
    		//die(json_encode($rows))
    		$this->view->type = $cab_type;
    		$this->view->count = $count;
    		$this->view->page = $page;
    		$this->view->pageSize = $pageSize;
    		$this->view->params = $condition;
    		$this->view->result = $rows;
    	//}
    	echo $this->view->render($this->tplDirectory . "addressbook.tpl");
    }
    
	function cityAction() {
    	$response = array();
    	$country_id = $this->_request->getParam('country_id');
    	$sm_code = $this->_request->getParam('sm_code');
    	if(!is_numeric($country_id)) exit(json_encode($response));
    	$term = $this->_request->getParam('term');
    	//if(empty($term)) exit(json_encode($response));
    	if(empty($sm_code)){
    	    $sm_code = '0';
    	}
    	$condition = array('country_id'=>$country_id, 'city_name_like'=>$term,'sm_code'=>$sm_code);
    	$list = Service_City::getByCondition($condition, 'city_name', 10);
    	$is_exist = empty($list) && Service_City::getByWhere(array('country_id' => $country_id,'sm_code' => $sm_code));
    	if(empty($list) && empty($is_exist)){
    	    $condition = array('country_id'=>$country_id, 'city_name_like'=>$term,'sm_code'=>'0');
    	    $list = Service_City::getByCondition($condition, 'city_name', 10);
    	}
    	foreach($list as $row) $response[] = $row['city_name'];
    	exit(json_encode($response));
    }


    public function postcodeAction() {
    	$response = array();
    	$country_id = trim($this->_request->getParam('country_id'));
    	if(!is_numeric($country_id)) exit(json_encode($response));
    	$city = trim($this->_request->getParam('city'));
    	if(empty($city)) exit(json_encode($response));
    	$aCity = Service_City::getByWhere(array('country_id'=>$country_id, 'city_name'=>$city,'sm_code'=>'0'), 'city_id');
    	$term = $this->_request->getParam('term');
    	//if(empty($term)) exit(json_encode($response));
    	$sm_code = trim($this->_request->getParam('sm_code'));
    	$cityInfo = Service_City::getByWhere(array('country_id' => $country_id, 'city_name'=>$city,'sm_code' => $sm_code));
    	if(!empty($cityInfo)) {
    	    unset($aCity);
    	    $aCity['city_id'] = $cityInfo['city_id'];
    	} 
    	if(empty($aCity)) exit(json_encode($response));
    	$condition = array('city_id'=>$aCity['city_id'], 'postcode_no_like'=>$term);
    	
    	$list = Service_Postcode::getByCondition($condition, '*', 10);
        $aPostcode = array(); 
        foreach($list as $row){
            if($row['postcode_no_end']==''){
                if(!in_array($row['postcode_no'],$aPostcode)){
                    $aPostcode[] = $row['postcode_no'];
                }
            }elseif($row['postcode_no_end']==$row['postcode_no']){
                if(!in_array($row['postcode_no'],$aPostcode)){
                    $aPostcode[] = $row['postcode_no'];
                }
            }else{
                if($row['postcode_no_end']!=$row['postcode_no']){
                    $length = strlen($row['postcode_no']);
                    for($postcode=$row['postcode_no'];$postcode<=$row['postcode_no_end'];$postcode++){
                        if(count($aPostcode)==10){
                            exit(json_encode($aPostcode));
                        }
                        if(!in_array($postcode,$aPostcode)){
                            $postcode = str_pad($postcode, $length, "0", STR_PAD_LEFT);
                            $aPostcode[] = strval($postcode);
                        }
                    }
                }
            }
            //$aPostcode[] =
        }
        exit(json_encode($aPostcode));
    	//foreach($list as $row) $response[] = $row['postcode_no'];
    	//exit(json_encode($response));
    }

    public function interceptAction(){
        $order_code = $this->_request->getParam('order_code','');
        $intercept_reason = $this->_request->getParam('intercept_reason','');
        $customer = $this->_customerAuth;
        $customerId = $customer['id'];
        $data = array(
            'order_code'=>$order_code,
            'intercept_reason'=>$intercept_reason,
        );
        $result = Service_OrderProcess::interceptTranslate($data,$customerId);
        die(Zend_Json::encode($result));
    }
	
	
   /**
     * @author colin-yang
     * @todo 用于下载订单模板
     */
    public function orderSelectTempleteAction(){
    	$fullPath = APPLICATION_PATH."/../data/file".'/orderSelect.xls';
    	//方法2
    	$filename = basename($fullPath);
    	header("Content-Type: APPLICATION/OCTET-STREAM");
    	//Force the download
    	$header="Content-Disposition: attachment; filename=".$filename.";";
    	header($header );
    	// 	header("Content-Transfer-Encoding: binary");
    	// 	header("Content-Length: ".$len);
    	echo file_get_contents($fullPath);
    	exit;
    }	
	

  /**
     * @author colin-yang
     * @todo 用于集货ASN上传订单
     */
    public function bulkorderAction(){
    	set_time_limit(0);
        $result = array("ask" => 0, "message" => "失败", 'error' => array(), 'data' => array());
        $path = APPLICATION_PATH . '/../data';
        //$field = $this->getRequest()->getParam('XMLForInput', 'XMLForInput');
        //print_r($this->_request->getParams());
        //exit;
        $customer = $this->_customerAuth;
        $customerId = $customer['id'];

        $warehouse_id = $this->_request->getParam('warehouse_select', '');
        $to_warehouse_id = $this->_request->getParam('to_warehouse_select', '');
        if (!empty($warehouse_id)) {
            $jhwarehouse = Service_Warehouse::getByField($warehouse_id);
    		if(empty($jhwarehouse)){    		
    			$result['message'] = '此订单交货仓库不存在';
    			echo json_encode($result);
    			exit;
    		}
    	}else{
    		$result['message'] = '此订单交货仓库必填';
    		echo json_encode($result);
    		exit;
    	}
    	//print_r($result);
    	//exit;
    	$field = 'XMLForInput';
    	$config = array();
    	$config['upload_path']		= $path;
    	$config['allowed_types']	= 'xls|xlsx';
    	$config['max_size']			= '50000';
    	$config['encrypt_name']		= true;
    	$upload	= new Common_UploadFile($config);
    	$upload->set_upload_path($path);
    	if ( ! $upload->do_upload($_FILES,$field) ){
    		$result['error'] =  $upload->display_errors();
    		echo json_encode($result);
    		exit;
    	}
    	
    	$resultArray = $upload->data();
    	$full_path = $resultArray['full_path'];
    	if(empty($resultArray) || empty($full_path)){
    		$result = array("ask"=>0,"message"=>"上传文件失败失败",'error'=>array());
    		echo json_encode($result);
    		exit;
    	}
    	
    	$resultArray = Common_Upload::readEXCEL($full_path);
    	if(empty($resultArray) || !is_array($resultArray)){
    		$result = array("ask"=>0,"message"=>"文件内容不符合格式或数据为空.",'error'=>array());
    		echo json_encode($result);
    		exit;
    	}
    	@unlink($full_path);
    	//读取product表根据XML中的SKU
    	$found_order_results = array();
    	/* print_r($resultArray);
    	exit; */
        $category = Common_DataCache::getProductCategory();
        $allOrders = array();
        $errorTip = ''; // 错误提示，有任何错误，都终止程序执行

        unset($resultArray[0]); // 去除标题行
        // 提取交易订单号，检查是否重复
        foreach ($resultArray as $row) {
            $orderCode = trim($row[0]);

            if ('' !== $orderCode) {
                if (in_array($orderCode, $allOrders, TRUE)) {
                    $errorTip = '交易订单号【' . $orderCode . '】重复，程序终止继续运行';
                    break;
                }

                $allOrders[] = $orderCode;
            }
        }

        if ('' !== $errorTip) { // 有重复交易订单 号
            exit(json_encode(array('ask' => 0, 'message' => $errorTip)));
        }

        foreach ($allOrders as $orderCode) {
            $condition = array(
                'customer_id' => $customerId,
                'order_code' => $orderCode,
                'except_deleted_status' => TRUE,
            );
            $orderInfo = Service_Orders::getRowByCondition($condition, '*');
            if ($orderInfo) {
                $order = array(
                    'order_id' => $orderInfo['order_id'],
                    'order_code' => $orderInfo['order_code'],
                    'reference_no' => $orderInfo['reference_no'],
                    'ref_tracking_number' => $orderInfo['ref_tracking_number'],
                    'sm_code' => $orderInfo['sm_code'],
                    'add_time' => $orderInfo['add_time'],
                    'is_valid' => '1',
                    'error' => array()
                );

                $orderAddressBook = Service_OrderAddressBook::getByField($orderInfo['order_id'],'order_id');
                if(!empty($orderAddressBook)){
                    $country = Service_Country::getByField($orderAddressBook['oab_country_id']);
                    $order['country_name'] = $country['country_name'];
                }else{
                    $order['country_name'] = '';
                }

                $condition['order_status'] = '2';
                $condition['order_mode_type'] = '1'; //集货模式的订单
    					//判断产品类型是否正确
                if ($orderInfo['order_mode_type'] != '1') {
                    $order['is_valid'] = '0'; //这个产品不能使用
                    $orderError = $order['error'];
                    $orderError[] = '此订单为备货订单，不能用于建立ASN';
                    $order['error'] = $orderError;
                    $errorTip = '交易订单号【' . $orderCode . '】不集货模式，程序终止继续运行';
                    break;
                } else {


    					//判断产品状态是否正确
                    if ($orderInfo['order_status'] != '2') {
                        $order['is_valid'] = '0';

                        $orderError = $order['error'];
                        if ($orderInfo['order_status'] == '0') {
                            $orderError[] = '此订单是删除状态，不能用于建立ASN';
                        } elseif ($orderInfo['order_status'] == '1') {
                            $orderError[] = '此订单是草稿状态，请提交订单到确认状态才可新建ASN';
                        } else {
                            $orderError[] = '此订单已新建过ASN，不可重复建立';
                        }

                        $order['error'] = $orderError;
                        $errorTip = '交易订单号【' . $orderCode . '】不是确认状态，程序终止继续运行';
                        break;
                    }
                    //判断客户是否一致
                    if ($orderInfo['customer_id'] != $customerId) {
                        $order['is_valid'] = '0';
                        $orderError = $order['error'];
                        $orderError[] = '此订单和客户不一致';
                        $order['error'] = $orderError;
                        $errorTip = '交易订单号【' . $orderCode . '】不属于当前客户，程序终止继续运行';
                        break;
                    }
                    if (isset($warehouse_id) && $warehouse_id != $orderInfo['warehouse_id']) {
                        $order['is_valid'] = '0';
                        $orderError = $order['error'];
                        $orderError[] = '此订单交货仓库与ASN交货仓库不一致';
                        $order['error'] = $orderError;
                        $errorTip = '交易订单号【' . $orderCode . '】所属仓库与当前仓库不一致，程序终止继续运行';
                        break;
                    }
                    if (isset($to_warehouse_id) && $to_warehouse_id != '' && $to_warehouse_id != $orderInfo['to_warehouse_id']) {
                        $order['is_valid'] = '0';
                        $orderError = $order['error'];
                       $orderError[] = Ec_Lang::getInstance()->getTranslate('PurposeWarehousesAndWarehousePurposesInconsistentOrders'); //目的仓不一致
                        $order['error'] = $orderError;
                        $errorTip = '交易订单号【' . $orderCode . '】所属目的仓与当前目的仓不一致，程序终止继续运行';
                        break;
                    }
                }
                $found_order_results[] = $order;
            } else {
                $order = array(
                    'order_id' => '0',
                    'order_code' => $orderCode,
                    'reference_no' => $orderCode,
                    'sm_code' => '',
                    'add_time' => '',
                    'is_valid' => '0',
                    'error' => array("此订单不存在")
                );
                $found_order_results[] = $order;
                $errorTip = '交易订单号【' . $orderCode . '】不存在，程序终止继续运行';
                break;
            }
        }//foreach($resultArray

        if ('' !== $errorTip) { // 有错误，程序终止继续运行
            exit(json_encode(array('ask' => 0, 'message' => $errorTip)));
        }

    	if(empty($found_order_results) || !is_array($found_order_results)){
    		$result = array("ask"=>0,"message"=>"在订单资料库中找不到对应的数据.",'error'=>array());
    		echo json_encode($result);
    		exit;
    	}
    	
    	//echo "sdf";exit;
    	$result = array("ask"=>'1','data'=>$found_order_results);
    	echo json_encode($result);
    	exit;
    }	
    /**
     * @author william-fan
     * @todo 用于自有运输渠道运输方式获取
     */
    public function shipMethodAction(){
    	if($this->_request->isPost()){
    		$warehouseId = $this->_request->getParam('warehouseId','');
    		$condition = array(
    				'warehouse_id_arr'=>array(0,$warehouseId),
    				'sm_channel'=>'1',
    				'sm_status'=>'1'
    		);
    		$shipMethods = Service_ShippingMethod::getByCondition($condition);
    		die(Zend_Json::encode($shipMethods));
    	}
    }

    public function getShipMethodAction(){
        //if($this->_request->isPost()){
        $warehouseId = $this->_request->getParam('warehouse_id','');
        $countryId = $this->_request->getParam("country_id","");
        $channel = $this->_request->getParam("sm_channel","");
        $customer = $this->_customerAuth;
        $needBuyInsurance = Service_ShippingMethod::getBuyInsuranceShipMethod();
        $limitation = Service_ShippingMethod::getDeliveryLimitation();
        $warehouse = Service_Warehouse::getByField($warehouseId);
        if($channel=="0"){
            $condition = array(
                'sm_channel'=>'1',
                'sm_status'=>'1'
            );
            $shipMethod = Service_ShippingMethod::getByCondition($condition,"*");
            foreach($shipMethod as $key=>$value){
                if( in_array( $value['sm_code'] ,$needBuyInsurance) && $warehouse['warehouse_code'] == 'SZ01')
                    $shipMethod[$key]['buyInsurance'] = 1;
                else
                    $shipMethod[$key]['buyInsurance'] = 0;

                if( isset( $limitation[$value['sm_code']]) )
                    $shipMethod[$key]['limitation'] = $limitation[$value['sm_code']];

                if($value['sm_code']=="CNDHL"){
                    $ftpMessageType = Service_FtpMessageType::getByField($customer['code'].'-CNDHL',"fmt_code");
                    if(empty($ftpMessageType)) unset($shipMethod[$key]);
                }
            }
            $shipMethod=Common_Common::multisort($shipMethod);
            die(Zend_Json::encode($shipMethod));
        }else{
            $condition = array(
                'warehouse_id_arr'=>array(0,$warehouseId),
                'country_id'=>$countryId,
            );
            $shipMethod = Service_SmCountryMap::getByCondition($condition,"distinct(sm_code),warehouse_id");
            $AllShipMethod = array();
            $existSm = array();
            foreach($shipMethod as $key=>$value){
                if($value['sm_code']=="CNDHL"){
                    $ftpMessageType = Service_FtpMessageType::getByField($customer['code'].'-CNDHL',"fmt_code");
                    if(empty($ftpMessageType)) continue;
                }
                $con = array(
                    'warehouse_id_arr'=>array(0,$value['warehouse_id']),
                    'sm_code'=>$value['sm_code'],
                    'sm_status'=>'1',
                );
                $smRowList = Service_ShippingMethod::getByCondition($con,"*");
                //$shipMethod[$key]['sm_name_cn'] = $smRow[0]['sm_name_cn'];
                //$shipMethod[$key]['sm_channel'] = $smRow[0]['sm_channel'];
                if(!empty($smRowList)){
                    foreach($smRowList as $SRLkey=>$SRLvalue){
                        if( in_array( $value['sm_code'] ,$needBuyInsurance) && $warehouse['warehouse_code'] == 'SZ01')
                            $SRLvalue['buyInsurance'] = 1;
                        else
                            $SRLvalue['buyInsurance'] = 0;

                        if( isset( $limitation[$SRLvalue['sm_code']]) )
                            $SRLvalue['limitation'] = $limitation[$value['sm_code']];

                        if(!in_array($SRLvalue['sm_code'],$existSm)){
                            $AllShipMethod[] = $SRLvalue;
                            $existSm[] = $SRLvalue['sm_code'];
                        }
                    }
                }
            }
            $AllShipMethod=Common_Common::multisort($AllShipMethod);
            die(Zend_Json::encode($AllShipMethod));
        }
        //}
    }

    public function createEbayOrderAction(){
        $warehouse = Common_DataCache::getWarehouse();

        if(!empty($warehouse)){
            foreach($warehouse as $keyw=>$wh){
                if($wh['warehouse_scope']=='0'){
                    unset($warehouse[$keyw]);
                }
            }
        }
        $this->view->warehouse = $warehouse;
        $warehouseJs = array();
        $warehouseIds = array();
        foreach($warehouse as $w){
            $warehouseJs[$w['warehouse_id']] = array(
                'warehouse_id'=>$w['warehouse_id'],
                'warehouse_name'=>$w['warehouse_code'],
                'country_id'=>$w['country_id'],
            );
            $warehouseIds[] = $w['warehouse_id'];
        }
        $warehouseIds[] = '0';
        $this->view->warehouseJs = Zend_Json::encode($warehouseJs);

        $province_array = Service_Region::getByCondition(array('parent_id'=>1));
        $this->view->province_array = $province_array;

        $this->view->country = Service_Country::getAll();

        $currencyAll = Common_DataCache::getCurrency();
        $this->view->currencyAll = $currencyAll;

        $this->view->city_array = array();
        if(isset($orderInfo)&&$orderInfo){
            //print_r(Service_Region::getByCondition(array('parent_id'=>$orderInfo['oab_state_id'])));
            if(isset($orderInfo['addressSender']['oab_state_id']) && $orderInfo['addressSender']['oab_state_id']>0){
                $this->view->city_array = Service_Region::getByCondition(array('parent_id'=>$orderInfo['addressSender']['oab_state_id']));;
            }
        }

        //$this->view->countryJs = Zend_Json::encode($countryArr);
        //$this->view->cityJs = Zend_Json::encode($cityArr);
        $ecg_category = Common_DataCache::getProductCategory();
        $this->view->ecg_category = $ecg_category;
        $this->view->orderType = Service_OrderProcess::getOrderTypeArr();

        $tpl = "ebay-order-create.tpl";
        echo Ec::renderTpl($this->tplDirectory . $tpl,'noleftlayout');
    }

    public function getInsuranceAmountAction() {
        $warehouse = trim( $this->_request->getParam('warehouse','') );
        $insuranceItem = trim( $this->_request->getParam('insuranceItem','') );
        $insuranceRate = trim( $this->_request->getParam('insuranceRate','') );
        $countryId = trim( $this->_request->getParam('country','') );
        $dealPrice = trim( $this->_request->getParam('dealPrice','') );
        $currency = trim( $this->_request->getParam('dealCurrency','') );
        $shipMethod = trim( $this->_request->getParam('shipMethod','') );

        $return = array('amount'=>0,'currency'=>'RMB','detail'=>array(),'premium'=>0,'fault'=>0);
        $allow = Service_ShippingMethod::getBuyInsuranceShipMethod();
        if( in_array( $shipMethod, $allow )){
            $obj = new Service_OtherFeeProcess();
            $param = array(
                'insuranceRate'=>$insuranceRate,
                'country'=>$countryId,
                'dealPrice'=>$dealPrice,
                'dealCurrency'=>$currency,
            );
            $amount = $obj->getAmount( $warehouse,$insuranceItem,$param );

            if( $amount ) {
                $return = $amount;
                $return['fault'] = 0;
            } else {
                $return['fault'] = 1;
            }
        }
        die(json_encode($return));
    }
    
}