<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Administrator
 * Date: 16-10-10
 * Time: 下午4:47
 * To change this template use File | Settings | File Templates.
 */
class Service_DHLApiProcess2
{
    private $statusKV = array('success'=>2, 'failure'=>3);

    private $requestXmlPath = '/var/java/DHLClient/TransformXMLtoPDF/RequestXML';
    private $responseXmlsPath = '/var/java/DHLClient/TransformXMLtoPDF/ResponseXMLS';
    private $pdfReportsPath = '/var/java/DHLClient/TransformXMLtoPDF/PDFReports';

    private $apiDhlRow = array();
    private $order_code = '';
    private $so_code = '';
    private $pieces = array();
    private $airwayBillNumber = '';
    private $aLicensePlate = array();
    private $dhlDataPath = '';
    private $resFileName = '';
    private $fileType='epl2';
    private $sendfile='0';

    private $error = '';
    private $result = array('ask'=>0, 'message'=>'');
    protected $xmlProcessObj='';


    /**
     * 构造函数
     * @param string $order_code 订单号
     * @param string $so_code 物流单号
     */
    public function __construct($order_code, $so_code, $pieces,$fileType='epl2') {
        $this->order_code = $order_code;
        $this->so_code = $so_code;
        $this->pieces = $pieces;
        $this->fileType = strtoupper($fileType);
        if($this->fileType=='PDF'){
            $this->sendfile='1';
        }
    }

    /**
     * 初始化在WEB中存放文件的目录
     */
    private function initDHLDataPath() {
        $this->dhlDataPath = APPLICATION_PATH.'/../data/dhl/'.date('Y/m');
        if(!file_exists($this->dhlDataPath)) {
            mkdir($this->dhlDataPath, 0777, true);
        }
    }

    /**
     * 检查接口记录表中是否存在数据，不存在则创建
     */
    private function checkIsExistData() {
        $this->apiDhlRow = Service_ApiDhl::getByField($this->order_code, 'order_code');
        if(empty($this->apiDhlRow)) {
            $insertRow['order_code'] = $this->order_code;
            $insertRow['so_code'] = $this->so_code;
            $insertRow['status'] = 1;
            $insertRow['create_time'] = date('Y-m-d H:i:s');
            Service_ApiDhl::add($insertRow);
            $this->apiDhlRow = Service_ApiDhl::getByField($this->order_code, 'order_code');
        }
    }

    /**
     * 请求XML文件路径
     * @return string
     */
    private function getReqFilePath() {
        return $this->dhlDataPath.'/REQ_'.$this->order_code.'.xml';
    }

    /**
     * 响应XML文件路径
     * @return string
     */
    private function getResFilePath() {
        return $this->dhlDataPath.'/RES_'.$this->order_code.'.xml';
    }

    /**
     * 标签PDF文件路径
     * @return string
     */
    private function getPdfFilePath() {
        return $this->dhlDataPath.'/PDF_'.$this->order_code.'.pdf';
    }

    /**
     * 标签EPL2文件路径
     * @return string
     */
    private function getEpl2FilePath() {
        return $this->dhlDataPath.'/'.$this->order_code.'.epl2';
    }

    /**
     * 向DHL接口发起请求
     * @return string|boolean
     */
    private function request() {
        /* $name = 'ShipmentValidateRequest_INT_DUT_AP_PieceEnabled_With2Pcs_PcsSeg.xml';
        if(@copy($this->getReqFilePath(), $this->requestXmlPath.'/'.$name)===false) {
            $this->error = '拷贝REQ文件失败';
            return false;
        } */
        ini_set("max_execution_time", "30");
        exec('/var/java/DHLClient/runDHLClient.sh '.$this->getReqFilePath(), $result);	//执行命令
        if(empty($result)) {
            $this->error = '请求接口失败';
            return false;
        }
        print_r($result);
        $this->resFileName = $result[0];
        //通过文件名判断是否请求失败
        if(strpos($this->resFileName, 'ShipmentResponse')===false) {
            $dom = new DOMDocument('1.0', 'UTF-8');
            $dom->load($this->responseXmlsPath.'/'.$this->resFileName);
            $codeNodes = $dom->getElementsByTagName('ConditionCode');
            $dataNodes = $dom->getElementsByTagName('ConditionData');
            if($codeNodes->length>0 && $dataNodes->length>0) {
                $this->error = $codeNodes->item(0)->textContent.':'.$dataNodes->item(0)->textContent;
            } else {
                $this->error = '请求接口出现错误，请检查文件：'.$this->resFileName;
            }
            return false;
        }
        return true;
    }

