<?php
/**
 * 构造DHL请求XML 
 * @author solar<solarzheng@cargofe.com.cn>
 */
class Service_DHLXmLogisticOrderlProcess
{
	public $order_code = '';
	
	public $version = '1.0';
	public $MessageTime = '';
	public $MessageReference = '';
	
	private $dom = null;
	private $elShipmentValidateRequestAP = null;
	private $orderRow = array();	//orders
	private $fmtRow = array();	//ftp_message_type
	private $consignee = array();
	private $shpper = array();
	private $pieces = array();
	private $totalWeight = 0.0;
	private $shipmentContent = '';
	private $shipperAccountNumber = '';
	
	public function __construct($order_code, $pieces) {
		$this->order_code = $order_code;
		$this->fmtRow = Service_FtpMessageType::getByField('DHL', 'fmt_code');
		$this->shipperAccountNumber = $this->fmtRow['fml_ems_no'];
		$this->pieces = $pieces;
	}
	
	/**
	 * 初始化
	 * @return true|string
	 */
	private function _init() {
		$this->orderRow = Service_LogisticsOrder::getByField($this->order_code, 'logistics_code');
		if(empty($this->orderRow)) return '找不到订单['.$this->order_code.']数据';
                $this->orderRow['currency_code']='USD';
		if($this->orderRow['currency_code']=='RMB') $this->orderRow['currency_code'] = 'CNY';
		$this->consignee = Service_LogisticsOrderAddress::getByWhere(array('logistics_code'=>$this->order_code,'loa_type'=>0));
		$this->shpper = Service_LogisticsOrderAddress::getByWhere(array('logistics_code'=>$this->order_code,'loa_type'=>0));
		return true;
	}
	
	/**
	 * 创建根节点req:ShipmentValidateRequestAP
	 */
	private function createShipmentValidateRequestAP() {
		$this->dom = new DOMDocument('1.0', 'UTF-8');
		$this->elShipmentValidateRequestAP = $this->dom->createElement('req:ShipmentValidateRequestAP');
		$this->elShipmentValidateRequestAP->setAttribute('xmlns:req', 'http://www.dhl.com');
		$this->elShipmentValidateRequestAP->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
		$this->elShipmentValidateRequestAP->setAttribute('xsi:schemaLocation', 'http://www.dhl.com ship-val-req_AP.xsd');
		$this->dom->appendChild($this->elShipmentValidateRequestAP);
	}
	
	/**
	 * 创建Request节点
	 */
	private function createRequest() {
		$elRequest = $this->dom->createElement('Request');
		$elServiceHeader = $this->dom->createElement('ServiceHeader');
		$this->MessageTime = date('Y-m-d').'T'.date('H:i:s.000-08:00');
		$elServiceHeader->appendChild($this->dom->createElement('MessageTime', $this->MessageTime));
		list($usec, $sec) = explode(" ", microtime());
		$microtime = (float)$usec + (float)$sec;
		$this->MessageReference = str_replace('.', '', $microtime.$sec).str_pad(rand(1,9999), 6, '0', STR_PAD_LEFT) ;
		if(strlen($this->MessageReference)<28){
			$this->MessageReference = str_replace('.', '', $microtime.$sec).str_pad(rand(1,9999), 7, '0', STR_PAD_LEFT) ;
		}
		$elServiceHeader->appendChild($this->dom->createElement('MessageReference', $this->MessageReference));
		$elServiceHeader->appendChild($this->dom->createElement('SiteID', $this->fmtRow['fmt_username']));
		$elServiceHeader->appendChild($this->dom->createElement('Password', $this->fmtRow['fmt_password']));
		$elRequest->appendChild($elServiceHeader);
		$this->elShipmentValidateRequestAP->appendChild($elRequest);
	}
	
		
	/**
	 * 创建Billing节点
	 */
	private function createBilling() {
		$elBilling = $this->dom->createElement('Billing');
		$elBilling->appendChild($this->dom->createElement('ShipperAccountNumber', $this->shipperAccountNumber));
		$elBilling->appendChild($this->dom->createElement('ShippingPaymentType', 'S'));
		$elBilling->appendChild($this->dom->createElement('DutyPaymentType', 'R'));
		$this->elShipmentValidateRequestAP->appendChild($elBilling);		
	}
	
