<?php
class Api_ServiceForOrder {

 protected $_customerId = null;
    
    protected $_customer = null;

    protected $_token = null;

    protected $_key = null;

    protected $_auth = false;

    protected $_error = null;    

    protected $_date = null;

    protected $_paramterArr = array();//将传递过来的对象转为数组存储
    

    private function _init ($headerRequest) {
        $this->_customerCode = (string) $headerRequest['customerCode'];
        $this->_operationCustomerCode = (string) $headerRequest['operationCustomerCode'];
        $this->_token = (string) $headerRequest['appToken'];
        $this->_key = (string) $headerRequest['appKey'];
    }
    /**
     * @author william-fan
     * @todo Authenticate
     */
	private function authenticate(){
        $customer = Service_Customer::getByField($this->_customerCode, 'customer_code');
        if (!$customer || $customer['customer_status'] != 2) {
            $this->_error = 'No Authority For ' . $this->_customerCode . '.';
            return false;
        }
        $this->_customer = $customer;
        if(!empty($this->_operationCustomerCode)){
			$opCustomer=Service_Customer::getByField($this->_operationCustomerCode, 'customer_code');
            if(empty($opCustomer)){
                $this->_error = 'Customer [' . $this->_operationCustomerCode . '] does not exist .';
                return false;
            }
            if(Service_CustomerRegister::getByCondition(array('regis_customer_code' => $this->_customerCode, 'customer_code' => $this->_operationCustomerCode)) == false){
                $this->_error = 'No authorization operation ' . $this->_operationCustomerCode . '.';
                return false;
            }
        }
        $customerAuth = Service_CustomerApi::getByField($this->_customerCode, 'customer_code');
        if ($customerAuth && $customerAuth['ca_token'] == $this->_token && $customerAuth['ca_key'] == $this->_key) {
            //当前客户代码改为操作客户代码
            if(!empty($this->_operationCustomerCode)){
                $this->_customerCode = $this->_operationCustomerCode;
				$this->_customer=$opCustomer;
            }
            $this->_auth = true;
            return true;
        }
        $this->_error = 'App Token/App Key Not match for ' . $this->_customerCode . '.';
        return false;
    }
	/**
	 * @todo 写日志
	 */
    private function logError ($error) {
        $logger = new Zend_Log();
        $uploadDir = APPLICATION_PATH . "/../data/log/";
        $writer = new Zend_Log_Writer_Stream($uploadDir . 'api-order.log');
        $logger->addWriter($writer);
        $logger->info(date('Y-m-d H:i:s') . ': ' . $error . " \n");
    }
    
	/**
	 * @author william-fan
	 * @todo 对wsdl 自动将多维数组转为一维数组的处理
	 */
    private function multiArr ($arr) {
        $return = array();
        if(is_array($arr)){
            $isMulti = true;
            foreach($arr as $k=>$v){
                if(!is_int($k)){
                    $isMulti = false;
                }
            }
            if(!$isMulti){
                $return[] = $arr;
            }else{
                $return = $arr;
            }             
        }else if(is_string($arr)){
            $return[] = $arr;
        }
        return $return;
    }
    
    /**
     * @author william-fam
     * @todo 公共方法
     */ 
    private function common ($paramter) {
		// var_dump($paramter);exit;
        // 对象转数组
        $this->_paramterArr = Common_Common::objectToArray($paramter);//对象转数组 
        $headRequest = $this->_paramterArr['HeaderRequest'];
        $this->_init($headRequest);
        //print_r($this->_paramterArr);
        //$this->_token = $this->_paramterArr['appToken'];
        //file_put_contents('error002.txt', '00000221'.$this->_token.var_export($this->_paramterArr,true));
        $this->_date = date('Y-m-d H:i:s');
        //file_put_contents('common.txt', '00000221'.$this->_token.var_export($this->_paramterArr,true));
        
        $this->authenticate();
        /* exit;
        file_put_contents('error003.txt', '0000020000555'.var_export($this->_paramterArr,true));return; */
    }
    
