<?php
/**
 * Created by JetBrains PhpStorm.
 * User: user
 * Date: 13-8-3
 * Time: 下午6:53
 * To change this template use File | Settings | File Templates.
 */
class Order_TestController extends Ec_Controller_Action
{
    public function preDispatch()
    {
        $this->tplDirectory = "order/views/default/";
    }

    public function offshelfAction(){//下架
        set_time_limit(0);
        for($i=0;$i<400000;$i++){
            $printType=0;
            $pickType=0;
            $offShelfQty=1;
            $pickTypeArray = array(
                'printType' => $printType,
                'type' => $pickType,
                'data' => array('4'),
            );
            $warehouseId = Service_User::getUserWarehouseId();
            $obj = new Service_OrderProcess();
            $result = $obj->batchPickupTransaction($pickTypeArray, $warehouseId);
            echo "offShelfcode ".$result['pick'][0]['pickCode']." create Success!<br>";
        }
    }

    public function packingAction(){
        set_time_limit(0);
        for($i=0;$i<2;$i++){
            $pickingRow = Service_Picking::getByCondition(
                array(
                    'picking_status'=>'0',
                    'picking_type'=>'0'
                ),$type = '*', $pageSize = 1, $page = 1, $order = "picking_id desc");
            echo "<pre>";
            var_dump( $pickingRow);
            echo "</pre>";
            $pickingCode = $pickingRow[0]['picking_code'];
            $packObj = new Service_PackProcess();
            $return = $packObj->getPickingByPickingCode($pickingCode,null, null, 0);
            echo "<pre>";
            var_dump($return);
            echo "</pre>";
            //$return['data']['']
            //$pickingCode = $return['pickingCode'];
            //$pickingDetail = Service_PickingDetail::getByCondition(array('picking_code'=>$pickingCode),"*",$pageSize="0",$page=1);
            /*foreach($pickingDetail as $key=>$value){
                $pickingCode = $pickingCode;
                $packageCode = "";
                $productBarcode = $value['product_barcode'];
                $packObj = new Service_PackProcess();
                $return = $packObj->getPickingByPickingCode($pickingCode,$productBarcode, null, 0);
                $packObj = new Service_PackProcess();
                $return = $packObj->assignOrderTransaction($pickingCode,$packageCode,$productBarcode,null);
                echo "<pre>";
                var_dump($return);
                echo "</pre>";
            }
            echo $pickingCode." packing complete</br>";*/
        }
    }

    public function qcAction(){
        header("Content-type:text/html;charset=utf-8");
        set_time_limit(0);
        for($i=0;$i<20000;$i++){
            $qcRow = Service_QualityControl::getByCondition(array('qc_status'=>'0'),"*",1,1,"qc_id desc");
            $qcCode = $qcRow[0]['qc_code'];
            $qcId = $qcRow[0]['qc_id'];
            $qcObj= new Service_QualityControlProcess();
            $result=$qcObj->getQcOrder($qcCode);
            if($result['state']){
                $qcData=$result['data'];
                $params = array(
                    "userId"=>$qcData['other']['qc_user_id'],
                    "qcId"=>$qcData['order']['qc_id'],
                    "productId"=>$qcData['order']['product_id'],
                    "productBarcode"=>$qcData['order']['product_barcode'],
                    "customerCode"=>$qcData['order']['customer_code'],
                    "productCategoryId"=>$qcData['order']['product']['pc_id'],
                    "firstReceived"=>$qcData['order']['product']['product_receive_status'],
                    "productWeight"=>rand(1,25)/10,
                    "receivedQty"=>rand(1,5),
                    "problemQty"=>'0',
                    "noLabelQty"=>'0',
                    "shelf"=>'',
                    "remark"=>'qc Test '.$i,
                );
                if(!$params['firstReceived']){
                    $params['product'] = array(
                        "category"=>'18',
                        'package'=>rand(1,5),
                        'declaredValue'=>rand(100,500),
                        'length'=>rand(10,20),
                        'width'=>rand(10,20),
                        'height'=>rand(10,20)
                    );
                }
                $qcObj= new Service_QualityControlProcess();
                $result=$qcObj->submit($params);
                //echo "<pre>";
                //var_dump($result);
                //echo "</pre>";
                if($result['state']=="1"){
                    echo "qc_code ".$qcCode." has check complete!</br>";
                }else{
                    echo "qc_code ".$qcCode." check failure!</br>";
                }
            }
        }
    }
    public function recAction(){
        set_time_limit(0);
        for($i=0;$i<20000;$i++){
            $receivingRow = Service_Receiving::getByCondition(array('receiving_status'=>4),"*",1,1,"receiving_id desc");
            $receivingCode = $receivingRow[0]['receiving_code'];
            $detail = Service_ReceivingDetail::getByCondition(array('receiving_code'=>$receivingCode),"*");
            $rdArr = array();
            foreach($detail as $k=>$v){
                $rdArr[] = $v['rd_id'];
            }
            $obj= new Service_ReceivingProcess();
            $return= $obj->submitReceived($rdArr);
            if($return['state']=="1"){
                $str = "";
                foreach($return['code'] as $val){
                    $str.=$val." ";
                }
                echo "Asncode ".$receivingCode." receivied Success!create new qc_code ".$str."</br>";
            }
        }
    }
    public function epacketAction(){
        $orderRow = Service_Orders::getByCondition(array(),"*",2,1,"order_id desc");
        $order = $orderRow[0];
        $receivingAddress = Service_OrderAddressBook::getByField($order['order_id'],'order_id',"*");
        $country = Service_Country::getByField($receivingAddress["oab_country_id"],"country_id","*");
        $shipToAddress = array(
            'email' => $receivingAddress['oab_email'],
            'company' => $receivingAddress['oab_company'],
            'contact' => "Andy Liu",
            'phone' => $receivingAddress['oab_cell_phone'],
            'street' => $receivingAddress['oab_street_address1'],
            'city' => $receivingAddress['oab_city'],
            'province' => $receivingAddress['oab_state'],
            'postcode' => $receivingAddress['oab_postcode'],
            'country' => $country['country_name_en'],
            'country_code' => $country['country_code'],
        );
        //echo "<pre>";
        //var_dump($shipToAddress);
        //echo "</pre>";
        $shipFromAddress = array(
            'contact' => 'Danny Zhou',
            'company' => 'cargo company',
            'street' => 'JinTian Road No.8086 AnLian A 25 Floor',
            'district' => 'Futian district',
            'city' => 'shenzhen city',
            'province' => 'GUANGDONG',
            'postcode' => '518026',
            'country' => 'CHINA',
            'email' => 'Dannyzhou@cargofe.com.cn',
            'mobile' => '13594268155',
        );
        $returnAddress = array(
            'company' => 'Cargo',     //公司
            'country' => "中国",     //国家 中国
            'province' => '广东',   //省
            'city' => 'shenzhen city',           //城市
            'district' => 'Futian district',   //区
            'street' => 'JinTian Road No.8086 AnLian A 25 Floor',       //街道
            'postcode' => '518026',   //邮编
            'contact' => 'Danny Murphy',     //联系人
        );
        $pickUpAddress = array(
            'email' => 'Dannyzhou@cargofe.com.cn',
            'company' => 'cargo company',
            'country' => '中国',
            'province' => '440000',
            'city' => '440300',
            'district' => '440304',
            'street' => 'JinTian Road',
            'postcode' => '518026',
            'contact' => 'Danny Zhou',
            'mobile' => '0755-5180256',
            'phone' => '13594268155',
        );

        $epacketService = Service_EpacketApi::getInstance();
        $pickUpType = 0;
        $epacketService->setPickUpType($pickUpType);

        $appUserId = "abing.967";
        $appPassword = "467813WCPT3NSGPMROI29DCWSWO3LFGM26IMW5ZPME32WPXMDMNQ6O201310946";

        $epacketService->setHeader($order['order_code'],$appUserId,$appPassword,$appUserId);
        $epacketService->verifyUser();

        $epacketService->setShipFromAddress($shipFromAddress);
        $epacketService->setShipToAddress($shipToAddress);
        $epacketService->setReturnAddress($returnAddress);
        if($pickUpType==0){
            $epacketService->setPickUpAddress($pickUpAddress);
        }
        $orderProduct = Service_OrderProduct::getByCondition(array("order_code"=>$order['order_code']),"*");
        foreach($orderProduct as $k=>$v){
            $product = Service_Product::getByField($v['product_id'],"product_id","*");
            $epacketItem = array(
                'skuid' => $product['product_sku'],
                'weight' => 0.1,
                'customs_title_cn' => $product['product_title'],
                'customs_title_en' => $product['product_title_en'],
                'declared_value' => $product['product_declared_value'],
                'currency_code' => '',
                'ebay_email' => '',
                'ebay_buyer_id' => 'joshuaw7',
                'ebay_item_id' => '181177693791',
                'ebay_item_title' => '',
                'ebay_message' => '',
                'ebay_site_id' => '',
                'ebay_transaction_id' => '1051636790008',
                'note' => '',
                'order_sales_record_number' => '',
                'payment_date' =>'2013-08-07',
                'paypal_email' => '',
                'paypal_message' => '',
                'posted_qty' => $v['op_quantity'],
                'received_amount' =>$v['op_quantity']*$product['product_declared_value'],
                'sales_record_number' => '',
                'sold_date' => '2013-08-05',
                'sold_price' => $product['product_sales_value'],
                'sold_qty' => $v['op_quantity'],
            );
            $epacketService->addItem($epacketItem);
        }

        $result = $epacketService->AddPackage();
        //echo "<pre>";
        //var_dump($result);
        //echo "<pre>";
        if (strtolower($result->AddAPACShippingPackageResult->Ack) == 'success') {

            $confirmEpacket = $epacketService->confirmPackage(array('track_number' => $result->AddAPACShippingPackageResult->TrackCode));
            if (strtolower($confirmEpacket->ConfirmAPACShippingPackageResult->Ack) == 'success') {
                $TrackDetail = array(
                    'PageSize'=>'0',
                    'TrackCode'=>$result->AddAPACShippingPackageResult->TrackCode,
                );
                $label = $epacketService->getShippingLabel($TrackDetail);

                $exist = Service_OrderPdf::getByField($order['order_code'],"order_code","*");

                $file = APPLICATION_PATH.'/../data/pdf/'.$order['order_code'].".pdf";
                echo "file=".$file."</br>";
                if(!file_exists($file)){
                    $fp=fopen($file, "w+");
                }
                file_put_contents($file,$label);

                if(empty($exist)){
                    $row = array(
                        'order_code'=>$order['order_code'],
                        'order_pdf'=>$label
                    );
                    $opdfid =  Service_OrderPdf::add($row);
                }else{
                    $row = array(
                        'order_pdf'=>$label
                    );
                    Service_OrderPdf::update($row,$order['order_code'],'order_code');
                }
                $ret = array(
                    'ask'=>'1',
                    'message'=>'成功获取pdf标签'
                );
                die(json_encode($ret));
            }
        } else {
            $getTrackCodeArray = array(
                'ebay_item_id' => '181177693791',
                'ebay_transaction_id' => '1051636790008',
            );
            $trackNumberResult = $epacketService->getTrackCode($getTrackCodeArray);
            if (strtolower($trackNumberResult->GetAPACShippingTrackCodeResult->Ack) == 'success') {
                $TrackDetail = array(
                    'PageSize'=>1,
                    'track_number'=>$trackNumberResult->GetAPACShippingTrackCodeResult->TrackCode,
                );
                $label = $epacketService->getShippingLabel($TrackDetail);
                $exist = Service_OrderPdf::getByField($order['order_code'],"order_code","*");
                $file = APPLICATION_PATH.'/../data/pdf/'.$order['order_code'].".pdf";
                echo "file=".$file."</br>";
                if(!file_exists($file)){
                    $fp=fopen($file, "w+");
                }
                file_put_contents($file,$label);
                if(empty($exist)){
                    $row = array(
                        'order_code'=>$order['order_code'],
                        'order_pdf'=>$label
                    );
                    $opdfid =  Service_OrderPdf::add($row);
                }else{
                    $row = array(
                        'order_pdf'=>$label
                    );
                    var_dump($row);
                    Service_OrderPdf::update($row,$order['order_code'],'order_code');
                }
                $ret = array(
                    'ask'=>'1',
                    'message'=>'成功获取pdf标签'
                );
                die(json_encode($ret));
            }else{
                $ret = array(
                    'ask'=>'0',
                    'message'=>'获取pdf标签失败'
                );
                die(json_encode($ret));
            }
        }
    }

    public function getpdfAction(){
        $v = Service_Orders::getByField("SOE88880009483","order_code","*");
        $epaService = new Service_EpacketWebService();
        $labelResult = $epaService->getOneLableByMailnum($v['ref_tracking_number']);
        $zipFileStream = file_get_contents($labelResult['url'],false,null);
        $zipFileName = APPLICATION_PATH.'/../data/pdf/EUB/'.$v['order_code'].".zip";
        file_put_contents($zipFileName,$zipFileStream);
        $zip = new ZipArchive;
        if ($zip->open($zipFileName) === TRUE)
        {
            $zip->extractTo(APPLICATION_PATH.'/../data/pdf/EUB/');
            $pdfFileName = $zip->getNameIndex(0);
            $zip->close();
        }
        rename(APPLICATION_PATH.'/../data/pdf/EUB/'.$pdfFileName,APPLICATION_PATH.'/../data/pdf/EUB/justfortest.pdf');
        unlink($zipFileName);
        echo "订单".$v['order_code']."获取单号地址标签成功\n";
    }
    public function testApiAction(){

    }

    public function submitToEpacketAction(){
        $orderCode='SOE88880007553';
        $v = Service_Orders::getByField($orderCode,"order_code","*");
        $orderXml = Service_EpacketWebService::getOrderContent($orderCode);
        $epaService = new Service_EpacketWebService();
        $result = $epaService->validate($orderXml);
        if($result['status']=="success"){
            $ret = $epaService->createEpacketOrder($orderXml);
            if(isset($ret['mailnum'])&&$ret['mailnum']!=""){
                $updateOrder = array(
                    'ref_tracking_number'=>$ret['mailnum']
                );
                Service_Orders::update($updateOrder,$v['order_id'],"order_id");
                $labelResult = $epaService->getOneLableByMailnum($ret['mailnum']);
                $zipFileStream = file_get_contents($labelResult['url'],false,null);
                $zipFileName = APPLICATION_PATH.'/../data/pdf/EUB/'.$v['order_code'].".zip";
                file_put_contents($zipFileName,$zipFileStream);
                $zip = new ZipArchive;
                if ($zip->open($zipFileName) === TRUE)
                {
                    $zip->extractTo(APPLICATION_PATH.'/../data/pdf/EUB/');
                    $pdfFileName = $zip->getNameIndex(0);
                    $zip->close();
                }
                rename(APPLICATION_PATH.'/../data/pdf/EUB/'.$pdfFileName,APPLICATION_PATH.'/../data/pdf/EUB/'.$v['order_code'].".pdf");
                unlink($zipFileName);
                echo "订单".$v['order_code']."获取单号".$ret['mailnum']."成功\n";
            }else{
                echo "订单".$v['order_code']."提交出错:".$ret['description']."\n";
            }
        }else{
            echo "订单".$v['order_code']."提交出错:".$result['description']."\n";
        }
    }
    public function importTrackingAction(){
        set_time_limit(0);
        $full_path = APPLICATION_PATH.'/../data/file/20140609.xls';
        $resultArray = Common_Upload::readEXCEL($full_path);
        unlink($full_path);
        foreach($resultArray as $key=>$value){
            $serviceTracking =array(
                'order_code'=>'',
                'warehouse_id'=>'1',
                'stn_code'=>$value[0],
                'sm_code'=>'BH-MPPG',
                'stn_status'=>'0',
                'stn_add_time'=>date("Y-m-d H:i:s"),
                'stn_update_time'=>date("Y-m-d H:i:s"),
            );
            $id = Service_ServiceTrackingNumber::add($serviceTracking);
            if($id){
                echo "行".$id."插入成功</br>";
            }
        }
    }
    public function getEubAddressAction(){
        //$orderCode = $this->_request->getParam("orderCode","");
        $orderCode = "SOE88880016205";
        $epaService = new Service_EpacketWebService();
        $orderXml = Service_EpacketWebService::getOrderContent($orderCode);
        $filePath = APPLICATION_PATH.'/../data/SOE88880016205.xml';
        if(!file_exists($filePath)){
            $fp= fopen($filePath,"w");
            fclose($fp);
        }
        file_put_contents($filePath,$orderXml,FILE_APPEND);
        exit;
        $result = $epaService->validate($orderXml);

        if($result['status']=="success"){
            $ret = $epaService->createEpacketOrder($orderXml);
            if(isset($ret['mailnum'])&&$ret['mailnum']!=""){
                $updateOrder = array(
                    'ref_tracking_number'=>$ret['mailnum']
                );
                Service_Orders::update($updateOrder,$orderCode,"order_code");
                $labelResult = $epaService->getOneLableByMailnum($ret['mailnum']);
                $zipFileStream = file_get_contents($labelResult['url'],false,null);
                $zipFileName = APPLICATION_PATH.'/../data/pdf/EUB/'.$orderCode.".zip";
                file_put_contents($zipFileName,$zipFileStream);
                $zip = new ZipArchive;
                if ($zip->open($zipFileName) === TRUE)
                {
                    $zip->extractTo(APPLICATION_PATH.'/../data/pdf/EUB/');
                    $pdfFileName = $zip->getNameIndex(0);
                    $zip->close();
                }
                rename(APPLICATION_PATH.'/../data/pdf/EUB/'.$pdfFileName,APPLICATION_PATH.'/../data/pdf/EUB/'.$orderCode.".pdf");
                unlink($zipFileName);
                echo "订单".$orderCode."获取单号".$ret['mailnum']."成功\n";
            }else{
                echo "订单".$orderCode."提交出错1:".$ret['description']."\n";
            }
        }else{
            echo "订单".$orderCode."提交出错2:".$result['description']."\n";
        }

        /*$labelResult = $epaService->getOneLableByMailnum('LN353372863CN');
        $zipFileStream = file_get_contents($labelResult['url'],false,null);
        $zipFileName = APPLICATION_PATH.'/../data/pdf/EUB/SOE88880006980'.".zip";
        file_put_contents($zipFileName,$zipFileStream);
        $zip = new ZipArchive;
        if ($zip->open($zipFileName) === TRUE)
        {
            $zip->extractTo(APPLICATION_PATH.'/../data/pdf/EUB/');
            $pdfFileName = $zip->getNameIndex(0);
            $zip->close();
        }
        rename(APPLICATION_PATH.'/../data/pdf/EUB/'.$pdfFileName,APPLICATION_PATH.'/../data/pdf/EUB/SOE88880006980'.".pdf");
        unlink($zipFileName);
        echo "订单SOE88880006980获取单号地址标签成功\n";*/
    }
    public function insertTrackingAction(){
        set_time_limit(0);
        //$file = APPLICATION_PATH.'/../data/20140702.txt';
        $trackingArr=file($file);
        foreach($trackingArr as $value){
            $shipOrderTracking = array(
                'order_code'=>'',
                'warehouse_id'=>'1',
                'stn_code'=>$value,
                'sm_code'=>'HKPG',
                'stn_status'=>'0',
                'stn_add_time'=>date("Y-m-d H:i:s"),
                'stn_update_time'=>date("Y-m-d H:i:s")
            );
            $sid = Service_ServiceTrackingNumber::add($shipOrderTracking);
            if($sid){
                echo $value."保存成功!<br>";
            }
        }
    }

    public function connectFtpAction(){

        $strServer = "dhl-sftp01.rze.deutschepost.de";
        $strServerPort = "22";
        $strServerUsername = "CRG";
        $strServerPassword = "Liit0kei";

        $resConnection = ssh2_connect($strServer,$strServerPort);
        if($resConnection){
            echo "connect success!";
        }else{
            die("can't connect!");
        }

        if(ssh2_auth_password($resConnection, $strServerUsername, $strServerPassword)){
            $resSFTP = ssh2_sftp($resConnection);
            $filePath = ssh2_sftp_realpath($resSFTP,"/CRG/");
            echo "filePath=".$filePath."</br>";
            //$destination_file = "/CRG/sendOrders.log";
            $source_file = APPLICATION_PATH.'/../data/log/sendOrders.log';
            /*$upload = ssh2_scp_send($resConnection,$source_file, $destination_file,0644);
            if($upload){
                echo "upload file success!</br>";
            }
            $rec_destination_file = APPLICATION_PATH.'/../data/log/efile.log';
            $download = ssh2_scp_recv($resConnection,$destination_file,$rec_destination_file);
            if($download){
                echo "download file success!</br>";
            }*/

            $opts = array(
                'http'=>array(
                    'method'=>"GET",
                    'timeout'=>60,
                )
            );
            $context = stream_context_create($opts);

            if(!copy($source_file,"ssh2.sftp://{$resSFTP}/CRG/text2.log")) {
                echo 'upload failed</br>';
            }else{
                echo "upload file Success!<br>";
            }
            if(!copy("ssh2.sftp://{$resSFTP}/CRG/text.log",APPLICATION_PATH.'/../data/log/efile2.log')){
                echo "download failed<br>";
            }else{
                echo "download file Success!<br>";
            }

        } else {
            echo "Unable to authenticate on server";
        }
        exit;

    }

    public function  exportExcelAction(){
        header('Pragma:public');
        header('Content-Type:application/x-msexecl;name=E8888.xls' );
        header("Content-Disposition:inline;filename=E8888.xls");

        echo "<table border='1'>";
        echo "<tr>";
        echo "<td>产品唯一识别码</td>";
        echo "<td>在途</td>";
        echo "<td>到货</td>";
        echo "<td>可用</td>";
        echo "<td>不良品</td>";
        echo "<td>冻结</td>";
        echo "<td>出库</td>";
        echo "</tr>";

        $condition1 = array(
            'customer_code'=>'E8888',
            'product_title'=>'LED电源',
        );

        $product = Service_Product::getByCondition($condition1,"*");
        foreach($product as $k=>$v){
            $condition = array(
                'product_id'=>$v['product_id']
            );
            $inventory = Service_ProductInventory::getByCondition($condition,"count(*)");
            $pageSize = 20;
            $totalPage = ceil($inventory/$pageSize);
            for($page=1;$page<=$totalPage;$page++){
                $inventoryList = Service_ProductInventory::getByCondition($condition,"*",$pageSize,$page,"");
                foreach($inventoryList as $key=>$value){
                    echo "<tr>";
                    echo "<td>".$value['product_barcode']."</td>";
                    echo "<td>".$value['pi_onway']."</td>";
                    echo "<td>".$value['pi_pending']."</td>";
                    echo "<td>".$value['pi_sellable']."</td>";
                    echo "<td>".$value['pi_unsellable']."</td>";
                    echo "<td>".$value['pi_reserved']."</td>";
                    echo "<td>".$value['pi_shipped']."</td>";
                    echo "</tr>";
                }
            }

        }
        echo "</table>";
    }

    public function exportTxtAction(){
        error_reporting(E_ALL);
        $fileName = "520678_20160520221554_PPS.txt";
        $filePath = APPLICATION_PATH . '/../data/Efile2015/'.$fileName;
        if(!file_exists($filePath)){
            $fp= fopen($filePath,"w");
            fclose($fp);
        }
        $shipBatchCodeArr = array(
            //'BHC140000143',
            //'BHC140000144',
            //'BHC140000145',
            //'BHC140000146',
            //'BHC140000147',
            'BHC160005323'
        );
        foreach($shipBatchCodeArr as $sb_code){
            $ShipBatchDetail = Service_ShipBatchDetail::getByCondition(array('sb_code'=>$sb_code),"*");
            foreach($ShipBatchDetail as $key=>$value){
                $obd = Service_OutboundBagDetail::getByCondition(array('ob_no'=>$value['ob_no']),"*");
                foreach($obd as $k=>$v){
                    $orderRow = Service_Orders::getByField($v['order_code'],"order_code","*");

                    if($orderRow['sm_code']=="CJ-DGMG"){
                        $orderReceiptAddress = Service_OrderAddressBook::getByCondition(array("order_code"=>$orderRow['order_code'],'oab_type'=>'0'),"*");
                        $shipOrder = Service_ShipOrder::getByField($orderRow['order_code'],"order_code","*");
                        $country = Service_Country::getByField($orderReceiptAddress[0]['oab_country_id'],'country_id',"*");
                        $ParcelContent = "";
                        $orderProduct = Service_OrderProduct::getByCondition(array('order_code'=>$orderRow['order_code']),"*");
                        //$op_declared_value = 0;
                        $address1 = str_replace(PHP_EOL, '',$orderReceiptAddress[0]['oab_street_address1']);
                        $address2 = str_replace(PHP_EOL, '',$orderReceiptAddress[0]['oab_street_address2']);
                        $totalDeclareValue = 0;
                        foreach($orderProduct as $op){
                            $totalDeclareValue+=$op['op_purpose_declared_value']*$op['op_quantity'];
                        }
                        foreach($orderProduct as $opk=>$opv){
                            $product = Service_Product::getByField($opv['product_id'],"product_id","*");

                            $content = "520678|".$shipOrder['tracking_number']."|".$orderReceiptAddress[0]['oab_firstname']."|".$address1."|".$address2."||".$orderReceiptAddress[0]['oab_city']."|".$orderReceiptAddress[0]['oab_state']."|".$orderReceiptAddress[0]['oab_postcode']."|".$orderReceiptAddress[0]['oab_cell_phone']."|".$orderReceiptAddress[0]['oab_email']."|".$country['country_code']."|".$country['country_name_en']."|CN|".$ParcelContent."|".$totalDeclareValue."|".($shipOrder['so_weight']*1000)."||".$opv['op_quantity']."|".$product['product_sku']."|".$ParcelContent."|".$opv['op_purpose_declared_value']."|||||USD||||PPS|||DDU||||".$shipOrder['tracking_number']."||\n";
                            file_put_contents($filePath,$content,FILE_APPEND);
                        }
                    }
                }
            }
        }

    }