	private function cutAddress($address1,$address2) {
		/*$address = trim($address);
		$addressLine = array();
		$total_len = strlen($address);
		if($total_len < 35) return array($address);
		$cut_num = ceil($total_len/34);
		$aAddress = explode(' ', $address);
		$letter_num = count($aAddress);
		if($letter_num == 1) return $aAddress;
		if($cut_num > $letter_num) return $aAddress;
		$len = floor($letter_num/$cut_num);
		$pos = 0;
		for($i=0; $i<$cut_num-1; $i++) {
			$addressLine[] = implode(' ', array_slice($aAddress, $pos, $len));
			$pos += $len;
		}
		$addressLine[] = implode(' ', array_slice($aAddress, $pos));*/
		$addressLine = array();
		$addressLine[] = $address1;
		if($address2!=""){
			$addressLine[] = $address2;
		}		
		return $addressLine;
	}	
	
	/**
	 * 创建Consignee节点
	 */
	private function createConsignee() {
		$elConsignee = $this->dom->createElement('Consignee');
		if($this->consignee['loa_company']=='') return '收件人公司名称不能为空';
		$elConsignee->appendChild($this->dom->createElement('CompanyName', $this->consignee['loa_company']));
		if($this->consignee['loa_address']=='') return '收件人地址不能为空';
                $elConsignee->appendChild($this->dom->createElement('AddressLine', $this->consignee['loa_address']));
		
		/* $elConsignee->appendChild($this->dom->createElement('AddressLine', $this->consignee['oab_street_address1']));
		if($this->consignee['oab_street_address2']) {
			$elConsignee->appendChild($this->dom->createElement('AddressLine', $this->consignee['oab_street_address2']));
		} */
		if($this->consignee['loa_city']=='') return '收件人城市不能为空';
		$elConsignee->appendChild($this->dom->createElement('City', $this->consignee['loa_city']));
		//$elConsignee->appendChild($this->dom->createElement('DivisionCode', ''));
		if($this->consignee['loa_zipcode']=='') return '收件人邮编不能为空';
		$elConsignee->appendChild($this->dom->createElement('PostalCode', $this->consignee['loa_zipcode']));
		if($this->consignee['loa_country']=='') return '收件人国家不能为空';
		$aCountry = Service_Country::getByField($this->consignee['loa_country']);
		$elConsignee->appendChild($this->dom->createElement('CountryCode', $aCountry['country_code']));
		$elConsignee->appendChild($this->dom->createElement('CountryName', $aCountry['country_name_en']));
		$elContact = $this->dom->createElement('Contact');
		if($this->consignee['loa_name']=='' && $this->consignee['loa_name']=='') {
			return '收件人姓名不能为空';
		}
		$elContact->appendChild($this->dom->createElement('PersonName', $this->consignee['loa_name']));
		if($this->consignee['loa_phone']=='') return '收件人电话不能为空';
		$elContact->appendChild($this->dom->createElement('PhoneNumber', $this->consignee['loa_phone']));
		/* $elContact->appendChild($this->dom->createElement('PhoneExtension', '8113'));
		$elContact->appendChild($this->dom->createElement('FaxNumber', $this->consignee['oab_phone']));
		$elContact->appendChild($this->dom->createElement('Telex', '454586')); */
		$elConsignee->appendChild($elContact);
		$this->elShipmentValidateRequestAP->appendChild($elConsignee);
		return true;
	}
	
	/**
	 * 创建Commodity节点
	 */
	private function createCommodity() {
		$elCommodity = $this->dom->createElement('Commodity');
		$elCommodity->appendChild($this->dom->createElement('CommodityCode', '1'));
		$elCommodity->appendChild($this->dom->createElement('CommodityName', 'String'));
		$this->elShipmentValidateRequestAP->appendChild($elCommodity);
	}
	
