<?php
/**
 * Created by JetBrains PhpStorm.
 * User: user
 * Date: 14-6-6
 * Time: 下午2:17
 * To change this template use File | Settings | File Templates.
 */
class Shipment_PrintController extends Ec_Controller_Action
{
    /*初始化*/
    public function preDispatch()
    {
        $this->tplDirectory = "shipment/views/order/";
        $this->serviceClass = new Service_Orders();
    }

    public function printEubLabelAction(){
        $orderCode = trim($this->_request->getParam("orderCode",""));
        $pdfFile = APPLICATION_PATH.'/../data/pdf/error.pdf';
        if ($orderCode) {
            $order = Service_Orders::getByField($orderCode,"order_code","*");
            if($order instanceof Zend_Db_Table_Row){
                $order = $order->toArray();
            }
            if(empty($order)){
                $order = Service_Orders::getByField($orderCode,"ref_tracking_number","*");
                if($order instanceof Zend_Db_Table_Row){
                    $order = $order->toArray();
                }
            }
            if($order){
                $pdfFile = APPLICATION_PATH.'/../data/pdf/EUB/'.$order['order_code'].".pdf";
                //标签不存在就去获取标签
                if(!file_exists($pdfFile)){
                    $epaService = new Service_EpacketWebService();
                    $labelResult = $epaService->getOneLableByMailnum($order['ref_tracking_number']);
                    if ('error' === strtolower(trim($labelResult['status']))) {
                        $pdfFile = APPLICATION_PATH.'/../data/pdf/request_error.pdf';
                    }else{
                        $zipFileStream = file_get_contents($labelResult['url'],false,null);
                        $zipFileName = APPLICATION_PATH.'/../data/pdf/EUB/'.$order['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/'.$order['order_code'].".pdf");
                        unlink($zipFileName);
                        $orderLog = array(
                            'order_id'=>$order['order_id'],
                            'order_code'=>$order['order_code'],
                            'ol_type'=>'1',
                            'order_status_from'=>$order['order_status'],
                            'order_status_to'=>$order['order_status_to'],
                            'ol_add_time'=>date("Y-m-d H:i:s"),
                            'user_id'=>0,
                            'ol_comments'=>'EUB打印单据时取标签'
                        );
                        Service_OrderLog::add($orderLog);
                        //echo "订单".$v['order_code']."获取单号地址标签成功\n";
                    }
                    //判断重新生成后的标签是否存在
                    if(!file_exists($pdfFile)){ // 再次确认标签是否存在
                        $pdfFile = APPLICATION_PATH.'/../data/pdf/create_error.pdf';
                    }
                }
            }
        }
        $pdfContent = file_get_contents($pdfFile,false,null);
        header('Content-Type: application/pdf; charset=utf-8');
        header('Content-Disposition:inline; filename=report.pdf');
        echo $pdfContent;
    }

    public function printUktlLabelAction(){
        $orderCode = $this->_request->getParam("orderCode","");
        $order = Service_Orders::getByField($orderCode,"order_code","*");
        if(empty($order)){
            $order = Service_Orders::getByField($orderCode,"ref_tracking_number","*");
            if(empty($order)){
                die("订单号或服务商单号不存在!");
            }
        }
        $pdfFile = APPLICATION_PATH.'/../data/pdf/UKTL/'.$order['order_code'].".pdf";
        $pdfContent = file_get_contents($pdfFile,false,null);
        header('Content-Type: application/pdf; charset=utf-8');
        header('Content-Disposition:inline; filename=UKTL-Label.pdf');
        echo $pdfContent;
    }
    public function printEtkLabelAction(){
        $orderCode = $this->_request->getParam("orderCode","");
        $order = Service_Orders::getByField($orderCode,"order_code","*");
        if(empty($order)){
            $order = Service_Orders::getByField($orderCode,"ref_tracking_number","*");
            if(empty($order)){
                die("订单号或服务商单号不存在!");
            }
        }
        $pdfFile = APPLICATION_PATH.'/../data/pdf/ETK/'.$order['order_code'].".pdf";
        $pdfContent = file_get_contents($pdfFile,false,null);
        header('Content-Type: application/pdf; charset=utf-8');
        header('Content-Disposition:inline; filename=ETK-Label.pdf');
        echo $pdfContent;
    }