    /**
     * @author william-fan
     * @todo 查询某个出货单下面的所有订单
     */
    public function getOrderProductBySbCode($paramter) {
    	set_time_limit(300);
    	$this->common($paramter);
    	$result = array(
    			'ask' => '1',
    			'Data' => array(),
    			'error' => array()
    	);
    	if ($this->_error) {
    		$error = $result['Error'];
    		$error[] =   array('errorMessage'=>$this->_error);
    		$result['error'] = $error;
    		return $result;
    	}
    	$sbCode = $this->_paramterArr['sbCode'];
    	//$detailLevel = $this->_paramterArr['detailLevel'];
    	//error_reporting(E_ALL);
    	if (empty($sbCode)) {
    		$this->_error= '出货总单号不能为空';
    		$result['ask'] = '0';
    		//$result['message'] = $this->_error;
    		$error = $result['error'];
    		$error[] =   array('errorMessage'=>$this->_error);
    		$result['error'] = $error;
    		return $result;
    	}
    	$shipBatch = Service_ShipBatch::getByField($sbCode,'sb_code');
    	//echo "<pre>";

    	
    	if(!empty($shipBatch)){
    		if($shipBatch['sb_status']!=''){
    			//获取出货单下面的袋子
    			$orders = array();
    			$bagCondition = array(
    				'sb_code'=>$sbCode
    			);
    			$bags = Service_ShipBatchDetail::getByCondition($bagCondition);
    			$data = array();
    			if(!empty($bags)){
    				foreach($bags as $key=>$bag){
    					//获取袋子和订单的关联信息
    					$bagOrders=Service_OutboundBagDetail::getByCondition(array('ob_no'=>$bag['ob_no']));
    					if(!empty($bagOrders)){
    						foreach($bagOrders as $keyb=>$bagorder){
    							$order = Service_Orders::getByField($bagorder['order_code'],'order_code');
    							if(!empty($order)){
    								$orderInfos = Service_Orders::getOrderAllInfo($bagorder['order_code'], $order['customer_id']);

    								if(!empty($orderInfos)){
    									$shipOrder = Service_ShipOrder::getByField($orderInfos['order_code'],'order_code');
    									
    									$order_product = $orderInfos['order_product'];
    									$orderDetail = array();
    									if(!empty($order_product)){
    										foreach($order_product as $op=>$product){
    											$productInfo = Service_Product::getByField($product['product_id']);
    											$puName = "个";
    											$hsCode = $productInfo['hs_code'];
    											$puCode = $productInfo['pu_code'];
    											if($puCode){
    												$puInfo = Service_ProductUom::getByField($puCode,'pu_code');
    												if(!empty($puInfo)){
    													$puName = $puInfo['pu_name'];
    												}
    											}
    											$detail = array(
    												'skuNo'=>$productInfo['product_sku'],
    												'skuName'=>$productInfo['product_title_en'],	
    												'skuCnName'=>$productInfo['product_title'],
    												'puName'=>$puName,
    												'hsCode'=>$hsCode,		
    												'skuDeclaredValue'=>$product['op_declared_value'],	
    												'quantity'=>$product['op_quantity'],
    											);
    											$hemList = Service_HsElementMap::getByCondition(array('product_id'=>$product['product_id']), 'hem_detail');
    											$elements = array();
    											foreach($hemList as $hemRow) $elements[] = $hemRow['hem_detail'];
    											$detail['specification'] = implode('|',$elements);
    											$orderDetail[] = $detail;
    										}
    									}
    									
    									$customer = Service_Customer::getByField($order['customer_id']);
    									$changeOrder = '1';
    									if($orderInfos['order_mode_type']=='1'){
    										$changeOrder = $orderInfos['change_order'];
    									}else{
    										$changeOrder ='1'; //备货模式换单
    									}
    									
    									$orderInfo = array(
    										'referenceNo'=>$orderInfos['reference_no'],
    										'orderType'=>$orderInfos['order_mode_type'],
    										'changeOrder'=>$changeOrder,	
    										'smCode'=>$orderInfos['sm_code'],
    										'Tracking_no'=>$shipOrder['tracking_number'],
    										'provinceName'=>$orderInfos['oab_state'],
    										'consigneeCountry'=>$orderInfos['country_name'],	
    										'consigneeLastname'=>$orderInfos['oab_lastname'],
    										'consigneeFirstname'=>$orderInfos['oab_firstname'],
    										'consigneeCompany'=>$orderInfos['oab_company'],
    										'consigneePostcode'=>$orderInfos['oab_postcode'],
    										'consigneeAddress1'=>$orderInfos['oab_street_address1'],
    										'consigneeAddress2'=>$orderInfos['oab_street_address2'],
    										'consigneePhone'=>$orderInfos['oab_phone'],
    										'consigneeEmail'=>$orderInfos['oab_email'],
    										'grossWt'=>$orderInfos['grossWt'],
    										'currency'=>$orderInfos['currency_code'],
    										'charge'=>$orderInfos['charge'],
                                                                                'deliveryAddress'=>$orderInfos['delivery_address'],
    										'shippingPremiumFee'=>$orderInfos['shipping_fee_estimate'],	
    										'Trade_platform'=>$customer['trade_name'],
    										'addTime'=>$orderInfos['add_time'],	
    										'shipTime'=>$shipBatch['sb_ship_time'],
    										'signTime'=>'',
                                            'isFBA' => $orderInfos['is_fba'],
                                            'isFBATax' => $orderInfos['is_fba_tax'],
    										'orderDetail'=>$orderDetail,
    									);
    									$orderOptionTime = Service_OrderOperationTime::getByField($orderInfos['order_code'],'order_code');
    									if(!empty($orderOptionTime)){
    										$orderInfo['shipTime'] = $orderOptionTime['ship_time'];
    									}
    									$data [] = array('orderInfo'=>$orderInfo);	
    								}
    							}
    						}
    						
    					}
    					
    				}
    			}
    			
    			$result['Data'] = $data;
    			
    		}else{
    			$result['ask'] = '0';
    			$error = $result['error'];
    			$error[] =   array('errorMessage'=>'出货单状态不对');
    			$result['error'] = $error;
    			//$result['Error'] = 
    		}
    	}else{
    		$result['ask'] = '0';
    		$error = $result['Error'];
    		$error[] =   array('errorMessage'=>'出货单不存在');
    		$result['error'] = $error;
    	}
    	
    	return $result;

    	//$result['Data'] = $orderInfo;
    	//return $result;
    }
    