    /**
     * 解析响应的XML文件
     */
    private function parseResFile() {
        if(@copy($this->responseXmlsPath.'/'.$this->resFileName, $this->getResFilePath())===false) {
            $this->error = '拷贝RES文件失败';
            return false;
        }
        $dom = new DOMDocument('1.0', 'UTF-8');
        $dom->load($this->getResFilePath());
        //运单号
        $nodes = $dom->getElementsByTagName('AirwayBillNumber');
        if($nodes->length == 0) {
            $this->error = '解析XML失败，不存在[AirwayBillNumber]字段';
            return false;
        }
        $this->airwayBillNumber = $nodes->item(0)->textContent;
        //跟踪号
        $diList = $dom->getElementsByTagName('DataIdentifier');
        $nodeList = $dom->getElementsByTagName('LicensePlate');
        $length = $nodeList->length;
        if($length > 0) {
            if($diList->length != $length) {
                $this->error = '解析XML失败，[DataIdentifier]和[LicensePlate]不一致';
                return false;
            }
            for($i=0; $i<$length; $i++) {
                $this->aLicensePlate[] = $diList->item($i)->textContent . $nodeList->item($i)->textContent;
            }
        } else {
            $this->error = '解析XML失败，不存在[LicensePlate]字段';
            return false;
        }
        return true;
    }

    /**
     * 生成PDF标签
     */
    private function generatePdf() {
        /*exec('/var/java/DHLClient/generateLabelAuto.sh '.$this->resFileName.' PDF', $result);
        echo '/var/java/DHLClient/generateLabelAuto.sh '.$this->resFileName.' PDF';*/
        echo 'pdf:';
        //print_r($result);
        //$pdfPath = $this->pdfReportsPath.'/Global_Label_'.$this->airwayBillNumber.'.pdf';


        $new_xml = simplexml_load_string(file_get_contents($this->getResFilePath()));
        $ServiceHeader = (array)($new_xml->Response->ServiceHeader);
        $Note = (array)($new_xml->Note);
        $actionNote = isset($Note['ActionNote'])?trim($Note['ActionNote']):'';
        if( $actionNote == "Success" ){
            $LabelImage = $new_xml->LabelImage->OutputImage;
            $file_data = base64_decode($LabelImage);
            $pdfPath = $this->pdfReportsPath.'/'.$this->airwayBillNumber.'.pdf';
            file_put_contents($pdfPath,$file_data);
        }else{
            $this->error = 'dhl接口返回错误';
            return false;
        }
        $pdfPath = $this->pdfReportsPath.'/'.$this->airwayBillNumber.'.pdf';
        if(@copy($pdfPath, $this->getPdfFilePath())===false) {
            $this->error = '拷贝PDF文件失败:'.$pdfPath;
            return false;
        }
        /*//此处发给环球ftp为了简便直接拷贝了，应该用ftp传过去
        $ftp = new Common_Ftp($this->_ftpConfig);
        //连接FTP
        if(!$ftp->connect()){
            $this->error = join('-', $ftp->getError());
            return false;
        }
        //切换至对应目录
        if(!$ftp->chgdir($this->_ftpDir, true)){
            $this->error = join('-', $ftp->getError());
            return false;
        }
        //上传文件
        if(!$ftp->upload($this->getPdfFilePath(), basename($this->getPdfFilePath()))){
            $this->error = join('-', $ftp->getError());
            return false;
        }*/
        /*$label = new Service_LabelSendProcess();
        $label->sendLabel($this->getPdfFilePath());*/
        /*if(@copy($this->getPdfFilePath(), '/home/hqlabel/')===false) {
            $this->error = '移动PDF文件失败:'.$pdfPath;
            return false;
        }*/
        return true;
    }

    /**
     * 生成EPL2数据
     */
    private function generateEpl2() {
        exec('/var/java/DHLClient/generateLabelAuto.sh '.$this->resFileName.' EPL2', $result);
        $epl2Path = $this->pdfReportsPath.'/'.$this->airwayBillNumber.'.epl2';
        if(@copy($epl2Path, $this->getEpl2FilePath())===false) {
            $this->error = '拷贝epl2文件失败:'.$epl2Path;
            return false;
        }
        return true;
    }