    public function sendEfileAction(){
        //die("XXXX");
        $strServer = "dhl-sftp01.rze.deutschepost.de";
        $strServerPort = "22";
        $strServerUsername = "CRG";
        $strServerPassword = "Liit0kei";

        $resConnection = ssh2_connect($strServer, $strServerPort);
        if(!$resConnection) die("Unable connect sftp on ".date("Y-m-d H:i:s")."\n");
        if(ssh2_auth_password($resConnection, $strServerUsername, $strServerPassword)){
            $resSFTP = ssh2_sftp($resConnection);

            $opts = array(
                'http'=>array(
                    'method'=>"GET",
                    'timeout'=>120,
                )
            );
            /*if(ssh2_sftp_unlink($resSFTP, "ssh2.sftp://{$resSFTP}/CRG/520678_20140825150049.txt")){
                $source_file =  APPLICATION_PATH . '/../data/Efile/520678_20140825(2).txt';
                if(file_exists($source_file)){
                    if(!copy($source_file,"ssh2.sftp://{$resSFTP}/CRG/520678_20140825(2).txt")) {
                        echo 'upload failed</br>';
                    }else{
                        echo "upload file Success on ".date("Y-m-d H:i:s")."\n";
                    }
                }
            }else{
                echo "delete fail";
            }*/
            $source_file =  APPLICATION_PATH . '/../data/Efile2015/520678_20150715215220.txt';
            if(file_exists($source_file)){
                if(!copy($source_file,"ssh2.sftp://{$resSFTP}/CRG/520678_20150715215220.txt")) {
                    echo 'upload failed</br>';
                }else{
                    echo "upload file Success on ".date("Y-m-d H:i:s")."\n";
                }
            }
        }else{
            echo "Unable to authenticate on server on ".date("Y-m-d H:i:s")."\n";
        }
    }

    public function deleteEfileAction(){
        //ssh2_sftp_unlink();
        $fileArr = array(
            '520678_20140627104349.txt',
            '520678_20140627115520.txt',
            '520678_20140628111846.txt',
            '520678_20140628112851.txt',
            '520678_20140630093402.txt',
            '520678_20140630111413.txt'
        );
        $strServer = "dhl-sftp01.rze.deutschepost.de";
        $strServerPort = "22";
        $strServerUsername = "CRG";
        $strServerPassword = "Liit0kei";

        $resConnection = ssh2_connect($strServer, $strServerPort);
        if(!$resConnection) die("Unable connect sftp on ".date("Y-m-d H:i:s")."\n");
        if(ssh2_auth_password($resConnection, $strServerUsername, $strServerPassword)){
            $resSFTP = ssh2_sftp($resConnection);

            foreach($fileArr as $file){
                if(ssh2_sftp_unlink($resSFTP,"/CRG/".$file)){
                    echo $file." delete success!\n";
                }else{
                    echo $file." delete failuer!\n";
                }
            }

        }else{
            echo "Unable to authenticate on server on ".date("Y-m-d H:i:s")."\n";
        }
    }

    public function batchUpdatePriceAction(){
        $full_path = APPLICATION_PATH.'/../data/file/price20140710.xls';
        $resultArray = "";//Common_Upload::readEXCEL($full_path);
        //unlink($full_path);
        foreach($resultArray as $key=>$value){
            //echo "<pre>";
            //var_dump($value);
            //echo "<pre>";
            //continue;
            $sku = $value[0];
            //$customerCode = "E8888";
            $newPrice = $value[5];
            $condition = array(
                'product_sku'=>$sku,
                //'customer_code'=>$customerCode,
            );
            $productList = Service_Product::getByCondition($condition,"*");
            $product = $productList[0];
            $updateProduct = array(
                'product_declared_value'=>$newPrice
            );
            if(Service_Product::update($updateProduct,$product['product_id'],"product_id")){
                echo "产品".$sku." 申报价值".$value[1]."=>".$value[2]." 成功！<br>";
            }
        }
    }

    public function createTrackingAction(){
        set_time_limit(0);
        $trackingStart = "RC43000001NL ";
        $trackingEnd   = "RC43999999NL";
        $preTracking = "RC";
        $endTracking = "NL";
        for($i = 43000001;$i<=43099999;$i++){
            $A1 = substr($i,0,1);
            $A2 = substr($i,1,1);
            $A3 = substr($i,2,1);
            $A4 = substr($i,3,1);
            $A5 = substr($i,4,1);
            $A6 = substr($i,5,1);
            $A7 = substr($i,6,1);
            $A8 = substr($i,7,1);
            //echo "A1=".$A1;
            //continue;
            $total = $A1*8+$A2*6+$A3*4+$A4*2+$A5*3+$A6*5+$A7*9+$A8*7;
            $model = $total%11;
            $trackingNumber = "";
            $result = 11 - $model;
            if($result<=9&&$result>=1){
                $trackingNumber = $result;
            }else if($result==10){
                $trackingNumber = 0;
            }else{
                $trackingNumber = 5;
            }
            $stnCode = $preTracking.$i.$trackingNumber.$endTracking;
            $tracking = array(
                'order_code'=>'',
                'warehouse_id'=>'1',
                'stn_code'=>$stnCode,
                'sm_code'=>'PNLG',
                'stn_status'=>'0',
                'stn_add_time'=>date("Y-m-d H:i:s"),
                'stn_update_time'=>date("Y-m-d H:i:s"),
            );
            if($id=Service_ServiceTrackingNumber::add($tracking)){
                echo $stnCode."新增成功</br>";
            }else{
                echo $stnCode."新增失败</br>";
            }
        }
    }

    public function exportProductAction(){
        $condition = array(
            'customer_code'=>'E8888',
            'product_status'=>'1',
        );
        $productList = Service_Product::getByCondition($condition,"*");
        header('Pragma:public');
        header('Content-Type:application/x-msexecl;name=E8888product.xls' );
        header("Content-Disposition:inline;filename=E8888product.xls");
        echo "<table border='1'>";
        echo "<tr><td>SKU</td><td>重量</td><td>产品接收类型</td></tr>";
        foreach($productList as $k=>$v){
            echo "<tr>";
            echo "<td>".$v['product_sku']."</td>";
            echo "<td>".$v['product_weight']."</td>";
            if($v['product_receive_status']=="1"){
                echo "<td>已收过货产品</td>";
            }else{
                echo "<td>新产品</td>";
            }
            echo "</tr>";
        }
        echo "</table>";
    }

    public function printPdfLabelAction(){
        $full_path = APPLICATION_PATH.'/../data/file/test2.pdf';
        $url = "http://yodel.oneworldexpress.co.uk/remote/_assets/pdf/2014_08/20140820_53f41c3646a7b.pdf";
        $content = file_get_contents($url);
        if(!file_exists($full_path)){
            touch($full_path);
        }
        file_put_contents($full_path,$content,FILE_APPEND);

    }
    public function createUktlAction(){
        $v = Service_Orders::getByField('SOE01740004142',"order_code","*");
        $uktlService = new Service_UktlWebService();
        $return = $uktlService->createUktlOrder($v['order_code']);
        if($return[0]!="SUCCESS"){
            var_dump($return);
        }else{
            $pdfLabelUrl = $return[1];
            $refTrackingNumber = $return[2];
            $updateOrder = array(
                'ref_tracking_number'=>$refTrackingNumber
            );
            Service_Orders::update($updateOrder,$v['order_id'],"order_id");
            $full_path = APPLICATION_PATH.'/../data/pdf/UKTL/test.pdf';
            $content = file_get_contents($pdfLabelUrl);
            if(!file_exists($full_path)){
                touch($full_path);
            }
            file_put_contents($full_path,$content,FILE_APPEND);
        }
    }

    public function getUktlAction(){
        error_reporting(E_ALL);
        $condition = array(
            'sm_code'=>'UKTL',
            'order_status'=>4,
            'empty_ref_tracking_number'=>'1',
        );
        $total = Service_Orders::getByCondition($condition,"count(*)");
        $pageSize = 20;
        $totalPage = ceil($total/$pageSize);
        for($page=1;$page<=$totalPage;$page++){
            $orderList = Service_Orders::getByCondition($condition,'*',$pageSize,$page,'order_id desc');
            foreach($orderList as $k=>$v){
              // 数据过滤
             if ('UKTL' !== trim($v['sm_code'])
                 || 4 !== (int) $v['order_status']
                 || '' !== trim($v['ref_tracking_number'])) {
                continue ;
             }

             // 集货模式需要反推ASN单状态
             if (1 === (int) $v['order_mode_type']) {
               $receivingDetail = Service_ReceivingOrderDetail::getByCondition(array(
                 'order_code' => $v['order_code'],
               ));

               // 没有提取到数据或不是在途、收货中状态，继续下一轮
               if (empty($receivingDetail) || !in_array((int) $receivingDetail[0]['rd_status'], array(0, 1), TRUE)) {
                 continue ;
               }

               $receiving = Service_Receiving::getByField((int) $receivingDetail[0]['receiving_id'], 'receiving_id');

               // 提取不到数据或不是集货ASN或状态不在待审核、已审核、在途、收货中状态之中，继续下一轮
               if (empty($receiving) || 1 !== (int) $receiving['receive_model_type'] || !in_array((int) $receiving['receiving_status'], array(3, 4, 5, 6), TRUE)) {
                 continue ;
               }
             }

                $uktlService = new Service_UktlWebService();
                $return = $uktlService->createUktlOrder($v['order_code']);
                if($return[0]!="SUCCESS"){
                    echo $v['order_code']." get label fail reason:</br>";
                    var_dump($return);
                }else{
                    $pdfLabelUrl = $return[1];
                    $refTrackingNumber = $return[2];
                    $updateOrder = array(
                        'ref_tracking_number'=>$refTrackingNumber
                    );
                    Service_Orders::update($updateOrder,$v['order_id'],"order_id");
                    $full_path = APPLICATION_PATH.'/../data/pdf/UKTL/'.$v['order_code'].'.pdf';
                    $content = file_get_contents($pdfLabelUrl);
                    if(!file_exists($full_path)){
                        touch($full_path);
                    }
                    file_put_contents($full_path,$content,FILE_APPEND);
                }
            }
        }
        echo "[" . date('Y-m-d H:i:s') . "] End run\r\n";
    }

    public function printPdfAction(){
        require_once APPLICATION_PATH.'/../libs/tcpdf/tcpdf.php';
        require_once APPLICATION_PATH.'/../libs/fpdi/fpdi.php';
        require_once APPLICATION_PATH.'/../libs/FPDFMerge.php';

        $pdfFile = APPLICATION_PATH.'/../data/pdf/EUB/SOE88880015806.pdf';
        $tempFile = APPLICATION_PATH.'/../data/pdf/EUB/'.time() . "" . rand(1,1000) . ".pdf";
        $tempDisFile = APPLICATION_PATH.'/../data/pdf/EUB/'.time() . "" . rand(1,1000) . ".pdf";
        if(!file_exists($tempFile)){
            touch($tempFile);
        }
        if(!file_exists($tempDisFile)){
            touch($tempDisFile);
        }

        $pdf = new FPDI();
        $content = file_get_contents($pdfFile);
        file_put_contents($tempFile, $content);
        $pagecount = $pdf->setSourceFile($tempFile);
        for($i = 1; $i <= $pagecount; $i ++) {
            $tplidx = $pdf->importPage($i);

            $resolution = array(
                102.50,
                100.50
            );
            $pdf->AddPage('P', $resolution);
            $pdf->useTemplate($tplidx, 0, 2, 0, 0, true);

        }

        $js = "";
        $js .= 'print({bUI: false,bSilent: true,bShrinkToFit: true});';//this.closeDoc();';

        // set javascript
        $pdf->IncludeJS($js);
        $pdf->Output($tempDisFile , 'F');
        $result = file_get_contents($tempDisFile);
        ! @unlink($tempFile);
        ! @unlink($tempDisFile);
        header('Content-Type: application/pdf; ');
        header('Content-Disposition:inline; filename=UKTL-Label.pdf');
        echo $result;
        //return $result;
    }

    public function printPdf2Action(){
        require_once APPLICATION_PATH.'/../libs/tcpdf/tcpdf.php';
        require_once APPLICATION_PATH.'/../libs/fpdi/fpdi.php';
        require_once APPLICATION_PATH.'/../libs/FPDFMerge.php';

        $pdfFile = APPLICATION_PATH.'/../data/pdf/EUB/SOE88880015806.pdf';
        $tempFile = APPLICATION_PATH.'/../data/pdf/EUB/'.time() . "" . rand(1,1000) . ".pdf";
        $tempDisFile = APPLICATION_PATH.'/../data/pdf/EUB/'.time() . "" . rand(1,1000) . ".pdf";
        if(!file_exists($tempFile)){
            touch($tempFile);
        }
        if(!file_exists($tempDisFile)){
            touch($tempDisFile);
        }

        $pdf = new FPDI();
        $content = file_get_contents($pdfFile);
        file_put_contents($tempFile, $content);
        $pagecount = $pdf->setSourceFile($tempFile);
        for($i = 1; $i <= $pagecount; $i ++) {
            $tplidx = $pdf->importPage($i);

            $resolution = array(
                102.50,
                100.50
            );
            $pdf->AddPage('P', $resolution);
            $pdf->useTemplate($tplidx, 0, 2, 0, 0, true);

        }

        $js = "";
        $js .= 'print({bUI: false,bSilent: true,bShrinkToFit: true});';//this.closeDoc();';
        $pdf->IncludeJS($js);
        $pdf->Output($tempDisFile , 'F');
        $result = file_get_contents($tempDisFile);
        ! @unlink($tempFile);
        ! @unlink($tempDisFile);
        header('Content-Type: application/pdf; ');
        header('Cache-Control: private, max-age=0, must-revalidate');
        header('Pragma: public');
        ini_set('zlib.output_compression','0');
        echo $result;
    }

    public function exportProductE888Action(){
        error_reporting(E_ALL);
        set_time_limit(0);
        require_once APPLICATION_PATH . '/../libs/PHPExcel.php';
        require_once APPLICATION_PATH . '/../libs/PHPExcel/IOFactory.php';
        $table = new PHPExcel();
        $table->getDefaultStyle()->getFont()->setName('宋体');
        $table->setActiveSheetIndex(0);
        $table->setActiveSheetIndex(0)->setTitle("荷兰小包订单");
        $objActSheet=$table->setActiveSheetIndex(0);

        $objActSheet->getColumnDimension('A')->setWidth(15);
        $objActSheet->getColumnDimension('B')->setWidth(20);
        $objActSheet->getColumnDimension('C')->setWidth(20);
        $objActSheet->getColumnDimension('D')->setWidth(20);
        $objActSheet->getColumnDimension('E')->setWidth(15);
        $objActSheet->getColumnDimension('F')->setWidth(15);
        $objActSheet->getColumnDimension('G')->setWidth(15);
        $objActSheet->getColumnDimension('H')->setWidth(15);
        $objActSheet->getColumnDimension('I')->setWidth(15);
        $objActSheet->getColumnDimension('J')->setWidth(15);
        $objActSheet->getColumnDimension('K')->setWidth(15);
        $objActSheet->getColumnDimension('L')->setWidth(15);
        $objActSheet->getColumnDimension('M')->setWidth(15);
        $objActSheet->getColumnDimension('N')->setWidth(15);
        $objActSheet->getColumnDimension('O')->setWidth(15);
        //客户代码	产品SKU	条码类型	产品代码	产品名称	英文名	状态	单位	申报币种	申报价值	产品重量（KG）	海关编码	招保料号	产品品类	供应商代码	长（CM）	宽（CM）	高（CM）	产品接收类型	质检类型	产品分类	产品添加时间	是否属于零件类	有无发票	产品型号	海关品名	是否带电池	电池类型	法定单位	法定数量	第二法定单位	第二法定数量	要素代码	要素名称	申报要素内容	法定单位	法定数量	第二法定单位	第二法定数量	要素代码	要素名称	申报要素内容	法定单位	法定数量	第二法定单位	第二法定数量	要素代码	要素名称	申报要素内容	法定单位	法定数量	第二法定单位	第二法定数量	要素代码	要素名称	申报要素内容	法定单位	法定数量	第二法定单位	第二法定数量	要素代码	要素名称	申报要素内容	法定单位	法定数量	第二法定单位	第二法定数量	要素代码	要素名称	申报要素内容	法定单位	法定数量	第二法定单位	第二法定数量	要素代码	要素名称	申报要素内容

        $objActSheet->setCellValue('A1','客户代码');
        $objActSheet->setCellValue('B1','产品SKU');
        $objActSheet->setCellValue('C1','条码类型');
        $objActSheet->setCellValue('D1','产品代码');
        $objActSheet->setCellValue('E1','产品名称');
        $objActSheet->setCellValue('F1','英文名');
        $objActSheet->setCellValue('G1','状态');
        $objActSheet->setCellValue('H1','单位');
        $objActSheet->setCellValue("I1","申报币种");
        $objActSheet->setCellValue("J1","申报价值");
        $objActSheet->setCellValue("K1","产品重量（KG）");
        $objActSheet->setCellValue("L1","招保料号");
        $objActSheet->setCellValue("M1","供应商代码");
        $objActSheet->setCellValue("N1","长（CM）");
        $objActSheet->setCellValue("O1","宽（CM）");
        $objActSheet->setCellValue("P1","高（CM）");
        $objActSheet->setCellValue("Q1","产品接收类型0:新产品;1:已收过货产品");
        $objActSheet->setCellValue("R1","质检类型0:不质检;1:质检");
        $objActSheet->setCellValue("S1","产品分类");
        $objActSheet->setCellValue("T1","产品添加时间");
        $objActSheet->setCellValue("U1","是否属于零件类0否1是");
        $objActSheet->setCellValue("V1","有无发票1:带票; 2:不带票");
        $objActSheet->setCellValue("W1","产品型号");
        $objActSheet->setCellValue("X1","海关品名");
        $objActSheet->setCellValue("Y1","是否带电池0:不带;1带");
        $objActSheet->setCellValue("Z1","电池类型1配置电池、2内置电池、3纽扣电池、4锂金属电池 0不带");

        $condition = array(
            'customer_code'=>'E8888',
            'product_status'=>'1',
        );
        $total = Service_Product::getByCondition($condition,"count(*)");
        $pageSize = 20;
        $totalPage = ceil($total/$pageSize);
        $index = 2;
        //die($totalPage);//898
        for($page=851;$page<=900;$page++){
            $rows = Service_Product::getByCondition($condition,"*",$pageSize,$page,"product_id asc");
            foreach($rows as $key=>$product){
                $objActSheet->setCellValue("A".$index,$product['customer_code']);
                $objActSheet->setCellValue("B".$index,$product['product_sku']);
                $status = $product['product_status']==1?"已备案":"未备案";
                $objActSheet->setCellValue("C".$index,$product['product_barcode']);
                $objActSheet->setCellValueExplicit("D".$index,$product['product_barcode'],PHPExcel_Cell_DataType::TYPE_STRING);
                $objActSheet->setCellValueExplicit("E".$index,$product['product_title'],PHPExcel_Cell_DataType::TYPE_STRING);
                $pUm = Service_ProductUom::getByField($product['pu_code'],'pu_code',"*");
                $objActSheet->setCellValue("F".$index,$product['product_title_en']);
                $objActSheet->setCellValue("G".$index,$status);
                $objActSheet->setCellValue("H".$index,$pUm['pu_name']);
                $objActSheet->setCellValue("I".$index,$product['currency_code']);
                $objActSheet->setCellValue("J".$index,$product['product_declared_value']);
                $productCategory  = Service_ProductCategory::getByField($product['pc_id'],'pc_id',"*");
                $objActSheet->setCellValue("K".$index,$product['product_weight']);
                $ds = Service_Distributor::getByPrimaryKey($product['distributor_id']);
                $objActSheet->setCellValue("L".$index,$product['product_weight']);
                $objActSheet->setCellValue("M".$index,$ds['distributor_code']);
                $objActSheet->setCellValue("N".$index,$product['product_length']);
                $objActSheet->setCellValue("O".$index,$product['product_width']);
                $objActSheet->setCellValue("P".$index,$product['product_height']);
                $objActSheet->setCellValue("Q".$index,$product['product_receive_status']);
                $objActSheet->setCellValue("R".$index,$product['product_is_qc']);
                $objActSheet->setCellValue("S".$index,$productCategory['pc_name']);
                $objActSheet->setCellValue("T".$index,$product['product_add_time']);
                $objActSheet->setCellValue("U".$index,$product['is_accessories']);
                $objActSheet->setCellValue("V".$index,$product['has_invoice']);
                $objActSheet->setCellValue("W".$index,$product['model_serial']);
                $objActSheet->setCellValue("X".$index,$product['hs_goods_name']);
                $objActSheet->setCellValue("Y".$index,$product['with_battery']);
                $objActSheet->setCellValue("Z".$index,$product['product_height']);

                $hsElementMap = Service_HsElementMap::getByCondition(array('product_id'=>$product['product_id']),"*");
                if($hsElementMap){
                    foreach($hsElementMap as $k=>$v){
                        $HE = Service_HsElement::getByField($v['he_id'],"he_id","*");
                        $hsElementMap[$k]['HE'] = $HE;
                        $HUM = Service_HsUomMap::getByField($v['product_id'],"product_id","*");
                        $hsElementMap[$k]['HUM'] = $HUM;
                        $HU = Service_HsUom::getByField($HUM['hu_id'],"hu_id","*");
                        $productUom = Service_ProductUom::getByField($HU['pu_code_law'],"pu_code","*");
                        $HU['pu_name'] = $productUom['pu_name'];
                        $productUomSecond = Service_ProductUom::getByField($HU['pu_code_second'],"pu_code","*");
                        $HU['pu_name_second'] = $productUomSecond['pu_name'];
                        $hsElementMap[$k]['HU'] = $HU;
                    }
                }else{
                    $row = array();
                    $HUM = Service_HsUomMap::getByField($product['product_id'],"product_id","*");
                    if($HUM){
                        $row['HUM'] =  $HUM;
                        $row['HE']['hs_code'] =  $product['hs_code'];
                        $HU = Service_HsUom::getByField($HUM['hu_id'],"hu_id","*");
                        $productUom = Service_ProductUom::getByField($HU['pu_code_law'],"pu_code","*");
                        $HU['pu_name'] = $productUom['pu_name'];
                        $productUomSecond = Service_ProductUom::getByField($HU['pu_code_second'],"pu_code","*");
                        $HU['pu_name_second'] = $productUomSecond['pu_name'];
                        $row['HU'] = $HU;

                    }

                    $hsElementMap[] = $row;
                }

                $productCol1 = 65;
                $productCol2 = 65;
                foreach($hsElementMap as $v){
                    if($productCol2>90){
                        $productCol1++;
                        $productCol2 = 65;
                        $objActSheet->setCellValueExplicit(chr($productCol1).chr($productCol2).$index, $v['HE']['hs_code'],PHPExcel_Cell_DataType::TYPE_STRING);
                        $productCol2++;
                    }else{
                        $objActSheet->setCellValueExplicit(chr($productCol1).chr($productCol2).$index,$v['HE']['hs_code'],PHPExcel_Cell_DataType::TYPE_STRING);
                        $productCol2++;
                    }
                    if($productCol2>90){
                        $productCol1++;
                        $productCol2 = 65;
                        $objActSheet->setCellValue(chr($productCol1).chr($productCol2).$index,$v['HU']['pu_name']);
                        $productCol2++;
                    }else{
                        $objActSheet->setCellValue(chr($productCol1).chr($productCol2).$index,$v['HU']['pu_name']);
                        $productCol2++;
                    }
                    if($productCol2>90){
                        $productCol1++;
                        $productCol2 = 65;
                        $objActSheet->setCellValueExplicit(chr($productCol1).chr($productCol2).$index,$v['HU']['pu_name_second'],PHPExcel_Cell_DataType::TYPE_STRING);
                        $productCol2++;
                    }else{
                        $objActSheet->setCellValueExplicit(chr($productCol1).chr($productCol2).$index,$v['HU']['pu_name_second'],PHPExcel_Cell_DataType::TYPE_STRING);
                        $productCol2++;
                    }
                    //$row.HUM.hum_quantity_law
                    if($productCol2>90){
                        $productCol1++;
                        $productCol2 = 65;
                        $objActSheet->setCellValue(chr($productCol1).chr($productCol2).$index,$v['HUM']['hum_quantity_law']);
                        $productCol2++;
                    }else{
                        $objActSheet->setCellValue(chr($productCol1).chr($productCol2).$index,$v['HUM']['hum_quantity_law']);
                        $productCol1++;
                    }
                    if($productCol2>90){
                        $productCol1++;
                        $productCol2 = 65;
                        $objActSheet->setCellValue(chr($productCol1).chr($productCol2).$index,$v['HUM']['hum_quantity_second']);
                        $productCol2++;
                    }else{
                        $objActSheet->setCellValue(chr($productCol1).chr($productCol2).$index,$v['HUM']['hum_quantity_second']);
                        $productCol2++;
                    }
                    if($productCol2>90){
                        $productCol1++;
                        $productCol2 = 65;
                        $objActSheet->setCellValueExplicit(chr($productCol1).chr($productCol2).$index,$v['HE']['he_code'],PHPExcel_Cell_DataType::TYPE_STRING);
                        $productCol2++;
                    }else{
                        $objActSheet->setCellValueExplicit(chr($productCol1).chr($productCol2).$index,$v['HE']['he_code'],PHPExcel_Cell_DataType::TYPE_STRING);
                        $productCol2++;
                    }
                    if($productCol2>90){
                        $productCol1++;
                        $productCol2 = 65;
                        $objActSheet->setCellValueExplicit(chr($productCol1).chr($productCol2).$index,$v['HE']['he_name'],PHPExcel_Cell_DataType::TYPE_STRING);
                        $productCol2++;
                    }else{
                        $objActSheet->setCellValueExplicit(chr($productCol1).chr($productCol2).$index,$v['HE']['he_name'],PHPExcel_Cell_DataType::TYPE_STRING);
                        $productCol2++;
                    }
                    if($productCol2>90){
                        $productCol1++;
                        $productCol2 = 65;
                        $objActSheet->setCellValueExplicit(chr($productCol1).chr($productCol2).$index,$v['hem_detail'],PHPExcel_Cell_DataType::TYPE_STRING);
                        $productCol2++;
                    }else{
                        $objActSheet->setCellValueExplicit(chr($productCol1).chr($productCol2).$index,$v['hem_detail'],PHPExcel_Cell_DataType::TYPE_STRING);
                        $productCol2++;
                    }
                }


                $index++;
            }
        }

        $objWriter = PHPExcel_IOFactory::createWriter($table, 'Excel5');
        header( "Pragma: public" );
        header( "Expires: 0" );
        header("Accept-Ranges: bytes");
        header('cache-control:must-revalidate');
        header("Content-Disposition: attachment; filename=productE8888.xls");
        header("Content-Type:APPLICATION/OCTET-STREAM;charset=utf-8");
        $objWriter->save('php://output');
    }