    /**
     * @author william-fan
     * @todo 查询某个订单的信息
     */
    public function getOrderByCode($paramter) {
    	$this->common($paramter);
    	$result = array(
    			'ask' => '1',
    			//'data' => array(),
    			'error' => array()
    	);
    	if ($this->_error) {
    		$result['message'] = $this->_error;
    		return $result;
    	}
        $filePath = APPLICATION_PATH.'/../data/log/'.'getOrderByCode.txt';
        if(!file_exists($filePath)){
            $fp= fopen($filePath,"w");
            fclose($fp);
        }
        file_put_contents($filePath,var_export($this->_paramterArr,true));
    
    	$ordersCode = $this->_paramterArr['orderCode'];
    	//$detailLevel = $this->_paramterArr['detailLevel'];
    	 
    	if (empty($ordersCode)) {
    		$this->_error= '订单号不能为空';
    		$result['ask'] = '0';
    		$result['error'] = array(
                'errorMessage'=>$this->_error
            );
    		return $result;
    	}
		$condition = array(
				'new_reference_no'=>$ordersCode,
				'customer_id'=>$this->_customer['customer_id']
		);
		$order = Service_Orders::getByCondition($condition,"*");
		if(!empty($order)){
			$ordersCode = $order[0]['order_code'];
		}
    	$order = Service_Orders::getOrderAllInfo($ordersCode, $this->_customer['customer_id']);
    	//echo "<pre>";
    	//print_r($order);
    	//exit;
    	if (empty($order)) {
    		$this->_error= '订单不存在 ' . $ordersCode;
    		$result['ask'] = '0';
    		$result['error'] = array(
                'errorMessage'=>$this->_error
            );
    		return $result;
    	}else{
    		$warehouseCode = '';
    		$warehouseInfo=Service_Warehouse::getByField($order['warehouse_id']);
    		if(!empty($warehouseInfo)){
    			$warehouseCode = $warehouseInfo['warehouse_code'];
    		}
    		$order['warehouse_code'] = $warehouseCode;
    	}
    	//print_r($order);
    	//         print_r($this->_customer);exit;
    	$orderProducts = $order['order_product'];
    	$orderDetail = array();
    	if($orderProducts){
    		foreach($orderProducts as $keyo=>$vallueo){
    			$orderDetail[] = array(
    				'productSku'=>$vallueo['product_sku'],
    				'opQuantity'=>$vallueo['op_quantity'],		
    			);
    		}
    	}
        $shipOrder = Service_ShipOrder::getByField($order['order_code'],"order_code","*");
    	$orderInfo = array(
    			'orderCode'=>$order['order_code'],
    			'orderType' => $order['order_mode_type'],
    			'warehouseCode' => $order['warehouse_code'],
                'tracking_number'=>isset($shipOrder['tracking_number'])?$shipOrder['tracking_number']:$order['ref_tracking_number'],
    			//'oabCountry' => $order['country_name'],
    			'smCode' => $order['sm_code'],
    			'orderStatus' => $order['order_status'],
    			'referenceNo' => $order['reference_no'],
    			'consigneeCountry'=>$order['country_name'],
    			'consigneeState'=> $order['oab_state'],
    			'consigneeCity'=> $order['oab_city'],
    			'consigneeName' => $order['oab_lastname'].$order['oab_firstname'],
    			'consigneeCompany' => $order['oab_company'],
    			'consigneePostcode' => $order['oab_postcode'],
    			'consigneeAddress1' => $order['oab_street_address1'],
    			'consigneeAddress2' => $order['oab_street_address2'],
    			'consigneePhone' => $order['oab_phone'],
    			'consigneeEmail' => $order['oab_email'],
    			'currency' => $order['currency_code'],
    			'transactionPrice' => $order['charge'],
                        'deliveryAddress'=>$order['delivery_address'],
                'isFBA' => $order['is_fba'],
            	'isFBATax' => $order['is_fba_tax'],
    			'Remark' => $order['remark'],
                        'isPod'=>$order['is_pod'],
                        'shipTime'=> $order['shipTime'],
                        'buyInsurance'=>$order['insurance'],
                        'insuranceCode'=>$order['insurance_code'],
                        'insuranceRate'=>$order['insurance_rate'],
    			'OrderDetail' => $orderDetail,
    	);
    	$result['data'] = $orderInfo;
    	return $result;
    }
    