	/**
	 * 创建Dutiable节点
	 */
	private function createDutiable() {
		$elDutiable = $this->dom->createElement('Dutiable');
		$purpose_declared_value = Service_LogisticsOrderHs::sumPurposeDeclaredValue($this->order_code);
		$elDutiable->appendChild($this->dom->createElement('DeclaredValue', sprintf('%.2f',$purpose_declared_value)));
		$elDutiable->appendChild($this->dom->createElement('DeclaredCurrency', 'USD'));	//暂时固定为USD
		$elDutiable->appendChild($this->dom->createElement('ShipperEIN', 'Text'));
		$this->elShipmentValidateRequestAP->appendChild($elDutiable);
	}
	
	/**
	 * 创建Reference节点
	 */
	private function createReference() {
		$elReference = $this->dom->createElement('Reference');
		$elReference->appendChild($this->dom->createElement('ReferenceID', $this->order_code));
		//$elReference->appendChild($this->dom->createElement('ReferenceType', 'St'));
		$this->elShipmentValidateRequestAP->appendChild($elReference);		
	}
	
	/**
	 * 创建并返回Pieces节点
	 */
	private function getPiecesElement() {
		$elPieces = $this->dom->createElement('Pieces');
		$contents = array();
		foreach($this->pieces as $piece) {
			$elPiece1 = $this->dom->createElement('Piece');
			$elPiece1->appendChild($this->dom->createElement('Weight', $piece['weight']));
			$elPiece1->appendChild($this->dom->createElement('Depth', $piece['length']));
			$elPiece1->appendChild($this->dom->createElement('Width', $piece['width']));
			$elPiece1->appendChild($this->dom->createElement('Height', $piece['height']));
			$elPieces->appendChild($elPiece1);
			$this->totalWeight += $piece['weight'];
			$contents[] = trim($piece['op_description']);
			//$this->shipmentContent .= $piece['op_description'].' ';
		}
		$contents=array_unique($contents);
		$stingshipmentContent = implode(' ', $contents);
		if(strlen($stingshipmentContent)>234){
			$stingshipmentContent = substr($stingshipmentContent, 0,234);
		}
		$this->shipmentContent = $stingshipmentContent;
		/* $elPiece1 = $this->dom->createElement('Piece');
		$elPiece1->appendChild($this->dom->createElement('Weight', '1.5'));
		$elPiece1->appendChild($this->dom->createElement('Depth', '1'));
		$elPiece1->appendChild($this->dom->createElement('Width', '2'));
		$elPiece1->appendChild($this->dom->createElement('Height', '3'));
		$elPieces->appendChild($elPiece1);
		$elPiece2 = $this->dom->createElement('Piece');
		$elPiece2->appendChild($this->dom->createElement('Weight', '2.5'));
		$elPiece2->appendChild($this->dom->createElement('Depth', '4'));
		$elPiece2->appendChild($this->dom->createElement('Width', '5'));
		$elPiece2->appendChild($this->dom->createElement('Height', '6'));
		$elPieces->appendChild($elPiece2); */
		return $elPieces;
	}
	
	/**
	 * 创建ShipmentDetails节点
	 */
	private function createShipmentDetails() {
		$elShipmentDetails = $this->dom->createElement('ShipmentDetails');
		$NumberOfPieces = count($this->pieces);
		$elShipmentDetails->appendChild($this->dom->createElement('NumberOfPieces', $NumberOfPieces));
		$elShipmentDetails->appendChild($this->dom->createElement('CurrencyCode', $this->orderRow['currency_code']));
		if($NumberOfPieces > 0)	$elShipmentDetails->appendChild($this->getPiecesElement());
		$elShipmentDetails->appendChild($this->dom->createElement('PackageType', 'EE'));
		$elShipmentDetails->appendChild($this->dom->createElement('Weight', $this->totalWeight));
		$elShipmentDetails->appendChild($this->dom->createElement('DimensionUnit', 'C'));
		$elShipmentDetails->appendChild($this->dom->createElement('WeightUnit', 'K'));
		$elShipmentDetails->appendChild($this->dom->createElement('GlobalProductCode', 'P'));
		$elShipmentDetails->appendChild($this->dom->createElement('LocalProductCode', 'P'));
		$elShipmentDetails->appendChild($this->dom->createElement('DoorTo', 'DD'));
		$elShipmentDetails->appendChild($this->dom->createElement('Date', date('Y-m-d')));
		$elShipmentDetails->appendChild($this->dom->createElement('Contents', $this->shipmentContent));
		$elShipmentDetails->appendChild($this->dom->createElement('IsDutiable', 'Y'));
		//$elShipmentDetails->appendChild($this->dom->createElement('InsuredAmount', '3000.10'));
		//$elShipmentDetails->appendChild($this->dom->createElement('CustData', '1'));
		$this->elShipmentValidateRequestAP->appendChild($elShipmentDetails);
	}
	
