<?php
/**
 * Created by JetBrains PhpStorm.
 * User: user
 * Date: 15-5-5
 * Time: 下午3:51
 * To change this template use File | Settings | File Templates.
 */
class Api_ServiceForDistribuction
{
    protected $_customerId = null;

    protected $_customer = null;

    protected $_token = null;

    protected $_key = null;

    protected $_auth = false;

    protected $_error = null;

    protected $_date = null;

    protected $_paramterArr = array();//将传递过来的对象转为数组存储

    public static $upperToUnderline = array(
        'ASNCode'=>'ASNCode',
        'receivingId'=>'receiving_id',
        'receivingCode'=>'receiving_code',
        'refCode'=>'ref_code',
        'isDelivery'=>'is_delivery',
        'referenceNo'=>'reference_no',
        'warehouseCode'=>'warehouse_code',
        'supplierId'=>'supplier_id',
        'receivingUpdateUser'=>'receiving_update_user',
        'receivingAddUser'=>'receiving_add_user',
        'customerId'=>'customer_id',
        'customerCode'=>'customer_code',
        'receivingType'=>'receiving_type',
        'receivingStatus'=>'receiving_status',
        'contacter'=>'contacter',
        'contactPhone'=>'contact_phone',
        'receivingDescription'=>'receiving_description',
        'receivingAddtime'=>'receiving_add_time',
        'receivingUpdatetime'=>'receiving_update_time',
        'refercenceFormId'=>'refercence_form_id',
        'iePort'=>'ie_port',
        'formType'=>'form_type',
        'trafName'=>'traf_name',
        'wrapType'=>'wrap_type',
        'packNo'=>'pack_no',
        'trafMode'=>'traf_mode',
        'tradeMode'=>'trade_mode',
        'transMode'=>'trans_mode',
        'contaId'=>'conta_id',
        'contaModel'=>'conta_model',
        'contaWt'=>'conta_wt',
        'haveconta'=>'haveconta',
        'edaDate'=>'eda_date',
        'expectedDate'=>'expected_date',
        'receiveMode'=>'receive_model_type',
        'roughWeight'=>'roughweight',
        'netWeight'=>'netweight',
    );

    public static  $underlineToUpper = array(
        'ASNCode'=>'ASNCode',
        'receiving_id'=>'receivingId',
        'receiving_code'=>'receivingCode',
        'reference_no'=>'referenceNo',
        'is_delivery'=>'isDelivery',
        'ref_code'=>'refCode',
        'warehouse_code'=>'warehouseCode',
        'supplier_id'=>'supplierId',
        'receiving_update_user'=>'receivingUpdateUser',
        'receiving_add_user'=>'receivingAddUser',
        'customer_id'=>'customerId',
        'customer_code'=>'customerCode',
        'receiving_type'=>'receivingType',
        'receiving_status'=>'receivingStatus',
        'contacter'=>'contacter',
        'contact_phone'=>'contactPhone',
        'receiving_description'=>'receivingDescription',
        'receiving_add_time'=>'receivingAddtime',
        'receiving_update_time'=>'receivingUpdatetime',
        'refercence_form_id'=>'refercenceFormId',
        'ie_port'=>'iePort',
        'form_type'=>'formType',
        'traf_name'=>'trafName',
        'wrap_type'=>'wrapType',
        'pack_no'=>'packNo',
        'traf_mode'=>'trafMode',
        'trade_mode'=>'tradeMode',
        'trans_mode'=>'transMode',
        'conta_id'=>'contaId',
        'conta_model'=>'contaModel',
        'conta_wt'=>'contaWt',
        'haveconta'=>'haveconta',
        'eda_date'=>'edaDate',
        'expected_date'=>'expectedDate',
        'receive_model_type'=>'receiveMode',
        'roughweight'=>'roughWeight',
        'netweight'=>'netWeight',
    );

    private function _init ($headerRequest) {
        $this->_customerId = (string) $headerRequest['customerCode'];
    }
    /**
     * @author william-fan
     * @todo Authenticate
     */
    private function authenticate(){
        $customer = Service_Customer::getByField($this->_customerId, 'customer_code');
        if (!$customer) {
            $this->_error = 'Not exist customerCode:' . $this->_customerId . '.';
            return false;
        }
        $this->_customer = $customer;
        return false;
    }

    /**
     * @author william-fam
     * @todo 公共方法
     */
    private function common ($paramter) {
        /*$filePath = APPLICATION_PATH.'/../data/log/'.'ServiceForOrder2.txt';
        $fp= fopen($filePath,"a");
        fputs($fp,var_export($paramter,true)."\n");
        fclose($fp);*/

        // var_dump($paramter);exit;
        // 对象转数组
        $this->_paramterArr = Common_Common::objectToArray($paramter);//对象转数组

        $this->_init($this->_paramterArr);

        $this->_date = date('Y-m-d H:i:s');

        $this->authenticate();
    }

    /**
     * @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;

        //$filePath = APPLICATION_PATH.'/../data/log/'.'orderLogSoap.txt';
        //$fp= fopen($filePath,"a");


        $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;
        $status = '1';
        if(isset($orderInfo) && $orderInfo['orderStatus']){
            $status = $orderInfo['orderStatus'];
        }

        $orderInfo=Api_OrderCheck::TransformData($orderInfo, $this->_customer);
        if($orderInfo['is_valid']=='0'){
            $result['error'] = $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();
        $orderInfo['platform'] = 1;
        if($orderInfo['customer_code']=="E0447"||$orderInfo['customer_code']=='E0259'){
            $orderInfo['trade_mode'] = "9610";
        }else{
            $orderInfo['trade_mode'] = "0110";
        }
        //file_put_contents($filePath,var_export($orderInfo,true));
        //fclose($fp);
        $doresult = $process->createOrderTransaction($orderInfo);
        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'] = '订单状态移动失败,状态不允许';
                return $result;
            }else{//更新状态
                if($status=='2'){
                    //确认确认
                    $moveresult=$process->confirm($result['orderCode'],$this->_customer['customer_id']);
                    if($moveresult['ask']==0){
                        $result['ask'] = '0';
                        $result['message'] = $result['message'].';移至确认失败';
                        $result['error'] = $moveresult['error'];
                    }else{
                        $result['message'] = $result['message'].';移至确认成功';
                    }
                }elseif($status=='4'){
                    //先确认订单 ，然后提交订单
                    $moveresult=$process->confirm($result['orderCode'],$this->_customer['customer_id']);
                    if($orderInfo['order_mode_type']=="1"){
                        if($moveresult['ask']==0){
                            $result['ask'] = '0';
                            $result['message'] = $result['message'].';移至确认失败';
                            $error=$moveresult['error'];
                            $error=array_merge($result['error'],$error);
                            $result['error'] = $error;
                        }else{
                            $result['message'] = '订单已提交至确认状态';
                        }
                    }else{
                        if($moveresult['ask']==0){
                            $result['ask'] = '0';
                            $result['message'] = $result['message'].';移至确认失败';
                            $error=$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['ask'] = '0';
                                $result['message'] = $result['message'].';移至已提交失败';
                                $error=$moveresult['error'];
                                $error=array_merge($result['error'],$error);
                                $result['error'] = $error;
                            }else{
                                //提交
                                $result['message'] = $result['message'].';移至已提交成功';
                            }
                        }
                    }

                }
            }
        }else{
            $result['message'] = $doresult['message'];
            $result['error'] = $doresult['error'];
        }
        //var_dump($result);
        return $result;
    }

    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;

        $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;
        }

        $orderInfo=Api_OrderCheck::TransformData($orderInfo, $this->_customer);

        $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']);
        }


        return $result;

    }

    /**
     * @author william-fan
     * @todo 转换参数到程序识别
     */
    private function transParam($orderInfo){
        $transOrder = array();

        if(isset($orderInfo['customerCode'])){
            $transOrder['customer_code'] = $orderInfo['customerCode'];
        }
        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'];
        }
        if(isset($orderInfo['orderType'])){
            $transOrder['order_type'] = $orderInfo['orderType'];
        }