    /**
     * @author william-fan
     * @todo 用于创建订单
     */
    public function createOrder($paramter){
    	$this->common($paramter);
    	$result = array(
    			'ask' => '0',
    			'message' => '',
    			'orderCode' => '',
    			'error' => array(),
    	);
    	if ($this->_error) {
    		$result['message'] = $this->_error;
    		return $result;
    	}
    	$orderInfo = $this->_paramterArr['orderInfo'];
        /*$filePath = APPLICATION_PATH.'/../data/log/'.'ServiceForOrder2.txt';
        if(!file_exists($filePath)){
            $fp= fopen($filePath,"w");
            fclose($fp);
        }
        file_put_contents($filePath,var_export($orderInfo,true));*/
    	
    	$paramOrder = $orderInfo; //订单原来传递的参数
    	$orderInfo = $this->transParam($orderInfo);

        $is_fba = isset($orderInfo['is_fba']) ? $orderInfo['is_fba'] : 0;
        $is_fba_tax = isset($orderInfo['is_fba_tax']) ? $orderInfo['is_fba_tax'] : 0;
        $is_pod = isset($orderInfo['is_pod']) ? $orderInfo['is_pod'] : 0;
    	//print_r($orderInfo);
    	$status = '1';
    	if(isset($orderInfo) && $orderInfo['orderStatus']){
    		$status = $orderInfo['orderStatus'];
    	}
    	//$status = $orderInfo['orderStatus'];
    	$orderInfo=Api_OrderCheck::TransformData($orderInfo, $this->_customer);
    	if($orderInfo['is_valid']=='0'){
    		$result['error'] = Common_TransError::Transerror($orderInfo['error']);
    		$result['message']='创建订单失败';
            $result['orderCode'] = isset($orderInfo['order_code'])?$orderInfo['order_code']:"";
    		return $result;
    	}
        if($is_fba !== ''){
          $orderInfo['is_fba'] = $is_fba;
        }
        if($is_fba_tax !== ''){
          $orderInfo['is_fba_tax'] = $is_fba_tax;
        }
        $orderInfo['order_status'] = $status;
    	$process = new Service_OrderProcess();
    	/* if($paramOrder['order_model']=='1'){
    		//集货模式的订单创建
    		$doresult = $process->createjhOrderTransaction($orderInfo);
    	}else{
    		//备货模式的订单创建
    		$doresult = $process->createOrderTransaction($orderInfo);
    	} */
    	
    	//echo "<pre>";
    	//print_r($orderInfo);
    	//exit;
        if($status=='4'&&$orderInfo['order_model']=="1"){
            $result['message'] = "集货订单只能到确认状态";
            return $result;
        }
        if($status=="2"||$status=="4"){
            $doresult = $process->createOrderToStatus24($orderInfo);
            /*if($doresult['ask']=='1'){
                $result['ask'] = '1';
                $result['message'] = $doresult['message'];
                $result['orderCode'] = $doresult['ordersCode'];
            }else{
                $result['message'] = $doresult['message'];
                $result['error'] = Common_TransError::Transerror($doresult['error']);
            }*/
        }else{
            $doresult = $process->createOrderTransaction($orderInfo);
        }
        if($doresult['ask']=='1'){
            $result['ask'] = '1';
            $result['message'] = $doresult['message'];
            $result['orderCode'] = $doresult['ordersCode'];
        }else{
            $result['message'] = $doresult['message'];
            $result['orderCode'] = isset($doresult['order_code'])?$doresult['order_code']:"";
            $result['error'] = Common_TransError::Transerror($doresult['error']);
        }
        $result['lessInvSku'] = isset($doresult['lessInvSku'])?$doresult['lessInvSku']:"";
    	/*if($doresult['ask']=='1'){
    		$result['ask'] = '1';
    		$result['message'] = $doresult['message'];
    		$result['orderCode'] = $doresult['ordersCode'];
    		//更新状态
    		if(!in_array($status, array(1,2,4))){//不再允许更新的状态之内
    			$result['ask'] = '1';
    			$result['message'] = $result['message'].';移动状态失败状态不允许';
    			$result['error'] = Common_TransError::Transerror(array('订单状态移动失败,状态不允许'));
    			return $result;
    		}else{//更新状态
    			if($status=='2'){
    				//确认确认
    				$moveresult=$process->confirm($result['orderCode'],$this->_customer['customer_id']);
    				if($moveresult['ask']==0){
    					$result['message'] = $result['message'].';移至确认失败';
    					$result['error'] = Common_TransError::Transerror($moveresult['error']);
    				}else{
    					$result['message'] = $result['message'].';移至确认成功';
    				}
    			}elseif($status=='4'){
    				//先确认订单 ，然后提交订单
    				$moveresult=$process->confirm($result['orderCode'],$this->_customer['customer_id']);
    				if($moveresult['ask']==0){
    					$result['message'] = $result['message'].';移至确认失败';
    					$error=Common_TransError::Transerror($moveresult['error']);
    					$error=array_merge($result['error'],$error);
    					$result['error'] = $error;
    				}else{
    					$result['message'] = $result['message'].';移至确认成功';
    					//确认成功 然后 提交订单
    					$moveresult=$process->submit($result['orderCode'],$this->_customer['customer_id']);
    					if($moveresult['ask']==0){
    						$result['message'] = $result['message'].';移至已提交失败';
    						$error=Common_TransError::Transerror($moveresult['error']);
    						$error=array_merge($result['error'],$error);
    						$result['error'] = $error;
    					}else{
    						//提交
    						$result['message'] = $result['message'].';移至已提交成功';
    					}
    				}
    			}else{
    				 
    			}
    		}
    	}else{
    		$result['message'] = $doresult['message'];
    		$result['error'] = Common_TransError::Transerror($doresult['error']);
    	}*/
    	//var_dump($result);
    	return $result;
    }
     /**
     * @author william-fan
     * @todo 更新单个订单
     */
    public function updateOrder($paramter){
    	$this->common($paramter);
    	$result = array(
            'ask' => '0',
            'message' => '',
            'orderCode' => '',
            'error' => array(),
        );
    	if ($this->_error) {
    		$result['message'] = $this->_error;
    		return $result;
    	}
    	$orderInfo = $this->_paramterArr['orderInfo'];
    	
    	$status = '1';
    	if(isset($orderInfo) && $orderInfo['orderStatus']){
    		$status = $orderInfo['orderStatus'];
    	}
    	
    	$orderInfo = $this->transParam($orderInfo); //转换成订单那块可以识别的键值
    	
    	/* echo "<pre>";
    	echo "转换成参数";
    	print_r($orderInfo); */

    	$ordersCode = $orderInfo['orderCode'];
    	$result['orderCode'] = $ordersCode;
    	if(empty($ordersCode)){
    		$this->_error = '订单号不能为空 ';
    		$result['message'] = $this->_error;
    		return $result;
    	}
    	$order = Service_Orders::getOrderAllInfo($ordersCode, $this->_customer['customer_id']);
    	
    	$orderInfo=$this->updateTransParam($orderInfo,$order);
    	
    	
    	
    	//echo "加入订单基本信息的参数";
    	//print_r($orderInfo);
    	
    	if(empty($order)){
    		$this->_error = '订单不存在 '.$ordersCode;
    		$result['message'] = $this->_error;
    		return $result;
    	}
        $is_fba = isset($orderInfo['is_fba']) ? $orderInfo['is_fba'] : '';
        $is_fba_tax = isset($orderInfo['is_fba_tax']) ? $orderInfo['is_fba_tax'] : '';

    	$orderInfo=Api_OrderCheck::TransformData($orderInfo, $this->_customer);

        if($orderInfo['is_valid']=='0'){
            $result['error'] = Common_TransError::Transerror($orderInfo['error']);
            $result['message']='更新订单失败';
            return $result;
        }

        if($is_fba !== ''){
          $orderInfo['is_fba'] = $is_fba;  
        }
        if($is_fba_tax !== ''){
          $orderInfo['is_fba_tax'] = $is_fba_tax;  
        }
    	$process = new Service_OrderProcess();
    	//备货模式订单更新
    	$doresult = $process->updateOrderTransaction($orderInfo, $ordersCode,$this->_customer['customer_id']);
    	
    	if($doresult['ask']=='1'){
    		$result['ask'] = '1';
    		$result['message'] = $doresult['message'];
    		$result['orderCode'] = $doresult['ordersCode'];
    		//更新状态
    		if(!in_array($status, array(1,2,4))){//不再允许更新的状态之内
    			$result['ask'] = '1';
    			$result['message'] = $result['message'].';移动状态失败状态不允许';
    			$result['error'] = Common_TransError::Transerror(array('订单状态移动失败,状态不允许'));
    			return $result;
    		}else{//更新状态
    			if($status=='2'){
    				//确认确认
    				$moveresult=$process->confirm($result['orderCode'],$this->_customer['customer_id']);
    				if($moveresult['result']==0){
    					$result['message'] = $result['message'].';移至确认失败';
    					$result['error'] = Common_TransError::Transerror($moveresult['error']);
    				}else{
    					$result['message'] = $result['message'].';移至确认成功';
    				}
    			}elseif($status=='4'){
    				//先确认订单 ，然后提交订单
    				$moveresult=$process->confirm($result['orderCode'],$this->_customer['customer_id']);
    				/* var_dump($moveresult);
    				var_dump($moveresult['result']==0); */
    				if($moveresult['result']==0){
    					$result['message'] = $result['message'].';移至确认失败';
    					$error=Common_TransError::Transerror($moveresult['error']);
    					$error=array_merge($result['error'],$error);
    					$result['error'] = $error;
    				}else{
    					$result['message'] = $result['message'].';移至确认成功';
    					//备货订单可以提交 集货订单不能提交
    					
    					//确认成功 然后 提交订单
    					$moveresult=$process->submit($result['orderCode'],$this->_customer['customer_id']);
    					if($moveresult['result']==0){
    						$result['message'] = $result['message'].';移至已提交失败';
    						$error=Common_TransError::Transerror($moveresult['error']);
    						$error=array_merge($result['error'],$error);
    						$result['error'] = $error;
    					}else{
    						//提交
    						$result['message'] = $result['message'].';移至已提交成功';
    					}
    				}
    			}else{
    					
    			}
    		}
    	}else{
    		$result['message'] = $doresult['message'];
    		$result['error'] = Common_TransError::Transerror($doresult['error']);
    	}
    	
    	//$result['message'] = $doresult['message'];
    	//$result['error']=Common_TransError::Transerror($doresult['error']);
    	
    	
    	//print_r($orderInfo);
    	//exit;
    	print_r($result);
    	
    	return $result;
    }
    /**
     * @author william-fan
     * @todo 更新订单状态
     */
 	public function updateOrderStatus($paramter) {

        $this->common($paramter);
        $result = array(
                'ask' => '0',
                'message' => '更新订单状态失败',
                'error' => array(),
        );

        if ($this->_error) {
            $result['message'] = $this->_error;
            return $result;
        }
        
        $ordersCode = $this->_paramterArr['orderCode'];
        //$result['orderCode'] = $ordersCode;

        if (empty($ordersCode)) {
            $this->_error = '订单号不能为空';
            $result['message'] = $this->_error;
            return $result;
        }
        $order = Service_Orders::getByField($ordersCode, 'order_code');
        if (empty($order)) {
            $this->_error = '订单不存在-->' . $ordersCode;
            $result['message'] = $this->_error;
            return $result;
        }
        //$process = new Api_ServiceForOrder();
        
        $status = $this->_paramterArr['orderStatus'];

        $doresult = $this->updateOrderStatusProcess($status, $order);
        //var_dump($doresult);
        if($doresult['ask']=='1'){
            $result['ask'] = "1";
        	$result['message'] = $doresult['message'];
        }else{
        	$result['message'] = $doresult['message'];
        	$result['error'] = Common_TransError::Transerror($doresult['error']);
        }
        return $result;
    }
    /**
     * @author william-fan
     * @todo 用于批量订单状态更新处理
     */
    private function updateOrderStatusProcess($status,$orderInfo){
    	$result = array(
                'ask' => '0',
                'message' => '',
                'error' => array(),
        );
    	$process = new Service_OrderProcess();
    	switch($status){
    		case "0":
    			$result=$process->deleteTranslate($orderInfo['order_code'],$this->_customer['customer_id']);
    			break;
    		case "1":
    			if($orderInfo['order_status']!='2'&&$orderInfo['order_status']!='3'&&$orderInfo['order_status']!="0"){
    				$result['message'] = '订单状态不允许直接移到草稿状态';
    			}elseif($orderInfo['order_status']=='3'){
                    $result = Service_OrderProcess::draftFromAbnormal($orderInfo['order_code'],$orderInfo['customer_id']);
                }elseif($orderInfo['order_status']=='0'){
                    $result = Service_OrderProcess::recoveryTranslate($orderInfo['order_code'],$orderInfo['customer_id']);
                }else{
    				$result=$process->draftTranslate($orderInfo['order_code'],$this->_customer['customer_id']);
    			}
    			break;
    		case "2":
    			var_dump($orderInfo['order_status']);
    			if($orderInfo['order_status']=='1'){
    				$result=$process->confirm($orderInfo['order_code'],$this->_customer['customer_id']);
    			}elseif($orderInfo['order_status']=='3'){
                    $result = $process->confirm($orderInfo['order_code'],$this->_customer['customer_id']);
                }else{
    				$result['message'] = '订单状态不允许到已确认';
    			}
    			break;
    		case "4":
    			if($orderInfo['order_status']=='2'){
    				$result=$process->submit($orderInfo['order_code'],$this->_customer['customer_id']);
    			}else{
    				$result['message'] = '订单状态不允许到已确认';
    			}
    			break;
    		default:
    			$result['message'] = '状态错误';
    			break;				
    	}
    	$result['error'] = Common_TransError::Transerror($result['error']);
    	return $result;
    }
    /**
     * @author william-fan
     * @todo 转换参数到程序识别
     */
    private function transParam($orderInfo){
    	$transOrder = array();
    	 
    	if(isset($orderInfo['orderMode'])){
    		$transOrder['order_model'] = $orderInfo['orderMode']; //备货模式订单
    	}
    	if(isset($orderInfo['orderCode'])){
    		$transOrder['orderCode'] = $orderInfo['orderCode'];
    	}
    	if(isset($orderInfo['warehouseCode'])){
    		$transOrder['warehouse_code'] = $orderInfo['warehouseCode'];
    	}
    	
    	if(isset($orderInfo['oabState'])){
    		$transOrder['oab_state'] = $orderInfo['oabState'];
    	}
    	if(isset($orderInfo['oabCity'])){
    		$transOrder['oab_city'] = $orderInfo['oabCity'];
    	}
    	if(isset($orderInfo['oabCountry'])){
    		$transOrder['oab_country_name'] = $orderInfo['oabCountry'];
    	}
    	if(isset($orderInfo['smCode'])){
    		$transOrder['sm_code'] = $orderInfo['smCode'];
    	}
    	if(isset($orderInfo['referenceNo'])){
    		$transOrder['reference_no'] = $orderInfo['referenceNo'];
    	}
    	/* if(isset($orderInfo['oabLastname'])){
    		$transOrder['oab_lastname'] = $orderInfo['oabLastname'];
    	} */
    	if(isset($orderInfo['oabName'])){
    		$transOrder['oab_firstname'] = $orderInfo['oabName'];
    	}
    	if(isset($orderInfo['oabCompany'])){
    		$transOrder['oab_company'] = $orderInfo['oabCompany'];
    	}
    	if(isset($orderInfo['oabPostcode'])){
    		$transOrder['oab_postcode'] = $orderInfo['oabPostcode'];
    	}
    	if(isset($orderInfo['oabStreetAddress1'])){
    		$transOrder['oab_street_address1'] = $orderInfo['oabStreetAddress1'];
    	}
    	if(isset($orderInfo['oabStreetAddress2'])){
    		$transOrder['oab_street_address2'] = $orderInfo['oabStreetAddress2'];
    	}
    	if(isset($orderInfo['oabPhone'])){
    		$transOrder['oab_phone'] = $orderInfo['oabPhone'];
    	}
    	if(isset($orderInfo['oabEmail'])){
    		$transOrder['oab_email'] = $orderInfo['oabEmail'];
    	}
    	if(isset($orderInfo['transactionPrice'])){
    		$transOrder['charge'] = $orderInfo['transactionPrice'];
    	}
    	if(isset($orderInfo['currency'])){
    		$transOrder['currency'] = $orderInfo['currency'];
    	}

    	if(isset($orderInfo['orderMode'])){
    		$transOrder['order_mode_type'] = $orderInfo['orderMode'];
    	}
    	
    	if(isset($orderInfo['trackingNumber'])){
    		$transOrder['ref_tracking_number'] = $orderInfo['trackingNumber'];
    	}
    	
        $transOrder['change_order'] = '1';
    	if(isset($orderInfo['channel'])){
    		$channel = (string)$orderInfo['channel'];
    		if($channel=='0'){
    			$transOrder['change_order'] = '1';
    		}elseif($channel=='1'){
    			$transOrder['change_order'] = '0';
    		}
    	}
    	
        if(isset($orderInfo['deliveryAddress'])){
            $transOrder['delivery_address'] = $orderInfo['deliveryAddress'];
        }
        if (isset($orderInfo['isFBA'])) {
            $transOrder['is_fba'] = $orderInfo['isFBA'];
        }
        if (isset($orderInfo['isFBATax'])) {
            $transOrder['is_fba_tax'] = $orderInfo['isFBATax'];
        }
    	if(isset($orderInfo['remark'])){
    		$transOrder['remark'] = $orderInfo['remark'];
    	}
    	if(isset($orderInfo['orderStatus'])){
    		$transOrder['orderStatus'] = $orderInfo['orderStatus'];
    	}
        if(isset($orderInfo['buyInsurance'])){
            $transOrder['insurance'] = $orderInfo['buyInsurance'];
        }
        if(isset($orderInfo['insuranceRate'])){
            $transOrder['insurance_rate'] = $orderInfo['insuranceRate'];
        }
        if(isset($orderInfo['insuranceName'])){
            $transOrder['insurance_name'] = $orderInfo['insuranceName'];
        }
        if(isset($orderInfo['isPod'])){
    		$transOrder['is_pod'] = $orderInfo['isPod'];
    	}
    	if(isset($orderInfo['orderProduct'])){
    		$prodetail = array();
    		$pradetail=$orderInfo['orderProduct'];
    		if(!empty($pradetail) && is_array($pradetail['0'])){
    			
    		}else{
    			$pradetail = array($pradetail);
    		}
    		foreach($pradetail as $key=>$value){
				$product = Service_Product::getByCondition(array('product_sku'=>$value['productSku'],'customer_code'=>$this->_customerCode),"*");
				if(isset($value['productTitleEn'])&&$value['productTitleEn']!=""){
					$productTitleEn = $value['productTitleEn'];
				}else{
					$productTitleEn = $product[0]['product_title_en'];
				}
    			$prodetail[$key] = array(
    					'product_sku'=>$value['productSku'],
                        'product_title_en'=>$productTitleEn,
    					'declare_price'=>$value['declaredValue'],
    					'op_quantity'=>$value['opQuantity'],
                        'op_declared_value'=>$value['purposeDeclaredValue'],
                        'ebay_item_id'=>$value['ebayItemId'],
                        'ebay_transaction_id'=>$value['ebayTransactionId'],
                        'ebay_buyer_id'=>$value['ebayBuyerId'],
    			);
    		}
    		$transOrder['productDeatil'] = $prodetail;
    	}
		if(isset($orderInfo['shippingInfo'])){
			$transOrder['shippingInfo'] = $orderInfo['shippingInfo'];
		}
		if(isset($orderInfo['dispatchNotice'])){
		    $transOrder['dispatchNotice'] = $orderInfo['dispatchNotice'];
		}
		if(isset($orderInfo['guarantee'])){
		    $transOrder['guarantee'] = $orderInfo['guarantee'];
		}
    	return $transOrder;
    }
    