	/**
	 * 创建Shipper节点
	 */
	/* private function createShipper() {
		$elShipper = $this->dom->createElement('Shipper');
		$elShipper->appendChild($this->dom->createElement('ShipperID', '550000055'));
		if($this->shpper['oab_company']=='') return '发件人公司名称不能为空';
		$elShipper->appendChild($this->dom->createElement('CompanyName', $this->shpper['oab_company']));
		if($this->shpper['oab_street_address1']=='') return '发件人地址不能为空';
		$elShipper->appendChild($this->dom->createElement('AddressLine', $this->shpper['oab_street_address1']));
		if($this->shpper['oab_city']=='') return '发件人城市不能为空';
		$elShipper->appendChild($this->dom->createElement('City', $this->shpper['oab_city']));
		//$elConsignee->appendChild($this->dom->createElement('DivisionCode', ''));
		if($this->shpper['oab_postcode']=='') return '发件人邮编不能为空';
		$elShipper->appendChild($this->dom->createElement('PostalCode', $this->shpper['oab_postcode']));
		if($this->shpper['oab_country_id']=='') return '发件人国家不能为空';
		$aCountry = Service_Country::getByField($this->shpper['oab_country_id']);
		$elShipper->appendChild($this->dom->createElement('CountryCode', $aCountry['country_code']));
		$elShipper->appendChild($this->dom->createElement('CountryName', $aCountry['country_name_en']));
		$elContact = $this->dom->createElement('Contact');
		if($this->shpper['oab_firstname']=='' && $this->shpper['oab_lastname']=='') {
			return '发件人姓名不能为空';
		}
		$elContact->appendChild($this->dom->createElement('PersonName', $this->shpper['oab_firstname'].' '.$this->shpper['oab_lastname']));
		if($this->shpper['oab_phone']=='') return '收件人电话不能为空';
		$elContact->appendChild($this->dom->createElement('PhoneNumber', $this->shpper['oab_phone']));
		$elContact->appendChild($this->dom->createElement('PhoneExtension', ''));
		$elContact->appendChild($this->dom->createElement('FaxNumber', $this->shpper['oab_fax']));
		$elContact->appendChild($this->dom->createElement('Telex', ''));
		$elShipper->appendChild($elContact);
		$this->elShipmentValidateRequestAP->appendChild($elShipper);
		return true;
	} */
	/* private function createShipper() {
		$elShipper = $this->dom->createElement('Shipper');
		$elShipper->appendChild($this->dom->createElement('ShipperID', '550000055'));
		$elShipper->appendChild($this->dom->createElement('CompanyName', 'Santa inc'));
		$elShipper->appendChild($this->dom->createElement('AddressLine', '333 Twin'));
		$elShipper->appendChild($this->dom->createElement('AddressLine', 'Suit 333'));
		$elShipper->appendChild($this->dom->createElement('City', 'Kuala Lumpur'));
		$elShipper->appendChild($this->dom->createElement('PostalCode', '94065'));
		$elShipper->appendChild($this->dom->createElement('CountryCode', 'MY'));
		$elShipper->appendChild($this->dom->createElement('CountryName', 'Malaysia'));
		$elContact = $this->dom->createElement('Contact');
		$elContact->appendChild($this->dom->createElement('PersonName', 'santa santa'));
		$elContact->appendChild($this->dom->createElement('PhoneNumber', '15356456364'));
		$elContact->appendChild($this->dom->createElement('PhoneExtension', '6536'));
		$elContact->appendChild($this->dom->createElement('FaxNumber', '17456356365'));
		$elContact->appendChild($this->dom->createElement('Telex', '74558'));
		$elShipper->appendChild($elContact);
		$this->elShipmentValidateRequestAP->appendChild($elShipper);
		return true;
	} */
	/* private function createShipper() {
		$elShipper = $this->dom->createElement('Shipper');
		$elShipper->appendChild($this->dom->createElement('ShipperID', $this->shipperAccountNumber));
		$elShipper->appendChild($this->dom->createElement('CompanyName', 'Cargo Service'));
		$elShipper->appendChild($this->dom->createElement('AddressLine', 'Lan Di DaJie'));
		//$elShipper->appendChild($this->dom->createElement('AddressLine', 'Suit 333'));
		$elShipper->appendChild($this->dom->createElement('City', 'TUEN MUN'));
		$elShipper->appendChild($this->dom->createElement('PostalCode', ''));
		$elShipper->appendChild($this->dom->createElement('CountryCode', 'HK'));
		$elShipper->appendChild($this->dom->createElement('CountryName', 'Hong Kong'));
		$elContact = $this->dom->createElement('Contact');
		$elContact->appendChild($this->dom->createElement('PersonName', 'John Lau'));
		$elContact->appendChild($this->dom->createElement('PhoneNumber', '66663339'));
		$elContact->appendChild($this->dom->createElement('PhoneExtension', '8888'));
		$elContact->appendChild($this->dom->createElement('FaxNumber', '66663339'));
		$elContact->appendChild($this->dom->createElement('Telex', '74558'));
		$elShipper->appendChild($elContact);
		$this->elShipmentValidateRequestAP->appendChild($elShipper);
		return true;
	} */
	private function createShipper() {
		$elShipper = $this->dom->createElement('Shipper');
		$elShipper->appendChild($this->dom->createElement('ShipperID', $this->shipperAccountNumber));
		$elShipper->appendChild($this->dom->createElement('CompanyName', '深圳市招海国际货运代理有限公司'));
		$elShipper->appendChild($this->dom->createElement('AddressLine', 'UNIT 02,9/F TEXACO ROAD,'));
		$elShipper->appendChild($this->dom->createElement('AddressLine', 'INDUSTRIAL CENTRE BLOCK B NO.14-22,'));
		$elShipper->appendChild($this->dom->createElement('AddressLine', 'WANG LUNG STREET,'));
		$elShipper->appendChild($this->dom->createElement('City', 'TSUEN WAN,N.T.'));
		$elShipper->appendChild($this->dom->createElement('PostalCode', ''));
		$elShipper->appendChild($this->dom->createElement('CountryCode', 'HK'));
		$elShipper->appendChild($this->dom->createElement('CountryName', 'Hong Kong'));
		$elContact = $this->dom->createElement('Contact');
		//$elContact->appendChild($this->dom->createElement('PersonName', 'Tony Lip'));
		$elContact->appendChild($this->dom->createElement('PersonName', 'Jane Lin'));
		$elContact->appendChild($this->dom->createElement('PhoneNumber', '85236102720'));
		//$elContact->appendChild($this->dom->createElement('PhoneExtension', ''));
		$elContact->appendChild($this->dom->createElement('FaxNumber', '85224190251'));
		//$elContact->appendChild($this->dom->createElement('Telex', ''));
		$elShipper->appendChild($elContact);
		$this->elShipmentValidateRequestAP->appendChild($elShipper);
		return true;
	}
	
	/**
	 * 生成XML文档
	 * @param string $path
	 * @return int|string
	 */
	public function generate($path) {
		$rInit = $this->_init();
		if($rInit !== true) return $rInit;
		$this->createShipmentValidateRequestAP();
		$this->createRequest();
		$this->elShipmentValidateRequestAP->appendChild($this->dom->createElement('LanguageCode', 'en'));
		$this->elShipmentValidateRequestAP->appendChild($this->dom->createElement('PiecesEnabled', 'Y'));
		$this->createBilling();
		$cResult = $this->createConsignee();
		if($cResult !== true) return $cResult;
		$this->createDutiable();
		$this->createReference();
		$this->createShipmentDetails();
		$sResult = $this->createShipper();
		if($sResult !== true) return $sResult;
		$this->elShipmentValidateRequestAP->appendChild($this->dom->createElement('LabelImageFormat', 'EPL2'));
		$result = $this->dom->save($path);
		if($result === false) return '生成订单['.$this->order_code.']的XML文件失败';
		else return true;
	}
	
}