    public function dianzichengAction(){
        echo Ec::renderTpl($this->tplDirectory . "dianzicheng.tpl", 'layout');
    }

    public function exportqcAction(){
        require_once APPLICATION_PATH . '/../libs/PHPExcel.php';
        require_once APPLICATION_PATH . '/../libs/PHPExcel/IOFactory.php';

        $table = new PHPExcel();
        $table->getDefaultStyle()->getFont()->setName('宋体');
        $table->setActiveSheetIndex(0);
        $table->setActiveSheetIndex(0)->setTitle("出区统计");
        $objActSheet=$table->setActiveSheetIndex(0);

        $objActSheet->getColumnDimension('A')->setWidth(15);
        $objActSheet->getColumnDimension('B')->setWidth(20);
        $objActSheet->getColumnDimension('C')->setWidth(20);
        $objActSheet->getColumnDimension('D')->setWidth(20);
        $objActSheet->getColumnDimension('E')->setWidth(15);

        $objActSheet->setCellValue('A1','客户代码');
        $objActSheet->setCellValue('B1','月份');
        $objActSheet->setCellValue('C1','报关票数');
        $objActSheet->setCellValue('D1','包裹数');
        $objActSheet->setCellValue('E1','申报价值(USD)');
        $objActSheet->setCellValue("F1","重量");


        $db = Common_Common::getAdapter();
        $customerList = Service_Customer::getByCondition(array('customer_status'=>'2'),"*");

        $index = 2;
        foreach($customerList as $customer){
            if($customer['customer_code']=="	E0207"||$customer['customer_code']=="E0110") continue;
            for($i=1;$i<=4;$i++){
                $objActSheet->setCellValue('A'.$index,$customer['customer_code']);
                $objActSheet->setCellValue('B'.$index,"2015-0{$i}");
                $sql = "SELECT count(orders.order_code) FROM ship_batch JOIN ship_batch_detail ON ship_batch.sb_code=ship_batch_detail.sb_code JOIN outbound_bag_detail ON ship_batch_detail.ob_no=outbound_bag_detail.ob_no JOIN orders ON orders.order_code=outbound_bag_detail.order_code WHERE ship_batch.sb_ship_time>='2015-0{$i}-01 00:00:00' AND ship_batch.sb_ship_time<='2015-0{$i}-31 23:59:59' AND orders.customer_code='".$customer['customer_code']."'";

                $count = $db->fetchOne($sql);
                $objActSheet->setCellValue('C'.$index,$count);
                $sql2 = "SELECT count(ship_order.so_id) FROM ship_batch JOIN ship_batch_detail ON ship_batch.sb_code=ship_batch_detail.sb_code JOIN outbound_bag_detail ON ship_batch_detail.ob_no=outbound_bag_detail.ob_no JOIN orders ON orders.order_code=outbound_bag_detail.order_code JOIN ship_order ON ship_order.order_code=orders.order_code WHERE ship_batch.sb_ship_time>='2015-0{$i}-01 00:00:00' AND ship_batch.sb_ship_time<='2015-0{$i}-31 23:59:59' AND orders.customer_code='".$customer['customer_code']."' AND orders.sm_code<>'HKDHL'";

                $count2 = $db->fetchOne($sql2);
                $sql3 = "SELECT count(ship_order_detail.sod_id) FROM ship_batch JOIN ship_batch_detail ON ship_batch.sb_code=ship_batch_detail.sb_code JOIN outbound_bag_detail ON ship_batch_detail.ob_no=outbound_bag_detail.ob_no JOIN orders ON orders.order_code=outbound_bag_detail.order_code JOIN ship_order_detail ON ship_order_detail.order_code=orders.order_code WHERE ship_batch.sb_ship_time>='2015-0{$i}-01 00:00:00' AND ship_batch.sb_ship_time<='2015-0{$i}-31 23:59:59' AND orders.customer_code='".$customer['customer_code']."' AND orders.sm_code='HKDHL'";

                $count3 = $db->fetchOne($sql3);
                $total = $count2+$count3;
                $objActSheet->setCellValue('D'.$index,$total);
                $sql4 = "SELECT SUM(order_product.op_declared_value*order_product.op_quantity) FROM ship_batch JOIN ship_batch_detail ON ship_batch.sb_code=ship_batch_detail.sb_code JOIN outbound_bag_detail ON ship_batch_detail.ob_no=outbound_bag_detail.ob_no JOIN orders ON orders.order_code=outbound_bag_detail.order_code JOIN order_product ON order_product.order_code=orders.order_code WHERE ship_batch.sb_ship_time>='2015-0{$i}-01 00:00:00' AND ship_batch.sb_ship_time<='2015-0{$i}-31 23:59:59' AND orders.customer_code='".$customer['customer_code']."'";
                $count4 = $db->fetchOne($sql4);
                $objActSheet->setCellValue('E'.$index,$count4);
                $sql5 = " SELECT SUM(ship_order.so_weight) FROM ship_batch JOIN ship_batch_detail ON ship_batch.sb_code=ship_batch_detail.sb_code JOIN outbound_bag_detail ON ship_batch_detail.ob_no=outbound_bag_detail.ob_no JOIN orders ON orders.order_code=outbound_bag_detail.order_code JOIN ship_order ON ship_order.order_code=orders.order_code WHERE ship_batch.sb_ship_time>='2015-0{$i}-01 00:00:00' AND ship_batch.sb_ship_time<='2015-0{$i}-31 23:59:59' AND orders.customer_code='".$customer['customer_code']."'";
                $count5 = $db->fetchOne($sql5);
                $objActSheet->setCellValue('F'.$index,$count5);
                $index++;
            }
        }

        $objWriter = PHPExcel_IOFactory::createWriter($table, 'Excel5');
        header( "Pragma: public" );
        header( "Expires: 0" );
        header("Accept-Ranges: bytes");
        header('cache-control:must-revalidate');
        header("Content-Disposition: attachment; filename=exprtQc.xls");
        header("Content-Type:APPLICATION/OCTET-STREAM;charset=utf-8");
        $objWriter->save('php://output');
    }

    public function exportrcAction(){
        require_once APPLICATION_PATH . '/../libs/PHPExcel.php';
        require_once APPLICATION_PATH . '/../libs/PHPExcel/IOFactory.php';

        $table = new PHPExcel();
        $table->getDefaultStyle()->getFont()->setName('宋体');
        $table->setActiveSheetIndex(0);
        $table->setActiveSheetIndex(0)->setTitle("入区单");
        $objActSheet=$table->setActiveSheetIndex(0);

        $objActSheet->getColumnDimension('A')->setWidth(15);
        $objActSheet->getColumnDimension('B')->setWidth(20);
        $objActSheet->getColumnDimension('C')->setWidth(20);
        $objActSheet->getColumnDimension('D')->setWidth(20);
        $objActSheet->getColumnDimension('E')->setWidth(15);

        $objActSheet->setCellValue('A1','客户代码');
        $objActSheet->setCellValue('B1','月份');
        $objActSheet->setCellValue('C1','报关票数');
        $objActSheet->setCellValue('D1','申报价值(USD)');

        $db = Common_Common::getAdapter();
        $index = 2;
        $customerList = Service_Customer::getByCondition(array('customer_status'=>'2'),"*");
        foreach($customerList as $customer){
            if($customer['customer_code']=="	E0207"||$customer['customer_code']=="E0110") continue;
            for($i=1;$i<=4;$i++){
                $sql = " select count(receiving_id) from receiving where receiving_add_time>='2015-0{$i}-01 00:00:00' and receiving_add_time<='2015-0{$i}-31 23:59:59' and customer_code='".$customer['customer_code']."'";
                //echo $sql."<br>";
                $objActSheet->setCellValue('A'.$index,$customer['customer_code']);
                $objActSheet->setCellValue('B'.$index,"2015-0{$i}");

                $count = $db->fetchOne($sql);
                $objActSheet->setCellValue('C'.$index,$count);
                $sql1 = "select sum(op_declared_value*rd_receiving_qty) from receiving r join receiving_detail rd on r.receiving_code=rd.receiving_code where r.customer_code='".$customer['customer_code']."' and r.receiving_add_time>='2015-0{$i}-01 00:00:00' and r.receiving_add_time<='2015-0{$i}-31 23:59:59' ";
                //echo $sql1."<br>";
                $count1 = $db->fetchOne($sql1);
                $sql2 = " select sum(op_declared_value*op_quantity) from receiving r join receiving_order_detail rod on r.receiving_code=rod.receiving_code join order_product op on op.order_code=rod.order_code where customer_code='".$customer['customer_code']."' and r.receiving_add_time>='2015-0{$i}-01 00:00:00' and r.receiving_add_time<='2015-0{$i}-31 23:59:59'";
                //echo $sql2."<br>";
                $count2 = $db->fetchOne($sql2);
                $total = $count1+$count2;
                $objActSheet->setCellValue('D'.$index,$total);
                $index++;
            }
        }
        //exit;

        $objWriter = PHPExcel_IOFactory::createWriter($table, 'Excel5');
        header( "Pragma: public" );
        header( "Expires: 0" );
        header("Accept-Ranges: bytes");
        header('cache-control:must-revalidate');
        header("Content-Disposition: attachment; filename=exprtRc.xls");
        header("Content-Type:APPLICATION/OCTET-STREAM;charset=utf-8");
        $objWriter->save('php://output');

    }

    public function exportttAction(){

        require_once APPLICATION_PATH . '/../libs/PHPExcel.php';
        require_once APPLICATION_PATH . '/../libs/PHPExcel/IOFactory.php';

        $full_path = APPLICATION_PATH.'/../data/file/ship_batch_detail(3).xls';

        $table = new PHPExcel();
        $table->getDefaultStyle()->getFont()->setName('宋体');
        $table->setActiveSheetIndex(0);
        $table->setActiveSheetIndex(0)->setTitle("入区单");
        $objActSheet=$table->setActiveSheetIndex(0);

        $objActSheet->getColumnDimension('A')->setWidth(15);
        $objActSheet->getColumnDimension('B')->setWidth(20);
        $objActSheet->getColumnDimension('C')->setWidth(20);
        $objActSheet->getColumnDimension('D')->setWidth(20);
        $objActSheet->getColumnDimension('E')->setWidth(15);

        $objActSheet->setCellValue('A1','订单号');
        $objActSheet->setCellValue('B1','客户代码');
        $objActSheet->setCellValue('C1','出货时间');
        $objActSheet->setCellValue("D1",'包裹数');
        $objActSheet->setCellValue('E1','申报价值(USD)');
        $objActSheet->setCellValue("F1",'出货重量');
        $objActSheet->setCellValue("G1",'出区单单号');

        $resultArray = Common_Upload::readEXCEL($full_path);
        $index = 2;
        $db = Common_Common::getAdapter();
        foreach($resultArray as $key=>$value){
            $objActSheet->setCellValue("A".$index,$value[0]);
            $objActSheet->setCellValue("B".$index,$value[1]);
            $objActSheet->setCellValueExplicit("C".$index,$value[2],PHPExcel_Cell_DataType::TYPE_STRING);
            //$objActSheet->setCellValue("C".$index,$value[2]);
            $sql = "select count(sod_id) from ship_order_detail where order_code='".$value[0]."'";
            $count = $db->fetchOne($sql);
            $objActSheet->setCellValue("D".$index,$count);
            $objActSheet->setCellValue("E".$index,$value[3]);
            $objActSheet->setCellValue("F".$index,$value[4]);
            $objActSheet->setCellValue("G".$index,$value[5]);
            $index++;
        }
        $objWriter = PHPExcel_IOFactory::createWriter($table, 'Excel5');
        header( "Pragma: public" );
        header( "Expires: 0" );
        header("Accept-Ranges: bytes");
        header('cache-control:must-revalidate');
        header("Content-Disposition: attachment; filename=exprtRc.xls");
        header("Content-Type:APPLICATION/OCTET-STREAM;charset=utf-8");
        $objWriter->save('php://output');
    }

    public function updateproductAction(){
        require_once APPLICATION_PATH . '/../libs/PHPExcel.php';
        require_once APPLICATION_PATH . '/../libs/PHPExcel/IOFactory.php';

        $full_path = APPLICATION_PATH.'/../data/file/woguang20150601-2.xls';

        $resultArray = Common_Upload::readEXCEL($full_path);
        //echo "<pre>";
        //var_dump($resultArray);
        //echo "</pre>";
        //exit;
        foreach($resultArray as $key=>$value){
            if($key==0) continue;
            $updateProduct = array(
                'product_declared_value'=>$value[1],
                'product_weight'=>$value[2],
                'model_serial'=>$value[3],
            );
            $pid = Service_Product::update($updateProduct,$value[0],'product_sku');
            if($pid){
                echo "product_sku[".$value[0]."]update Success!<br>";
            }else{
                echo "product_sku[".$value[0]."]update failure!<br>";
            }
        }
    }