    /**
     * @author william-fan
     * @todo 用于修改订单信息
     * $orderRow 更改的订单
     * $orderInfo 订单信息
     */
    private function updateTransParam($orderRow,$orderInfo){
    	$updateRow = array();
    	
    	$warehouseId = $orderInfo['warehouse_id'];
    	
    	$changeOrder = isset($orderRow['change_order'])&&$orderRow['change_order']!==''?$orderRow['change_order']:$orderInfo['change_order'];
    	$trackingNumber = isset($orderRow['ref_tracking_number'])&&$orderRow['ref_tracking_number']!==''?$orderRow['ref_tracking_number']:$orderInfo['ref_tracking_number'];
    	$orderType = isset($orderRow['order_type'])&&$orderRow['order_type']!==''?$orderRow['ref_tracking_number']:$orderInfo['order_type'];
    	$oabCountry = isset($orderRow['oab_country_name'])&&$orderRow['oab_country_name']!==''?$orderRow['oab_country_name']:$orderInfo['country_name'];
    	$smCode	= isset($orderRow['sm_code'])&&$orderRow['sm_code']!==''?$orderRow['sm_code']:$orderInfo['sm_code'];
		$referenceNo = isset($orderRow['reference_no'])&&$orderRow['reference_no']!==''?$orderRow['reference_no']:$orderInfo['reference_no'];
		$oabLastname = isset($orderRow['oab_lastname'])&&$orderRow['oab_lastname']!==''?$orderRow['oab_lastname']:$orderInfo['oab_lastname'];
		$oabFirstname = isset($orderRow['oab_firstname'])&&$orderRow['oab_firstname']!==''?$orderRow['oab_firstname']:$orderInfo['oab_firstname'];
    	$oabCompany = isset($orderRow['oab_company'])&&$orderRow['oab_company']!==''?$orderRow['oab_company']:$orderInfo['oab_company'];
    	$oabState = isset($orderRow['oab_state'])&&$orderRow['oab_state']!==''?$orderRow['oab_state']:$orderInfo['oab_state'];
    	$oabCity = isset($orderRow['oab_city'])&&$orderRow['oab_city']!==''?$orderRow['oab_city']:$orderInfo['oab_city'];
    	$oabPostcode = isset($orderRow['oab_postcode'])&&$orderRow['oab_postcode']!==''?$orderRow['oab_postcode']:$orderInfo['oab_postcode'];
    	$oabStreetAddress1 = isset($orderRow['oab_street_address1'])&&$orderRow['oab_street_address1']!==''?$orderRow['oab_street_address1']:$orderInfo['oab_street_address1'];
    	$oabStreetAddress2 = isset($orderRow['oab_street_address2'])&&$orderRow['oab_street_address2']!==''?$orderRow['oab_street_address2']:$orderInfo['oab_street_address2'];
    	$oabPhone = isset($orderRow['oab_phone'])&&$orderRow['oab_phone']!==''?$orderRow['oab_phone']:$orderInfo['oab_phone'];
    	$oabEmail = isset($orderRow['oab_email'])&&$orderRow['oab_email']!==''?$orderRow['oab_email']:$orderInfo['oab_email'];
    	$currency = isset($orderRow['currency'])&&$orderRow['currency']!==''?$orderRow['currency']:$orderInfo['currency_code'];
    	$charge = isset($orderRow['charge'])&&$orderRow['charge']!==''?$orderRow['charge']:$orderInfo['charge'];
        $deliveryAddress = isset($orderRow['delivery_address'])&&$orderRow['delivery_address']!==''?$orderRow['delivery_address']:$orderInfo['delivery_address'];
        $remark = isset($orderRow['remark'])&&$orderRow['remark']!==''?$orderRow['remark']:$orderInfo['remark'];
        $is_fba = isset($orderRow['is_fba']) && $orderRow['is_fba'] !== '' ? $orderRow['is_fba'] : $orderInfo['is_fba'];
        $is_fba_tax = isset($orderRow['is_fba_tax']) && $orderRow['is_fba_tax'] !== '' ? $orderRow['is_fba_tax'] : $orderInfo['is_fba_tax'];
        $buyInsurance = isset($orderRow['insurance']) && $orderRow['insurance'] !== '' ? $orderRow['insurance'] : $orderInfo['insurance'] ;
        $insuranceRate = isset($orderRow['insurance_rate']) && $orderRow['insurance_rate'] !== '' ? $orderRow['insurance_rate'] : $orderInfo['insurance_rate'] ;
        $insuranceName = isset($orderRow['insurance_name']) && $orderRow['insurance_name'] !== '' ? $orderRow['insurance_name'] : $orderInfo['insurance_name'] ;
    	$is_pod = isset($orderRow['is_pod']) && $orderRow['is_pod'] !== '' ? $orderRow['is_pod'] : $orderInfo['is_pod'];
    	$productDetail = isset($orderRow['productDeatil'])&&$orderRow['productDeatil']!==''?$orderRow['productDeatil']:$orderInfo['order_product'];
    	
    	/* var_dump($orderRow);
    	var_dump($orderRow['change_order']!=''); */
		
		//print_r($orderInfo);
		
    	$updateRow['warehouse_id'] = $warehouseId;
 
    	if(isset($orderRow['warehouse_code']) && $orderRow['warehouse_code']!==''){
    		$updateRow['warehouse_code'] = $orderRow['warehouse_code'];
    	}else{
    		$warehouse = Service_Warehouse::getByField($warehouseId);
    		$updateRow['warehouse_code'] = $warehouse['warehouse_code'];
    	}
    	if(isset($orderRow['oab_country_name']) && $orderRow['oab_country_name']!==''){
    		$updateRow['oab_country_name'] = $orderRow['oab_country_name'];
    	}else{
    		$country = Service_Country::getByField($oabCountry,'country_name');
    		$updateRow['oab_country_name'] = $country['country_name'];
    	}
    	
    	$updateRow['change_order'] = $changeOrder;
    	$updateRow['order_type'] = $orderType;
    	
    	$updateRow['sm_code'] = $smCode;
    	$updateRow['reference_no'] = $referenceNo;
    	$updateRow['oab_lastname'] = $oabLastname;
    	$updateRow['oab_firstname'] = $oabFirstname;
    	$updateRow['oab_company'] = $oabCompany;
    	$updateRow['oab_state'] = $oabState;
    	$updateRow['oab_city'] = $oabCity;
    	$updateRow['oab_postcode'] = $oabPostcode;
    	$updateRow['oab_street_address1'] = $oabStreetAddress1;
    	$updateRow['oab_street_address2'] = $oabStreetAddress2;
    	$updateRow['oab_phone'] = $oabPhone;
    	$updateRow['oab_email'] = $oabEmail;
    	$updateRow['currency'] = $currency;
    	$updateRow['charge'] = $charge;
        $updateRow['delivery_address'] = $deliveryAddress;
    	$updateRow['remark'] = $remark;
        $updateRow['insurance'] = $buyInsurance;
        $updateRow['insurance_rate'] = $insuranceRate;
        $updateRow['insurance_name'] = $insuranceName;
        $updateRow['is_pod']=$is_pod;

    	if(isset($orderRow['productDeatil'])){
    		//客户传过来了产品
    		$cdProductDetail = $orderRow['productDeatil']; //客户传过来的产品详情
    		$updateRow['productDeatil'] = $cdProductDetail;
    	}else{
    		$detailAll = array();
    		foreach($productDetail as $key=>$product){
    			$detail = array(
    				'productSku'=>$product['product_sku'],
    				//''	
    				'opQuantity'=>$product['op_quantity']	
    			);
    			$detailAll[] = $detail;
    		}
    		$updateRow['productDeatil'] = $detailAll;
    	}
    	
    	return $updateRow;
    }