    /**
     * 记录发送接口情况
     * @param int $status
     */
    private function updateApiDhl($status) {
        $ad_id = $this->apiDhlRow['ad_id'];
        unset($this->apiDhlRow['ad_id']);
        $this->apiDhlRow['comment'] = $this->error;
        $this->apiDhlRow['status'] = $this->statusKV[$status];
        $this->apiDhlRow['update_time'] = date('Y-m-d H:i:s');
        if($status=='success') {
            $this->apiDhlRow['airway_Bill_number'] = $this->airwayBillNumber;
            $this->apiDhlRow['license_plate'] = implode(',', $this->aLicensePlate);
        }
        Service_ApiDhl::update($this->apiDhlRow, $ad_id);
    }

    /**
     * 返回结果
     * @param int $ask
     * @return array
     */
    private function getResult($ask = 0) {
        $this->result['message'] = $this->error;
        $this->result['ask'] = $ask;
        if($ask == 1) {
            if($this->fileType=='PDF'){
                $path = $this->getPdfFilePath();
            }else{
                $path = $this->getEpl2FilePath();
            }
            $this->result['PDF'] = $path;
            $this->result['AirwayBillNumber'] = $this->airwayBillNumber;
            $this->result['LicensePlates'] = $this->aLicensePlate;
        }
        return $this->result;
    }
    public function setXmlProcess($type=null){
        if(!$this->xmlProcessObj&&!$type){
            $this->xmlProcessObj=new Service_DHLXmlProcess2($this->order_code,$this->pieces);
            return $this;
        }
        switch($type){
            case 'logistic_order':
                $this->xmlProcessObj=new Service_DHLXmLogisticOrderlProcess($this->order_code,$this->pieces);
                break;
            default :
                $this->xmlProcessObj=new Service_DHLXmlProcess2($this->order_code,$this->pieces);
        }
        return $this;
    }
    /**
     * 调用接口
     * @return array
     */
    public function runAPI() {
        $this->initDHLDataPath();	//文件路径
        $this->checkIsExistData();	//检查记录
        //生成XML文件
        if(! $this->xmlProcessObj){
            $this->setXmlProcess();
        }
        $xmlProcess = $this->xmlProcessObj;
        if($this->fileType=='PDF'){
            $gResult = $xmlProcess->generate($this->getReqFilePath(),'PDF');
        }else{
            $gResult = $xmlProcess->generate($this->getReqFilePath());
        }
        if($gResult === true) {
            $this->apiDhlRow['request_xml_path'] = $this->getReqFilePath();
        } else {
            $this->error = $gResult;
            $this->updateApiDhl('failure');
            return $this->getResult();
        }
        //请求接口
        $rResult = $this->request();
        if($rResult === false) {
            $this->updateApiDhl('failure');
            return $this->getResult();
        }
        //解析响应XML
        $pResult = $this->parseResFile();
        if($pResult === true) {
            $this->apiDhlRow['response_xml_path'] = $this->getResFilePath();
        } else {
            $this->updateApiDhl('failure');
            return $this->getResult();
        }
        //生成标签
        if($this->fileType=='PDF'){
            $lResult=$this->generatePdf();
            $path = $this->getPdfFilePath();
        }else{
            $lResult = $this->generateEpl2();
            $path = $this->getEpl2FilePath();
        }
        if($lResult === true) {
            $this->apiDhlRow['label_pdf_path'] = $path;
        } else {
            $this->updateApiDhl('failure');
            return $this->getResult();
        }
        //调用成功
        $this->updateApiDhl('success');
        //货物超长
        $this->orderWidthWigth();
        if($this->sendfile=='1'){
            //pdf时候是环球的，发送发票和标签给环球
            $this->sendfile();
        }
        return $this->getResult(1);
    }
    /**
     * //货物超长
     */
    private function orderWidthWigth() {
        $width  = 0;
        $weight =   0;
        foreach($this->pieces AS $value){
            if($width < $value['length'])$width = $value['length'];
            if($width < $value['width'])$width = $value['width'];
            if($width < $value['height'])$width = $value['height'];

            if($weight < $value['weight'])$weight = $value['weight'];
        }

        if($width > 120 || $weight > 70){
            Service_Exception::addExceptionByCode('orderWidthWigth' , $this->order_code);
        }
    }
    private function sendfile(){
        if($this->sendfile=='1'){
            //只有是要发送给环球标示时候才会发送给环球。
            $label = new Service_LabelSendProcess();
            $label->sendLabel($this->getPdfFilePath(),$this->order_code);
        }
    }
}