        $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['isPod'])) {
            $transOrder['is_pod'] = $orderInfo['isPod'];
        }

        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['dispatchNotice'])){
            $transOrder['dispatchNotice'] = $orderInfo['dispatchNotice'];
        }
        if(isset($orderInfo['guarantee'])){
            $transOrder['guarantee'] = $orderInfo['guarantee'];
        }
        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){
                $prodetail[$key] = array(
                    'product_sku'=>$value['productSku'],
                    'product_title_en'=>$value['productTitleEn'],
                    'declare_price'=>$value['declaredValue'],
                    'op_quantity'=>$value['opQuantity'],
                    'op_declared_value'=>$value['purposeDeclaredValue'],
                    'piecesDetail'=>$value['piecesDetail']
                );
            }
            $transOrder['productDeatil'] = $prodetail;
        }
        if(isset($orderInfo['piecesDetail'])){
            $piecesDetail = array();
            $piecesDetail = $orderInfo['piecesDetail'];
            if(!empty($pradetail) && !is_array($piecesDetail['0'])){
                $piecesDetail = array($piecesDetail);
            }
            $transOrder['piecesDetail'] = $piecesDetail;
        }
        if(isset($orderInfo['shippingInfo'])){
            $transOrder['shippingInfo'] = $orderInfo['shippingInfo'];
        }
        return $transOrder;
    }

    public function createAsn($paramter){
        $this->common($paramter);
        $result = array(
            'ask' => 'Error',
            'message' => '',
            'ASNCode' => '',
            'error'=>'',
        );


        $headerRequest = $this->_paramterArr ;
        /*$filePath = APPLICATION_PATH.'/../data/log/'.'DebugLog.txt';
        if(!file_exists($filePath)){
            $fp= fopen($filePath,"w");
            fclose($fp);
        }
        file_put_contents($filePath,var_export($this->_paramterArr,true));*/
        $customerCode = $headerRequest['customerCode'];
        $customerRow = Service_Customer::getByField($customerCode,'customer_code',"*");

        $asnInfo = $this->_paramterArr;
        $asnData = array();
        $relateArr = self::$upperToUnderline;
        foreach($asnInfo as $k=>$v){
            if($k!="ASNItems"){
                $asnData[$relateArr[$k]] = $v;
            }
        }
        $warehouseRow = Service_Warehouse::getByField($asnData['warehouse_code'],"warehouse_code","*");
        $asnData['warehouseId'] = $warehouseRow['warehouse_id'];
        $asnInfo['warehouseId'] = $warehouseRow['warehouse_id'];
        $asnData['from_system'] = "1";

        if($asnData['receive_model_type']=="1"){
            $errorMsg = "";
            $orderCodeArr = array();
            if(is_array($asnInfo['ASNItems']['OrderInfo'])){
                foreach($asnInfo['ASNItems']['OrderInfo'] as $key=>$value){
                    $orderRow = Service_Orders::getByField($value,"order_code","*");
                    if(!empty($orderRow)){
                        $orderCodeArr[$orderRow['order_id']] = $orderRow['order_code'];
                    }else{
                        $errorMsg.="订单:".$value."不存在;";
                    }
                }
            }else{
                $orderRow = Service_Orders::getByField($asnInfo['ASNItems']['OrderInfo'],"order_code","*");
                if(!empty($orderRow)){
                    $orderCodeArr[$orderRow['order_id']] = $orderRow['order_code'];
                }else{
                    $errorMsg.="订单:".$asnInfo['ASNItems']['OrderInfo']."不存在;";
                }
            }
            if($errorMsg!=""){
                $result['ask'] = "0";
                $result['message'] = $errorMsg;
                return $result;
            }
            $asnData['asn_order'] = $orderCodeArr;
        }else{
            $productSku = array();
            $sku = array();
            $decleardValue = array();
            $productInfos = $asnInfo['ASNItems']['productInfo'];
            if(!isset($productInfos[0])){
                //处理只有一个sku的情况bug
                $productInfos = array($productInfos);
            }
            foreach($productInfos as $key=>$value){
                $product = Service_Product::getByCondition(
                    array('product_sku'=>$value['productSku'],'customer_code'=>$customerCode),"*");
                $productSku[$product[0]['product_id']] = $value['productSku'];
                $sku[$product[0]['product_id']] = $value['quantity'];
                if(isset($value['declaredValue'])&&$value['declaredValue']!=""){
                    $decleardValue[$product[0]['product_id']] = $value['declaredValue'];
                }
                /*if(isset($value['isNewGoodsId'])&&$value['isNewGoodsId']!=""){
                    $isNewGoodsId[$product[0]['product_id']] = $value['isNewGoodsId'];
                }*/
                if(isset($value['hsCode'])&&$value['hsCode']!=""){
                    $hsCode[$product[0]['product_id']] = $value['hsCode'];
                }
                if(isset($value['hsGoodsName'])&&$value['hsGoodsName']!=""){
                    $hsGoodsName[$product[0]['product_id']] = $value['hsGoodsName'];
                }
                if(isset($value['gModel'])&&$value['gModel']!=""){
                    $gModel[$product[0]['product_id']] = $value['gModel'];
                }
            }
            $asnData['product_sku'] = $productSku;
            $asnData['sku'] = $sku;
            if(!empty($decleardValue))
                $asnData['declared_value'] = $decleardValue;
            if(!empty($isNewGoodsId)) $asnData['is_new_goods_id'] = $decleardValue;
            if(!empty($hsCode)) $asnData['hs_code'] = $hsCode;
            if(!empty($hsGoodsName)) $asnData['hs_goods_name'] = $hsGoodsName;
            if(!empty($gModel)) $asnData['g_model'] = $gModel;
        }

        $ASNObj = new Service_AsnProccess();
        //file_put_contents($filePath,var_export($asnData,true),FILE_APPEND);
        $doresult = array();
        //$asnData['trade_mode'] = "0110";
        if($asnData['receive_model_type']=="1"){
            //集货模式
            $doresult = $ASNObj->createjihuoTransaction($asnData, $customerRow['customer_id'], $asnInfo['warehouseId']);
            //exit('cc');
        }else{
            $doresult = $ASNObj->createTransaction($asnData, $customerRow['customer_id'], $asnInfo['warehouseId']);
        }
        if (isset($doresult['msg'])) {
            $result['message'] = $doresult['msg'];
        }

        $result['ask']=$doresult['ask'];
        $result['ASNCode'] = $doresult['ASNCode'];
        //$result['time'] = date("Y-m-d H:i:s");
        //$return['message'] = "";
        if($result['ask']=="1"){
            $ftpMessageSendlistRow = array(
                'fmt_code'=>'ASNSH-TO-FX',
                'fmt_type'=>'FXSYS',
                'refercence_no'=>$doresult['ASNCode'],
                'fml_status'=>'1',
                'fml_add_time'=>date("Y-m-d H:i:s"),
            );
            Service_FtpMessageSendlist::add($ftpMessageSendlistRow);
            $ftpMessageSendlistRow = array(
                'fmt_code'=>'ASNWCSH-TO-FX',
                'fmt_type'=>'FXSYS',
                'refercence_no'=>$doresult['ASNCode'],
                'fml_status'=>'1',
                'fml_add_time'=>date("Y-m-d H:i:s"),
            );
            Service_FtpMessageSendlist::add($ftpMessageSendlistRow);
        }
        if($result['ask']=='0'){
            $result['message'] = $doresult['msg'];
            $result['error'] = implode(";",$doresult['error']);
            return $result;
        }elseif($asnData['receiving_status']=="2"){
            $return = Service_AsnProccess::confirmASn($doresult['ASNCode'],$customerRow['customer_id']);
            if($return['ask']=="0"){
                $error = array_merge($doresult['error'],$return['error']);
                $result['error'] = implode(";",$error);// Common_TransError::Transerror($result['error']);
                $return['message'] = "收货单号".$doresult['ASNCode']."创建成功,提交确认失败!";
                $result['ask'] = "1";
                return $result;
            }
            $return['message'] = "收货单号".$doresult['ASNCode']."创建成功,已提交到确认状态";
        }elseif($asnData['receiving_status']=="3"){
            $return = Service_AsnProccess::confirmASn($doresult['ASNCode'],$customerRow['customer_id']);
            if($return['ask']=="0"){
                $error = array_merge($doresult['error'],$return['error']);
                $result['error'] = $error;// Common_TransError::Transerror($result['error']);
                $result['ask'] = "1";
                return $result;
            }
            /*if($asnData['receive_model_type'] =="1"){
                $result['message'] = "集货ASN不能提交到待审核,现已提交到确认状态";
                return $result;
            }*/
            $return2 = Service_AsnProccess::PendingAsn($doresult['ASNCode'],$customerRow['customer_id']);
            if($return2['ask']=="0"){
                $error = array_merge($doresult['error'],$return['error']);
                $result['error'] = $error;// Common_TransError::Transerror($result['error']);
                $result['ask'] = "1";
                return $result;
            }

            $result['message'] = "收货单号".$doresult['ASNCode']."创建成功,且已提交到待审核状态";
        }

        return $result;
    }

    public function getOrderByCode($paramter){
        $paramter = Common_Common::objectToArray($paramter);
        $ordersCode = $paramter['orderCode'];

        /*$filePath = APPLICATION_PATH.'/../data/log/'.'getOrderByCode.txt';
        if(!file_exists($filePath)){
            $fp= fopen($filePath,"w");
            fclose($fp);
        }
        file_put_contents($filePath,var_export($paramter,true),FILE_APPEND);*/

        $result = array(
            'ask' => '1',
            'data' => array(),
            'error' => array()
        );

        if (empty($ordersCode)) {
            $this->_error= '订单号不能为空';
            $result['ask'] = '0';
            $result['message'] = $this->_error;
            return $result;
        }

        $orderRow = Service_Orders::getByField($ordersCode,'order_code',"*");

        if (empty($orderRow)) {
            $this->_error= '订单不存在 ' . $ordersCode;
            $result['ask'] = '0';
            $result['message'] = $this->_error;
            return $result;
        }else{
            $customer = Service_Customer::getByField($orderRow['customer_code'],'customer_code',"*");
            $order = Service_Orders::getOrderAllInfo($ordersCode, $customer['customer_id']);
            $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){
                $p = Service_Product::getByField($vallueo['product_id'],'product_id',"*");
                $orderDetail[] = array(
                    'productSku'=>$vallueo['product_sku'],
                    'opQuantity'=>$vallueo['op_quantity'],
                    'productWeight'=>$p['product_weight'],
                );
            }
        }
        $shipOrder = Service_ShipOrder::getByField($ordersCode,'order_code',"*");
        $orderInfo = array(
            'orderCode'=>$order['order_code'],
            'orderType' => $order['order_mode_type'],
            'warehouseCode' => $order['warehouse_code'],
            'trackingNumber' => isset($shipOrder['tracking_number'])?$shipOrder['tracking_number']:"",
            'pp_barcode'=>isset($shipOrder['pp_barcode'])?$shipOrder['pp_barcode']:"",
            'so_weight'=>isset($shipOrder['so_weight'])?$shipOrder['so_weight']:"",
            //'oabCountry' => $order['country_name'],
            "so_fee_weight"=>isset($shipOrder['so_fee_weight'])?$shipOrder['so_fee_weight']:"",
            "so_vol_weight"=>isset($shipOrder['so_vol_weight'])?$shipOrder['so_vol_weight']:"",
            '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'],
            'Remark' => $order['remark'],
            'OrderDetail' => $orderDetail,
        );
        $result['data'] = $orderInfo;
        return $result;
    }

    public function register($request){
        $paramter = Common_Common::objectToArray($request);

        $time	= date('Y-m-d H:i:s');
        $name	= $paramter['username'];
        $pwd	= $paramter['userpwd'];
        $repwd	= $paramter['repwd'];
        $registerRow=array(
            'customer_password'		=> $pwd,
            're_password'			=> $repwd,
            'customer_email'		=> $name,
            'customer_activate_code'=> substr(md5($time),0,12),
            'reg_step'				=> 1,
            'check_verify'		=>0,
            'customer_platform'=>'FX',
        );
        //print_r($registerRow);
        /*$filePath = APPLICATION_PATH.'/../data/log/'.'soap-register.txt';
        if(!file_exists($filePath)){
            $fp= fopen($filePath,"w");
            fclose($fp);
        }
        file_put_contents($filePath,var_export($paramter,true));*/
        $process = new Service_CustomerProcess();
        $result=$process->createTransaction($registerRow);
        if($result['ask']=="0"){
            return $result;
        }
        $session= new Zend_Session_Namespace('register');
        $session->data	= array(
            'id'		=> $result['customer_id'],
            'code'		=> $result['customer_code'],
            'email'		=> $name,
            'current'	=> 2
        );

        $id		= $session->data['id'];
        $code	= $session->data['code'];
        $email	= $session->data['email'];
        $country = Service_Country::getByField($paramter['country'],'country_code',"*");
        $parms	= $paramter;
        $parms['country'] = $country['country_id'];
        $base	= array(
            'customer_company_name'		=> $parms['companyname'],
            'trade_name'		=> $parms['trade_name'],
            'trade_co'		=> $parms['trade_co'],
            //'customer_customs_hscode'	=> $parms['customscode'],
            'customer_currency'			=> $parms['currency'],
            'customer_license'			=> empty($imgs['license']) ? '' : $imgs['license'],
            'customer_idcard'			=> empty($imgs['identity']) ? '' : $imgs['identity'],
            'customer_customlsn'			=> empty($imgs['customlsn']) ? '' : $imgs['customlsn'],

            'customer_firstname'		=> empty($parms['firstname']) ? '' : $parms['firstname'],
            'customer_lastname'			=> empty($parms['lastname']) ? '' : $parms['lastname'],
            'customer_telephone'		=> empty($parms['telphone']) ? '' : $parms['telphone'],
            'customer_fax'				=> empty($parms['fax']) ? '' : $parms['fax'],
            'reg_step'					=> 3,
            'customer_country'			=> empty($parms['country']) ? '' : $parms['country'],
            'customer_province'			=> empty($parms['province']) ? '' : $parms['province'],
            'customer_city'			=> empty($parms['city']) ? '' : $parms['city'],
            'customer_postno'		=> empty($parms['postno']) ? '' : $parms['postno'],
            'customer_address'					=> empty($parms['address']) ? '' : $parms['address'],
            'customer_provision'					=> empty($parms['provision']) ? '' : $parms['provision'],
            'customer_signature'					=> empty($parms['signature']) ? '' : $parms['signature'],



        );
        $book	= array(
            'customer_id'				=> $id,
            'customer_code'				=> $code,
            'cab_country_id'			=> $parms['country'],
            'cab_firstname'			=> empty($parms['firstname']) ? '' : $parms['firstname'],
            'cab_lastname'			=> empty($parms['lastname']) ? '' : $parms['lastname'],
            'cab_state'					=> empty($parms['state']) ? '' : $parms['state'],
            'cab_city'					=> empty($parms['city']) ? '' : $parms['city'],
            'cab_postcode'				=> empty($parms['postcode']) ? '' : $parms['postcode'],
            'cab_street_address1'		=> empty($parms['address']) ? '' : $parms['address']
        );
        $process = new Service_CustomerProcess();
        $result=$process->completeTransaction($parms,$imgs);
        return $result;
    }

    public function updateAsn($request){

        $result = array(
            'ask'=>'0',
            'message'=>'',
            'error'=>'',
            'ASNCode'=>'',
        );

        $this->common($request);
        if ($this->_error) {
            $result['message'] = $this->_error;
            return $result;
        }

        $customerCode = $this->_paramterArr['customerCode'];
        $customerRow = Service_Customer::getByField($customerCode,'customer_code',"*");

        $asnCoode = $this->_paramterArr['ASNCode'];
        /*$filePath = APPLICATION_PATH.'/../data/log/'.'soap-CreateProduct.txt';
        if(!file_exists($filePath)){
            $fp= fopen($filePath,"w");
            fclose($fp);
        }*/
        //file_put_contents($filePath,date("Y-m-d H:i:s"),FILE_APPEND);
        if(empty($asnCoode)){
            $result['message'] = 'ASN单号为空';
            return $result;
        }else{
            $receiving = Service_Receiving::getByField($asnCoode,'receiving_code');
            if(empty($receiving)){
                $result['message'] = 'ASN单号['.$asnCoode.']不存在';
                return $result;
            }else{
                if($receiving['customer_code']!=$this->_paramterArr['customerCode']){
                    $result['message'] = 'ASN单号['.$asnCoode.']不属于客户['.$this->_paramterArr['customerCode'].']';
                    return $result;
                }
                $receivingCondition = array(
                    'receiving_code'=>$asnCoode,
                );
                if($receiving['receive_model_type']=='1'){
                    //集货模式
                    //传错参数
                    if(isset($this->_paramterArr['ASNItems']['productInfo'])){
                        $result['message'] = '集货的ASN,不能传递产品信息';
                        return $result;
                    }
                    $detail = Service_ReceivingOrderDetail::getByCondition($receivingCondition,'*');
                }elseif($receiving['receive_model_type']=='0'){
                    //备货模式
                    //print_r($this->_paramterArr);
                    if(isset($this->_paramterArr['ASNItems']['OrderInfo'])){
                        $result['message'] = '备货的ASN,不能传递订单信息';
                        return $result;
                    }
                    $detail = Service_ReceivingDetail::getByCondition($receivingCondition,'*');
                }else{
                    $result['message'] = '订单模式错误';
                    return $result;
                }
            }
        }
        $asnInfo = $this->_paramterArr;
        //print_r($this->_paramterArr);
        //file_put_contents($filePath,var_export($this->_paramterArr,true));
        $asnInfo = $this->ASNupdateTransParam($asnInfo,$receiving,$detail,$receiving['receive_model_type']);
        /*$filePath = APPLICATION_PATH.'/../data/log/'.'soap-CreateProduct.txt';
        if(!file_exists($filePath)){
            $fp= fopen($filePath,"w");
            fclose($fp);
        }
        //file_put_contents($filePath,date("Y-m-d H:i:s"),FILE_APPEND);
        file_put_contents($filePath,var_export($asnInfo,true));*/

        $asnData = array();
        $relateArr = self::$upperToUnderline;
        foreach($asnInfo as $k=>$v){
            if($k!="ASNItems"){
                $asnData[$relateArr[$k]] = $v;
            }
        }

        $warehouseRow = Service_Warehouse::getByField($asnData['warehouse_code'],"warehouse_code","*");
        $asnData['warehouseId'] = $warehouseRow['warehouse_id'];

        if($asnData['receive_model_type']=="1"){
            $orderCodeArr = array();
            foreach($asnInfo['ASNItems']['OrderInfo'] as $key=>$value){
                if($key=="orderCode"){
                    $orderRow = Service_Orders::getByField($value,"order_code","*");
                    $orderCodeArr[$orderRow['order_id']] = $orderRow['order_code'];
                }else{
                    $orderRow = Service_Orders::getByField($value['orderCode'],"order_code","*");
                    $orderCodeArr[$orderRow['order_id']] = $value['orderCode'];
                }
            }
            $asnData['asn_order'] = $orderCodeArr;
        }else{
            $productSku = array();
            $sku = array();
            $decleardValue = array();
            foreach($asnInfo['ASNItems']['productInfo'] as $key=>$value){
                $product = Service_Product::getByCondition(
                    array('product_sku'=>$value['productSku'],'customer_code'=>$customerCode),"*");
                $productSku[$product[0]['product_id']] = $product[0]['product_sku'];
                $sku[$product[0]['product_id']] = $value['quantity'];
                if(isset($value['declaredValue'])&&$value['declaredValue']!=""){
                    $decleardValue[$product[0]['product_id']] = $value['declaredValue'];
                }
            }
            $asnData['product_sku'] = $productSku;
            $asnData['sku'] = $sku;
            if(!empty($decleardValue))
                $asnData['declared_value'] = $decleardValue;
        }

        $ASNObj = new Service_AsnProccess();

        $asn_arrays = Service_AsnProccess::checkReferenceNo(array('reference_no'=>$asnData['ref_code'],'customer_id'=>$customerRow['customer_id']));

        $error = array();
        if($asn_arrays){
            foreach($asn_arrays as $row){
                if($row['receiving_code']!=$asnData['ASNCode']){
                    $error[] =  '客户参考号已存在!';
                    break;
                }
            }
        }
        if(!empty($error)){
            //$result['error'] = $error;
            $result['error'] = implode(";",$error);
            $result['ask'] = "0";
            $result['ASNCode'] = $asnData['ASNCode'];
            return $result;
        }

        if($asnData['receive_model_type']=="0"){
            //备货模式
            $doresult = $ASNObj->updateTransaction($asnData, $customerRow['customer_id'], $asnData['warehouseId']);
        }else{
            $doresult = $ASNObj->updatejihuoTransaction($asnData, $customerRow['customer_id'], $asnData['warehouseId']);
        }
        /*if (isset($doresult['msg'])) {
            $result['msg'] = $doresult['msg'];
        }*/
        //$result['error']=$doresult['error'];
        $result['error'] = empty($doresult['error'])?"":implode(";",$doresult['error']);
        $result['ask']=$doresult['ask'];
        $result['message'] = $doresult['msg'];
        $result['ASNCode'] = $doresult['ASNCode'];
        return $result;
    }

    public function getAsnByCode($request){
        $this->common($request);
        $result = array(
            'ask'=>'0',
            'message'=>'',
            'error'=>'',
            'Data'=>'',
        );
        if ($this->_error) {
            $result['message'] = $this->_error;
            return $result;
        }
        //$receivingRow = array();
        $receivingCode = $this->_paramterArr['ASNCode'];
        $referenceNo = $this->_paramterArr['referenceNo'];
        if($receivingCode==""&&$referenceNo==""){
            $result['message'] = "ASN单号和客户参考号不能同时为空";
            return $result;
        }
        $condition = array(
            'receiving_code'=>$receivingCode,
            'reference_no'=>$referenceNo,
            'customer_code'=>$this->_paramterArr['customerCode'],
            'receiving_status_arr'=>array('1','2','3','4','5','6','7'),
        );
        $receivingList = Service_Receiving::getByCondition($condition);

        //$row = Service_Receiving::getByField($receivingCode,'receiving_code',"*");
        if(empty($receivingList)){
            $result['message'] = "无数据";
            return $result;
        }
        $row = $receivingList[0];
        /*if($row['customer_code']!=$this->_paramterArr['customerCode']){
            $result['message'] = "ASN单号[".$this->_paramterArr['ASNCode']."]不属于客户[".$this->_paramterArr['customerCode']."]";
            return $result;
        }*/

        /*$row = Service_Receiving::getByField($receivingCode,'receiving_code',"*");
        if(empty($row)){
            $result['message'] = "ASN单号[".$this->_paramterArr['ASNCode']."]不存在";
            return $result;
        }
        if($row['customer_code']!=$this->_paramterArr['customerCode']){
            $result['message'] = "ASN单号[".$this->_paramterArr['ASNCode']."]不属于客户[".$this->_paramterArr['customerCode']."]";
            return $result;
        }*/
        $warehouseRow = Service_Warehouse::getByField($row['warehouse_id'],"warehouse_id","*");
        $row['warehouse_code'] = $warehouseRow['warehouse_code'];
        $receivingRow = array();
        $relate = self::$underlineToUpper;
        foreach($row as $k=>$v){
            $receivingRow[$relate[$k]] = $v;
        }
        if($receivingRow['receiveMode']=="1"){
            $receivingOrderDetail = Service_ReceivingOrderDetail::getByCondition(array('receiving_code'=>$receivingRow['receivingCode']),"*");
            $orders = array();
            foreach($receivingOrderDetail as $key=>$value){
                $orderRow = Service_Orders::getByField($value['order_code'],"order_code","*");
                $orderRow['orderCode'] = $orderRow['order_code'];
                $orders[] = $orderRow;
            }
            $receivingRow['OrderDetail'] = $orders;
        }else{
            $receivingDetail = Service_ReceivingDetail::getByCondition(array('receiving_code'=>$receivingRow['receivingCode']),"*");
            $products = array();
            foreach($receivingDetail as $k=>$v){
                $p = Service_Product::getByField($v['product_id'],"product_id","*");
                $p['productSku'] = $p['product_sku'];
                $products[] = $p;
                $receivingDetail[$k]['product_sku'] = $p['product_sku'];
            }
            $receivingRow['productDetail'] = $products;
            $receivingRow['receivingDetail'] = $receivingDetail;
        }
        $result['ask'] = "1";
        $result['error'] = "";
        $result['message'] = "";
        $result['Data'] = $receivingRow;

        return $result;
    }

    public function createProduct($request){

        $result = array('ask'=>'0','message'=>'','error'=>'','skuNo'=>'');
        $this->common($request);
        if ($this->_error) {
            $result['message'] = $this->_error;
            return $result;
        }

        $row = array();
        $time = date('Y-m-d H:i:s');

        if(!isset($this->_paramterArr['UOM'])||$this->_paramterArr['UOM']==""){
            $this->_paramterArr['UOM'] = "007";
        }
        /*$filePath = APPLICATION_PATH.'/../data/log/'.'soap-CreateProduct-Response.txt';
        if(!file_exists($filePath)){
            $fp= fopen($filePath,"w");
            fclose($fp);
        }
        file_put_contents($filePath,var_export($this->_paramterArr,true),FILE_APPEND);*/
        $productUomArr= Service_Product::getProductUom();
        if(!in_array($this->_paramterArr['UOM'],$productUomArr)){
            $resultArray['ask']='0';
            $resultArray['message'] = "产品单位字段[UOM]只能填值:001,002,003,004,005,006,007,008,009,010,011,012,013,014,015,016,017,018,019,020,021,022,023,025,026,027,028,029,031,034,037,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,139,140,141,142,163";
            $resultArray['error'][] = "产品单位字段[UOM]只能填值:001,002,003,004,005,006,007,008,009,010,011,012,013,014,015,016,017,018,019,020,021,022,023,025,026,027,028,029,031,034,037,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,139,140,141,142,163";
            return $resultArray;
        }

        $row['product_sku'] =  $this->_paramterArr['skuNo'];//sku编码
        $row['product_title'] =  $this->_paramterArr['skuName'];//中文名称
        $row['product_title_en'] = $this->_paramterArr['productTtitleEn'];
        //$row['pu_code'] = $ProductInfo['UOM'];//产品单位
        $row['product_barcode_type'] = $this->_paramterArr['barcodeType'];//条码类型
        $row['product_barcode'] = $this->_paramterArr['barcodeDefine'];//自定义条码
        $row['product_weight'] = $this->_paramterArr['weight'];//重量
        $row['has_invoice'] = $this->_paramterArr['hasInvoice'];//是否有发票
        $row['currency_code'] = 'USD';//币种
        $row['hs_goods_name'] = $this->_paramterArr['hsGoodsName'];
        $row['hs_code'] = $this->_paramterArr['hsCode'];
        $row['product_declared_value'] = $this->_paramterArr['productDeclaredValue'];
        $row['is_accessories'] = $this->_paramterArr['is_accessories'];
        if($row['is_accessories']!='1'){
            $row['is_accessories'] = 0;
        }
        $row['customer_id'] = $this->_customer['customer_id'];
        $row['customer_code'] = $this->_customer['customer_code'];;
        $row['product_add_time'] = $time;
        $row['product_update_time'] = $time;
        $row['with_battery'] = isset($this->_paramterArr['with_battery'])?$this->_paramterArr['with_battery']:'0';
        $row['battery_type'] = isset($this->_paramterArr['battery_type'])?$this->_paramterArr['battery_type']:"0";
        $row['pu_code'] = $this->_paramterArr['UOM'];//产品单位

        $result = Service_Product::createProductForSoap($row,$row['customer_code']);
        //file_put_contents($filePath,date("Y-m-d H:i:s"),FILE_APPEND);
        //file_put_contents($filePath,var_export($result,true),FILE_APPEND);

        $resultArray = array();
        if($result['ask']==1){
            $resultArray['ask'] = '1';
            $resultArray['message'] = $result['message'];
            $resultArray['skuNo'] = $row['product_sku'];
        }else{
            $resultArray['ask']='0';
            $resultArray['message'] = $result['message'];
            $resultArray['error'] = $result['error']['error'];
        }

        return $resultArray;

    }

    public function getProduct($request){
        $paramter = Common_Common::objectToArray($request);
        /*$filePath = APPLICATION_PATH.'/../data/log/'.'soap-getProduct.txt';
        if(!file_exists($filePath)){
            $fp= fopen($filePath,"w");
            fclose($fp);
        }
        file_put_contents($filePath,var_export($paramter,true));*/
        $productList = Service_Product::getByCondition($paramter,"*");
        $result = array(
            'ask'=>'0',
            'message'=>'',
            'productData'=>'',
        );
        if(!empty($productList)){
            foreach($productList as $key=>$product){
                if($product['product_status']=='2'){
                    $productList[$key]['pu_code_law'] = "";
                    $productList[$key]['pu_code_second'] = "";
                    $productList[$key]['hum_quantity_law'] = "";
                    $productList[$key]['hum_quantity_second'] = "";
                    $productList[$key]['hsElement'] = "";
                    continue;
                }
                $hsElementMap = Service_HsElementMap::getByCondition(array('product_id'=>$product['product_id']),"*");
                foreach($hsElementMap as $k=>$hem){
                    $HE = Service_HsElement::getByField($hem['he_id'],"he_id","*");
                    $hsElementMap[$k]['he_code'] = $HE['he_code'];
                    $hsElementMap[$k]['he_name'] = $HE['he_name'];
                }
                $HUM = Service_HsUomMap::getByField($product['product_id'],"product_id","*");
                $HU = Service_HsUom::getByField($HUM['hu_id'],"hu_id","*");
                //$productUom = Service_ProductUom::getByField($HU['pu_code_law'],"pu_code","*");
                $productList[$key]['pu_code_law'] = $HU['pu_code_law'];
                $productList[$key]['pu_code_second'] = $HU['pu_code_second'];
                $productList[$key]['hum_quantity_law'] = $HUM['hum_quantity_law'];
                $productList[$key]['hum_quantity_second'] = $HUM['hum_quantity_second'];
                $productList[$key]['hsElement'] = $hsElementMap;
            }
            $result['ask'] = 1;
            $result['productData'] = $productList;
        }else{
            $result['message'] = "NO DATA";
        }
        return $result;
    }

    public function getStock($request){
        $this->common($request);
        $condition_array = array();
        $condition_array['product_sku'] = $this->_paramterArr['skuNo'];
        $customerRow = Service_Customer::getByField($this->_paramterArr['customerCode'],'customer_code',"*");
        $condition_array['customer_code'] = $this->_paramterArr['customerCode'];

        $product_array = Service_Product::getByCondition($condition_array);

        if(empty($product_array)){
            $result_array['ask'] = '0';
            $result_array['message'] = '非法的产品SKU.';
            return 	$result_array;
        }

        $condition_array = array();
        $condition_array['product_id'] =  $product_array[0]['product_id'];
        $condition_array['customer_id'] = $customerRow['customer_id'];;
        $ProductInventoryArray =  Service_ProductInventory::getByCondition($condition_array);
        if(empty($ProductInventoryArray)){
            $result_array['ask'] = '0';
            $result_array['message'] = '没找到库存数据.';
            return 	$result_array;
        }

        $return_data_array = array();

        $productRow = Service_Product::getByCondition($condition_array,"*");
        foreach($ProductInventoryArray as $k =>$row){
            $warehouse_id = $row['warehouse_id'];
            $warehouse_array = Service_Warehouse::getByField($warehouse_id,'warehouse_id');
            if(empty($warehouse_array)){continue;}

            $return_data_array[] = array(
                'skuNo'=>$this->_paramterArr['skuNo'],
                'customerCode'=>$this->_paramterArr['customerCode'],
                'warehouseCode'=>$warehouse_array['warehouse_code'],
                'onwayQty'=>$row['pi_onway'],//在途数
                'pendingQty'=>$row['pi_pending'],//到货（未上架数量）
                'sellableQty'=>$row['pi_sellable'],//可用
                'unsellableQty'=>$row['pi_unsellable'],//不可用
                'reservedQty'=>$row['pi_reserved'],//冻结数量
                'shippedQty'=>$row['pi_shipped'],//已出库数量
            );
        }//foreach

        $result_array['ask'] = '1';
        $result_array['message'] = '获取库存信息成功.';
        $result_array['data'] =  $return_data_array;
        return $result_array;

    }

    public function swapOrderCreate($request){
        $result = array('ask'=>'0','message'=>'','error'=>'','swo_code'=>'');
        $this->common($request);
        if ($this->_error) {
            $result['message'] = $this->_error;
            return $result;
        }
        $swapOrderDetail = $this->_paramterArr['swapOrderDetail'];
        $swd = array();
        /*$filePath = APPLICATION_PATH.'/../data/log/'.'soap-CreateSwapOrder.txt';
        if(!file_exists($filePath)){
            $fp= fopen($filePath,"w");
            fclose($fp);
        }
        file_put_contents($filePath,var_export( $this->_paramterArr,true),FILE_APPEND);*/
        if(!isset($swapOrderDetail[0])){
            //处理只有一个sku的情况bug
            $swd = array($swapOrderDetail);
        }else{
            $swd = $swapOrderDetail;
        }
        $data = array(
            'customer_id'=>$this->_customer['customer_id'],
            'customer_code'=>$this->_paramterArr['customerCode'],
            'serial_code'=>$this->_paramterArr['serial_code'],
            'remark'=>$this->_paramterArr['remark'],
            'isAbnormal'=>$this->_paramterArr['isAbnormal'],
            'swapOrderDetail'=>$swd
        );
        //file_put_contents($filePath,date("Y-m-d H:i:s"),FILE_APPEND);
        //file_put_contents($filePath,var_export($data,true),FILE_APPEND);
        $swobj = new Service_SwapOrderProcess();
        $return = $swobj->createTransaction($data);
        //file_put_contents($filePath,var_export($return,true),FILE_APPEND);
        return $return;
    }

    public function  ASNupdateTransParam($receivingRow,$receivingInfo,$detail,$type='1'){
        $updateRow = array();


        $referenceNo = isset($receivingRow['refCode'])&&$receivingRow['refCode']!==''?$receivingRow['refCode']:$receivingInfo['reference_no'];
        $isDelivery = isset($receivingRow['isDelivery'])&&$receivingRow['isDelivery']!==''?$receivingRow['isDelivery']:$receivingInfo['is_delivery'];
        $iePort = isset($receivingRow['iePort'])&&$receivingRow['iePort']!==''?$receivingRow['iePort']:$receivingInfo['ie_port'];
        $formType = isset($receivingRow['formType'])&&$receivingRow['formType']!==''?$receivingRow['formType']:$receivingInfo['form_type'];
        $trafName = isset($receivingRow['trafName'])&&$receivingRow['trafName']!==''?$receivingRow['trafName']:$receivingInfo['traf_name'];
        $wrapType = isset($receivingRow['wrapType'])&&$receivingRow['wrapType']!==''?$receivingRow['wrapType']:$receivingInfo['wrap_type'];
        $packNo = isset($receivingRow['packNo'])&&$receivingRow['packNo']!==''?$receivingRow['packNo']:$receivingInfo['pack_no'];
        $trafMode = isset($receivingRow['trafMode'])&&$receivingRow['trafMode']!==''?$receivingRow['trafMode']:$receivingInfo['traf_mode'];
        $tradeMode = isset($receivingRow['tradeMode'])&&$receivingRow['tradeMode']!==''?$receivingRow['tradeMode']:$receivingInfo['trade_mode'];
        $transMode = isset($receivingRow['transMode'])&&$receivingRow['transMode']!==''?$receivingRow['transMode']:$receivingInfo['trans_mode'];
        $roughWeight = isset($receivingRow['roughWeight'])&&$receivingRow['roughWeight']!==''?$receivingRow['roughWeight']:$receivingInfo['roughweight'];

        $instructions = isset($receivingRow['roughWeight'])&&$receivingRow['roughWeight']!==''?$receivingRow['roughWeight']:$receivingInfo['roughweight'];




        if(isset($receivingRow['warehouseCode']) && $receivingRow['warehouseCode']!==''){
            $updateRow['warehouseCode'] = $receivingRow['warehouseCode'];
        }else{
            $warehouseId = $receivingInfo['warehouse_id'];
            $warehouse = Service_Warehouse::getByField($warehouseId);
            $updateRow['warehouseCode'] = $warehouse['warehouse_code'];
        }

        $updateRow['refCode'] = $referenceNo;
        $updateRow['isDelivery'] = $isDelivery;
        $updateRow['iePort'] = $iePort;
        $updateRow['formType'] = $formType;
        $updateRow['trafName'] = $trafName;
        $updateRow['wrapType'] = $wrapType;
        $updateRow['packNo'] = $packNo;
        $updateRow['trafMode'] = $trafMode;
        $updateRow['tradeMode'] = $tradeMode;
        $updateRow['transMode'] = $transMode;
        $updateRow['receiveMode'] = $receivingInfo['receive_model_type'];
        $updateRow['roughWeight'] = $roughWeight;
        $updateRow['instructions'] = $instructions;
        $updateRow['ASNCode'] = $receivingRow['ASNCode'];

        if($type=='1'){
            //集货模式
            if(!isset($receivingRow['ASNItems']['OrderInfo'])){
                //没传递值用原来的
                $details = array();
                foreach($detail as $key=>$value){
                    $detailArr = array(
                        'orderCode'=>$value['order_code']
                    );
                    $details[] = $detailArr;
                }
                $updateRow['ASNItems']['OrderInfo'] = $details;
            }else{
                $updateRow['ASNItems']['OrderInfo'] =  $receivingRow['ASNItems']['OrderInfo'];
            }
        }else{
            //备货模式
            if(!isset($receivingRow['ASNItems']['productInfo'])){
                //没传递值用原来的
                $details = array();
                foreach($detail as $key=>$value){
                    $product = Service_Product::getByField($value['product_id']);
                    $detailArr = array(
                        'productSku'=>$product['product_sku'],
                        'quantity'=>$value['rd_receiving_qty'],
                        'declaredValue'=>$value['op_declared_value']
                    );
                    $details[] = $detailArr;
                }
                $updateRow['ASNItems']['productInfo'] = $details;
            }else{
                $updateRow['ASNItems']['productInfo'] = $receivingRow['ASNItems']['productInfo'];
            }
        }
        return $updateRow;
    }

    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'];
        $is_pod = isset($orderRow['is_pod']) && $orderRow['is_pod'] !== '' ? $orderRow['is_pod'] : $orderInfo['is_pod'];

        $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'] ;

        $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['is_fba'] = $is_fba;
        $updateRow['is_fba_tax'] = $is_fba_tax;
        $updateRow['delivery_address'] = $deliveryAddress;
        $updateRow['remark'] = $remark;
        $updateRow['is_pod'] = $is_pod;

        $updateRow['insurance'] = $buyInsurance;
        $updateRow['insurance_rate'] = $insuranceRate;
        $updateRow['insurance_name'] = $insuranceName;

        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 getSwapOrder($request){
        $this->common($request);
        $result = array(
            'ask' => '0',
            'message' => '',
            'error' => array(),
            'swapOrderData'=>'',
        );
        if ($this->_error) {
            $result['message'] = $this->_error;
            return $result;
        }
        $swoCode = $this->_paramterArr['swo_code'];
        $condition = array(
            'customer_code'=>$this->_paramterArr['customerCode'],
            'swo_code'=>$this->_paramterArr['swo_code'],
            'serial_code'=>$this->_paramterArr['serial_code'],
        );
        $swapOrderList = Service_SwapOrder::getByCondition($condition,"*");
        if(empty($swapOrderList)){
            $result['messsage'] = "不存在符合条件的易货单号";
            return $result;
        }
        $swapOrderData = array();
        foreach($swapOrderList as $key=>$value){
            $swapOrderDetail  = Service_SwapOrderDetail::getByCondition(array('swo_code'=>$value['swo_code']),"*");
            $swo = array(
                'customerCode'=>$value['customer_code'],
                'swo_code'=>$value['swo_code'],
                'serial_code'=>$value['serial_code'],
                'swapOrderDetail'=>$swapOrderDetail
            );
            $swapOrderData[] = $swo;
        }
        $result['ask'] = 1;
        /*$filePath = APPLICATION_PATH.'/../data/log/'.'soap-CreateSwapOrder.txt';
        if(!file_exists($filePath)){
            $fp= fopen($filePath,"w");
            fclose($fp);
        }
        //file_put_contents($filePath,date("Y-m-d H:i:s"),FILE_APPEND);
        file_put_contents($filePath,var_export($swo,true));*/
        $result['swapOrderData'] = $swapOrderData;
        return $result;
    }

    public function getOrderByReferenceNo($request){
        $this->common($request);
        $result = array(
            'ask' => '0',
            'message' => '',
            'error' => array(),
            'orderDataArr'=>'',
        );
        if ($this->_error) {
            $result['message'] = $this->_error;
            return $result;
        }
        $condition = array(
            'customer_code'=>$this->_paramterArr['customerCode'],
            'reference_no'=>$this->_paramterArr['reference_no'],
        );
        $orderList = Service_Orders::getByCondition($condition,"*");
        $orderDataArr = array();
        if(empty($orderList)){
            $result['message'] = "不存在交易号[".$this->_paramterArr['reference_no']."]的订单";
            return $result;
        }else{
            foreach($orderList as $key=>$value){
                $orderRow = Service_Orders::getByField($value['order_code'],'order_code',"*");

                $customer = Service_Customer::getByField($orderRow['customer_code'],'customer_code',"*");
                $order = Service_Orders::getOrderAllInfo($value['order_code'], $customer['customer_id']);
                $warehouseCode = '';
                $warehouseInfo=Service_Warehouse::getByField($order['warehouse_id']);
                if(!empty($warehouseInfo)){
                    $warehouseCode = $warehouseInfo['warehouse_code'];
                }
                $order['warehouse_code'] = $warehouseCode;


                $orderProducts = $order['order_product'];
                $orderDetail = array();
                if($orderProducts){
                    foreach($orderProducts as $keyo=>$vallueo){
                        $p = Service_Product::getByField($vallueo['product_id'],'product_id',"*");
                        $orderDetail[] = array(
                            'productSku'=>$vallueo['product_sku'],
                            'opQuantity'=>$vallueo['op_quantity'],
                            'productWeight'=>$p['product_weight'],
                        );
                    }
                }
                $shipOrder = Service_ShipOrder::getByField($value['order_code'],'order_code',"*");
                $orderInfo = array(
                    'orderCode'=>$order['order_code'],
                    'orderType' => $order['order_mode_type'],
                    'warehouseCode' => $order['warehouse_code'],
                    'trackingNumber' => $shipOrder['order_code'],
                    'pp_barcode'=>$shipOrder['pp_barcode'],
                    'so_weight'=>$shipOrder['so_weight'],
                    //'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'],
                    'Remark' => $order['remark'],
                    'OrderDetail' => $orderDetail,
                );
                $orderDataArr[] = $orderInfo;
            }
        }
        $result['ask'] = 1;
        $result['orderDataArr'] = $orderDataArr;
        return $result;
    }

    public function getOrderTracking($request){
        $this->common($request);
        $orderRow = Service_Orders::getByField($this->_paramterArr['order_code'],"order_code","*");
        if(empty($orderRow)) return $result = array('ask'=>'0');
        $trackingInfo = Service_ShipOrderTracking::getByCondition(array('order_code'=>$this->_paramterArr['order_code']),'*');
        $result = array(
            'ask'=>'1',
            'order_code'=>$orderRow['order_code'],
            'order_status'=>$orderRow['order_status'],
            'trackingInfo'=>$trackingInfo
        );
        return $result;
    }

    public function createShipperAddress($request){
        $this->common($request);
        $result = array(
            'ask' => '0',
            'message' => '',
        );
        $customer_code = $this->_paramterArr['customer_code'];
        $password = $this->_paramterArr['password'];
        $checkCustomer = Service_Customer::getByCondition(array('customer_code'=>$customer_code,'customer_password'=>$password),"count(*)");
        if(!$checkCustomer){
            $result['ask'] = "0";
            $result['message'] = "帐号或密码有误".$password;
            return $result;
        }
        /*$filePath = APPLICATION_PATH.'/../data/log/'.'CreateSwapOrder111.txt';
        if(!file_exists($filePath)){
            $fp= fopen($filePath,"w");
            fclose($fp);
        }
        file_put_contents($filePath,var_export($this->_paramterArr),FILE_APPEND);*/
        $customerRow = Service_Customer::getByField($customer_code,"customer_code","*");
        $row = array(
            'customer_code'=>$customer_code,
            'customer_id'=>$customerRow['customer_id'],
            'cab_type'=>2,
            'cab_company'=>$this->_paramterArr['cab_company'],
            'cab_lastname'=>$this->_paramterArr['cab_lastname'],
            'cab_country_id'=>49,
            'cab_state'=>$this->_paramterArr['cab_state'],
            'cab_city'=>$this->_paramterArr['cab_city'],
            'cab_street_address1'=>$this->_paramterArr['cab_street_address1'],
            'cab_street_address2'=>$this->_paramterArr['cab_street_address2'],
            'cab_postcode'=>$this->_paramterArr['cab_postcode'],
            'cab_cell_phone'=>$this->_paramterArr['cab_cell_phone'],
            'cab_fax'=>$this->_paramterArr['cab_fax'],
            'cab_email'=>$this->_paramterArr['cab_email'],
            'cab_note'=>$this->_paramterArr['cab_note'],
        );
        $message = "";
        if($row['cab_email']==''){
            $message .= '邮箱不能为空,';
        }else if(!preg_match("/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/",$row['cab_email'])){

            $message .= '邮箱格式不对,';
        }
        if($row['cab_lastname']==''){
            $message .= '客户姓名必填,';
        }
        if($row['cab_country_id']=='253'){
            if($row['cab_state']==''||$row['cab_state']=='0'){
                $message .= '州必填,';
            }
        }
        if($row['cab_company']==''){
            $message .= '公司名必填,';
        }
        if(strlen($row['cab_company'])>30){
            $message .= '公司名长度不能大于30字符,';
        }
        if($row['cab_country_id']==''){
            $message .= '国家必填,';
        }
        if($row['cab_cell_phone']==''){
            $message .= '电话必填,';
        }
        if($row['cab_street_address1']==''){
            $message .= '地址1必填,';
        }
        if($row['cab_city']==''){
            $message .= '城市必填,';
        }
        if($row['cab_state']==''){
            $message .= '省份必填,';
        }

        if(preg_match("/[\x7f-\xff]/",$row['cab_lastname'])) {
            $message .= '客户姓名不能包含中文,';
        }
        if(preg_match("/[\x7f-\xff]/",$row['cab_company'])) {
            $message .= '公司名不能包含中文,';
        }
        if(preg_match("/[\x7f-\xff]/",$row['cab_state'])) {
            $message .= '省份不能包含中文,';
        }
        if(preg_match("/[\x7f-\xff]/",$row['cab_city'])) {
            $message .= '城市不能包含中文,';
        }
        if(preg_match("/[\x7f-\xff]/",$row['cab_street_address1'])) {
            $message .= '地址1不能包含中文,';
        }
        if($message!=""){
            $result['ask'] = "0";
            $result['message'] = $message;
            return $result;
        }
        $condition = array(
            'customer_code'=>$customer_code,
            'cab_type'=>2,
        );
        $existAddress = Service_CustomerAddressBook::getByCondition($condition,"*");
        if(!empty($existAddress)){
            Service_CustomerAddressBook::update($row,$existAddress[0]['cab_id'],"cab_id");
            $result['ask'] = "1";
            $result['message'] = "发件人地址已更新成功";
            return $result;
        }else{
            Service_CustomerAddressBook::add($row);
            $result['ask'] = "1";
            $result['message'] = "发件人地址已添加";
            return $result;
        }
    }

    public function interceptOrder($request){
        $this->common($request);
        $result = array(
            'ask' => '0',
            'message' => '',
        );
        $customer_code = $this->_paramterArr['customerCode'];
        //$password = $this->_paramterArr['password'];
        $orderCode = $this->_paramterArr['orderCode'];
        $reason = $this->_paramterArr['reason'];
        /*$checkCustomer = Service_Customer::getByCondition(array('customer_code'=>$customer_code,'customer_password'=>$password),"count(*)");
        if(!$checkCustomer){
            $result['ask'] = "0";
            $result['message'] = "帐号或密码有误";
            return $result;
        }*/
        $orderRow = Service_Orders::getByField($orderCode,"order_code","*");
        if(empty($orderRow)){
            $result['message'] = "订单号[".$orderCode."]不存在";
            return $result;
        }else{
            if($orderRow['customer_code']!=$customer_code){
                $result['message'] = "订单[".$orderCode."]不属于客户".$customer_code;
                return $result;
            }
            if($orderRow['order_status']!="4"){
                $result['message'] = "订单[".$orderCode."]不是已提交状态";
                return $result;
            }
        }
        $data = array(
            'order_code'=>$orderCode,
            'intercept_reason'=>$reason,
        );
        $result = Service_OrderProcess::interceptTranslate($data,$this->_customer['customer_id']);
        if($result['ask']=="0"){
            $result['interceptStatus'] = "F";
        }else{
            switch ($orderRow['order_status']) {
                case "4":
                    $result['interceptStatus'] = "S";
                    break;
                case "5":
                case "6":
                case "7":
                    $result['interceptStatus'] = "W";
                    break;
                default:
                    $result['interceptStatus'] = "F";
            }
        }
        return  $result;
        //exit;
        /*

        die(Zend_Json::encode($result));*/
    }

    public function deleteAsn($request){
        $this->common($request);
        $result = array(
            'ask' => '0',
            'message' => '入区单删除成功',
        );
        $customer_code = $this->_paramterArr['customerCode'];
        $receivingCode = $this->_paramterArr['receivingCode'];
        $reason = $this->_paramterArr['reason'];
        $receivingRow = Service_Receiving::getByField($receivingCode,'receiving_code',"*");
        if(empty($receivingRow)){
            $result['message'] = "入区单[".$receivingCode."]不存在";
            return $result;
        }
        if($receivingRow['customer_code']!=$customer_code){
            $result['message'] = "入区单[".$receivingCode."]不属于客户".$customer_code;
            return $result;
        }
        if($receivingRow['trade_mode']!="0110"){
            $result['message'] = "入区单[".$receivingCode."]不是0110";
            return $result;
        }
        $asnStatus = Service_AsnProccess::getAsnStatus();
        if(!in_array($receivingRow['receiving_status'],array('1','2','3','4'))){
            $result['message'] = "入区单[".$receivingCode."]是".$asnStatus[$receivingRow['receiving_status']]."状态,不能删除";
            return $result;
        }
        $result = Service_AsnProccess::deleteAsnFromFxInterface($receivingCode,$reason);
        return $result;
    }

    public function getIMEICode($request){
        $this->common($request);
        $result = array(
            'ask' => '0',
            'message' => '',
            'IMEIData'=>"",
        );
        $customer_code = $this->_paramterArr['customerCode'];
        $order_code = $this->_paramterArr['orderCode'];
        $orderRow = Service_Orders::getByField($order_code,"order_code","*");
        if(empty($orderRow)){
            $result['message'] = "订单号[".$order_code."]不存在";
            return $result;
        }else{
            if($orderRow['customer_code']!=$customer_code){
                $result['message'] = "订单[".$order_code."]不属于客户".$customer_code;
                return $result;
            }
        }
        $orderIMEI = Service_OrderImei::getByCondition(array('order_code'=>$order_code),"*");
        if(empty($orderIMEI)){
            $result['ask'] = 1;
            $result['message'] = "订单[".$order_code."]没有IMEI系列号!";
            return $result;
        }else{
            $result['ask'] = 1;
            $result['IMEIData'] = $orderIMEI;
            return $result;
        }
    }
    
    public function getAvailableQuantity( $request ) {
        $this->common($request);
        $result = array(
            'ask' => '0',
            'message' => '',
        );
        $sku = $this->_paramterArr['sku'];
        $data = $tmpData = array();

        if( !empty( $sku ) ) {
            if( is_string( $sku ) ) {
                $sku = array( $sku );
            }
            $condition = array( 'customer_code' => $this->_customer['customer_code'] );
            foreach( $sku as $value ) {
                $tmpValue = trim( $value );
                if( $tmpValue === '' ) continue;

                $condition['product_sku'] = $tmpValue;
                $product = Service_Product::getByCondition( $condition );
                if( empty( $product ) ) continue;

                $iCondition = array(
                    'customer_code' => $this->_customer['customer_code'],
                    'product_id' => $product[0]['product_id'],
                    'ib_status' => 1,
                );
                //暂时不做分页循环取
                $inventories = Service_InventoryBatch::getByCondition( $iCondition );

                $quantity = 0;
                $productCache[ $product[0]['product_id'] ] = $product[0];
                foreach( $inventories as $inventory ) {
                    //统计出货记录
                    $condition = array(
                        'ib_id' => $inventory['ib_id'],
                    );
                    $sumQty = Service_InventoryBatchOutbound::getByCondition( $condition, 'sum(ibo_quantity) as sum_qty');
                    //查询来源产品
                    if( $inventory['from_product_id'] != 0 ) {
                        if( !isset( $tmpData[ $inventory['from_product_id'] ] ) ) {
                            $tmpProduct = Service_Product::getByField( $inventory['from_product_id'], 'product_id');
                            $tmpData[ $inventory['from_product_id'] ] = array(
                                'customerCode' => $tmpProduct['customer_code'],
                                'sku' => $tmpValue,
                                'quantity' => -($sumQty[0]['sum_qty']),
                                'originalSku'=> $tmpProduct['product_sku'],
                            );
                        }
                        $tmpData[ $inventory['from_product_id'] ]['quantity'] += $inventory['ib_quantity'];
                    } else {
                        if( !isset( $tmpData[ $product[0]['product_id'] ] ) ) {
                            $tmpData[  $product[0]['product_id'] ] = array(
                                'customerCode' => $product[0]['customer_code'],
                                'sku' => $product[0]['product_sku'],
                                'quantity' => -($sumQty[0]['sum_qty']),
                                'originalSku'=> $product[0]['product_sku'],
                            );
                        }
                        $tmpData[  $product[0]['product_id'] ]['quantity'] += $inventory['ib_quantity'];
                    }
                }
            }
            foreach( $tmpData as $key => $value ) {
                if( $value['quantity'] > 0 ) {
                    $data[] = $value;
                }
            }
        }
        if( !empty( $data ) ) {
            $result['ask'] = 1;
            $result['data'] = $data;
        } else {
            $result['message'] = '没有库存数据';
        }
        return $result;
    }

    public function getOrderBySbCode($request){
        //$this->common($request);
        $this->_paramterArr = Common_Common::objectToArray($request);//对象转数组
        $result = array(
            'ask' => '0',
            'message' => '',
            'orderCode'=>'',
        );
        $sbCode = $this->_paramterArr['sbCode'];
        //$customer_code = $this->_paramterArr['customerCode'];
        $shipBatch = Service_ShipBatch::getByField($sbCode,'sb_code',"*");
        if(empty($shipBatch)){
            $result['message'] = '出货总单['.$sbCode.']不存在';
        }else{
            $shipBatchDetail  = Service_ShipBatchDetail::getByCondition(array('sb_code'=>$sbCode),"*");
            $orderCodeArr = array();
            if(!empty($shipBatchDetail)){
                foreach($shipBatchDetail as $sbd){
                    $outboundDetail = Service_OutboundBagDetail::getByCondition(array('ob_no'=>$sbd['ob_no']),"*");
                    if(!empty($outboundDetail)){
                        foreach($outboundDetail as $obd){
                            $orderCodeArr[] = $obd['order_code'];
                        }
                    }
                }
            }
            $result['ask'] = 1;
            $result['orderCode'] = $orderCodeArr;
        }
        return $result;
    }

}