    public function getOrderTrackingByCode($paramter){
        $this->common($paramter);
        $result = array(
            'ask' => '0',
            'message' => '',
            'trackingData' => array(),
        );
        if ($this->_error) {
            $result['message'] = $this->_error;
            return $result;
        }
        $ordersCode = $this->_paramterArr['orderCode'];
        if (empty($ordersCode)) {
            $this->_error = '订单号不能为空';
            $result['message'] = $this->_error;
            return $result;
        }
        $orderRow = Service_Orders::getByField($ordersCode,"order_code","*");
        if(empty($orderRow)){
            $orders = Service_Orders::getByCondition(array('except_order_status_delete'=>1,'reference_no'=>$ordersCode),"*");
            if(empty($orders)){
                $this->_error = '订单号不存在';
                $result['message'] = $this->_error;
                return $result;
            }
            $orderRow = $orders[0];
        }
        if($orderRow['customer_code']!=$this->_customerCode){
            $this->_error = '订单号不匹配';
            $result['message'] = $this->_error;
            return $result;
        }
        $shipOrder = Service_ShipOrder::getByField($orderRow['order_code'],"order_code","*");
        if(empty($shipOrder)){
            $this->_error = '订单未出货';
            $result['message'] = $this->_error;
            return $result;
        }
        $trackingData = array(
            'tracking_number'=>$shipOrder['tracking_number'],
            'so_weight'=>$shipOrder['so_weight'],
            'so_declared_value'=>$shipOrder['so_declared_value'],
        );
        $orderAddress = Service_OrderAddressBook::getByField($orderRow['order_code'],"order_code","*");
        $country = Service_Country::getByField($orderAddress['oab_country_id'],"country_id","*");
        $trackingData['country_code'] = $country['country_code'];
        $orderProduct = Service_OrderProduct::getByCondition(array('order_code'=>$orderRow['order_code']),"*");
        $productDetail = array();
        foreach($orderProduct as $key=>$value){
            $v = array();
            $p = Service_Product::getByField($value['product_id'],"product_id","*");
            $v['product_sku'] = $p['product_sku'];
            $v['op_quantity'] = $value['op_quantity'];
            $productDetail[] = $v;
        }
        $trackingInfo = Service_ShipOrderTracking::getByCondition(array('order_code'=>$orderRow['order_code']),'*');
        $trackingData['trackingInfo'] = $trackingInfo;
        $trackingData['pdouctDetail'] = $productDetail;
        $result['trackingData'] = $trackingData;
        $result['ask'] = 1;
        return $result;
    }