    public function receivingToFenxiaoAction(){
        $httpURL = "http://testapi.sinob2b.com/rs/oms/receivingOrder/updateReceivingOrderStatus";
        $postHeader = array("Content-Type: application/x-www-form-urlencoded; charset=UTF-8");
        $appSercet = "1747dfbf884ac612e050007f01000ac5";
        $appKey = "1747dfbf884ac612e050007f01000ac5";
        $asnNumber = "BHR160004328";
        $receivingRow = Service_Receiving::getByField($asnNumber,'receiving_code',"*");
        $receivingAttribute = Service_ReceivingAttribute::getByField($asnNumber,'receiving_code',"*");
        $rohStatus = "AUDIT";
        $receivedTime = date("Y-m-d H:i:s");

        $param = array(
            'timestamp'=>strtotime($receivedTime),
            'asnNumber'=>$asnNumber,
            'rohStatus'=>'AUDIT',
            'receivedTime'=>$receivedTime,
        );
		$items = array();
        $receivingOrderDetail = Service_ReceivingOrderDetail::getByCondition(array('receiving_code'=>$asnNumber),"*");
		foreach($receivingOrderDetail as $rod){
			$orderProduct = Service_OrderProduct::getByCondition(array('order_code'=>$rod['order_code']),"*");
			foreach($orderProduct as $op){
				$product = Service_Product::getByField($op['product_id'],"product_id","*");
				$ite = array(
					'sku'=>$product['product_sku'],
					'quantity'=>$op['op_quantity'],
					'weight'=>$product['product_weight'],
					'qc'=>'Y'
				);
				$items[] = $ite;
			}
		}
        /*$items = array();
		$receivingDetail = Service_ReceivingDetail::getByCondition(array('receiving_code'=>$asnNumber),"*");
        foreach($receivingDetail as $key=>$value){
            $product = Service_Product::getByField($value['product_id'],"product_id","*");
            $ite = array(
                'sku'=>$product['product_sku'],
                'quantity'=>$value['rd_receiving_qty'],
                'weight'=>$product['product_weight'],
                'qc'=>'Y'
            );
            $items[] = $ite;
        }*/

        $shalArr = array();
        $shalArr[] = "appKey".$appKey;
        foreach($param as $key=>$val){
            $shalArr[] = $key.$val;
        }
        foreach($items as $k=>$v){
            foreach($v as $key=>$val){
                $shalArr[] = "items.".$key.$val;
            }
        }
        sort($shalArr);
        $shalStr = "";
        foreach($shalArr as $val){
            $shalStr.=$val;
        }
        $sign = sha1($shalStr.$appSercet);

        $requestParam = "appKey=".$appKey;
        foreach($param as $key=>$val){
            $requestParam.="&".$key."=".$val;
        }
        foreach($items as $k=>$v){
            foreach($v as $key=>$value){
                $requestParam.="&items.".$key."=".$value;
            }
        }
        $requestParam.="&sign=".$sign;
        echo $requestParam;
        $ch = curl_init($httpURL);
        curl_setopt($ch, CURLOPT_URL, $httpURL);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $postHeader);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$requestParam);

        $response = curl_exec($ch);
        if(curl_errno($ch)){
            print curl_error($ch);
        }

        $obj = json_decode($response);

        $result = Common_Common::objectToArray($obj);
        echo "<pre>";
        var_dump($result);
        echo "</pre>";
        exit;
    }

    public function swaporderToFenxiaoAction(){
        $httpURL = "http://api.sinob2b.com/rs/oms/swapOrder/update";
        $postHeader = array("Content-Type: application/x-www-form-urlencoded; charset=UTF-8");
        $appSercet = "1747dfbf884ac612e050007f01000ac5";
        $appKey = "1747dfbf884ac612e050007f01000ac5";
        $actionUrl = "/rs/oms/swapOrder/update";
        $swo_code = "SWO150000034";
        $swapRow = Service_SwapOrder::getByField($swo_code,"swo_code","*");
        $timestamp = strtotime($swapRow['last_update_time']);
        $order_code = $swapRow['swo_code'];
        $status = "S";
        $message = "易货成功";
        $finishTime = $swapRow['last_update_time'];
        $shalstr = $actionUrl."appKey{$appKey}finishTime{$finishTime}message{$message}order_code{$order_code}status{$status}timestamp{$timestamp}{$appSercet}";
        $sign = sha1($shalstr);
        $ch = curl_init($httpURL);
        curl_setopt($ch, CURLOPT_URL, $httpURL);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $postHeader);
        curl_setopt($ch, CURLOPT_POST, 1);
        $param = array(
            'appKey'=>$appKey,
            'timestamp'=>$timestamp,
            'order_code'=>$order_code,
            'status'=>$status,
            'message'=>$message,
            'finishTime'=>$finishTime,
            'sign'=>$sign,
        );
        curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($param));
        $response = curl_exec($ch);
        if(curl_errno($ch)){
            print curl_error($ch);
        }
        echo $order_code.":".$response."</br>";
        $obj = json_decode($response);
        $result = Common_Common::objectToArray($obj);
        if($result['ack']=="Success"){
            $update = array(
                'has_send'=>1,
            );
            Service_SwapOrder::update($update,$order_code,'swo_code');
        }else{
            $update = array(
                'remark'=>$result['data'],
            );
            Service_SwapOrder::update($update,$order_code,'swo_code');
        }
    }

    public function comitToEbayAction(){
        //phpinfo();
        //exit;
        error_reporting(E_ALL);
        set_time_limit(0);
        //SOE02480005304
        $orderCode = $this->_request->getParam("order_code","SOE01740003720");
        $order = Service_Orders::getByField($orderCode,"order_code","*");
        $receivingAddress = Service_OrderAddressBook::getByField($order['order_id'],'order_id',"*");
        $country = Service_Country::getByField($receivingAddress["oab_country_id"],"country_id","*");
        $shipToAddress = array(
            'email' => $receivingAddress['oab_email'],
            'company' => $receivingAddress['oab_company'],
            'contact' => "Andy Liu",
            'phone' => $receivingAddress['oab_cell_phone'],
            'street' => $receivingAddress['oab_street_address1'],
            'city' => $receivingAddress['oab_city'],
            'province' => $receivingAddress['oab_state'],
            'postcode' => $receivingAddress['oab_postcode'],
            'country' => $country['country_name_en'],
            'country_code' => $country['country_code'],
        );
        $shipFromAddress = array(
            'contact' => 'Danny Zhou',
            'company' => 'cargo company',
            'street' => 'JinTian Road No.8086 AnLian A 25 Floor',
            'district' => 'Futian district',
            'city' => 'shenzhen city',
            'province' => 'GUANGDONG',
            'postcode' => '518026',
            'country' => 'CHINA',
            'email' => 'Dannyzhou@cargofe.com.cn',
            'mobile' => '13594268155',
        );
        $returnAddress = array(
            'company' => 'Cargo',     //公司
            'country' => "中国",     //国家 中国
            'province' => '广东',   //省
            'city' => 'shenzhen city',           //城市
            'district' => 'Futian district',   //区
            'street' => 'JinTian Road No.8086 AnLian A 25 Floor',       //街道
            'postcode' => '518026',   //邮编
            'contact' => 'Danny Murphy',     //联系人
        );
        $pickUpAddress = array(
            'email' => 'Dannyzhou@cargofe.com.cn',
            'company' => 'cargo company',
            'country' => '中国',
            'province' => '440000',
            'city' => '440300',
            'district' => '440304',
            'street' => 'JinTian Road',
            'postcode' => '518026',
            'contact' => 'Danny Zhou',
            'mobile' => '0755-5180256',
            'phone' => '13594268155',
        );

        $eabyService = Service_EBAYApiProcess::getInstance();
        $pickUpType = 0;
        $eabyService->setPickUpType($pickUpType);
        //$appUserId = "fzffzw84";
        //$appPassword = "84089ZG8D1NW2Z4BY85ESXGCOFMUZB1KFLC9LIYXPW6OH2PEL7MTK2013154828";沙箱

        $DevID="c336f0c5-3df1-4df5-9de8-4f3aeafad286";//c336f0c5-3df1-4df5-9de8-4f3aeafad286
        $AppID="cargo3a33-16c0-4cc1-9493-ebe3ee4dc87";//cargo3a33-16c0-4cc1-9493-ebe3ee4dc87
        $CertID="bf0c88e8-b371-4a74-803a-75df19500454";//bf0c88e8-b371-4a74-803a-75df19500454
        $token = "AgAAAA**AQAAAA**aAAAAA**xJ+bVQ**nY+sHZ2PrBmdj6wVnY+sEZ2PrA2dj6AFmIegDZmAoA6dj6x9nY+seQ**7O0BAA**AAMAAA**TFlC41n0bTRXsoQFVIJDqJvtxwOQ+FniyE//znLyKWVLlZ4C57lhMzd42/79Ofxt1C1TSGBCjD3xJg4m1luodsJJ0BB4Y9oLLu7TqKxtUQPAIELLH7zQZqoV3YWGechQE/UQaNDSJ1hkys0Ke8LOBgu3ENnDs+5aB38EaGgxz4I126t6k/Cp7nQ0HGknQOtEgCuZt+vIg7H631qwaISwK0aelL0ZJAbf+fhlOWrQsdLaq800n+y/qox1lNBGt7+H1WtUDSrWn7DEqhFo+Lm0eILtzIyq562grAaQ1gV4lhWHH17zWVK7Xg5R6+O8wRFYqJDct1N+I6awTXuFMpucMGddMaiL6GQX0SrPYnFwoKeyo4gXuZSbDj6J54/U7JTI3RaPxQ4MNdfyxLVnLv6Mv0Y9vBPr6fYEXkVzu8hIcnLEC0AUPfzP/MqkAghxxB6Csb+X8ecpRfd8bjL+cniOyZxX7YDnrgPgE0SCotLXqK293YbPVuau728HgB3+0RhuacfUeaL4goJm9Bte5fFIxhlJ1HUcFEK1m9aOlewql5LTxV5WNYtJqlMyamrvOKR7LLHYwdunItZ6mHgqGXYFZW9VDd+BEN8RqBCqdec1i9IejzGFh+tm0e09zLLzkrKVBGqREndewpThV/2JV1tsht8KcJQNC5sCaxuLxYdJCvKkTgB7zjTKWge5Z6NhAHAllNt9/XnpviK+4Bn9V594l2DTD853P04ai/7EV3Zv4RMi6Lve+XpimRd3zQFnZLBr";

        $headerArr = array(
            'APIDevUserID'=>$DevID, //APIDevUserID
            'APISellerUserToken'=>$token,//APISellerUserToken
            'APISellerUserID'=>'abing.967',//APISellerUserID
            'AppID'=>$AppID,//AppID
            'AppCert'=>$CertID,//AppCert
            'MessageID'=>$order['order_code'],
            'Carrier'=>'CNPOST',
            'Version'=>'4.0.0',
        );

        $eabyService->setHeader($headerArr);
        //$eabyService->verifyUser();
        //print_r($epacketService);
        $eabyService->setShipFromAddress($shipFromAddress);
        $eabyService->setShipToAddress($shipToAddress);
        $eabyService->setReturnAddress($returnAddress);
        if($pickUpType==0){
            $eabyService->setPickUpAddress($pickUpAddress);
        }

        $orderProduct = Service_OrderProduct::getByCondition(array("order_code"=>$order['order_code']),"*");
        foreach($orderProduct as $k=>$v){
            $product = Service_Product::getByField($v['product_id'],"product_id","*");
            $epacketItem = array(
                'skuid' => $product['product_sku'],
                'weight' => $product['product_weight'],
                'customs_title_cn' => $product['product_title'],
                'customs_title_en' => $product['product_title_en'],
                'declared_value' => $product['product_declared_value'],
                'currency_code' => '',
                'ebay_email' => '',
                'ebay_buyer_id' => 'joshuaw7',
                'ebay_item_id' => '181177693791',
                'ebay_item_title' => '',
                'ebay_message' => '',
                'ebay_site_id' => '',
                'ebay_transaction_id' => '1051636790008',
                'note' => '',
                'order_sales_record_number' => '',
                'payment_date' =>'2015-07-08',
                'paypal_email' => '',
                'paypal_message' => '',
                'posted_qty' => $v['op_quantity'],
                'received_amount' =>$v['op_quantity']*$product['product_declared_value'],
                'sales_record_number' => '',
                'sold_date' => '2013-08-05',
                'sold_price' => $product['product_sales_value'],
                'sold_qty' => $v['op_quantity'],
            );
            $eabyService->addItem($epacketItem);
        }

        $result = $eabyService->AddPackage();
        print_r($result);
        if (strtolower($result->AddAPACShippingPackageResult->Ack) == 'success') {
            $confirmEpacket = $eabyService->confirmPackage(array('track_number' => $result->AddAPACShippingPackageResult->TrackCode));
            if (strtolower($confirmEpacket->ConfirmAPACShippingPackageResult->Ack) == 'success') {
                $TrackDetail = array(
                    'PageSize'=>'0',
                    'TrackCode'=>$result->AddAPACShippingPackageResult->TrackCode,
                );
                $label = $eabyService->getShippingLabel($TrackDetail);

                $file = APPLICATION_PATH.'/../data/pdf/'.$order['order_code'].".pdf";
                echo "file=".$file."</br>";
                if(!file_exists($file)){
                    $fp=fopen($file, "w+");
                }
                file_put_contents($file,$label);
                $ret = array(
                    'ask'=>'1',
                    'message'=>'成功获取pdf标签'
                );
                die(json_encode($ret));
            }else{
                $ret = array(
                    'ask'=>'0',
                    'message'=>'获取pdf标签失败'
                );
                die(json_encode($ret));
            }
        } else {
            $getTrackCodeArray = array(
                'ebay_item_id' => '181177693791',
                'ebay_transaction_id' => '1051636790008',
            );
            $trackNumberResult = $eabyService->getTrackCode($getTrackCodeArray);
            if (strtolower($trackNumberResult->GetAPACShippingTrackCodeResult->Ack) == 'success') {
                $TrackDetail = array(
                    'PageSize'=>1,
                    'track_number'=>$trackNumberResult->GetAPACShippingTrackCodeResult->TrackCode,
                );
                $label = $eabyService->getShippingLabel($TrackDetail);
                $file = APPLICATION_PATH.'/../data/pdf/'.$order['order_code'].".pdf";
                if(!file_exists($file)){
                    $fp=fopen($file, "w+");
                }
                file_put_contents($file,$label);
                $ret = array(
                    'ask'=>'1',
                    'message'=>'成功获取pdf标签'
                );
                die(json_encode($ret));
            }else{
                $ret = array(
                    'ask'=>'0',
                    'message'=>'获取pdf标签失败'
                );
                die(json_encode($ret));
            }
        }
    }

    public function completeToFxAction(){
        $httpURL = "http://testapi.sinob2b.com/rs/oms/receivingOrder/updateReceivingOrderStatus";
        $postHeader = array("Content-Type: application/x-www-form-urlencoded; charset=UTF-8");
        $appSercet = "1747dfbf884ac612e050007f01000ac5";
        $appKey = "1747dfbf884ac612e050007f01000ac5";
        $asnNumber = "BHR160004328";
        $receivingRow = Service_Receiving::getByField($asnNumber,'receiving_code',"*");
        $receivingAttribute = Service_ReceivingAttribute::getByField($asnNumber,'receiving_code',"*");
        $rohStatus = "DONE";
        $receivedTime = $receivingAttribute['receiving_time'];

        $param = array(
            'timestamp'=>strtotime($receivingAttribute['receiving_time']),
            'asnNumber'=>$asnNumber,
            'rohStatus'=>'DONE',
            'receivedTime'=>$receivedTime,
        );
		
		$items = array();
		$receivingOrderDetail = Service_ReceivingOrderDetail::getByCondition(array('receiving_code'=>$asnNumber),"*");
		foreach($receivingOrderDetail as $rod){
			$orderProduct = Service_OrderProduct::getByCondition(array('order_code'=>$rod['order_code']),"*");
			foreach($orderProduct as $op){
				$product = Service_Product::getByField($op['product_id'],"product_id","*");
				$ite = array(
					'sku'=>$product['product_sku'],
					'quantity'=>$op['op_quantity'],
					'weight'=>$product['product_weight'],
					'qc'=>'Y'
				);
				$items[] = $ite;
			}
		}
		
        /*$receivingDetail = Service_ReceivingDetail::getByCondition(array('receiving_code'=>$asnNumber),"*");
        $items = array();
        foreach($receivingDetail as $key=>$value){
            $product = Service_Product::getByField($value['product_id'],"product_id","*");
            $ite = array(
                'sku'=>$product['product_sku'],
                'quantity'=>$value['rd_putaway_qty'],
                'weight'=>$product['product_weight'],
                'qc'=>'Y'
            );
            $items[] = $ite;
        }*/

        $shalArr = array();
        $shalArr[] = "appKey".$appKey;
        foreach($param as $key=>$val){
            $shalArr[] = $key.$val;
        }
        foreach($items as $k=>$v){
            foreach($v as $key=>$val){
                $shalArr[] = "items.".$key.$val;
            }
        }
        sort($shalArr);
        $shalStr = "";
        foreach($shalArr as $val){
            $shalStr.=$val;
        }
        $sign = sha1($shalStr.$appSercet);

//$requestParam = "appKey=".$appKey."&timestamp=".$timestamp."&asnNumber=".$asnNumber."&rohStatus=".$rohStatus."&receivedTime=".urlencode($receivedTime)."&items.sku=TESTPDUCT-01&items.sku=TESTPDUCT-02&items.weight=1.4&items.weight=1.2&items.quantity=1&items.quantity=2&items.qc=N&items.qc=N&sign=".$sign;
        $requestParam = "appKey=".$appKey;
        foreach($param as $key=>$val){
            $requestParam.="&".$key."=".$val;
        }
        foreach($items as $k=>$v){
            foreach($v as $key=>$value){
                $requestParam.="&items.".$key."=".$value;
            }
        }
        $requestParam.="&sign=".$sign;
        $ch = curl_init($httpURL);
        curl_setopt($ch, CURLOPT_URL, $httpURL);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $postHeader);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$requestParam);

        $response = curl_exec($ch);
        if(curl_errno($ch)){
            print curl_error($ch);
        }

        $obj = json_decode($response);

        $result = Common_Common::objectToArray($obj);
        echo "<pre>";
        var_dump($result);
        echo "</pre>";
        exit;
    }

    public function createOrderAction(){
        echo "<meta charset='utf-8' />";
        set_time_limit(0);
        //订单创建接口
        $wsdlurl = 'http://120.24.90.64:2015/default/distribuction';
        $client = new SoapClient($wsdlurl);
        $productDeatil = array(
            '0'=>array(
                'productSku'=>'S0182015-1',
                'productTitleEn'=>'just for test!',
                'opQuantity'=>'1',
                'declaredValue'=>'111',
                'purposeDeclaredValue'=>'110',
            ),
            '1'=>array(
                'productSku'=>'11-2712504',
                'productTitleEn'=>'just for test!',
                'opQuantity'=>'1',
                'declaredValue'=>'111',
                'purposeDeclaredValue'=>'110',
            ),
        );
        $ordersinfo['orderMode'] = '0'; //备货模式订单
        $ordersinfo['customerCode'] = 'E0207';
        $ordersinfo['channel'] = '0';
        $ordersinfo['trackingNumber'] = '159862401';
        $ordersinfo['warehouseCode'] = 'sz01';
        $ordersinfo['oabCountry'] = 'US';
        $ordersinfo['smCode'] = 'SZY-EMS';
        $ordersinfo['referenceNo'] = '3578412601';
        $ordersinfo['oabName'] = 'Lincen';
        $ordersinfo['oabCompany'] = 'usa newyork';
        $ordersinfo['oabState'] = 'Golden State';
        $ordersinfo['oabCity'] = 'San Francisco';
        $ordersinfo['oabPostcode'] = '12111-1234';
        $ordersinfo['oabStreetAddress1'] = 'asdqw ad';
        $ordersinfo['oabPhone'] = '86-80808888';
        $ordersinfo['oabEmail'] = '1231231@11.com';
        $ordersinfo['currency'] = 'RMB';
        $ordersinfo['transactionPrice'] = '86';
        $ordersinfo['remark'] = 'just for test';
        $ordersinfo['orderStatus'] = '1';
        $ordersinfo['orderProduct'] = $productDeatil;
        //$paragram['orderInfo'] = $ordersinfo;
        $client = new SoapClient($wsdlurl);
        $result = $client->createOrder($ordersinfo);
        $result = Common_Common::objectToArray($result);
        echo  "<pre>";
        var_dump($result);
        echo "</pre>";
        exit();
    }

    public function createAsnAction(){
        echo "<meta charset='utf-8' />";
        set_time_limit(0);
        //R150001414
        $wsdlurl = 'http://120.24.90.64:2015/default/distribuction';
        $UpdateASNInfo = array(
            //'ASNCode'=>'BHR150001062',
            'warehouseCode'=>'SZ01',
            'customerCode'=>'E0207',
            'refCode'=>'123435450',
            'isDelivery'=>'0',
            'iePort'=>'5345',
            'formType'=>'I211',
            'trafName'=>'154354',
            'wrapType'=>'1',
            'packNo'=>'1',
            'trafMode'=>'Y',
            'tradeMode'=>'0110',
            'transMode'=>'3',
            'receiveMode'=>'0',
            'receivingStatus'=>'3',
            'roughWeight'=>'1',
            'instructions'=>'just for test update API',
            'ASNItems'=>array(
                'productInfo'=>array(
                    array(
                        'productSku'=>'MB396',
                        'quantity'=>'2',
                        'declared_value'=>'1',
                    ),
                    array(
                        'productSku'=>'MB397',
                        'quantity'=>'1',
                        'declared_value'=>'2.5',
                    ),
                ),
            )
        );
        $client = new SoapClient($wsdlurl);
        $result=$client->createAsn($UpdateASNInfo);
        echo "<pre>";
        var_dump($result);
        echo "</pre>";
        exit;
    }

    public function createXmlAction(){
        /*$ftProcess = new Service_FtpMessageProcess();
        $sendList = Service_FtpMessageSendlist::getByCondition(array('fmt_code'=>'MCK', 'fml_status'=>1,'refercence_no'=>'BHC150000144'));
        var_dump($sendList);
        foreach($sendList as $sendRow) {
            $affect = $ftProcess->updateSendMessage($sendRow);
            if(!$affect) {
                echo "创建出库报文失败[".$sendRow['refercence_no']."]\r\n";
            }
        }*/
		
		$httpURL = "http://api.sinob2b.com/rs/oms/swapOrder/update";
		$postHeader = array("Content-Type: application/x-www-form-urlencoded; charset=UTF-8");
		$appSercet = "1747dfbf884ac612e050007f01000ac5";
		$appKey = "1747dfbf884ac612e050007f01000ac5";
		$actionUrl = "/rs/oms/swapOrder/update";
		$total = Service_SwapOrder::getByCondition(array('swo_status'=>5),"count(*)");
		$pageSize = 20;
		$totalPage = ceil($total/$pageSize);
		for($page=1;$page<=$totalPage;$page++){
			$swapOrderList = Service_SwapOrder::getByCondition(array('swo_status'=>5),"*",$pageSize,$page);
			foreach($swapOrderList as $swapRow){
				$timestamp = strtotime($swapRow['last_update_time']);
				$order_code = $swapRow['swo_code'];
				$status = "S";
				$message = "易货成功";
				$finishTime = $swapRow['last_update_time'];
				$shalstr = $actionUrl."appKey{$appKey}finishTime{$finishTime}message{$message}order_code{$order_code}status{$status}timestamp{$timestamp}{$appSercet}";
				$sign = sha1($shalstr);
				$ch = curl_init($httpURL);
				curl_setopt($ch, CURLOPT_URL, $httpURL);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($ch, CURLOPT_HTTPHEADER, $postHeader);
				curl_setopt($ch, CURLOPT_POST, 1);
				$param = array(
					'appKey'=>$appKey,
					'timestamp'=>$timestamp,
					'order_code'=>$order_code,
					'status'=>$status,
					'message'=>$message,
					'finishTime'=>$finishTime,
					'sign'=>$sign,
				);
				curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($param));
				$response = curl_exec($ch);
				if(curl_errno($ch)){
					print curl_error($ch);
				}
				echo $order_code.":".$response."</br>";
				$obj = json_decode($response);
				$result = Common_Common::objectToArray($obj);
				echo $swapRow['swo_code']." ".$result['ack']."</br>";
				if($result['ack']=="Success"){
					$update = array(
						'has_send'=>1,
					);
					Service_SwapOrder::update($update,$order_code,'swo_code');
				}else{
					$update = array(
						'remark'=>$result['data'],
					);
					Service_SwapOrder::update($update,$order_code,'swo_code');
				}
			}
		}
		
    }

    public function fxbagAction(){
        set_time_limit(0);
        $smArr = array(
            'BHSGG'=>'BH-SGG',
            'THHK'=>"THHK",
        );
        $bagArr = array(
            'BHSGG'=>'BHSGGBAG20150731',
            'THHK'=>"THHKBAG20150731",
        );
        //$prefix = "";
        foreach($smArr as $key=>$sm_code){
            $ob_no = $bagArr[$key];
            //$obResult = Service_OutboundBag::create($ob_no, $sm_code,"0110");
            //break;
            $condition = array(
                'order_status'=>'7',
                'trade_mode'=>'0110',
                'sm_code'=>$sm_code,
            );
            $count = Service_Orders::getByCondition($condition,"count(*)");
            $pageSize =20;
            $totalPage = ceil($count/$pageSize);
            for($page = 1;$page<=$totalPage;$page++){
                $orderList = Service_Orders::getByCondition($condition,"*",$pageSize,$page,"order_id");
                foreach($orderList as $orderRow){
                    if(in_array($orderRow['customer_code'],array('E0110', 'E0207'))){
                        throw new Exception( $orderRow['order_code']."这是测试账号的订单，不能出货");
                    }
                    $soProcess = new Service_ShipOrderProcess();
                    $shipOrder = Service_ShipOrder::getByField($orderRow['order_code'],"order_code","*");
                    $volArr['realWeight'] = $shipOrder['so_weight'];
                    $order_id = $orderRow['order_id'];
                    $order_code = $orderRow['order_code'];
                    $weight = $shipOrder['so_weight'];
                    $tracking_number = $shipOrder['tracking_number'];
                    $so_code = $shipOrder['so_code'];

                    $db = Common_Common::getAdapter();
                    $db->beginTransaction();
                    try {
                        $ob_no=strtoupper($ob_no);
                        $tracking_number=strtoupper($tracking_number);
                        $so_code=strtoupper($so_code);
                        $order_code=strtoupper($order_code);
                        $realWeight = $volArr['realWeight'];

                        //处理重量啦啦啦
                        $shipMethod = Service_ShippingMethod::getByField($sm_code,'sm_code',"*");
                        $volWeight = 0;
                        if($shipMethod['sm_code']=="HKDHL"){
                            $shipOrder = Service_ShipOrder::getByField($order_code,'order_code',"*");
                            $volWeight = $shipOrder['so_vol_weight'];
                            $weight = $shipOrder['so_weight'];
                            $realWeight = $volWeight>$weight?$volWeight:$weight;
                        }else{
                            if($shipMethod['sm_is_volume']=="1"){
                                foreach($volArr['volArr'] as $key=>$value){
                                    $length = $value['length'];
                                    $width = $value['width'];
                                    $height = $value['height'];
                                    if($length>0 && $width>0 && $height>0 && $shipMethod['sm_vol_rate']>0){
                                        $vWeight = ($length*$width*$height)/$shipMethod['sm_vol_rate'];
                                        $vWeight = sprintf('%.2f',$vWeight);
                                        $volArr['volArr'][$key]['vol_weight'] = $vWeight;
                                        $volWeight+=$vWeight;
                                    }else{
                                        throw new Exception($orderRow['order_code'].'长、宽、高、运输方式体积转换率都必须大于0');
                                        break;
                                    }
                                    //break;
                                }
                                $realWeight = $volWeight>$weight?$volWeight:$weight;
                            }
                        }
                        //检查订单扫描重量和产品净重
                        $orderProductInfo	= Service_OrderProduct::getByCondition(array('order_code'=>$order_code));
                        $weightTotal		= 0;
                        foreach($orderProductInfo as $k=>$v){
                            $productInfo	= Service_Product::getByField($v['product_id'],'product_id');
                            if(1 == $productInfo['product_type']){
                                $productCombineRelation = Service_ProductCombineRelation::getByCondition(array('product_id'=>$v['product_id']),"*");
                                foreach($productCombineRelation as $k1=>$v1){
                                    $relationProduct = Service_Product::getByField($v1['pcr_product_id'],'product_id',"*");
                                    $weightTotal += $v['op_quantity']*$v1['pcr_quantity']*$relationProduct['product_weight'];
                                }
                            }else{
                                $weightTotal += $v['op_quantity']*$productInfo['product_weight'];
                            }
                            $hsCode = Service_Hscodes::getByField($productInfo['hs_code'],'hs_code');
                            if($hsCode['hs_code_status']=='-1'){
                                throw new Exception($orderRow['order_code']."产品sku".$productInfo['product_sku']."海关编码已禁用");
                            }
                        }
                        if($realWeight>0 && $weightTotal>$realWeight){
                            throw new Exception($orderRow['order_code'].'产品毛重['.$weightTotal.']大于录入订单重量['.$realWeight.']');
                        }

                        //物流信息和状态
                        $soResult = $soProcess->shipping($so_code, $weight, $tracking_number,$volWeight,$volArr);
                        if(!is_array($soResult)) throw new Exception($soResult);
                        //创建包袋订单行
                        $obdResult = $soProcess->addBagDetail($order_id, $order_code, $ob_no, $soResult['so_code'], $realWeight);
                        if(!$obdResult) throw new Exception($orderRow['order_code'].'创建包袋订单行失败');
                        $orderRow = Service_Orders::getByField($order_id,"order_id","*");


                        //订单状态
                        $updateRow['order_status'] = 8;
                        $updateRow['update_time'] = date('Y-m-d H:i:s');
                        $oResult = Service_Orders::update($updateRow, $order_id);

                        $w = Service_Warehouse::getByField($orderRow['warehouse_id'],'warehouse_id','*');
                        if($orderRow['order_mode_type']=="1"){
                            $sotDescription = "集货订单出货装袋";
                        }else{
                            $sotDescription = "备货订单出货装袋";
                        }
                        $shipOrderTracking = array(
                            'order_code'=>$order_code,
                            'sot_location'=>$w['warehouse_desc'],
                            'sot_add_time'=>date("Y-m-d H:i:s"),
                            'warehouse_id'=>$orderRow['warehouse_id'],
                            'sot_description'=>$sotDescription,
                            'sot_type'=>'0',
                            'sot_time_offset'=>'',
                            'tracking_number'=>$order_code,
                            'ref_tracking_number'=>'',
                            'status_desc'=>'已装袋',
                            'user_id'=>Service_User::getUserId(),
                        );
                        Service_ShipOrderTracking::add($shipOrderTracking);

                        $uopt = array(
                            'ship_time'=>date("Y-m-d H:i:s"),
                            'ship_user_id'=>Service_User::getUserId(),
                        );
                        Service_OrderOperationTime::update($uopt,$order_code,'order_code');

                        $stateFrom = $orderRow['order_status'];
                        $olResult = Service_OrderLog::log($order_id, $order_code, $stateFrom, 8, 0, '订单出货');
                        if(!$oResult || !$olResult) throw new Exception($orderRow['order_code'].'数据库异常，更改订单状态失败');
                        //解冻预扣金额
                        $unfreezeRet = Service_CustomerBalanceProcess::unfreezeFee($order_code);
                        if($unfreezeRet !== true) throw new Exception($unfreezeRet);
                        //扣运费 和其它费用
                        $volArr['realWeight'] = $realWeight;
                        $feeResult = $soProcess->shipFee($order_code,$volArr);
                        if($feeResult !== true) throw new Exception($feeResult);

                        //bug 之前扣会读取不到批次你妹啊
                        if($orderRow['order_mode_type']=="0"){//集货模式的订单，无须扣库存  0:备货模式1:集货模式
                            //扣库存
                            $piResult = $soProcess->reduceStock($order_code);
                            if($piResult !== true) throw new Exception($piResult);
                        }

                        //提交事务
                        $db->commit();
                        //$db->rollback();
                        $result['state'] = 1;
                        $result['so_code'] = $soResult['so_code'];
                        echo $orderRow['order_code']."装袋成功!<br>";
                    } catch (Exception $e) {
                        $db->rollback();
                        echo $e->getMessage()."</br>";
                    }

                }
            }
        }
    }

    public function getEbayAction(){
        //error_reporting(E_ALL);
        //phpinfo();
        //exit;

        //set_time_limit(0);
        $soapUrl = "https://api.apacshipping.ebay.com.hk/aspapi/v4/ApacShippingService?WSDL";
        $client = new SoapClient($soapUrl);
        $DevID="c336f0c5-3df1-4df5-9de8-4f3aeafad286";//c336f0c5-3df1-4df5-9de8-4f3aeafad286
        $AppID="cargo3a33-16c0-4cc1-9493-ebe3ee4dc87";//cargo3a33-16c0-4cc1-9493-ebe3ee4dc87
        $CertID="bf0c88e8-b371-4a74-803a-75df19500454";//bf0c88e8-b371-4a74-803a-75df19500454
        $token = "AgAAAA**AQAAAA**aAAAAA**xJ+bVQ**nY+sHZ2PrBmdj6wVnY+sEZ2PrA2dj6AFmIegDZmAoA6dj6x9nY+seQ**7O0BAA**AAMAAA**TFlC41n0bTRXsoQFVIJDqJvtxwOQ+FniyE//znLyKWVLlZ4C57lhMzd42/79Ofxt1C1TSGBCjD3xJg4m1luodsJJ0BB4Y9oLLu7TqKxtUQPAIELLH7zQZqoV3YWGechQE/UQaNDSJ1hkys0Ke8LOBgu3ENnDs+5aB38EaGgxz4I126t6k/Cp7nQ0HGknQOtEgCuZt+vIg7H631qwaISwK0aelL0ZJAbf+fhlOWrQsdLaq800n+y/qox1lNBGt7+H1WtUDSrWn7DEqhFo+Lm0eILtzIyq562grAaQ1gV4lhWHH17zWVK7Xg5R6+O8wRFYqJDct1N+I6awTXuFMpucMGddMaiL6GQX0SrPYnFwoKeyo4gXuZSbDj6J54/U7JTI3RaPxQ4MNdfyxLVnLv6Mv0Y9vBPr6fYEXkVzu8hIcnLEC0AUPfzP/MqkAghxxB6Csb+X8ecpRfd8bjL+cniOyZxX7YDnrgPgE0SCotLXqK293YbPVuau728HgB3+0RhuacfUeaL4goJm9Bte5fFIxhlJ1HUcFEK1m9aOlewql5LTxV5WNYtJqlMyamrvOKR7LLHYwdunItZ6mHgqGXYFZW9VDd+BEN8RqBCqdec1i9IejzGFh+tm0e09zLLzkrKVBGqREndewpThV/2JV1tsht8KcJQNC5sCaxuLxYdJCvKkTgB7zjTKWge5Z6NhAHAllNt9/XnpviK+4Bn9V594l2DTD853P04ai/7EV3Zv4RMi6Lve+XpimRd3zQFnZLBr";
        $order['AddAPACShippingPackageRequest'] = array(
            'APIDevUserID'=>$DevID, //APIDevUserID
            'APISellerUserToken'=>$token,//APISellerUserToken
            'APISellerUserID'=>'abing.967',//APISellerUserID
            'AppID'=>$AppID,//AppID
            'AppCert'=>$CertID,//AppCert
            'MessageID'=>'SOE01740003720',
            'Carrier'=>'CNPOST',
            'Version'=>'4.0.0',
            'Service'=>'EPACK',
        );
        $order['AddAPACShippingPackageRequest']['OrderDetail'] = array(
            'EMSPickUpType'=>'1',
            'ExternalRefId'=>'101010101',
            'PickUpAddress'=>array(
                'Email'=>'dannyzhou@globex.cn',
                'Company'=>'cargo company',
                'CountryCode'=>'CN',
                'Province'=>'440000',
                'City'=>'440300',
                'District'=>'440304',
                'Street'=>'JinTian Road',
                'Postcode'=>'518026',
                'Contact'=>'Danny Zhou',
                'Mobile'=>'13594268155',
                'Phone'=>'0755-5180256',
            ),
            'ShipFromAddress'=>array(
                'Contact'=>'Danny Zhou',
                'Company'=>'cargo company',
                'Street'=>'JinTian Road No.8086 AnLian A 25 Floor',
                'District'=>'Futian district',
                'City'=>'shenzhen city',
                'Province'=>'GUANGDONG',
                'Postcode'=>'518026',
                'CountryCode'=>'CN',
                'Email'=>'dannyzhou@globex.cn',
                'Mobile'=>'13594268155',
                'Phone'=>'0755-21629199',
            ),
            'ShipToAddress'=>array(
                'Email'=>'237094549@qq.com',
                'Company'=>'Alan Harris',
                'Contact'=>'Andy Liu',
                'Phone'=>'041-329-5500',
                'Street'=>'5 Dewdrop PL',
                'City'=>'Ningi',
                'District'=>'',
                'Province'=>'Queensland',
                'Postcode'=>'451100',
                'CountryCode'=>'US',
                'Mobile'=>'12321232123'
            ),
            'ReturnAddress'=>array(
                'Company'=>'Cargo',
                'CountryCode'=>'CN',
                'Province'=>'440000',
                'City'=>'shenzhen city',
                'District'=>'Futian district',
                'Street'=>'JinTian Road No.8086 AnLian A 25 Floor',
                'Postcode'=>'518026',
                'Contact'=>'Danny Murphy',
            ),
            'ShippingPackage'=>array(
                'Description'=>'just for test',
                'Length'=>10,
                'Height'=>10,
                'Width'=>10,
                'Incoterms'=>'DDU',
                'CollectionInstructions'=>'轻拿轻放',
                'DeliveryInstructions'=>'轻拿轻放',
            ),
            'ItemList'=>array(
                'Item'=>array(
                    '0'=>array(
                        'EBayItemID'=>'181177693791', //eBay 物品号 380515348639
                        'EBayTransactionID'=>'1051636790008', //eBay 交易号，拍卖的物品请输入 0
                        'EBayBuyerID'=>'joshuaw7',//eBay 买家 ID
                        'EBayEmail'=>'',
                        'SoldQTY'=>'1',
                        'PostedQTY'=>'1',
                        'SalesRecordNumber'=>'',
                        'OrderSalesRecordNumber'=>'',
                        'OrderID'=>'',
                        'EBaySiteID'=>'',
                        'ReceivedAmount'=>'',
                        'PaymentDate'=>'2015-07-08',
                        'SoldPrice'=>'11',
                        'SoldDate'=>'2015-07-05',
                        'CurrencyCode'=>'USD',
                        'EBayMessage'=>'',
                        'PayPalEmail'=>'',
                        'PayPalMessage'=>'',
                        'Note'=>'just for test!',
                        'SKU'=>array(
                            "SKUID"=>"2014071102",
                            "Weight"=>"0.5000",
                            "CustomsTitle"=>"文具",
                            "CustomsTitleEN"=>"just for test",
                            "DeclaredValue"=>"21.0000",
                            "OriginCountryName"=>"China",
                            "OriginCountryCode"=>"CN",
                            'HTSNumber'=>'CA',
                        )
                    ),
                ),
            ),
        );

        $response = $client->AddAPACShippingPackage($order);
        $result = Common_Common::objectToArray($response);
        echo "<pre>";
        var_dump($result);
        echo "</pre>";
        exit;

        exit;
        set_time_limit(0);
        $DevID="c336f0c5-3df1-4df5-9de8-4f3aeafad286";//c336f0c5-3df1-4df5-9de8-4f3aeafad286
        $AppID="cargo3a33-16c0-4cc1-9493-ebe3ee4dc87";//cargo3a33-16c0-4cc1-9493-ebe3ee4dc87
        $CertID="bf0c88e8-b371-4a74-803a-75df19500454";//bf0c88e8-b371-4a74-803a-75df19500454
        $token = "AgAAAA**AQAAAA**aAAAAA**xJ+bVQ**nY+sHZ2PrBmdj6wVnY+sEZ2PrA2dj6AFmIegDZmAoA6dj6x9nY+seQ**7O0BAA**AAMAAA**TFlC41n0bTRXsoQFVIJDqJvtxwOQ+FniyE//znLyKWVLlZ4C57lhMzd42/79Ofxt1C1TSGBCjD3xJg4m1luodsJJ0BB4Y9oLLu7TqKxtUQPAIELLH7zQZqoV3YWGechQE/UQaNDSJ1hkys0Ke8LOBgu3ENnDs+5aB38EaGgxz4I126t6k/Cp7nQ0HGknQOtEgCuZt+vIg7H631qwaISwK0aelL0ZJAbf+fhlOWrQsdLaq800n+y/qox1lNBGt7+H1WtUDSrWn7DEqhFo+Lm0eILtzIyq562grAaQ1gV4lhWHH17zWVK7Xg5R6+O8wRFYqJDct1N+I6awTXuFMpucMGddMaiL6GQX0SrPYnFwoKeyo4gXuZSbDj6J54/U7JTI3RaPxQ4MNdfyxLVnLv6Mv0Y9vBPr6fYEXkVzu8hIcnLEC0AUPfzP/MqkAghxxB6Csb+X8ecpRfd8bjL+cniOyZxX7YDnrgPgE0SCotLXqK293YbPVuau728HgB3+0RhuacfUeaL4goJm9Bte5fFIxhlJ1HUcFEK1m9aOlewql5LTxV5WNYtJqlMyamrvOKR7LLHYwdunItZ6mHgqGXYFZW9VDd+BEN8RqBCqdec1i9IejzGFh+tm0e09zLLzkrKVBGqREndewpThV/2JV1tsht8KcJQNC5sCaxuLxYdJCvKkTgB7zjTKWge5Z6NhAHAllNt9/XnpviK+4Bn9V594l2DTD853P04ai/7EV3Zv4RMi6Lve+XpimRd3zQFnZLBr";
        $sellerId = "abing.967";
        $orderCode = "SOE01740020727";
        $order = Service_Orders::getByField($orderCode,"order_code","*");
        // 数据过滤
        /*if (!in_array(trim($order['sm_code']),array('WG-FEDEX','WG-CNPOST','CNPOST','FEDEX'))
            || 1 !== (int) $order['order_mode_type']
            || 4 !== (int) $order['order_status']
            || '' !== trim($order['ref_tracking_number'])) {
            die("FFFFFF") ;
        }*/
        $receivingAddress = Service_OrderAddressBook::getByField($order['order_id'],'order_id',"*");
        $country = Service_Country::getByField($receivingAddress["oab_country_id"],"country_id","*");
        $shipToAddress = array(
            'email' => $receivingAddress['oab_email'],
            'company' => $receivingAddress['oab_company'],
            'contact' => $receivingAddress['oab_firstname'],
            'phone' => $receivingAddress['oab_cell_phone'],
            'street' => $receivingAddress['oab_street_address1'],
            'city' => $receivingAddress['oab_city'],
            'District' => $receivingAddress['oab_state'],
            'postcode' => $receivingAddress['oab_postcode'],
            'country' => $country['country_name_en'],
            'country_code' => $country['country_code'],
        );
        $ebayWebService = Service_EBAYApiProcess::getInstance();
        //die("ssssss1");
        $Carrier = "CNPOST";
        $service = "EPACK";
        /*if($order['sm_code']=="WG-FEDEX"||$order['sm_code']=="FEDEX"){
            $Carrier = "FEDEX";
            $service = "INT_EC";
        }*/
        $header = array(
            'APIDevUserID'=>$DevID,
            'APISellerUserToken'=>$token,
            'APISellerUserID'=>$sellerId,
            'AppID'=>$AppID,
            'AppCert'=>$CertID,
            'MessageID'=>$order['order_code'],
            'Carrier'=>$Carrier,
            'Version'=>'4.0.0',
            'Service'=>$service,
        );
        $ebayWebService->setHeader($header);
        //$ebayWebService->verifyUser();
        $pickUpType = 0;
        $ebayWebService->setPickUpType($pickUpType);
        $shipFromAddress = array(
            'contact' => 'Danny Zhou',
            'company' => 'cargo company',
            'street' => 'JinTian Road No.8086 AnLian A 25 Floor',
            'district' => 'Futian district',
            'city' => 'shenzhen city',
            'province' => 'GUANGDONG',
            'postcode' => '518026',
            'country' => 'CHINA',
            'email' => 'Dannyzhou@globex.cn',
            'mobile' => '13594268155',
        );
        $returnAddress = array(
            'company' => 'Cargo',     //公司
            'country' => "中国",     //国家 中国
            'province' => '广东',   //省
            'city' => 'shenzhen city',           //城市
            'district' => 'Futian district',   //区
            'street' => 'JinTian Road No.8086 AnLian A 25 Floor',       //街道
            'postcode' => '518026',   //邮编
            'contact' => 'Danny Murphy',     //联系人
        );
        $pickUpAddress = array(
            'email' => 'Dannyzhou@globex.cn',
            'company' => 'cargo company',
            'country' => '中国',
            'province' => '440000',
            'city' => '440300',
            'district' => '440304',
            'street' => 'JinTian Road',
            'postcode' => '518026',
            'contact' => 'Danny Zhou',
            'mobile' => '0755-5180256',
            'phone' => '13594268155',
        );
        $ebayWebService->setShipToAddress($shipToAddress);
        $ebayWebService->setShipFromAddress($shipFromAddress);
        $ebayWebService->setReturnAddress($returnAddress);
        $ebayWebService->setPickUpAddress($pickUpAddress);
        $orderProduct = Service_OrderProduct::getByCondition(array("order_code"=>$order['order_code']),"*");
        foreach($orderProduct as $k=>$v){
            $product = Service_Product::getByField($v['product_id'],"product_id","*");
            $ebayDetail = Service_EbayOrderDetail::getByField($v['op_id'],"op_id","*");
            $epacketItem = array(
                'skuid' => $product['product_sku'],
                'weight' => $product['product_weight'],
                'customs_title_cn' => $product['product_title'],
                'customs_title_en' => $product['product_title_en'],
                'declared_value' => $product['product_declared_value'],
                'currency_code' => 'USD',
                'ebay_email' => '',
                'ebay_buyer_id' => $ebayDetail['ebay_buyer_id'],
                'ebay_item_id' => $ebayDetail['ebay_item_id'],
                'ebay_item_title' => '',
                'ebay_message' => '',
                'ebay_site_id' => '',
                'ebay_transaction_id' => $ebayDetail['ebay_transaction_id'],
                'order_id'=>'',
                'note' => '',
                'order_sales_record_number' => '',
                'payment_date' =>'',
                'paypal_email' => '',
                'paypal_message' => '',
                'posted_qty' => $v['op_quantity'],
                'received_amount' =>'',
                'sales_record_number' => '',
                'sold_date' => '',
                'sold_price' => $product['product_sales_value'],
                'sold_qty' => $v['op_quantity'],
            );
            $ebayWebService->addItem($epacketItem);
        }
        $result = $ebayWebService->AddPackage();
        if (strtolower($result->AddAPACShippingPackageResult->Ack) == 'success'){
            $confirmEpacket = $ebayWebService->confirmPackage(array('track_number' => $result->AddAPACShippingPackageResult->TrackCode));
            if (strtolower($confirmEpacket->ConfirmAPACShippingPackageResult->Ack) == 'success') {
                $label = $ebayWebService->getShippingLabel($result->AddAPACShippingPackageResult->TrackCode);
                $file = APPLICATION_PATH.'/../data/pdf/ebay/'.$order['order_code'].".pdf";
                if(!file_exists($file)){
                    $fp=fopen($file, "w+");
                }
                file_put_contents($file,$label);
                $ret = array(
                    'ask'=>'1',
                    'message'=>'成功获取pdf标签'
                );
                die(json_encode($ret));
            }
        }else{
            $ret = Common_Common::objectToArray($result);
            echo "<pre>";
            var_dump($ret);
            echo "</pre>";
        }
    }

    public function commitToEbayAction(){
        error_reporting(E_ALL);
        $wsdlUrl = "https://api.apacshipping.ebay.com.hk/aspapi/v4/ApacShippingService?WSDL";
        $DevID="78d0e8cd-de24-48ed-9515-ab90455d9242";//c336f0c5-3df1-4df5-9de8-4f3aeafad286
        $AppID="jeremyyi-19b0-4518-a946-27c6ddf6e4e2";//cargo3a33-16c0-4cc1-9493-ebe3ee4dc87
        $CertID="6e9d991d-b989-431f-8141-f0ada5a056ba";//bf0c88e8-b371-4a74-803a-75df19500454
        $token = "AgAAAA**AQAAAA**aAAAAA**VX/AVQ**nY+sHZ2PrBmdj6wVnY+sEZ2PrA2dj6AHmIakDZmAqQ6dj6x9nY+seQ**JPECAA**AAMAAA**HUgeD5fKUg5lT46qkf2rozJuv05m7H5/hmBCi7ArioCM3VlBUBnk6SKNpzRfMoMs80p72pKoX/T8Shfi9jYMC5lGSTsANLJA+e1cpl7G4hrj0lzU2Q93O9JtOGQVnEdy/OtEHl4DPAg0E7zRen+ZnwmwP987wdvCYKUg3oGPa6bm1z6XXtn50biK6OK4l35pw6sMRgvxFyqQPGcb1hrEsRbyw0NyAyTtZh4+yfRa65IUIGVf288gTFeQHbAgi8jOrYUBRFs/HpPuzLZVi8KxgnIwmVTw8IinMens1rTmd5quZX7z5BnIRgm8BeyuYEWUSRL0wRy68q8b/whbABIhd47JE3CXyh6WRhM5ea8MrTV77QTN92V2e/uKlyTt/Qz4tQg8I1L6kCmHkXV1jaXwNHyOW6Sd9yMrgTPJ1bgR/WHOAhRv6NuPLmgZGQ7jQGyRROss8dF1+9vpsPZmn0/ZbycKBHCXgAgUgLObYjS63hnqNgYLe8zHdOT458JIfeA6i0o9iCJbqHzpoyfuyUts1PQjo9Ohop7q5+SVKTkZPl906b6w86dF1rew7hOCNAxusY0trmQFsf7kKfb5Zbme1y1/WbCIu5XFnohQh73Bo80dl/bW9q5jk/0Hy5Lou9YKLWjt1LO2x+aj2yK+m2UzwE1bvBrXVdlqiDv3Wy4zS5gOQ++OiqTO079s2HAch16+C0rc7Ot1ExR22YtYGv1JwwKHGHwsRVhc9Qd6FQkGxNWfPxbSJFX/i42nYrJphV4w";
        $sellerId = "myledmart";
        $client = new SoapClient($wsdlUrl);
        $order_code = "SOE01740020727";
        $order = Service_Orders::getByField($order_code,"order_code","*");

        $receivingAddress = Service_OrderAddressBook::getByField($order['order_id'],'order_id',"*");
        $country = Service_Country::getByField($receivingAddress["oab_country_id"],"country_id","*");
        $orderRequest['AddAPACShippingPackageRequest'] = array(
            'APIDevUserID'=>$DevID, //APIDevUserID
            'APISellerUserToken'=>$token,//APISellerUserToken
            'APISellerUserID'=>$sellerId,//APISellerUserID
            'AppID'=>$AppID,//AppID
            'AppCert'=>$CertID,//AppCert
            'MessageID'=>$order['order_id'],
            'Carrier'=>'CNPOST',
            'Version'=>'4.0.0',
            'Service'=>'EPACK',
        );
        $orderRequest['AddAPACShippingPackageRequest']['OrderDetail'] = array(
            'EMSPickUpType'=>'1',
            'ExternalRefId'=>'101010101',
            //PickUpAddress 揽收地址信息。
            //揽收地址现阶段只支持部分城市，
            //province/city/district 值请参考揽收
            //地址代码表。
            //国际 e 邮宝的订单必须使用中文地址。
            //FedEx 的订单必须使用英文地址。
            'PickUpAddress'=>array(
                'Email'=>'szsc_baiban@china-fec.com',
                'Company'=>'招海',
                'CountryCode'=>'CN',
                'Province'=>'广东',
                'City'=>'深圳市',
                'District'=>'南山区',
                'Street'=>'广东省深圳市南山区临海大道53号前海湾保税港区',
                'Postcode'=>'518000',
                'Contact'=>'周彩云',
                'Mobile'=>'18718573382',
                'Phone'=>'18718573382',
            ),
            //ShipFromAddress
            //寄件人地址信息，必须以英文填写。
            //此地址将被打印在标签的寄件人地
            //址一栏中。
            'ShipFromAddress'=>array(
                'Contact'=>'Cherry Zhou',
                'Company'=>'Shenzhen Baohong Ecommerce Integrated Services Co-, Ltd',
                'Street'=>'4/F, Block 5,Qianhaiwan Free Trade Port Area,No.53  Linhai Rd. Nanshan  District, Shenzhen, P.R.C.',
                'District'=>'Nanshan',
                'City'=>'Shenzhen',
                'Province'=>'Guangdong',
                'Postcode'=>'518000',
                'CountryCode'=>'CN',
                'Email'=>'szsc_baiban@china-fec.com',
                'Mobile'=>'18718573382',
                'Phone'=>'18718573382',
            ),
            //ReturnAddress
            //退货地址信息，并且必须保持与寄
            //件人地址是中英文翻译的关系。
            //对国际 e 邮宝，请填写中文地址。
            //对 FedEx，请填写英文地址。
            /*'ReturnAddress'=>array(
                'Company'=>'Cargo',
                'CountryCode'=>'CN',
                'Province'=>'440000',
                'City'=>'shenzhen city',
                'District'=>'Futian district',
                'Street'=>'JinTian Road No.8086 AnLian A 25 Floor',
                'Postcode'=>'518026',
                'Contact'=>'Danny Murphy',
            ),
            //ShippingPackage 为 FedEx 包裹必填字段。 国际 e 邮宝包裹不需填写。
            'ShippingPackage'=>array(
                'Description'=>'just for test',
                'Length'=>10,
                'Height'=>10,
                'Width'=>10,
                'Incoterms'=>'DDU',
                'CollectionInstructions'=>'轻拿轻放',
                'DeliveryInstructions'=>'轻拿轻放',
            ),*/
            //ShipToAddress
            //收件人地址信息。此地址将被打印
            //在标签的收件人地址一栏中。 支持
            //英语及俄语。
            'ShipToAddress'=>array(
                'Email'=>'237094549@qq.com',
                'Company'=>'Alan Harris',
                'Contact'=>'Andy Liu',
                'Phone'=>'041-329-5500',
                'Street'=>'5 Dewdrop PL',
                'City'=>'Ningi',
                'District'=>'',
                'Province'=>'Queensland',
                'Postcode'=>'451100',
                'CountryCode'=>'US',
                'Mobile'=>'12321232123'
            ),
        );
        $orderRequest['AddAPACShippingPackageRequest']['OrderDetail']['ItemList']['Item'] = array();
        $orderProduct = Service_OrderProduct::getByCondition(array("order_code"=>$order['order_code']),"*");
        foreach($orderProduct as $k=>$v){
            $product = Service_Product::getByField($v['product_id'],"product_id","*");
            $ebayDetail = Service_EbayOrderDetail::getByField($v['op_id'],"op_id","*");
            $epacketItem = array(
                'EBayItemID'=>$ebayDetail['ebay_item_id'],
                'EBayTransactionID'=>$ebayDetail['ebay_transaction_id'],
                'EBayBuyerID'=>$ebayDetail['ebay_buyer_id'],
                'EBayItemTitle'=>$v['product_title_en'],
                'EBayEmail'=>'',
                'SoldQTY'=>$v['op_quantity'],
                'PostedQTY'=>$v['op_quantity'],
                'SalesRecordNumber'=>'',
                'OrderSalesRecordNumber'=>'',
                'OrderID'=>'',
                'EBaySiteID'=>'',
                'ReceivedAmount'=>'',
                'PaymentDate'=>'',
                'SoldPrice'=>'',
                'SoldDate'=>'',
                'CurrencyCode'=>'USD',
                'EBayMessage'=>'',
                'PayPalEmail'=>'',
                'PayPalMessage'=>'',
                'Note'=>'',
                'SKU'=>array(
                    'SKUID' => $product['product_sku'],//SKU ID
                    'Weight' => $product['product_weight'],//物品重量（千克），国际 e 邮宝包裹可用值 0-2 FedEx: 0.005-200KG
                    'CustomsTitle' => $product['hs_goods_name'],//英文报关名称 FedEx 不需填写 国际 e 邮宝包裹请填中文报关名
                    'CustomsTitleEN' => $product['product_title_en'], //英文报关名称
                    'DeclaredValue' => $product['product_declared_value'],//物品申报价值 对 BP_MINIPAK，申报价值不得超 过 22 欧
                    'OriginCountryName' => empty($item['origin_country_name']) ? 'China' : $item['origin_country_name'],//原产地名称，可用值请填写原产国 英文名称
                    'OriginCountryCode' => empty($item['origin_country_code']) ? 'CN' : $item['origin_country_code'],//原产地国家二字码
                    'HTSNumber'=>'',//关税代码，最小长度为 2
                ),
            );
            $orderRequest['AddAPACShippingPackageRequest']['OrderDetail']['ItemList']['Item'][] = $epacketItem;
        }
        $response = $client->AddAPACShippingPackage($orderRequest);
        echo "<pre>";
        var_dump($response);
        echo "</pre>";
        echo "after AddAPACShippingPackage</br>";
        if (strtolower($response->AddAPACShippingPackageResult->Ack) == 'success'){
            $confirmArray = array(
                'ConfirmAPACShippingPackageRequest' => array(
                    'APIDevUserID'=>$DevID, //APIDevUserID
                    'APISellerUserToken'=>$token,//APISellerUserToken
                    'APISellerUserID'=>$sellerId,//APISellerUserID
                    'AppID'=>$AppID,//AppID
                    'AppCert'=>$CertID,//AppCert
                    'MessageID'=>$order['order_id'],
                    'Carrier'=>'CNPOST',
                    'Version'=>'4.0.0',
                    'Service'=>'EPACK',
                    'TrackCode'=>$response->AddAPACShippingPackageResult->TrackCode
                ),
            );
            $response2 = $client->ConfirmAPACShippingPackage($confirmArray);
            echo "<pre>";
            var_dump($response2);
            echo "</pre>";
            echo "after ConfirmAPACShippingPackage</br>";
            if (strtolower($response2->ConfirmAPACShippingPackageResult->Ack) == 'success'){
                $getLabelArray = array(
                    'GetAPACShippingLabelRequest' => array(
                        'APIDevUserID'=>$DevID, //APIDevUserID
                        'APISellerUserToken'=>$token,//APISellerUserToken
                        'APISellerUserID'=>$sellerId,//APISellerUserID
                        'AppID'=>$AppID,//AppID
                        'AppCert'=>$CertID,//AppCert
                        'MessageID'=>$order['order_id'],
                        'Carrier'=>'CNPOST',
                        'Version'=>'4.0.0',
                        'Service'=>'EPACK',
                        'TrackCode'=>$response->AddAPACShippingPackageResult->TrackCode,
                        'PageSize'=>1,
                    ),
                );
                //$getLabelArray['GetAPACShippingLabelRequest']['TrackCode'] = $trackNumber;
                //$getLabelArray['GetAPACShippingLabelRequest']['PageSize'] = '1';
                $response3 = $client->GetAPACShippingLabel($getLabelArray);
                echo "<pre>";
                var_dump($response3);
                echo "</pre>";
                echo "after GetAPACShippingLabel</br>";
            }
        }
    }

    public function getebaylabelAction(){
        set_time_limit(0);
        $wsdlUrl = "https://api.apacshipping.ebay.com.hk/aspapi/v4/ApacShippingService?WSDL";
        $DevID="78d0e8cd-de24-48ed-9515-ab90455d9242";//c336f0c5-3df1-4df5-9de8-4f3aeafad286
        $AppID="jeremyyi-19b0-4518-a946-27c6ddf6e4e2";//cargo3a33-16c0-4cc1-9493-ebe3ee4dc87
        $CertID="6e9d991d-b989-431f-8141-f0ada5a056ba";//bf0c88e8-b371-4a74-803a-75df19500454
        $token = "AgAAAA**AQAAAA**aAAAAA**VX/AVQ**nY+sHZ2PrBmdj6wVnY+sEZ2PrA2dj6AHmIakDZmAqQ6dj6x9nY+seQ**JPECAA**AAMAAA**HUgeD5fKUg5lT46qkf2rozJuv05m7H5/hmBCi7ArioCM3VlBUBnk6SKNpzRfMoMs80p72pKoX/T8Shfi9jYMC5lGSTsANLJA+e1cpl7G4hrj0lzU2Q93O9JtOGQVnEdy/OtEHl4DPAg0E7zRen+ZnwmwP987wdvCYKUg3oGPa6bm1z6XXtn50biK6OK4l35pw6sMRgvxFyqQPGcb1hrEsRbyw0NyAyTtZh4+yfRa65IUIGVf288gTFeQHbAgi8jOrYUBRFs/HpPuzLZVi8KxgnIwmVTw8IinMens1rTmd5quZX7z5BnIRgm8BeyuYEWUSRL0wRy68q8b/whbABIhd47JE3CXyh6WRhM5ea8MrTV77QTN92V2e/uKlyTt/Qz4tQg8I1L6kCmHkXV1jaXwNHyOW6Sd9yMrgTPJ1bgR/WHOAhRv6NuPLmgZGQ7jQGyRROss8dF1+9vpsPZmn0/ZbycKBHCXgAgUgLObYjS63hnqNgYLe8zHdOT458JIfeA6i0o9iCJbqHzpoyfuyUts1PQjo9Ohop7q5+SVKTkZPl906b6w86dF1rew7hOCNAxusY0trmQFsf7kKfb5Zbme1y1/WbCIu5XFnohQh73Bo80dl/bW9q5jk/0Hy5Lou9YKLWjt1LO2x+aj2yK+m2UzwE1bvBrXVdlqiDv3Wy4zS5gOQ++OiqTO079s2HAch16+C0rc7Ot1ExR22YtYGv1JwwKHGHwsRVhc9Qd6FQkGxNWfPxbSJFX/i42nYrJphV4w";
        $sellerId = "myledmart";
        $client = new SoapClient($wsdlUrl);
        $getLabelArray = array(
            'GetAPACShippingLabelRequest' => array(
                'APIDevUserID'=>$DevID, //APIDevUserID
                'APISellerUserToken'=>$token,//APISellerUserToken
                'APISellerUserID'=>$sellerId,//APISellerUserID
                'AppID'=>$AppID,//AppID
                'AppCert'=>$CertID,//AppCert
                'MessageID'=>date("Y-m-d H:i:s"),
                'Carrier'=>'CNPOST',
                'Version'=>'4.0.0',
                'Service'=>'EPACK',
                'TrackCode'=>'LK586646415CN',
                'PageSize'=>1,
            ),
        );
        $result = $client->GetAPACShippingLabel($getLabelArray);
        $result = objectToArray($result);
        echo "<pre>";
        var_dump($result);
        echo "</pre>";
        exit;
    }

    public function caldifInventoryAction(){
        exit;
        set_time_limit(0);
        error_reporting(E_ALL);
        require_once APPLICATION_PATH . '/../libs/PHPExcel.php';
        require_once APPLICATION_PATH . '/../libs/PHPExcel/IOFactory.php';

        $full_path = APPLICATION_PATH.'/../data/file/kc.xls';

        $resultArray = Common_Upload::readEXCEL($full_path);

        foreach($resultArray as $key=>$value){
            if($key==0) continue;
            $goods_code = $value[0];
            $zb_qty1 = $value[1];
            $unit1 = $value[2];
            $productList = Service_Product::getByCondition(array('goods_id'=>$goods_code),"*");
            $csc_qty1 = 0;
            $csc_qty2 = 0;
            $zb_qty2 = 0;
            $unit2 = "";
            foreach($productList as $k=>$product){
                $productInventory = Service_ProductInventory::getByCondition(array('product_id'=>$product['product_id'],'warehouse_id'=>'1'),"*");
                if(!empty($productInventory)){
                    $inventory = $productInventory[0];
                    if($inventory['pi_sellable']>0){
                        $hemList = Service_HsElementMap::getByCondition(array('product_id'=>$product['product_id']),'hem_detail');
                        $elements = array();
                        foreach($hemList as $hemRow) $elements[] = $hemRow['hem_detail'];
                        $receivingXmlDetail['g_model'] = implode('|',$elements);
                        $hs_uom_map = Service_HsUomMap::getByField($product['product_id'],'product_id',"*");
                        $quantitylaw1 = isset($hs_uom_map['hum_quantity_law'])?$hs_uom_map['hum_quantity_law']:'0';
                        $csc_qty1 += $quantitylaw1*$inventory['pi_sellable'];
                        $quantitylaw2 = isset($hs_uom_map['hum_quantity_second'])?$hs_uom_map['hum_quantity_second']:"0";
                        $csc_qty2 += $quantitylaw2*$inventory['pi_sellable'];
                        if(!empty($hs_uom_map)) $hs_uom = Service_HsUom::getByField($hs_uom_map['hu_id'],'hu_id',"*");
                        //$receivingXmlDetail['unit_1'] = isset($hs_uom['pu_code_law'])?$hs_uom['pu_code_law']:"";
                        $unit2 = isset($hs_uom['pu_code_second'])?$hs_uom['pu_code_second']:"";
                    }

                }
            }
            $inventoryDifference = array(
                'goods_code'=>$goods_code,
                'zb_qty1'=>$zb_qty1,
                'csc_qty1'=>$csc_qty1,
                'dif_value1'=>$csc_qty1-$zb_qty1,
                'unit1'=>$unit1,
                'zb_qty2'=>$zb_qty2,
                'csc_qty2'=>$csc_qty2,
                'dif_value2'=>$csc_qty2-$zb_qty2,
                'unit2'=>$unit2,
                'deal_status'=>0,
            );
            Service_InventoryDifference::add($inventoryDifference);
            $filePath = APPLICATION_PATH.'/../data/log/'.'Debug.txt';
            if(!file_exists($filePath)){
                $fp= fopen($filePath,"w");
                fclose($fp);
            }
            file_put_contents($filePath,var_export("料件号[".$goods_code."]处理完毕\n",true),FILE_APPEND);
        }
        echo "rund end!(^-^)";
    }

    public function calqtyAction(){
        exit;
        set_time_limit(0);
        error_reporting(E_ALL);
        $count = Service_ReceivingXmlDetail::getByCondition(array(),"count(*)");
        $pageSize = 20;
        $totalPage = ceil($count/$pageSize);
        for($page = 1;$page<=$totalPage;$page++){
            $receivingXmlDetailList = Service_ReceivingXmlDetail::getByCondition(array(),"*",$pageSize,$page,'rxd_id asc');
            foreach($receivingXmlDetailList as $rxd){
                $receiving = Service_Receiving::getByField($rxd['from_id'],'receiving_code',"*");
                if($receiving['receive_model_type']=="1"){
                    $productList = Service_OrderProduct::getJoinProductByCondition(array('goods_id'=>$rxd['goods_id'],'receiving_code'=>$receiving['receiving_code']));
                }else{
                    $productList = Service_ReceivingDetail::getJoinProductByCondition(array('goods_id'=>$rxd['goods_id'],'receiving_code'=>$receiving['receiving_code']));
                }
                $real_qty1 = 0;
                $real_qty2 = 0;
                foreach($productList as $p){
                    if($receiving['receive_model_type']=="1"){
                        $quantity = $p['op_quantity'];
                    }else{
                        $quantity = $p['rd_receiving_qty'];
                    }

                    $hemList = Service_HsElementMap::getByCondition(array('product_id'=>$p['product_id']), 'hem_detail');
                    $elements = array();

                    foreach($hemList as $hemRow) $elements[] = $hemRow['hem_detail'];
                    $receivingXmlDetail['g_model'] = implode('|',$elements);
                    $hs_uom_map = Service_HsUomMap::getByField($p['product_id'],'product_id',"*");
                    $quantitylaw1 = isset($hs_uom_map['hum_quantity_law'])?$hs_uom_map['hum_quantity_law']:'0';
                    $real_qty1 += $quantitylaw1*$quantity;
                    $quantitylaw2 = isset($hs_uom_map['hum_quantity_second'])?$hs_uom_map['hum_quantity_second']:"0";
                    $real_qty2 += $quantitylaw2*$quantity;
                    /*if(!empty($hs_uom_map)) $hs_uom = Service_HsUom::getByField($hs_uom_map['hu_id'],'hu_id',"*");
                    $receivingXmlDetail['unit_1'] = isset($hs_uom['pu_code_law'])?$hs_uom['pu_code_law']:"";
                    $receivingXmlDetail['unit_2'] = isset($hs_uom['pu_code_second'])?$hs_uom['pu_code_second']:"";*/
                }
                $dif_qty1 = $real_qty1-$rxd['qty_1'];
                $dif_qty2 = $real_qty2-$rxd['qty_2'];
                $updateRxd = array(
                    'real_qty1'=>$real_qty1,
                    'real_qty2'=>$real_qty2,
                    'dif_qty1'=>$dif_qty1,
                    'dif_qty2'=>$dif_qty2,
                );
                Service_ReceivingXmlDetail::update($updateRxd,$rxd['rxd_id'],"rxd_id");
                $filePath = APPLICATION_PATH.'/../data/log/'.'Debug2.txt';
                if(!file_exists($filePath)){
                    $fp= fopen($filePath,"w");
                    fclose($fp);
                }
                file_put_contents($filePath,var_export("入区单[".$rxd['from_id']."]料件号[".$rxd['goods_id']."]处理完毕\n",true),FILE_APPEND);
            }
        }
        echo "run end!(^-^)";
    }

    public function addpostcodeAction(){
        /*set_time_limit(0);
        for($postcode = 5440300;$postcode<=5440306;$postcode++){
            $postcodeArr = array(
                'country_id'=>'216',
                'city_id'=>'370048',
                'postcode_no'=>$postcode
            );
            Service_Postcode::add($postcodeArr);
        }
        echo "run end!";*/
        //$ftProcess = new Service_FtpReceiveProcess();
        //$sendRow = Service_FtpMessageSendlist::getByField("BHR150002474A","refercence_no","*");
        //$affect = $ftProcess->updateSendMessage($sendRow);

    }

    public function changhaiguanAction(){
        exit;
        require_once APPLICATION_PATH . '/../libs/PHPExcel.php';
        require_once APPLICATION_PATH . '/../libs/PHPExcel/IOFactory.php';

        $full_path = APPLICATION_PATH.'/../data/file/test2.xls';

        $resultArray = Common_Upload::readEXCEL($full_path);
        //echo "<pre>";
        //var_dump($resultArray);
        //echo "</pre>";
        //exit;
        foreach($resultArray as $key=>$value){
            if($key==0) continue;
            $orderRow = Service_Orders::getByField($value[0],"reference_no","*");
            if(!empty($orderRow)){
                $orderProduct = Service_OrderProduct::getByCondition(array('order_code'=>$orderRow['order_code'],"product_barcode"=>$value[2]),"*",1,1);
                if(!empty($orderProduct)){
                    $updateOP = array(
                        'op_purpose_declared_value'=>$value[4],
                    );
                    Service_OrderProduct::update($updateOP,$orderProduct[0]['op_id'],"op_id");
                    echo "reference_no=".$value[0]."&order_code=".$orderRow['order_code']."</br>";
                }
            }
            /*$updateProduct = array(
                'product_declared_value'=>$value[1],
                'product_weight'=>$value[2],
                'model_serial'=>$value[3],
            );
            $pid = Service_Product::update($updateProduct,$value[0],'product_sku');
            if($pid){
                echo "product_sku[".$value[0]."]update Success!<br>";
            }else{
                echo "product_sku[".$value[0]."]update failure!<br>";
            }*/
        }
    }

    public function addstnAction(){
        exit;
        set_time_limit(0);
        $prefix = "RX";
        $arefix = "DE";
        for($go=90931108;$go<=90941108;$go++){
            $gs = (string)$go;
            $r =  $gs{0}*8+$gs{1}*6+$gs{2}*4+$gs{3}*2+$gs{4}*3+$gs{5}*5+$gs{6}*9+$gs{7}*7;
            $result = 11-$r%11;
            if($result>=1&&$result<=9){
                $stnCode = $prefix.$gs.$result.$arefix;
            }
            if($result==10){
                $stnCode = $prefix.$gs.'0'.$arefix;
            }
            if($result==11){
                $stnCode = $prefix.$gs.'5'.$arefix;
            }
            $stnRow = array(
                'warehouse_id'=>'1',
                'stn_code'=>$stnCode,
                'sm_code'=>'CJ-DGMG',
                'stn_status'=>'0',
                'stn_add_time'=>date("Y-m-d H:i:s"),
                'stn_update_time'=>date("Y-m-d H:i:s"),
            );
            //echo "<pre>";
            //var_dump($stnRow);
            //echo "</pre>";
            //echo "stnCode=".$stnCode."</br>";
            $id = Service_ServiceTrackingNumber::add($stnRow);
            if($id){
                echo "stnCode=".$stnCode." add success!</br>";
            }else{
                echo "stnCode=".$stnCode." add failure!</br>";
            }
        }
    }

    public function exportDhlAction(){
        error_reporting(E_ALL);
        $sql = "SELECT ship_batch.sb_code,ship_batch.sb_ship_time,customer.customer_company_name,orders.order_code, ship_order.tracking_number,orders.sm_code,ship_order.so_weight,country.country_name,logistics_cost.total_fee as l_total_fee,cost_recording.total_fee as c_total_fee,logistics_cost.currency_code AS l_currency_code,cost_recording.currency_code AS c_currency_code FROM ship_batch JOIN ship_batch_detail ON ship_batch.sb_code=ship_batch_detail.sb_code JOIN outbound_bag_detail ON outbound_bag_detail.ob_no=ship_batch_detail.ob_no JOIN orders ON outbound_bag_detail.order_code=orders.order_code JOIN ship_order ON orders.order_code=ship_order.order_code JOIN order_address_book ON order_address_book.order_id=orders.order_id JOIN country ON country.country_id=order_address_book.oab_country_id JOIN customer ON orders.customer_code=customer.customer_code JOIN logistics_cost ON logistics_cost.order_code=orders.order_code JOIN cost_recording ON cost_recording.order_code=orders.order_code WHERE ship_batch.sb_ship_time>='2015-10-01 00:00:00' AND ship_batch.sb_ship_time<='2015-10-31 23:59:59'";
        $tableObj = new Table_Orders();
        $result = $tableObj->getAdapter()->fetchAll($sql);
        //var_dump($result);
        //exit;
        $filename = "ship_batch.xls";
        header('Pragma:public');
        header("Content-Type:application/x-msexecl;name={$filename}");
        header("Content-Disposition:inline;filename={$filename}");
        echo "<table border='1'>";
        echo "<tr>";
        echo "<td>sb_code</td>";
        echo "<td>sb_ship_time</td>";
        echo "<td>customer_code</td>";
        echo "<td>order_code</td>";
        echo "<td>tracking_number</td>";
        echo "<td>sm_code</td>";
        echo "<td>so_weight</td>";
        echo "<td>country_code</td>";
        echo "<td>件数</td>";
        echo "<td>应收运费</td>";
        echo "<td>应收运费币种</td>";
        echo "<td>应付运费</td>";
        echo "<td>应付运费币种</td>";
        echo "</tr>";


        foreach($result as $key=>$value){

            echo "<tr>";
            echo "<td>{$value['sb_code']}</td>";
            echo "<td>{$value['sb_ship_time']}</td>";
            echo "<td>{$value['customer_company_name']}</td>";
            echo "<td>{$value['order_code']}</td>";
            echo "<td>{$value['tracking_number']}</td>";
            echo "<td>{$value['sm_code']}</td>";
            echo "<td>{$value['so_weight']}</td>";
            echo "<td>{$value['country_name']}</td>";
            $sql = "select count(*) from ship_order_detail where order_code='".$value['order_code']."'";
            $ret = $tableObj->getAdapter()->fetchOne($sql);
            if($ret==0){
                echo "<td>1</td>";
            }else{
                echo "<td>$ret</td>";
            }
            echo "<td>{$value['l_total_fee']}</td>";
            echo "<td>{$value['l_currency_code']}</td>";

            echo "<td>{$value['c_total_fee']}</td>";
            echo "<td>{$value['c_currency_code']}</td>";

            echo "</tr>";
        }
        echo "</table>";
    }

    public function autoRunAction(){
        error_reporting(E_ALL);
        Service_CustomerWarehouseFee::autoRunFeeByDate(0);
        //Service_CustomerWarehouseFee::autoRunCangchu2Fee();
    }

    public function sendEmailAction(){
        $params = array(
            'bodyType' => 'test',
            'email' => array('dannyzhou@globex.cn'),
            'subject' => 'test' . date('Y-m-d H:i:s'),
            'body' => '<span>test</span>',
            /*  'attachment'=>array(
                  'file'=>file_get_contents($url),
                  'fileType'=>'image/gif',
                  'fileName'=>'order.gif'
              )*/
        );
        $rr = Common_Email::send($params);
        var_dump($rr);
    }

    public function mkxmlAction(){
        //$hscodeArr = Service_ShipBatchDetail::getHscode('BHC150000142');
        //$hscodeArr = array_chunk($hscodeArr,1);
        //var_dump($hscodeArr);
        //$sb_code = 'BHC150000142';
        error_reporting(E_ALL);
        //$sb_code='BHC150001740';
        //Service_ShipOrderProcess::splitShipBatch($sb_code);
        $fileName = 'BHC150000205.xml';
        //$relativePath = APPLICATION_PATH.'/../data/ftp/outbound_send/';
        $absolutePath = APPLICATION_PATH.'/../data/ftp/outbound_send/';
        if(!file_exists($absolutePath)) {
            mkdir($absolutePath, 0777, true);
        }
        $obxProcess = new Service_OutBillXmlProcess('BHC150000205');
        $result = $obxProcess->generate($absolutePath.'/'.$fileName);
    }
    public function xyzAction(){
        error_reporting(E_ALL);
        $fileName = 'BHC150000205A.xml';
        //$relativePath = APPLICATION_PATH.'/../data/ftp/outbound_send/';
        $absolutePath = APPLICATION_PATH.'/../data/ftp/outbound_send/';
        if(!file_exists($absolutePath)) {
            mkdir($absolutePath, 0777, true);
        }
        $obxProcess = new Service_SpOutBillXmlProcess('BHC150000205A');
        $result = $obxProcess->generate($absolutePath.'/'.$fileName);
    }

    public function exportE8888Action(){
        $batteryType = array(
            '0'=>'不带',
            '1'=>'配置电池',
            '2'=>'内置电池',
            '3'=>'纽扣电池',
            '4'=>'锂金属电池',
        );
        $product_barcode_type = array(
            '0'=>'默认条码',
            '1'=>'自定义条码',
            '2'=>'序列号'
        );
        header('Pragma:public');
        header('Content-Type:application/x-msexecl;name=E8888.xls' );
        header("Content-Disposition:inline;filename=E8888.xls");

        echo "<table border='1'>";
        echo "<tr>";
        echo "<td>产品SKU</td>";
        echo "<td>产品名称</td>";
        echo "<td>英文品名</td>";
        echo "<td>单位</td>";
        echo "<td>条码类型</td>";
        echo "<td>产品条码</td>";
        echo "<td>申报币种</td>";
        echo "<td>申报价值(USD)</td>";
        echo "<td>重量(KG)</td>";
        echo "<td>海关品名</td>";
        echo "<td>海关编码</td>";
        echo "<td>供应商代码</td>";
        echo "<td>产品型号</td>";
        echo "<td>是否带电池</td>";
        echo "<td>电池类型</td>";
        echo "<td>图片URL1</td>";
        echo "<td>图片URL2</td>";
        echo "</tr>";
        //产品SKU	产品名称	英文品名	单位	条码类型	产品条码	申报币种	 申报价值(USD)	重量(KG)	有无发票	海关品名	海关编码	供应商代码	产品型号	是否带电池	电池类型	图片URL1	图片URL2
        $condition = array(
            'customer_code'=>'E8888',
            'product_status'=>'1',
        );
        $count = Service_Product::getByCondition($condition,"count(*)");
        $pageSize = 200;
        $totalPage = ceil($count/$pageSize);
        for($page=1;$page<=$totalPage;$page++){
            $productList = Service_Product::getByCondition($condition,"*",$pageSize,$page,'product_id asc');
            foreach($productList as $product){
                echo "<tr>";
                echo "<td>".$product['product_sku']."</td>";
                echo "<td>".$product['product_title']."</td>";
                echo "<td>".$product['product_title_en']."</td>";
                echo "<td style='vnd.ms-excel.numberformat:@'>".$product['pu_code']."</td>";
                echo "<td>".$product_barcode_type[$product['product_barcode_type']]."</td>";
                echo "<td>".$product['product_barcode']."</td>";
                echo "<td>".$product['currency_code']."</td>";
                echo "<td>".$product['product_declared_value']."</td>";
                echo "<td>".$product['product_weight']."</td>";
                echo "<td>".$product['hs_goods_name']."</td>";
                echo "<td style='vnd.ms-excel.numberformat:@'>".$product['hs_code']."</td>";
                if($product['distributor_id']!="0"){
                    $disc = Service_Distributor::getByPrimaryKey($product['distributor_id']);
                    echo "<td>".$disc['distributor_code']."</td>";
                }else{
                    echo "<td></td>";
                }
                echo "<td>".$product['model_serial']."</td>";
                if($product['with_battery']=="1"){
                    echo "<td>是</td>";
                    echo "<td>".$batteryType[$product['battery_type']]."</td>";
                }else{
                    echo "<td>否</td>";
                    echo "<td></td>";
                }
                echo "<td></td>";
                echo "<td></td>";
                echo "</tr>";
            }
        }
        echo "</table>";

    }

    public function getEtkAction(){
        $orderCode = 'SOE02590003496';
        $orderXml = Service_EpacketWebService::getOrderContent($orderCode);
        $eub      = new Service_EpacketWebService();
        $response = $eub->validate($orderXml);
        if ('success' === strtolower(trim($response['status']))){
            $response2 = $eub->createEpacketOrder($orderXml);
            echo "<pre>";
            var_dump($response2);
            echo "</pre>";
        }
    }

    public function exportpgAction(){
        set_time_limit(0);
        $totalSql = "SELECT count(*) FROM product_inventory JOIN product ON product.product_id=product_inventory.product_id WHERE 1 AND customer_code NOT IN('E0207','E0110')";
        $db=Common_Common::getAdapter();
        $total = $db->fetchOne($totalSql);
        $pageSize = 20;
        $totalPage = ceil($total/$pageSize);
        for($page=1;$page<=$totalPage;$page++){
            $start = ($page - 1) * $pageSize;
            $sqlselect = "SELECT product.customer_code,product.product_sku,product.product_barcode,product.goods_id,product_inventory.pi_sellable,product_inventory.pi_reserved,product_inventory.pi_shipped,product.hs_code,product.hs_goods_name,product.product_id FROM product_inventory JOIN product ON product.product_id=product_inventory.product_id WHERE 1 AND customer_code NOT IN('E0207','E0110') order by pi_id asc limit ".$start.", ".$pageSize;
            $piList = $db->fetchAll($sqlselect);
            foreach($piList as $product){
                $result = $db->fetchRow(
                    "SELECT * FROM temp_pi WHERE goods_id = :goods_id",
                    array('goods_id' => $product['goods_id'])
                );
                $pi_total = $product['pi_sellable']+$product['pi_reserved'];
                $hsuommap = Service_HsUomMap::getByField($product['product_id'],'product_id',"*");
                $hum_quantity_law_total = $hsuommap['hum_quantity_law']*$pi_total;
                $hum_quantity_second_total = $hsuommap['hum_quantity_second']*$pi_total;
                if(!empty($result)){
                    $updateRow = array(
                        'pi_total'=>$pi_total+$result['pi_total'],
                        'pi_ship_total'=>$product['pi_shipped']+$result['pi_shipped'],
                        'hum_quantity_law_total'=>$hum_quantity_law_total+$result['hum_quantity_law_total'],
                        'hum_quantity_second_total'=>$hum_quantity_second_total+$result['hum_quantity_second_total'],
                    );
                    $where = $db->quoteInto('tp_id = ?', $result['tp_id']);
                    $db->update('temp_pi', $updateRow, $where);
                }else{
                    $row = array (
                        'goods_id'    => $product['goods_id'],
                        'hs_code'     => $product['hs_code'],
                        'hs_goods_name' => $product['hs_goods_name'],
                        'pi_total'=>$pi_total,
                        'pi_ship_total'=>$product['pi_shipped'],
                        'hum_quantity_law_total'=>$hum_quantity_law_total,
                        'hum_quantity_second_total'=>$hum_quantity_second_total,
                    );
                    $db->insert('temp_pi',$row);
                }
            }

        }
        echo "run End!";
    }

    public function postTestAction(){
        $codeArr = array(
            'BHR160001270-01',
            'BHR160001271-01',
        );
        foreach($codeArr as $code){
            $fileName = $code.'.xml';
            /*if($row['fmt_code']=="MRK-RQJT"){
                $relativePath = '/inbound_send/RQJT/'.date('Y/m/d');
            }else{
                $relativePath = APPLICATION_PATH.'/../data/ftp/inbound_send/'.date('Y/m/d');
            }*/
            $absolutePath = APPLICATION_PATH.'/../data/ftp';
            if(!file_exists($absolutePath)) {
                mkdir($absolutePath, 0777, true);
            }
            $obxProcess = new Service_ReceiveXmlProcess($code);
            $result = $obxProcess->generate($absolutePath.'/'.$fileName);
        }
        //echo Ec::renderTpl($this->tplDirectory . "test.tpl", 'layout');
    }

    public function postDateAction(){
        $date_start = "2016-02-16";
        $dataFormat = '/^(19|20)\d{2}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$/';
        if(preg_match('/^\d{5}$/',$date_start)){
            $date_start = gmdate("Y-m-d", PHPExcel_Shared_Date::ExcelToPHP($date_start));
            echo $date_start."=date_start1</br>";
        }else{
            echo $date_start."=date_start2</br>";
        }
        if(!preg_match($dataFormat, $date_start)){
            echo $date_start."不是日期格式，建议格式2015-08-08";
        }else{
            echo $date_start."是日期格式";
        }
        exit;
    }

    public function testSplitAction(){
        $sb_code = "BHC160004991";
        $shipBatchAttribute = Service_ShipBatchAttribute::getByField($sb_code,'sb_code',"*");
        $hscodeArr = Service_ShipBatch::getSplit20($sb_code);
        echo "<pre>";
        var_dump($hscodeArr);
        echo "</pre>";
        $sphscodeArr = array_chunk($hscodeArr,20);
        $index = 90;
        $gross_weight = Service_ShipBatchDetail::sumGrossWeight($sb_code);
        $net_weight = number_format(Service_ShipBatchDetail::sumNetWeight($sb_code),2,'.','');
        $totalSX = count($sphscodeArr);
        $gtReduceNt = $gross_weight-$net_weight;
        $gtSp = $gtReduceNt/$totalSX;
        $packNoSp = floor($shipBatchAttribute['pack_no']/$totalSX);
        $kvCurrency = Service_Currency::getKeyVal();
        foreach($sphscodeArr as $key=>$codeArr){
            $subSbCode = $sb_code.chr($index);
            $shipBatchXml = array(
                'sb_code'=>$sb_code,
                'sub_sb_code'=>$subSbCode,
                'gross_wt'=>0,
                'net_wt'=>'0',
                'pack_no'=>'',
                'ship_batch_xml_status'=>'1',
                'sbx_add_time'=>date("Y-m-d H:i:s"),
                'sbx_update_time'=>date("Y-m-d H:i:s"),
                'total_price'=>'',
            );
            $sbxid = Service_ShipBatchXml::add($shipBatchXml);
            //$sbxid = 0;
            $no = 1;
            $allTotalPrice = 0;
            $ntw = 0;
            foreach($codeArr as $conditionArrStr){
                $conditionArr = explode("|",$conditionArrStr);
                $condition = array(
                    'sb_code'=>$sb_code,
                    'hs_code'=>$conditionArr[0],
                    'pu_code'=>$conditionArr[1],
                    'pu_code_law'=>$conditionArr[2],
                    'pu_code_second'=>$conditionArr[3],
                    'currency_code'=>$conditionArr[4],
                );
                $OrderProductList = Service_ShipBatch::getProductByCondition($condition);
                unset($OrderProductList['total']);
                foreach($OrderProductList as $op){
                    $hemList = Service_HsElementMap::getByCondition(array('product_id'=>$op['product_id']), 'hem_detail');
                    $ntw+=$op['net_weight'];
                    $elements = array();
                    foreach($hemList as $hemRow) {
                        $hem_detail = trim($hemRow['hem_detail']);
                        $elements[] = $hem_detail ? $hem_detail : '/';
                    }
                    $QTY = $op['hum_quantity_law'];
                    $total_price = sprintf("%.2f", $op['total_price']);
                    $allTotalPrice+=$total_price;
                    $DECL_PRICE = sprintf("%.4f", $total_price/$op['quantity']);
                    $hum_quantity_second =  $op['pu_code_second'] ? $op['hum_quantity_second'] : '';
                    $shipBatchXmlDetail = array(
                        'sbx_id'=>$sbxid,
                        'sb_code'=>$sb_code,
                        'sub_sb_code'=>$subSbCode,
                        'g_no'=>$no,
                        'goods_id'=>$op['goods_id'],
                        'merger_g_no'=>$no,
                        'merger_mode'=>'1',
                        'code_ts'=>$op['hs_code'],
                        'g_name_cn'=>$op['hs_goods_name'],
                        'g_model'=>implode('|',$elements),
                        'g_name_en'=>'',
                        'g_qty'=>$op['quantity'],
                        'g_unit'=>$op['pu_code'],
                        'decl_price'=>$DECL_PRICE,
                        'curr'=>$kvCurrency[$op['currency_code']],
                        'qty_1'=>$QTY,
                        'unit_1'=>$op['pu_code_law'],
                        'qty_2'=>$hum_quantity_second,
                        'unit_2'=>$op['pu_code_second'],
                        'origin_country'=>'110',
                        'decl_total'=>$total_price,
                    );
                    Service_ShipBatchXmlDetail::add($shipBatchXmlDetail);
                    $no++;
                }
            }
            $gwt = 0;
            $pn = 0;
            if($key==($totalSX-1)){
                $gwt = $ntw+($gtReduceNt-($gtSp*($totalSX-1)));
                if($packNoSp>=1){
                    $pn = $shipBatchAttribute['pack_no']-(($totalSX-1)*$packNoSp);
                }else{
                    $pn = 1;
                }
            }else{
                $gwt = $ntw+$gtSp;
                $pn = $packNoSp>1?$packNoSp:"1";
            }
            $updateShipBatchXml = array(
                'gross_wt'=>$gwt,
                'net_wt'=>$ntw,
                'pack_no'=>$pn,
                'total_price'=>$allTotalPrice,
            );
            Service_ShipBatchXml::update($updateShipBatchXml,$sbxid,'sbx_id');
            /*if($shipBatchAttribute['trade_mode']!="0110"){
                if ($shipBatchAttribute['form_type']=='E2F') {
                    $aMessage['fmt_code'] = 'ZCCQ';
                }else{
                    $aMessage['fmt_code'] = 'MCK';
                }
                $aMessage['fmt_type'] = 'BSG011';
                $aMessage['refercence_no'] = $subSbCode;
                $aMessage['fml_status'] = 1;
                $aMessage['fml_add_time'] = date('Y-m-d H:i:s');
                Service_FtpMessageSendlist::add($aMessage);
            }*/
            $index--;
        }
    }

    public function createXml2Action(){
        error_reporting(E_ALL);
        $sbCode = 'BHC160005272';
        $shipBatch = Service_ShipBatch::getByField($sbCode, 'sb_code');
        //echo "<pre>";
        //print_r($shipBatch);
        $apishipbatch = Service_ApiShipBatchSend::getByField($sbCode, 'sb_code');
        $send_count = 0;
        if (!empty($apishipbatch) && $apishipbatch['send_count'] > 10) {
            echo "出区单：{$sbCode}已经发送订单数据给招宝超过10次\r\n";
            return;
        }
        if (!empty($apishipbatch)) {
            $send_count = $apishipbatch['send_count'];
        }
        if (!empty($shipBatch)) {
            if ($shipBatch['sb_status'] != '') {
                //获取出货单下面的袋子
                $orders = array();
                $bagCondition = array(
                    'sb_code' => $sbCode
                );
                $bags = Service_ShipBatchDetail::getByCondition($bagCondition);
                //print_r($bags);
                $data = array();
                if (!empty($bags)) {
                    foreach ($bags as $key => $bag) {
                        //获取袋子和订单的关联信息
                        $bagOrders = Service_OutboundBagDetail::getByCondition(array('ob_no' => $bag['ob_no']));
                        //print_r($bagOrders);
                        if (!empty($bagOrders)) {
                            foreach ($bagOrders as $keyb => $bagorder) {
                                $orderInfos = Service_Orders::getByField($bagorder['order_code'], 'order_code');
                                //print_r($orderInfos);
                                if (!empty($orderInfos)) {
                                    //$orderInfos = Service_Orders::getByField($bagorder['order_code']);
                                    $orderAddressCondition = array(
                                        'order_code' => $bagorder['order_code'],
                                    );
                                    $orderAddress = Service_OrderAddressBook::getByCondition($orderAddressCondition);
                                    $orderAddressInfo = array();
                                    if (!empty($orderAddress)) {
                                        foreach ($orderAddress as $address) {
                                            if ($address['oab_type'] == '0') {
                                                $orderAddressInfo = $address;
                                                $country = Service_Country::getByField($address['oab_country_id']);
                                                $orderAddressInfo['country_name'] = $country['country_name'];
                                            }
                                        }
                                    } else {
                                        $orderAddress = array();
                                    }

                                    $shipOrder = Service_ShipOrder::getByField($orderInfos['order_code'], 'order_code');

                                    $order_productCondition = array(
                                        'order_code' => $orderInfos['order_code']
                                    );
                                    $order_product = Service_OrderProduct::getByCondition($order_productCondition, "*");
                                    //print_r($order_product);
                                    //exit;
                                    //$order_product = $orderInfos['order_product'];
                                    $orderDetail = array();
                                    if (!empty($order_product)) {
                                        foreach ($order_product as $op => $product) {
                                            $productInfo = Service_Product::getByField($product['product_id']);
                                            /* print_r($productInfo);
                                              print_r($product);
                                              exit; */
                                            $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'];
                                                }
                                            }
                                            //print_r($puInfo);

                                            $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;
                                        }
                                    }
                                    //exit;
                                    $customer = Service_Customer::getByField($orderInfos['customer_id']);
                                    $changeOrder = '1';
                                    if ($orderInfos['order_mode_type'] == '1') {
                                        $changeOrder = $orderInfos['change_order'];
                                    } else {
                                        $changeOrder = '1'; //备货模式换单
                                    }

                                    $orderInfo = array(
                                        'FormID' => 'BHC160005272A',
                                        'ID' => 'BHC160005272A',
                                        'referenceNo' => $orderInfos['reference_no'],
                                        'orderType' => $orderInfos['order_mode_type'],
                                        'changeOrder' => $changeOrder,
                                        'smCode' => $orderInfos['sm_code'],
                                        'tracking_no' => $shipOrder['tracking_number'],
                                        'provinceName' => $orderAddressInfo['oab_state'],
                                        'consigneeCountry' => $orderAddressInfo['country_name'],
                                        'consigneeLastname' => $orderAddressInfo['oab_lastname'],
                                        'consigneeFirstname' => $orderAddressInfo['oab_firstname'],
                                        'consigneeCompany' => $orderAddressInfo['oab_company'],
                                        'consigneePostcode' => $orderAddressInfo['oab_postcode'],
                                        'consigneeAddress1' => $orderAddressInfo['oab_street_address1'],
                                        'consigneeAddress2' => $orderAddressInfo['oab_street_address2'],
                                        'consigneePhone' => $orderAddressInfo['oab_phone'],
                                        'consigneeEmail' => $orderAddressInfo['oab_email'],
                                        'grossWt' => $orderInfos['grossWt'],
                                        'currency' => $orderInfos['currency_code'],
                                        'charge' => $orderInfos['charge'],
                                        'shippingPremiumFee' => $orderInfos['shipping_fee_estimate'],
                                        'trade_platform' => $customer['trade_name'],
                                        'addTime' => $orderInfos['add_time'],
                                        'shipTime' => $shipBatch['sb_ship_time'],
                                        'signTime' => '',
                                        //'orderDetail'=>$orderDetail,
                                        'OrderDetail' => $orderDetail
                                    );
                                    $orderOptionTime = Service_OrderOperationTime::getByField($orderInfos['order_code'], 'order_code');
                                    if (!empty($orderOptionTime)) {
                                        $orderInfo['shipTime'] = $orderOptionTime['ship_time'];
                                    }
                                    //$data [] = array('Tbl_OrderInfo'=>$orderInfo);
                                    $data [] = $orderInfo;
                                    //$data[] = array('orderinfo'=>$orderInfo);
                                }
                            }
                        }
                    }
                }

                $result['OrderInfo'] = $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;
        }

        //$request['OrderInfo']=array();
        $request['orderinfo'] = $data;
        $dom = new DOMDocument('1.0', 'UTF-8');
        $infoHeadNode = $dom->createElement('orderinfo');
        //echo "<pre>";
        //var_dump($request['orderinfo']);
        //echo "</pre>";
        //exit;
        foreach($request['orderinfo'] as $data){
            $infoNode = $dom->createElement('orderinfoList');
            $infoNode->appendChild($dom->createElement('FormID',$data['FormID']));
            $infoNode->appendChild($dom->createElement('ID', $data['ID']));
            $infoNode->appendChild($dom->createElement('referenceNo', $data['referenceNo']));
            $infoNode->appendChild($dom->createElement('orderType', $data['orderType']));
            $infoNode->appendChild($dom->createElement('changeOrder', $data['changeOrder']));
            $infoNode->appendChild($dom->createElement('smCode', $data['smCode']));
            $infoNode->appendChild($dom->createElement('tracking_no', $data['tracking_no']));
            $infoNode->appendChild($dom->createElement('provinceName', $data['provinceName']));
            $infoNode->appendChild($dom->createElement('consigneeCountry', $data['consigneeCountry']));
            $infoNode->appendChild($dom->createElement('consigneeLastname',$data['consigneeLastname']));
            $infoNode->appendChild($dom->createElement('consigneeFirstname',$data['consigneeFirstname']));
            $infoNode->appendChild($dom->createElement('consigneeCompany',$data['consigneeCompany']));
            $infoNode->appendChild($dom->createElement('consigneePostcode',$data['consigneePostcode']));
            $infoNode->appendChild($dom->createElement('consigneeAddress1', $data['consigneeAddress1']));
            $infoNode->appendChild($dom->createElement('consigneeAddress2', $data['consigneeAddress2']));
            $infoNode->appendChild($dom->createElement('consigneePhone', $data['consigneePhone']));
            $infoNode->appendChild($dom->createElement('consigneeEmail', $data['consigneeEmail']));
            $infoNode->appendChild($dom->createElement('grossWt',$data['grossWt']));
            $infoNode->appendChild($dom->createElement('currency', $data['currency']));
            $infoNode->appendChild($dom->createElement('charge', $data['charge']));	//原来是5875344345
            $infoNode->appendChild($dom->createElement('shippingPremiumFee', $data['shippingPremiumFee']));
            $infoNode->appendChild($dom->createElement('trade_platform', $data['trade_platform']));
            $infoNode->appendChild($dom->createElement('addTime', $data['addTime']));
            $infoNode->appendChild($dom->createElement('shipTime', $data['shipTime']));
            $detailHeadNode = $dom->createElement('OrderDetail');
            foreach($data['OrderDetail'] as $detail){
                $detailNode = $dom->createElement('OrderDetailList');
                $detailNode->appendChild($dom->createElement('skuNo',$detail['skuNo']));
                $detailNode->appendChild($dom->createElement('skuName',$detail['skuName']));
                $detailNode->appendChild($dom->createElement('skuCnName',$detail['skuCnName']));
                $detailNode->appendChild($dom->createElement('puName',$detail['puName']));
                $detailNode->appendChild($dom->createElement('hsCode',$detail['hsCode']));
                $detailNode->appendChild($dom->createElement('skuDeclaredValue',$detail['skuDeclaredValue']));
                $detailNode->appendChild($dom->createElement('specification',$detail['specification']));
                //$detailNode->appendChild($dom->createElement('quantity',$detail['quantity']));
                //$detailNode->appendChild($dom->createElement('quantity',$detail['quantity']));
                $detailHeadNode->appendChild($detailNode);
            }
            $infoNode->appendChild($detailHeadNode);
            $infoHeadNode->appendChild($infoNode);
        }
        $dom->appendChild($infoHeadNode);
        $path = APPLICATION_PATH.'/../data/ftp/'.$sbCode.".xml";
        $dom->save($path);
    }

    public function mkxml2Action(){
        /*$receivingCode = "BHR160001333-01";
        $absolutePath = APPLICATION_PATH.'/../data/ftp/inbound_send/'.date('Y/m/d');
        if(!file_exists($absolutePath)) {
            mkdir($absolutePath, 0777, true);
        }
        $fileName = "BHR160001333-01.xml";
        $row = Service_FtpMessageSendlist::getByField($receivingCode,'refercence_no',"*");
        $obxProcess = new Service_Receiving0110XmlProcess($row['refercence_no']);
        $result = $obxProcess->generate($absolutePath.'/'.$fileName);*/

        /*$orderCode = "SOE02070002417";
        $UspsClass = new Service_UspsInterface();
        $response = $UspsClass->getOrderInfo($orderCode);
        echo "<pre>";
        var_dump($response);
        echo "</pre>";
        exit;*/
        $swo_code = "SWO160006831";
        $httpURL = "http://119.145.38.243:8089/rs/oms/swapOrder/update";
        $postHeader = array("Content-Type: application/x-www-form-urlencoded; charset=UTF-8");
        $appSercet = "1747dfbf884ac612e050007f01000ac5";
        $appKey = "1747dfbf884ac612e050007f01000ac5";
        $actionUrl = "/rs/oms/swapOrder/update";
        //$swo_code = "SWO150000045";
        $swapRow = Service_SwapOrder::getByField($swo_code,"swo_code","*");
        $swapOrderDetail = Service_SwapOrderDetail::getByCondition(array('swo_code'=>$swo_code),"*");
        $timestamp = strtotime($swapRow['last_update_time']);
        $order_code = $swapRow['swo_code'];
        $status = "S";
        $message = "易货成功";
        $finishTime = $swapRow['last_update_time'];
        //$shalstr = $actionUrl."appKey{$appKey}finishTime{$finishTime}message{$message}order_code{$order_code}status{$status}timestamp{$timestamp}{$appSercet}";
        //$sign = sha1($shalstr);
        $ch = curl_init($httpURL);
        curl_setopt($ch, CURLOPT_URL, $httpURL);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $postHeader);
        curl_setopt($ch, CURLOPT_POST, 1);
        $param = array(
            //'appKey'=>$appKey,
            'timestamp'=>$timestamp,
            'order_code'=>$swo_code,
            'status'=>$status,
            'message'=>$message,
            'finishTime'=>$finishTime,
            //'sign'=>$sign,
        );
        $items = array();
        foreach($swapOrderDetail as $swod){
            $v = array(
                'customer_code'=>$swod['from_customer_code'],
                'product_sku'=>$swod['from_sku'],
                'to_sku'=>$swod['to_sku'],
                'quantity'=>$swod['quantity'],
                'qcRejectionRate'=>$swod['qualified_rate'],
                'qcOperator'=>$swod['qc_subject'],
                'qcRmk'=>$swod['qc_remark'],
                'qcQuantity'=>$swod['real_qc_quantity'],
            );
            $items[] = $v;
        }
        $shalArr = array();
        $shalArr[] = "appKey".$appKey;
        foreach($param as $key=>$val){
            $shalArr[] = $key.$val;
        }
        foreach($items as $k=>$v){
            foreach($v as $key=>$val){
                $shalArr[] = "items.".$key.$val;
            }
        }
        sort($shalArr);
        $shalStr = "";
        foreach($shalArr as $val){
            $shalStr.=$val;
        }
        $sign = sha1($shalStr.$appSercet);

        $requestParam = "appKey=".$appKey;
        foreach($param as $key=>$val){
            $requestParam.="&".$key."=".$val;
        }
        foreach($items as $k=>$v){
            foreach($v as $key=>$value){
                $requestParam.="&items.".$key."=".$value;
            }
        }
        $requestParam.="&sign=".$sign;

        $ch = curl_init($httpURL);
        curl_setopt($ch, CURLOPT_URL, $httpURL);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $postHeader);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$requestParam);

        $response = curl_exec($ch);
        if(curl_errno($ch)){
            print curl_error($ch);
        }

        $response = curl_exec($ch);
        if(curl_errno($ch)){
            print curl_error($ch);
        }
        echo $order_code.":".$response."</br>";
        $obj = json_decode($response);
        $result = Common_Common::objectToArray($obj);
        echo "<pre>";
        var_dump($result);
        echo "</pre>";
        /*if($result['ack']=="Success"){
            $update = array(
                'has_send'=>1,
            );
            Service_SwapOrder::update($update,$order_code,'swo_code');
        }else{
            $update = array(
                'remark'=>$result['data'],
            );
            Service_SwapOrder::update($update,$order_code,'swo_code');
        }*/
    }

    public function sendOrderAction(){
        error_reporting(E_ALL);
        $sb_code = "BHC160004843";
        $cmblapi = new Service_CMBLApiProcess();
        $cmblapi->sendOrder($sb_code);
    }

    public function recalculateAction(){
        $keys           = array(
            'warehouseId'               => 1,
            'countryId'                 => 253,
            'smCode'                    => 'HKDHL',
            'weight'                    => 0.1,
            'order_code'                => 'SOEC0010020975',
            'realWeight'                => 0,
            'customerCode'              => 'EC001',
            'city_name'=>'ABBOT',
            'cityId'=>'386603',
        );
        $objCalculate   = new Common_CalculateShipping();
        $objCalculate->setParams($keys);
        $aCalculate = $objCalculate->getRate();
        echo "<pre>";
        var_dump($aCalculate);
        echo "</pre>";
        exit;
    }

    public function addhscodeAction(){
        set_time_limit(0);
        error_reporting(E_ALL);
        $totalSql = "SELECT count(*) FROM tmp_hscode where tag=0";
        $db=Common_Common::getAdapter();
        $total = $db->fetchOne($totalSql);
        $pageSize = 20;
        $totalPage = ceil($total/$pageSize);
        for($page=1;$page<=$totalPage;$page++){
            $start = ($page - 1) * $pageSize;
            $sqlselect = "SELECT * FROM tmp_hscode WHERE 1 AND tag=0 order by th_id asc limit ".$start.", ".$pageSize;
            $thList = $db->fetchAll($sqlselect);
            //echo "<pre>";
            //var_dump($thList);
            //echo "</pre>";
            //break;
            foreach($thList as $value){
                $hscodeRow = Service_Hscodes::getByField($value['hs_code'],"hs_code","*");
                if(empty($hscodeRow)){
                    $hsrow = array(
                        'p_name'=>$value['p_name'],
                        'hs_category_code'=>'',
                        'hs_code'=>$value['hs_code'],
                        'hs_code_description'=>'',
                        'hs_code_status'=>1
                    );
                    Service_Hscodes::add($hsrow);
                    $hs_uom = array(
                        'hs_code'=>$value['hs_code'],
                        'pu_code_law'=>$value['pu_code_law'],
                        'pu_code_second'=>$value['pu_code_law'],
                        'hu_add_time'=>date("Y-m-d H::i:s"),
                        'hu_update_time'=>date("Y-m-d H::i:s"),
                        'hu_status'=>'1',
                        'hu_description'=>'',
                    );
                    Service_HsUom::add($hs_uom);
                    $str = $value['hs_code']."新增成功!";
                }else{
                    $updateHURow = array(
                        'pu_code_law'=>$value['pu_code_law'],
                        'pu_code_second'=>$value['pu_code_second'],
                        'hu_add_time'=>date("Y-m-d H::i:s"),
                        'hu_update_time'=>date("Y-m-d H::i:s"),
                    );
                    Service_HsUom::update($updateHURow,$value['hs_code'],'hs_code');
                    $str = $value['hs_code']."更新成功!";
                }
                $filePath = APPLICATION_PATH.'/../data/log/'.'hsCode.txt';
        if(!file_exists($filePath)){
            $fp= fopen($filePath,"w");
            fclose($fp);
        }
        file_put_contents($filePath,var_export($str,true));
            }
        }
        echo "run end (^_^)";
    }

    public function downLoadTemplatAction(){
        error_reporting(E_ALL);
        $ordersOperationUrl = 'http://api.4px.com/OrderOnlineService.dll?wsdl';
        //在线订单操作工具(1.运费试算 2.查询轨迹 3.申请拦截 4.查询跟踪号 5.打印标签)
        $ordersToolUrl = 'http://api.4px.com/OrderOnlineToolService.dll?wsdl';
        //获取打印数据
        $getPdfUrl = 'http://aeapi.4px.com/label/printOrder';

        //密钥
        $authToken = '2785FEA7FB95A55446E1B3325D7E52BE';
        $soap = new Service_FourpxWebService();

        $result = array(
            'status' => 0,
            'message' => '操作失败'
        );
        $orderCode='SOE05890000115';

        $file = APPLICATION_PATH . '/../data/pdf/Fourpx/' . $orderCode . '.pdf';
        // 文件不存在则创建

        $specSmCode = array('4PX-EU_PACKET', '4PX-RU_POST-LINK_RMAIL', '4PX-Singapo_SPack_IMAIR', '4PX-SG_ordinary_mail+');

        //if(!file_exists($file)){
            $orderRow = Service_Orders::getByField($orderCode,'order_code',"*");
            if($orderRow['ref_tracking_number']=="") return false;
            if (in_array($orderRow['sm_code'], $specSmCode)&&$orderRow['sm_code']!='4PX-EU_PACKET') {
                $type = 3;
            } else {
                $type = 1;
            }
            $xml = '<?xml version="1.0" encoding="utf-8" ?>' .
                "<labelRequest>" .
                "<authToken>" . $authToken . "</authToken>".
                "<printConfig>" .
                "<labelFormat>pdf</labelFormat>" .
                "<labelType>" . $type . "</labelType>" .
                "<labelSize>label_80x90</labelSize>";
            if ($type == 3) {
                $xml .= "<declarationLabel>Y</declarationLabel>";
            }
            $xml .="</printConfig>" .
                "<trackingNumbers>" .
                "<trackingNumber>" . $orderRow['ref_tracking_number'] . "</trackingNumber>" .
                "</trackingNumbers>" .
                "</labelRequest>";

            $str = "token=".$authToken."&request=".$xml;
            //第一种发送方式，也是推荐的方式：
            $header[] = "Content-type:application/x-www-form-urlencoded";
            $ch = curl_init ($getPdfUrl);
            curl_setopt($ch, CURLOPT_URL, $getPdfUrl);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $str);
            $response = curl_exec($ch);
            if(curl_errno($ch)){
                $result['message'] = curl_error($ch);
                curl_close($ch);
                return $result;
            }
            curl_close($ch);
            echo "response=".$response;
            //$response = $soap->simplest_xml_to_array($response);
            var_dump($response);

        //$result = $soap->getPdfByOrderCode('SOE05890000114');
        //var_dump($result);
        exit;
        //}

        //Common_Common::downloadFile($fullPath);

        require_once APPLICATION_PATH . '/../libs/PHPExcel.php';
        require_once APPLICATION_PATH . '/../libs/PHPExcel/IOFactory.php';

        $fullPath = APPLICATION_PATH."/../data/file/shdgsgds.xls";

        $resultArray = Common_Upload::readEXCEL($fullPath);

        foreach($resultArray as $key=>$value){
            if($key==0) continue;
            if($value[11]=="") continue;
            $customerRow = Service_Customer::getByField($value[2],"customer_code","*");
            $cc = explode(",",$value[9]);
            $condition = array(
                'customer_code'=>$value[2],
                'cab_type'=>2,
            );
            $cba = Service_CustomerAddressBook::getByCondition($condition,"*");
            if(!empty($cba)){
                $update = array(
                    'cab_company'=>$value[11],
                );
                echo "<pre>";
                var_dump($cba);
                echo "</pre>";
                Service_CustomerAddressBook::update($update,$cba[0]['cab_id'],'cab_id');
            }
            /*$customerAddress = array(
                'customer_code'=>$value[2],
                'customer_id'=>$customerRow['customer_id'],
                'cab_type'=>2,
                'cab_company'=>$value[1],
                'cab_lastname'=>$value[3],
                'cab_country_id'=>49,
                'cab_state'=>trim($cc[1]),
                'cab_city'=>$cc[0],
                'cab_street_address1'=>$value[10],
                'cab_street_address2'=>"",
                'cab_postcode'=>"",
                //'cab_phone'=>$this->_paramterArr['cab_phone'],
                'cab_cell_phone'=>$value[5],
                'cab_fax'=>"",
                'cab_email'=>$value[3],
                'cab_note'=>$value[7],
            );*/
            //echo "<pre>";
            //var_dump($customerAddress);
            //echo "</pre>";

            //Service_CustomerAddressBook::add($customerAddress);
        }
    }

    public function calWeightAction(){
        $sb_code='BHC160005728';
        $shipBatchAttribute = Service_ShipBatchAttribute::getByField($sb_code,'sb_code',"*");
        $hscodeArr = Service_ShipBatch::getSplit20($sb_code);
        $sphscodeArr = array_chunk($hscodeArr,20);
        $index = 65;
        $gross_weight = Service_ShipBatchDetail::sumGrossWeight($sb_code);
        $net_weight = number_format(Service_ShipBatchDetail::sumNetWeight($sb_code),2,'.','');
        $totalSX = count($sphscodeArr);
        $gtReduceNt = $gross_weight-$net_weight;
        $gtSp = $gtReduceNt/$totalSX;
        $packNoSp = floor($shipBatchAttribute['pack_no']/$totalSX);
        $kvCurrency = Service_Currency::getKeyVal();
        foreach($sphscodeArr as $key=>$codeArr){
            $subSbCode = $sb_code.chr($index);
            $shipBatchXml = array(
                'sb_code'=>$sb_code,
                'sub_sb_code'=>$subSbCode,
                'gross_wt'=>0,
                'net_wt'=>'0',
                'pack_no'=>'',
                'ship_batch_xml_status'=>'1',
                'sbx_add_time'=>date("Y-m-d H:i:s"),
                'sbx_update_time'=>date("Y-m-d H:i:s"),
                'total_price'=>'',
            );
            //$sbxid = Service_ShipBatchXml::add($shipBatchXml);
            //$sbxid = 0;
            $no = 1;
            $allTotalPrice = 0;
            $ntw = 0;
            foreach($codeArr as $conditionArrStr){
                $conditionArr = explode("|",$conditionArrStr);
                $condition = array(
                    'sb_code'=>$sb_code,
                    'hs_code'=>$conditionArr[0],
                    'pu_code'=>$conditionArr[1],
                    'pu_code_law'=>$conditionArr[2],
                    'pu_code_second'=>$conditionArr[3],
                    'currency_code'=>$conditionArr[4],
                );
                $OrderProductList = Service_ShipBatch::getProductByCondition($condition);
                unset($OrderProductList['total']);
                foreach($OrderProductList as $op){
                    $hemList = Service_HsElementMap::getByCondition(array('product_id'=>$op['product_id']), 'hem_detail');
                    $ntw+=$op['net_weight'];
                    $elements = array();
                    foreach($hemList as $hemRow) {
                        $hem_detail = trim($hemRow['hem_detail']);
                        $elements[] = $hem_detail ? $hem_detail : '/';
                    }
                    $QTY = $op['hum_quantity_law'];
                    $total_price = sprintf("%.2f", $op['total_price']);
                    $allTotalPrice+=$total_price;
                    $DECL_PRICE = sprintf("%.4f", $total_price/$op['quantity']);
                    $hum_quantity_second =  $op['pu_code_second'] ? $op['hum_quantity_second'] : '';
                    $shipBatchXmlDetail = array(
                        //'sbx_id'=>$sbxid,
                        'sb_code'=>$sb_code,
                        'sub_sb_code'=>$subSbCode,
                        'g_no'=>$no,
                        'goods_id'=>$op['goods_id'],
                        'merger_g_no'=>$no,
                        'merger_mode'=>'1',
                        'code_ts'=>$op['hs_code'],
                        'g_name_cn'=>$op['hs_goods_name'],
                        'g_model'=>implode('|',$elements),
                        'g_name_en'=>'',
                        'g_qty'=>$op['quantity'],
                        'g_unit'=>$op['pu_code'],
                        'decl_price'=>$DECL_PRICE,
                        'curr'=>$kvCurrency[$op['currency_code']],
                        'qty_1'=>$QTY,
                        'unit_1'=>$op['pu_code_law'],
                        'qty_2'=>$hum_quantity_second,
                        'unit_2'=>$op['pu_code_second'],
                        'origin_country'=>'110',
                        'decl_total'=>$total_price,
                    );
                    //Service_ShipBatchXmlDetail::add($shipBatchXmlDetail);
                    $no++;
                }
            }
            $gwt = 0;
            $pn = 0;
            if($key==($totalSX-1)){
                $gwt = $ntw+($gtReduceNt-($gtSp*($totalSX-1)));
                if($packNoSp>=1){
                    $pn = $shipBatchAttribute['pack_no']-(($totalSX-1)*$packNoSp);
                }else{
                    $pn = 1;
                }
            }else{
                $gwt = $ntw+$gtSp;
                $pn = $packNoSp>1?$packNoSp:"1";
            }
            $updateShipBatchXml = array(
                'gross_wt'=>$gwt,
                'net_wt'=>$ntw,
                'pack_no'=>$pn,
                'total_price'=>$allTotalPrice,
            );
            //Service_ShipBatchXml::update($updateShipBatchXml,$sbxid,'sbx_id');
            /*if($shipBatchAttribute['trade_mode']!="0110"){
                if ($shipBatchAttribute['form_type']=='E2F') {
                    $aMessage['fmt_code'] = 'ZCCQ';
                }else{
                    $aMessage['fmt_code'] = 'MCK';
                }
                $aMessage['fmt_type'] = 'BSG011';
                $aMessage['refercence_no'] = $subSbCode;
                $aMessage['fml_status'] = 1;
                $aMessage['fml_add_time'] = date('Y-m-d H:i:s');
                Service_FtpMessageSendlist::add($aMessage);
            }*/
            $index++;
        }
    }

    public function getSingopongAction(){
        $order_code = "SOE01740023859";
        $orderCodeArr = array();
        $orderCodeArr[] = $order_code;
        $orderProcess = new Service_OrderProcess();
        $result = $orderProcess->orderArrPickupTransaction($orderCodeArr, 1,"",1);
        echo "<pre>";
        var_dump($result);
        echo "</pre>";
        exit;
        $orderCodeArr = array(
            'SOE06930001317',
            'SOE06930001332',
            'SOE06930001451',
            'SOE06930001452',
            'SOE06930001453',
            'SOE06930001454',
            'SOE06930001455',
            'SOE06930001667',
        );
        foreach($orderCodeArr as $orderCode){
            $shipOrder = Service_ShipOrder::getByField($orderCode,'order_code',"*");
            $apiDhlRow = Service_ApiDhl::getByField($orderCode, 'order_code');
            if (empty($apiDhlRow)) {
                $insertRow['order_code'] = $orderCode;
                $insertRow['so_code'] = $shipOrder['so_code'];
                $insertRow['airway_Bill_number'] = $shipOrder['tracking_number'];
                $insertRow['label_pdf_path'] = $shipOrder['file_path'];
                $insertRow['status'] = 1;
                $insertRow['create_time'] = date('Y-m-d H:i:s');
                Service_ApiDhl::add($insertRow);
                $apiDhlRow = Service_ApiDhl::getByField($orderCode, 'order_code');
                $invoice = new Service_InvoiceProcess($orderCode);
                $invoiceResult = $invoice->getResult();
            }else{
                $invoice = new Service_InvoiceProcess($orderCode);
                $invoiceResult = $invoice->getResult();
                echo "<pre>";
                var_dump($invoiceResult);
                echo "</pre>";
            }
        }
        exit;
        $result = Service_BHHKDHLApiProcess::queryAwbCode('SOE06930001451');
        echo $result;
        $resultArr = json_decode($result);
        $result = Common_Common::objectToArray($resultArr);
        echo $result['Data'][0]['AWB'];
        exit;

    }

    public function exportInventoryBatchAction(){
        require_once APPLICATION_PATH . '/../libs/PHPExcel.php';
        require_once APPLICATION_PATH . '/../libs/PHPExcel/IOFactory.php';

        $table = new PHPExcel();
        $table->getDefaultStyle()->getFont()->setName('宋体');
        $table->setActiveSheetIndex(0);
        $table->setActiveSheetIndex(0)->setTitle("批次与库存");
        $objActSheet=$table->setActiveSheetIndex(0);

        $objActSheet->getColumnDimension('A')->setWidth(15);
        $objActSheet->getColumnDimension('B')->setWidth(20);
        $objActSheet->getColumnDimension('C')->setWidth(20);
        $objActSheet->getColumnDimension('D')->setWidth(20);
        $objActSheet->getColumnDimension('E')->setWidth(15);
        $objActSheet->getColumnDimension('F')->setWidth(25);

        $objActSheet->setCellValue('A1','产品条码');
        $objActSheet->setCellValue('B1','可用库存');
        $objActSheet->setCellValue("C1","冻结库存");
        $objActSheet->setCellValue('D1','问题库存');
        $objActSheet->setCellValue('E1','批次可用数量');
        $objActSheet->setCellValue('F1','可用+冻结-可用数量');

        $condition = array();
        $count = Service_ProductInventory::getByCondition($condition,"count(*)");
        $pageSize = 50;
        $index = 2;
        $totalPage = ceil($count/$pageSize);
        for($page=1;$page<=$totalPage;$page++){
            $productInventory = Service_ProductInventory::getByCondition($condition,"*",$pageSize,$page,"pi_id asc");
            foreach($productInventory as $pi){
                if($pi['pi_sellable']==0) continue;
                $product = Service_Product::getByField($pi['product_id'],"product_id","*");
                $inventoryBatch = Service_InventoryBatch::getByCondition(array('ib_quantity_gt'=>0,'product_id'=>$pi['product_id']),"*");
                $ibQuantity = 0;
                if(!empty($inventoryBatch)){
                    foreach($inventoryBatch as $ib){
                        $ibQuantity+=$ib['ib_quantity'];
                    }
                }
                $totalUse =$pi['pi_sellable']+$pi['pi_reserved'];
                $div = $totalUse - $ibQuantity;
                if($div==0) continue;
                $objActSheet->setCellValue("A".$index,$product['product_barcode']);
                $objActSheet->setCellValue("B".$index,$pi['pi_sellable']);
                $objActSheet->setCellValue("C".$index,$pi['pi_reserved']);
                $objActSheet->setCellValue("D".$index,$pi['pi_unsellable']);
                $objActSheet->setCellValue("E".$index,$ibQuantity);
                $objActSheet->setCellValue('F'.$index,$div);
                $index++;
            }
        }
        $objWriter = PHPExcel_IOFactory::createWriter($table, 'Excel5');

        header( "Pragma: public" );
        header( "Expires: 0" );
        header("Accept-Ranges: bytes");
        header('cache-control:must-revalidate');
        header("Content-Disposition: attachment; filename=exprtRc.xls");
        header("Content-Type:APPLICATION/OCTET-STREAM;charset=utf-8");
        $objWriter->save('php://output');
    }

    public function addElementAction(){
        set_time_limit(0);
        error_reporting(E_ALL);
        $condition = array(
            'hs_code_status'=>'1',
        );
        $total = Service_Hscodes::getByCondition($condition,"count(*)");
        $pageSize = 20;
        $totalPage = ceil($total/$pageSize);
        for($page=1;$page<=$totalPage;$page++){
            $hsCodeList = Service_Hscodes::getByCondition($condition,"*","he_id asc",$pageSize,$page);
            foreach($hsCodeList as $hsCode){
                $existOtherElement = Service_HsElement::getByCondition(array('hs_code'=>$hsCode['hs_code'],"he_code"=>'其他'),"*");
                if(!empty($existOtherElement)) continue;
                $hElement = Service_HsElement::getByCondition(array('hs_code'=>$hsCode['hs_code']),"*",0,0,"he_sort desc");
                $addElement = array(
                    'hs_code'=>$hsCode['hs_code'],
                    'he_code'=>'其他',
                    'he_name'=>'其他',
                    'he_sort'=>$hElement[0]['he_sort']+1,
                    'he_add_time'=>date("Y-m-d H:i:s"),
                    'he_update_time'=>date("Y-m-d H:i:s"),
                    'he_status'=>'1',
                    'hs_category_code'=>$hsCode['hs_category_code'],
                );
                Service_HsElement::add($addElement);
                echo "海关编码[".$hsCode['hs_code']."]已添加申报要素[其他]</br>";
            }
        }
    }

    public function getPlvAction(){
        error_reporting(E_ALL);
        $obj = Process_ShipFeeProcess::getInstance();
        $obj->run('weight');
        //$obj->run('price');
        exit;
        set_time_limit(0);
        $index=20000;
        for($i=10000;$i<10999;$i++){
            $stnTow = array(
                'order_code'=>'',
                'warehouse_id'=>'1',
                'stn_code'=>'BUBBE'.$index."10861YQ",
                'sm_code'=>'ALBP-EU',
                'stn_status'=>'1',
                'stn_add_time'=>date("Y-m-d H:i:s"),
                'stn_update_time'=>date("Y-m-d H:i:s"),
            );
            Service_ServiceTrackingNumber::add($stnTow);
            $index+=1;
        }
        exit;
        require_once APPLICATION_PATH . '/../libs/PHPExcel.php';
        require_once APPLICATION_PATH . '/../libs/PHPExcel/IOFactory.php';
        $fullPath = APPLICATION_PATH."/../data/file/HullVSLece.xls";

        $resultArray = Common_Upload::readEXCEL($fullPath);
        var_dump($resultArray);
    }

    public function editElementAction(){
        require_once APPLICATION_PATH . '/../libs/PHPExcel.php';
        require_once APPLICATION_PATH . '/../libs/PHPExcel/IOFactory.php';
        $fullPath = APPLICATION_PATH."/../data/file/product222.xls";
        //$resultArray = Common_Upload::readEXCEL($fullPath);
        echo "<pre>";
        var_dump($resultArray);
        echo "</pre>";
        exit;
        foreach($resultArray as $key=>$value){
            if($key==0) continue;
            $productList = Service_Product::getByCondition(array('goods_id'=>$value[0]),"*");
            if(empty($productList)) continue;
            //$elementArr = explode("|",$value[6]);
            foreach($productList as $p){
                $updateP = array(
                    'hs_goods_name'=>$value[5],
                );
                Service_Product::update($updateP,$p['product_id'],"product_id");
                /*$hsElementMap = Service_HsElementMap::getByCondition(array('product_id'=>$p['product_id']),"*",0,0,'he_id asc');
                var_dump($hsElementMap);
                foreach($hsElementMap as $hemk=>$hemv){
                    $updateHemv = array(
                        'hem_detail'=>$elementArr[$hemk],
                    );
                    Service_HsElementMap::update($updateHemv,$hemv['hem_id'],"hem_id");
                }*/
            }
        }
        echo "run end!";
        echo "</pre>";
    }

    public function testInterfaceAction(){
        $testuid = "f1e9295c3a581304013a5820bf450000";
        $testpassword = "197682ce38751a5f39dcf6b65772018b";
        $uid = "8a2aa9e15b195820015b1982895f0001";
        $password = "a5d884d6d923ca4243d5324dfb4d1851";
        $POWS = new Service_ParcelOprWebService($uid, $password);

        $parcelList = array(
            'parcelstatus' => '0',
            'apmethod' => 'BEPP',
            'apname' => 'jiang',
            'apaddress' => 'sz longhua',
            'apdestination' => 'US',
            //'aplabel' => 'tmp',
            //'aptrackingNumber' => 'ATP10086BE',
            //'apnote' => 'tmp',
            //'apBuyerID' => 'tmp',
            //'apItemurl' => 'tmp',
            //'apItemTitle' => '1201201',
            //'apTransactionID' => '',
            //'apFromEmail' => '',
            //'ebayID' => '',
            'apTel' => '13266712227',
            'zipCode' => '518000',
            'refNo' =>'SOE'.date("YmdHis"),
            //'aptype' => 'G',
            'apdescriptions' => 'test1;test2;test3',
            'apquantitys' => '1;1;1',
            'apweight' => '2',
            'apvalue' => '30',
            'apweights' => '0.5;0.5;1',
            'apvalues' => '10;10;10',
            'apGross' => '1.00',
            'city' => 'sz',
            'province' => 'gd',
            'customsArticleNames'=>'test11;test21;test31',
        );

        $result = $POWS->addParcel($parcelList);
        var_dump($result);
    }
    public function auto4pxAction(){
        $order_code = $this->_request->getParam("code","");
        $v = Service_Orders::getByField($order_code,"order_code","*");
        if($order_code=="") exit("请输入订单号");
        $soap = new Service_FourpxWebService();
        $condition = array(
            'sm_code_Arr' => array(
                '4PX-LYT_GH', //A6
                '4PX-EU_PACKET', //DS
                '4PX-RU_POST-LINK_RMAIL', //BA
                '4PX-HKDHL', //A1
                '4PX-YX', //AI
                '4PX-SG_ordinary_mail+',     //CQ
                'LYT-SMTGH-X',
            ),
            'order_status' => '4',
            // 'order_mode_type'=>'0',
            'ref_tracking_number' => '',
            'add_time_start'=>date('Y-m-d H:i:s',strtotime('-10 day')),
        );
        if (!in_array(trim($v['sm_code']), $condition['sm_code_Arr'])
            // || 0 !== (int) $v['order_mode_type']
            || 4 !== (int) $v['order_status'] || '' !== trim($v['ref_tracking_number'])) {
            exit("订单不是已提交状态");
        }
        // 创建并预报接口
        $result = $soap->createAndPreAlertOrderService($v['order_code']);
        if(!is_array($result)){
            $errorText = "订单" . $v['order_code'] . "提交出错: action: " .$result. "\n";
            $errorLog = array(
                'order_code' => $v['order_code'],
                'sm_code' => $v['sm_code'],
                'content' => $errorText,
            );
            Service_TrackingErrorLog::add($errorLog);
            //echo $errorText;
            exit($errorText);
        }
        if ($result['return']['ack'] == 'Failure') {
            $cnAtcion = '';
            $cnMessage = '';
            if (isset($result['return']['errors']['cnAction'])) {
                $cnAtcion.= $result['return']['errors']['cnAction'];
                $cnMessage.=$result['return']['errors']['cnMessage'];
            } elseif (isset($result['return']['errors'][0])) {
                foreach ($result['return']['errors'] as $e) {
                    $cnAtcion.=',' . $e['cnAction'];
                    $cnMessage.=',' . $e['cnMessage'];
                }
            }
            $errorText = "订单" . $v['order_code'] . "提交出错: action: " . $cnAtcion . ' message: ' . $cnMessage . "\n";
            $errorLog = array(
                'order_code' => $v['order_code'],
                'sm_code' => $v['sm_code'],
                'content' => $errorText,
            );
            Service_TrackingErrorLog::add($errorLog);
            //echo $errorText;
            exit($errorText);
        }
        $updateOrder = array(
            'ref_tracking_number' => $result['return']['trackingNumber']
        );
        $orderLog = array(
            'order_id' => $v['order_id'],
            'order_code' => $v['order_code'],
            'ol_type' => '1',
            'order_status_from' => $v['order_status'],
            'order_status_to' => $v['order_status'],
            'ol_add_time' => date("Y-m-d H:i:s"),
            'user_id' => 0,
            'ol_comments' => '4PX自动取单号以及标签->autoFourpx.php'
        );
        Service_OrderLog::add($orderLog);
        Service_Orders::update($updateOrder, $v['order_id'], "order_id");
        echo "订单" . $v['order_code'] . "获取单号" . $result['return']['trackingNumber'] . "成功\n";
        // 获取打印面单接口
        $response = $soap->getPdfByOrderCode($v['order_code']);
        if ($response['status']) {
            echo "订单" . $v['order_code'] . "获取打印标签成功URL:" . $response['url'] . "\n";
        } else {
            echo "订单" . $v['order_code'] . "获取打印标签失败" . $response['message'] . "\n";
        }
    }

    public function autoTestAction(){
        $condition = array(
            'sm_code'=>'THHK',
            'customer_code_Arr'=>array('E0693','E0750','E0851','E0909','E0207'),
            'order_status'=>4,
            'warehouse_id'=>1,
            'order_mode_type'=>'0',
        );
        $total = Service_Orders::getByCondition($condition,"count(*)");
        $pageSize = 100;
        $totalPage = ceil($total/$pageSize);
        for($page=1;$page<=$totalPage;$page++){
            $rows = Service_Orders::getByCondition($condition, "*", $pageSize, $page, 'order_id desc' );
            foreach($rows as $key=>$value){
                $orderCodeArr = array();
                $orderCodeArr[] = $value['order_code'];
                $orderProcess = new Service_OrderProcess();
                $result = $orderProcess->orderArrPickupTransaction($orderCodeArr, 1,"",1);
                if ($result['pick_code']!='' ){
                    $pickRow = Service_Picking::getByField($result['pick_code'],"picking_code","*");
                    if ($pickRow['picking_type'] != '0') {
                        //一票多件确认下架
                        $pickCodes = array();
                        $pickCodes[] = $result['pick_code'];
                        $obj = new Service_PickProcess();
                        $return = $obj->confirmPickerTransaction($pickCodes);
                        if($return['state']=="1"){
                            $orderCode = $value['order_code'];
                            $packingCode = "";
                            $packObj = new Service_PackProcess();
                            $return = $packObj->packTransaction($orderCode, $packingCode, 1, 1);
                            if($return['state']=="0"){
                                $errorText = "打包贴标失败:".implode(";",$return['error']);
                                $errorLog = array(
                                    'order_code' => $value['order_code'],
                                    'sm_code' => $value['sm_code'],
                                    'content' => $errorText,
                                );
                                Service_TrackingErrorLog::add($errorLog);
                                continue;
                            }
                        }else{
                            $errorText = "确认下架失败:".implode(";",$return['message']);
                            $errorLog = array(
                                'order_code' => $value['order_code'],
                                'sm_code' => $value['sm_code'],
                                'content' => $errorText,
                            );
                            Service_TrackingErrorLog::add($errorLog);
                            continue;
                        }
                        //订单变成已录单状态
                        /*$updateOrder = array(
                            'order_status' => '14',
                            'update_time' => date('Y-m-d H:i:s', time()),
                        );
                        Service_Orders::update($updateOrder, $value['order_code'], 'order_code');*/
                        //添加日志
                        $orderLog = array(
                            'order_id' => $value['order_id'],
                            'order_code' => $value['order_code'],
                            'ol_type' => '0',
                            'order_status_from' => $value['order_status'],
                            'order_status_to' => '14',
                            'ol_add_time' => date("Y-m-d H:i:s"),
                            'user_id' => 0,
                            'ol_ip' => Common_Common::getIP(),
                            'ol_comments' => '特定客户特定渠道订单自动下架打包操作',
                        );
                        Service_OrderLog::add($orderLog);
                    }else{
                        //单票打包
                        $pickingCode = $result['pick_code'];
                        $orderProduct = Service_OrderProduct::getByCondition(array('order_code'=>$value['order_code']),"*");
                        $productBarcode = $orderProduct[0]['product_barcode'];
                        $packageCode = "";
                        $packObj = new Service_PackProcess();
                        $return = $packObj->assignOrderTransaction($pickingCode,$packageCode,$productBarcode,1);
                        if($return['state']=="0"){
                            $errorText = "单票打包失败:".implode(";",$return['error']);
                            $errorLog = array(
                                'order_code' => $value['order_code'],
                                'sm_code' => $value['sm_code'],
                                'content' => $errorText,
                            );
                            Service_TrackingErrorLog::add($errorLog);
                            continue;
                        }
                        //订单变成已录单状态
                        /*$updateOrder = array(
                            'order_status' => '14',
                            'update_time' => date('Y-m-d H:i:s', time()),
                        );*/
                        //Service_Orders::update($updateOrder, $value['order_code'], 'order_code');
                        //添加日志
                        $orderLog = array(
                            'order_id' => $value['order_id'],
                            'order_code' => $value['order_code'],
                            'ol_type' => '0',
                            'order_status_from' => $value['order_status'],
                            'order_status_to' => '14',
                            'ol_add_time' => date("Y-m-d H:i:s"),
                            'user_id' => 0,
                            'ol_ip' => Common_Common::getIP(),
                            'ol_comments' => '特定客户特定渠道订单自动下架打包操作',
                        );
                        Service_OrderLog::add($orderLog);
                    }
                }else{
                    $errorText = isset($return['errors'][0]) ? $return['errors'][0]['message'] :'没有找到未下架订单';
                    $errorLog = array(
                        'order_code' => $value['order_code'],
                        'sm_code' => $value['sm_code'],
                        'content' => "下架失败:".$errorText,
                    );
                    Service_TrackingErrorLog::add($errorLog);
                    continue;
                }
            }
        }
        echo "[" . date('Y-m-d H:i:s') . "] End run\r\n";
    }

}
