<?php
class Service_DHLApiProcess 
{	
	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 $dhlreponsePath = ''; //DHL接口返回保存文件路径
	
	private $error = '';
	private $result = array('ask'=>0, 'message'=>'');
    protected $xmlProcessObj='';

    protected $_log;


        /**
	 * 构造函数
	 * @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';
		}
        $this->_log = Common_Log::getInstance()->setLogFile('CNDHL.log');
	}
	
	/**
	 * 初始化在WEB中存放文件的目录
	 */
	private function initDHLDataPath() {
		$this->dhlDataPath = APPLICATION_PATH.'/../data/dhl/'.date('Y/m');
		if(!file_exists($this->dhlDataPath)) {
			mkdir($this->dhlDataPath, 0777, true);
		}
		$this->dhlreponsePath = APPLICATION_PATH.'/../data/dhlreponse/'.date('Y/m');
		if(!file_exists($this->dhlreponsePath)) {
			mkdir($this->dhlreponsePath, 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返回结果路径
	 */
	private function getDHLFilePath(){
		return $this->dhlreponsePath."/".$this->order_code.'.reponse';
	}
	/**
	 * 向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", "600");
		exec('/var/java/DHLClient/runDHLClient.sh '.$this->getReqFilePath(), $result);	//执行命令
		if(empty($result)) {
			$this->error = '请求接口失败';
			return false;
		}
		$this->resFileName = $result[0];
		//通过文件名判断是否请求失败
		if(strpos($this->resFileName, 'ShipmentValidateResponse')===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() {
		/*echo 'ssssssssss';
		echo $this->responseXmlsPath.'/'.$this->resFileName;*/
		/*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);
		//$pdfPath = $this->pdfReportsPath.'/Global_Label_'.$this->airwayBillNumber.'.pdf';
		$pdfPath = $this->pdfReportsPath.'/'.$this->airwayBillNumber.'.pdf';
		if(@copy($pdfPath, $this->getPdfFilePath())===false) {
			$this->error = '拷贝PDF文件失败:'.$pdfPath;
			return false;
		}*/
		if(empty($this->labimage)){
			$this->error = 'epl文件为空';
			return false;
		}
		if(!file_put_contents($this->getPdfFilePath(),$this->labimage)){
			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;
		}*/
		if(empty($this->labimage)){
			$this->error = 'epl文件为空';
			return false;
		}
		if(!file_put_contents($this->getEpl2FilePath(),$this->labimage)){
			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){
                $orderRow = Service_Orders::getByField($this->order_code,'order_code',"*");
                if($orderRow['sm_code']=="HKDHL"||$orderRow['sm_code']=="CNDHL"){
                    $this->xmlProcessObj=new Service_DHLXmlProcess($this->order_code,$this->pieces);
                    return $this;
                }else{
                    $type = "WWDHL";
                }
            }
            switch($type){
                case 'logistic_order':
                    $this->xmlProcessObj=new Service_DHLXmLogisticOrderlProcess($this->order_code,$this->pieces);
                   break;
                case 'WWDHL':
                    $this->xmlProcessObj=new Service_WWDHLXmlProcess($this->order_code,$this->pieces);
                    break;
               default :
                    $this->xmlProcessObj=new Service_DHLXmlProcess($this->order_code,$this->pieces);
            }
            return $this;
        }
	/**
	 * 调用接口
	 * @return array
	 */
	public function runAPI() {
        $this->_log->log( $this->order_code);
        $t1 = mktime();
        $this->_log->log( 'init:'.$t1 );

		$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');
            $t4 = mktime();
            $this->_log->log( 'end:'.$t4 );
            $total = $t4 - $t1;
            $this->_log->log( 'total:'.$total );
			return $this->getResult();
		}
        $t2 = mktime();
        $this->_log->log( 'start request:'.$t2 );
		//请求接口
		//$rResult = $this->request();
		$rResult = $this->curlrequest();
        $t3 = mktime();
        $this->_log->log( 'end request:'.$t3 );
		if($rResult === false) {
			$this->updateApiDhl('failure');
            $t4 = mktime();
            $this->_log->log( 'end:'.$t4 );
            $total = $t4 - $t1;
            $this->_log->log( 'total:'.$total );
			return $this->getResult();
		}
		//解析响应XML
		$pResult = $this->parseResFile();
		if($pResult === true) {
			$this->apiDhlRow['response_xml_path'] = $this->getResFilePath();
		} else {
			$this->updateApiDhl('failure');
            $t4 = mktime();
            $this->_log->log( 'end:'.$t4 );
            $total = $t4 - $t1;
            $this->_log->log( 'total:'.$total );
			return $this->getResult();
		}
		//生成标签
		if($this->fileType=='PDF'){
			$lResult=$this->generatePdf();
			$path = $this->getPdfFilePath();
		}else{
			$lResult = $this->generateEpl2();
			//$res = $this->curlgenerateEpl2();
			$path = $this->getEpl2FilePath();
		}
		if($lResult === true) {
			$this->apiDhlRow['label_pdf_path'] = $path;
		} else {
			$this->updateApiDhl('failure');
            $t4 = mktime();
            $this->_log->log( 'end:'.$t4 );
            $total = $t4 - $t1;
            $this->_log->log( 'total:'.$total );
			return $this->getResult();
		}
		//调用成功
		$this->updateApiDhl('success');
                //货物超长
                $this->orderWidthWigth();
		if($this->sendfile=='1'){
			//pdf时候是环球的，发送发票和标签给环球
			$this->sendfile();
		}
        $t4 = mktime();
        $this->_log->log( 'end:'.$t4 );
        $total = $t4 - $t1;
        $this->_log->log( 'total:'.$total );
        if( $total > 15 ) {
            $this->_log->log( "******************************************\n" );
        }
		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);
		}
	}

	/**
	 * @todo 用于curl 对接dhl
	 */
	private function curlrequest(){
		/*$name = 'ShipmentValidateRequest_INT_DUT_AP_PieceEnabled_With2Pcs_PcsSeg.xml';
		echo $this->getReqFilePath(), $this->requestXmlPath.'/'.$name;
		if(@copy($this->getReqFilePath(), $this->requestXmlPath.'/'.$name)===false) {
			$this->error = '拷贝REQ文件失败';
			return false;
		}*/
		$Curl = curl_init();
		$header = array();
		$header[] = "Content-type: application/x-www-form-urlencoded;charset=UTF-8";

		//$this->request_url = 'http://xmlpitest-ea.dhl.com/XMLShippingServlet';
		//http://xmlpitest-ea.dhl.com/XMLShippingServlet
		$this->request_url = 'http://xmlpi-ea.dhl.com/XMLShippingServlet';
		//echo $this->getResFilePath();
		$request_xml = file_get_contents($this->getReqFilePath());

		curl_setopt($Curl, CURLOPT_URL, $this->request_url);
		curl_setopt($Curl, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($Curl, CURLOPT_TIMEOUT, 30);
		curl_setopt($Curl, CURLOPT_HTTPHEADER, $header);
		curl_setopt($Curl, CURLOPT_POST, 1);
		curl_setopt($Curl, CURLOPT_POSTFIELDS, $request_xml);

		$simple = curl_exec($Curl);
		curl_close($Curl);
		/*echo 'eeeeeeeeeee';
		print_r($simple);*/
		if(empty($simple)) {
			$this->error = '请求接口失败,接口没返回任何数据!';
			return false;
		}
		//保存返回的内容
		file_put_contents($this->getDHLFilePath(),$simple);

		$simple = iconv('ISO-8859-1','UTF-8',$simple);

		$new_xml = simplexml_load_string($simple);
		$ServiceHeader = (array)($new_xml->Response->ServiceHeader);
		$Note = (array)($new_xml->Note);
		$actionNote = isset($Note['ActionNote'])?trim($Note['ActionNote']):'';
		if( $actionNote == "Success" ){
			//file_put_contents($this->getResFilePath());
			if(@file_put_contents($this->getResFilePath(),$simple )===false) {
				$this->error = '拷贝RES文件失败';
				return false;
			}
			$tracking_number = $new_xml->AirwayBillNumber;
			$LabelImage = $new_xml->LabelImage->OutputImage;
			//echo $tracking_number;
			$this->labimage = base64_decode($LabelImage);
			//$filename = $this->load_label($LabelImage,$tracking_number);
			//$this->updatePackageExp($package_id,$prepare_goods_id,$serial_no,$tracking_number,'',$filename);
		}else{
			$response = (array)$new_xml->Response->Status->Condition;
			$response_content = addslashes(trim($response['ConditionData']));
			$this->error = $response_content;
			//$this->errorLog($package_id,$response_content);
			return false;
		}
		return true;
	}

}