    public function getPdfLabelAction(){
        $orderCode = trim($this->_request->getParam("orderCode",""));
        $pdfFile = APPLICATION_PATH.'/../data/pdf/error.pdf';
        if ($orderCode) {
            $order = Service_Orders::getByField($orderCode,"order_code","*");
            if($order instanceof Zend_Db_Table_Row){
                $order = $order->toArray();
            }
            if(empty($order)){
                $order = Service_Orders::getByField($orderCode,"ref_tracking_number","*");
                if($order instanceof Zend_Db_Table_Row){
                    $order = $order->toArray();
                }
            }
            $tmp = '';
            if($order){
                switch($order['sm_code']){
                    case 'SZY-EUB':
                    case 'WG-EUB':
                        $tmp = 'EUB';
                        break;
                    case 'UKTL';
                        $tmp = 'UKTL';
                        break;
                    case 'SZY-ETK':
                        $tmp = 'ETK';
                        break;
                    case 'BH-HKDHL':
                        $tmp='BHHKDHL';
                        break;
					  case 'PNLG':
                        $tmp='PNLG';
                        break;
                    case 'PNLN':
                        $tmp='PNLN';
                        break;
                    case '4PX-LYT_GH':
                    case '4PX-EU_PACKET':
                    case '4PX-RU_POST-LINK_RMAIL':
                    case '4PX-HKDHL':
                    case '4PX-YX':
                    case '4PX-SG_ordinary_mail+':
                    case 'LYT-SMTGH-X':
                        $fourPx = true;
                        $tmp = 'Fourpx';
                        break;
                    case 'Rumall-RU-G':
                        $tmp='RUMAll-RU-G';
                        break;
                    case 'Rumall-RU-EP':
                        $tmp='RUMAll-RU-EP';
                        break;
                    case 'BH-SFEP':
                        $tmp='BHSFEP';
                        break;
                    case 'CJ-DGMG':
                    case 'CJ-DGMP':
                    case 'DGM-US' :
                        $tmp='CJ';
                        break;
                    case 'BH-3HPA':
                    case 'BH-3H':
                    case 'BH-UKECSLTYD':
                    case 'BH-UKECSLTRM':
                    case 'BH-CORREOS':
                    case 'BH-19EURDPDDE':
                    case 'BH-DAC':
                    case 'BH-SL018':
                    case 'BH-IESLTANPOST':
                        $tmp = 'oneWorldExpress';
                        break;
                    case 'DHL-TH':
                        $tmp = 'DHLTH';
                        break;
                    case 'BH-BEAT':
                    case 'BH-NLAT':
                        $tmp = "BHAT";
                        break;
                    default:
                        break;
                }
            }
            if($order && $tmp){
                $labelResult = Service_OrdersLabel::getByField($order['order_code'],'order_code');
                if(!empty($labelResult['ol_content'])){
                    $content = base64_decode($labelResult['ol_content']);
                    header('Content-Type: application/pdf; charset=utf-8');
                    header('Content-Disposition:inline; filename=report.pdf');
                    echo $content;
                    exit;
                }else{
                    $pdfFile = APPLICATION_PATH.'/../data/pdf/'.$tmp.'/'.$order['order_code'].".pdf";
                    //标签不存在就去获取标签
                    if(!file_exists($pdfFile)){
                        if($tmp=='BHHKDHL'){
                            $trackingNumber=  Service_ShipOrder::getByField($order['order_code'], 'order_code');
                            if(!empty($trackingNumber)){
                                $bhhkdhlService=new Service_BHHKDHLApiProcess($order['order_code'], '', '');
                                $bhhkdhlService->setWaybillNumber($trackingNumber['tracking_number']);
                                $bhhkdhlService->generatePdf();
                            }
                        }elseif($tmp=='PNLG'||$tmp=='PNLN'){
                            if(!empty($order['ref_tracking_number'])){
                                $savePdfPath=array(
                                    'PNLG'=> APPLICATION_PATH . '/../data/pdf/PNLG/',
                                    'PNLN'=>APPLICATION_PATH . '/../data/pdf/PNLN/',
                                );
                                $UspsClass = new Service_UspsInterface();
                                $pdfPath=$UspsClass->getLabel($order['order_code'], $order['ref_tracking_number']);
                                if($pdfPath['pdfUrl']){
                                    $b=fopen($pdfPath['pdfUrl'],'r');
                                    $content='';
                                    while(!feof($b)){
                                        $content.=fread($b,1024);
                                    }
                                    file_put_contents($savePdfPath[$order['sm_code']].$order['order_code'].'.pdf' , $content);
                                }
                            }
                        }elseif($tmp=='RUMAll-RU-EP'||$tmp=='RUMAll-RU-G'){
                            $rumalService=new Service_RumalApiProcess();
                            if(!empty($order['reference_no'])&&(!empty($order['ref_tracking_number'])||!empty($order['agent_mailno']))){
                                $p=$rumalService->genaratLabel($order['reference_no']);
                                if(strpos($p,'%PDF-1.4')!==FALSE){
                                    file_put_contents($pdfFile, $p);
                                    Service_OrdersLabel::add(array('order_code'=>$order['order_code'],'ol_content'=>  base64_encode($p),'ol_time'=>date('Y-m-d H;i:s')));
                                }
                            }
                        }elseif($fourPx){
                            $soap = new Service_FourpxWebService();
                            $result = $soap->getPdfByOrderCode($orderCode);
                            if ($result['status']) {
                                $orderLog = array(
                                    'order_id'=>$order['order_id'],
                                    'order_code'=>$order['order_code'],
                                    'ol_type'=>'1',
                                    'order_status_from'=>$order['order_status'],
                                    'order_status_to'=>$order['order_status'],
                                    'ol_add_time'=>date("Y-m-d H:i:s"),
                                    'user_id'=>0,
                                    'ol_comments'=>'4PX打印单据时取标签'
                                );
                                Service_OrderLog::add($orderLog);
                            }
                        }elseif($tmp =='CJ'){
                            $labelResult = Service_OrdersLabel::getByField($order['order_code'],'order_code');
                            if(!empty($labelResult['ol_content'])){
                                $labelString = base64_decode($labelResult['ol_content']);
                                $dirPath = dirname($pdfFile);
                                $dirPath=str_replace("\\","/",$dirPath);
                                mkdir($dirPath);
                                chmod($dirPath,0777);
                                file_put_contents($pdfFile, $labelString);
                            }
                        }elseif($tmp=="BHSFEP"){
                            $labelResult = Service_OrdersLabel::getByField($order['order_code'],'order_code');
                            $content='';
                            if(!empty($labelResult['ol_content'])){
                                $content = base64_decode($labelResult['ol_content']);
                            }else{
                                $UspsClass = new Service_UspsInterface();
                                $pdfPath=$UspsClass->getLabel($order['order_code'], $order['ref_tracking_number']);
                                if($pdfPath['pdfUrl']){
                                    $b=fopen($pdfPath['pdfUrl'],'r');
                                    while(!feof($b)){
                                        $content.=fread($b,1024);
                                    }
                                    $fileContent = file_get_contents($pdfPath['pdfUrl']);
                                    Service_OrdersLabel::add(array(
                                        'order_code'=>$order['order_code'],
                                        'ol_content'=>  base64_encode($fileContent),
                                        'ol_time'=>date('Y-m-d H:i:s')));
                                }
                            }
                            header('Content-Type: application/pdf; charset=utf-8');
                            header('Content-Disposition:inline; filename=report.pdf');
                            echo $content;
                            exit;
                        }elseif($tmp=="BHAT"){
                            $labelResult = Service_OrdersLabel::getByField($order['order_code'],'order_code');
                            $content='';
                            if(!empty($labelResult['ol_content'])){
                                $content = base64_decode($labelResult['ol_content']);
                            }else{
                                $pdfUrl = "http://sandbox.faryaa.com//webservice/print-label/print-content?user_code=T068&order_number=".$order['agent_mailno']."&print_type=1&print_size=1&file_type=pdf";
                                //$content = file_get_contents($pdfUrl);
                                $b=fopen($pdfUrl,'r');
                                while(!feof($b)){
                                    $content.=fread($b,1024);
                                }
                            }
                            header('Content-Type: application/pdf; charset=utf-8');
                            header('Content-Disposition:inline; filename=report.pdf');
                            echo $content;
                        }else{
                            $epaService = new Service_EpacketWebService();
                            $labelResult = $epaService->getOneLableByMailnum($order['ref_tracking_number']);
                            $result = $epaService->getPdfByOrderCode($order['order_code']);
                            if($result){
                                $orderLog = array(
                                    'order_id'=>$order['order_id'],
                                    'order_code'=>$order['order_code'],
                                    'ol_type'=>'1',
                                    'order_status_from'=>$order['order_status'],
                                    'order_status_to'=>$order['order_status'],
                                    'ol_add_time'=>date("Y-m-d H:i:s"),
                                    'user_id'=>0,
                                    'ol_comments'=>'EUB打印单据时取标签'
                                );
                                Service_OrderLog::add($orderLog);
                            }
                        }


                        //判断重新生成后的标签是否存在
                        if(!file_exists($pdfFile)){ // 再次确认标签是否存在
                            $pdfFile = APPLICATION_PATH.'/../data/pdf/create_error.pdf';
                        }
                    }
                }
            }
        }
        $pdfContent = file_get_contents($pdfFile,false,null);
        header('Content-Type: application/pdf; charset=utf-8');
        header('Content-Disposition:inline; filename=report.pdf');
        echo $pdfContent;
    }
}