    public function intercept($paramter){
        $this->common($paramter);
        /*$result = array(
            'ask' => '0',
            'message' => '',
        );*/
        $ordersCode = $this->_paramterArr['orderCode'];
        $intercept_reason = $this->_paramterArr['intercept_reason'];
        $orderRow = Service_Orders::getByField($ordersCode,'order_code',"*");
        $data = array(
            'order_code'=>$ordersCode,
            'intercept_reason'=>$intercept_reason,
        );
        $result = Service_OrderProcess::interceptTranslate($data,$orderRow['customer_id']);
        return $result;
    }

    public function getOrderException($paramter){
        $this->common($paramter);
        $result = array(
            'ask' => '0',
            'message' => '',
            //'trackingData' => array(),
        );
        $ordersCode = $this->_paramterArr['orderCode'];
        if (empty($ordersCode)) {
            $this->_error = '订单号不能为空';
            $result['message'] = $this->_error;
            return $result;
        }
        $orderRow = Service_Orders::getByField($ordersCode,"order_code","*");
        if(empty($orderRow)){
            $this->_error = '订单号不存在';
            $result['message'] = $this->_error;
            return $result;
        }
        $exception = Service_Exception::getByCondition(array('e_refer_no'=>$ordersCode),"*");
        if(empty($exception)){
            $result['message'] = "订单无异常";
        }else{
            $orderStaus = Service_OrderProcess::getJHStatusText2($orderRow['order_status']);
            foreach($exception as $key=>$value){
                $exception[$key]['order_code'] = $ordersCode;
                $exception[$key]['order_status'] = $orderStaus;
                if($value['et_code']=="orderSubmit"&&$orderRow['order_status']>3){
                    $exception[$key]['e_status'] = "已处理";
                }elseif($value['et_code']=="orderConfirm"&&$orderRow['order_status']>2){
                    $exception[$key]['e_status'] = "已处理";
                }else{
                    $exception[$key]['e_status'] = "待处理";
                }
            }
            $result['ask'] = "1";
            $result['exceptionData'] = $exception;
        }
        return $result;
    }

    public function deleteByOrderCode($paramter){
        $this->common($paramter);
        $result = array(
            'ask' => '1',
            'message' => "",
            'error' => array()
        );
        if ($this->_error) {
            $result['ask'] = "0";
            $result['message'] = $this->_error;
            return $result;
        }
        $ordersCode = $this->_paramterArr['orderCode'];

        if (empty($ordersCode)) {
            $this->_error= '订单号不能为空';
            $result['ask'] = '0';
            $result['message'] = $this->_error;
            return $result;
        }
        $result = Service_OrderProcess::deleteTranslate($ordersCode,$this->_customer['customer_id']);
        if($result['ask']=='1'){
            $result['message'] =  '订单号'."[{$ordersCode}]删除成功.";
        }else{
            $result['message'] =  '订单号'."[{$ordersCode}]删除失败.";
        }
        return $result;
    }
    
}