<?php
/**
 * 生成出库单报文XML 
 * @author solar<solarzheng@cargofe.com.cn>
 */
class Service_OutBillXmlProcess
{
	public $version = '1.0';
	public $sendtime = '';
	public $MessageID = 0;
	public $formID = '';
	
	private $dom = null;
	private $elMessage = null;
	private $elHead = null;
	private $elDeclaration = null;
	private $elBillHead = null;
	
	private $sb_code = '';
	private $sbRow = array();
	private $sbaRow = array();	//ship_batch_attribute
	private $fmtRow = array();	//ftp_message_type
	private $fmtRows = array();	//ftp_message_type
	private $productList = array();
	private $customerRow = array();
	private $gross_weight = 0;
	private $net_weight = 0;
	private $kvCurrency = array();
	private $totalPrice = 0;	//总价
	
	public function __construct($sb_code) {
		$this->formID = $sb_code;
		$this->sb_code = $sb_code;
		$this->sbRow = Service_ShipBatch::getByField($sb_code, 'sb_code');
		$this->sbaRow = Service_ShipBatchAttribute::getByField($sb_code, 'sb_code');
		$aOrderCode = Service_ShipBatch::getOrderCodes($this->sb_code);
		$this->productList = Service_OrderProduct::getOutBillProducts($aOrderCode);
		//$this->totalPrice = $this->productList['total'];
		unset($this->productList['total']);
		$firstRow = current($this->productList);
		$this->customerRow = Service_Customer::getByField($firstRow['customer_id']);
		if ($this->sbaRow['form_type']=="E2F") {
			$this->fmtRow = Service_FtpMessageType::getByField(5, 'fmt_id');
			/*$customer=Service_Orders::getByField($aOrderCode,'order_code');
			$this->customerRow=Service_Customer::getByField($customer['customer_code'],'customer_code');*/
			//$this->fmtRow=$fmtRow[0];
			$this->fmtRows=$this->fmtRow;
		$this->fmtRow['agent_code']=$this->customerRow['trade_co'];
		$this->fmtRow['agent_name']=$this->customerRow['trade_name'];

		}else{
			$this->fmtRow = Service_FtpMessageType::getByField('MCK', 'fmt_code');
			$this->fmtRows=$this->fmtRow;
		}
        if($this->sbaRow['gross_wt']>0 && $this->sbaRow['net_wt']>0){
            $this->gross_weight = $this->sbaRow['gross_wt'];
            $this->net_weight = number_format($this->sbaRow['net_wt'],2,'.','');
        }else{
            $this->gross_weight = Service_ShipBatchDetail::sumGrossWeight($sb_code);
            $this->net_weight = number_format(Service_ShipBatchDetail::sumNetWeight($sb_code),2,'.','');
        }
		$this->kvCurrency = Service_Currency::getKeyVal();
		//发送时间
		$this->sendtime = date('YmdHis').str_pad(rand(1,888), 3, '0', STR_PAD_LEFT);
		//MessageID
		$this->MessageID = ++$this->fmtRow['fmt_form_id'];
		Service_FtpMessageType::update(array('fmt_form_id'=>$this->MessageID), $this->fmtRow['fmt_id']);
	}
	
	/**
	 * 创建根节点Message
	 */
	private function createMessage() {
		$this->dom = new DOMDocument('1.0', 'UTF-8');
		$this->elMessage = $this->dom->createElement('Message');
		$this->elMessage->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
		$this->dom->appendChild($this->elMessage);
	}
	
	/**
	 * 创建Head节点
	 */
	private function createHead() {
		$this->elHead = $this->dom->createElement('Head');
		$this->elHead->appendChild($this->dom->createElement('MessageID', $this->MessageID));
		$this->elHead->appendChild($this->dom->createElement('FunctionCode', '2'));
		$this->elHead->appendChild($this->dom->createElement('MessageType', $this->fmtRow['fmt_type']));
		$this->elHead->appendChild($this->dom->createElement('SenderID', $this->fmtRow['fml_sender_id']));
		$this->elHead->appendChild($this->dom->createElement('ReceiverID', $this->fmtRow['fml_receiver_id']));
		$this->elHead->appendChild($this->dom->createElement('SendTime', $this->sendtime));
		$this->elHead->appendChild($this->dom->createElement('Version', $this->version));
		$this->elMessage->appendChild($this->elHead);
	}
	
	/**
	 * 创建Declaration节点
	 */
	private function createDeclaration() {
		$this->elDeclaration = $this->dom->createElement('Declaration');
		$this->elMessage->appendChild($this->elDeclaration);		
	}
	
	/**
	 * 创建WAREHOUSE_BILL_HEAD节点
	 */
	private function createBillHead() {
		$this->elBillHead = $this->dom->createElement('WAREHOUSE_BILL_HEAD');
		$this->elBillHead->appendChild($this->dom->createElement('SERIAL_NO', $this->sbRow['sb_id']));
		$this->elBillHead->appendChild($this->dom->createElement('FORM_ID', $this->formID));
		$this->elBillHead->appendChild($this->dom->createElement('DECL_PORT', $this->fmtRow['fmt_decl_port']));
		$this->elBillHead->appendChild($this->dom->createElement('I_E_PORT', $this->sbaRow['ie_port']));
		$this->elBillHead->appendChild($this->dom->createElement('I_E_MODE', $this->fmtRow['fmt_ie_mode']));
		$this->elBillHead->appendChild($this->dom->createElement('PS_TYPE', $this->fmtRow['fml_ps_type']));
		$this->elBillHead->appendChild($this->dom->createElement('RELATIVE_FORM_TYPE', $this->fmtRow['relative_form_type']));
		$this->elBillHead->appendChild($this->dom->createElement('FORM_TYPE', $this->fmtRow['form_type']));
		$this->elBillHead->appendChild($this->dom->createElement('EMS_NO', $this->fmtRow['fml_ems_no']));
		$this->elBillHead->appendChild($this->dom->createElement('EMS_COP_NO'));
		$this->elBillHead->appendChild($this->dom->createElement('TRAF_NAME'));
		//if($this->sbaRow['traf_name']=='truck') $this->sbaRow['voyage_no'] = '';
		$this->elBillHead->appendChild($this->dom->createElement('VOYAGE_NO'));
		$this->elBillHead->appendChild($this->dom->createElement('BILL_NO'));
        $gw = $this->gross_weight>1?$this->gross_weight:"1";
		$this->elBillHead->appendChild($this->dom->createElement('GROSS_WT', $gw));
		$this->elBillHead->appendChild($this->dom->createElement('NET_WT', $this->net_weight));
		$this->elBillHead->appendChild($this->dom->createElement('PACK_NO', $this->sbaRow['pack_no']));
		//$this->elBillHead->appendChild($this->dom->createElement('WRAP_TYPE', $this->sbaRow['wrap_type']));
		$this->elBillHead->appendChild($this->dom->createElement('WRAP_TYPE', '7'));	//固定为其他
		$this->elBillHead->appendChild($this->dom->createElement('I_E_DATE'));
		$this->elBillHead->appendChild($this->dom->createElement('TRAF_MODE', $this->sbaRow['traf_mode']));
		$this->elBillHead->appendChild($this->dom->createElement('TRADE_CO', $this->fmtRow['agent_code']));
		$this->elBillHead->appendChild($this->dom->createElement('TRADE_NAME', $this->fmtRow['agent_name']));
		$this->elBillHead->appendChild($this->dom->createElement('TRADE_MODE', $this->sbaRow['trade_mode']));
		$this->elBillHead->appendChild($this->dom->createElement('TRANS_MODE', $this->sbaRow['trans_mode']));
		$this->elBillHead->appendChild($this->dom->createElement('AGENT_CODE', $this->fmtRows['agent_code']));
		$this->elBillHead->appendChild($this->dom->createElement('AGENT_NAME', $this->fmtRows['agent_name']));
		$this->elBillHead->appendChild($this->dom->createElement('TRADE_COUNTRY', $this->sbaRow['country_id']));
		$this->elBillHead->appendChild($this->dom->createElement('OWNER_CODE', $this->fmtRow['agent_code']));
		$this->elBillHead->appendChild($this->dom->createElement('OWNER_NAME', $this->fmtRow['agent_name']));
		$this->elBillHead->appendChild($this->dom->createElement('NOTE_S'));
		/* $consignee = '收货人：'.$this->sbaRow['consignee'];
		$total = '总价：'.$this->totalPrice;
		$this->elBillHead->appendChild($this->dom->createElement('NOTE_S', $consignee.'  '.$total)); */
		$this->elBillHead->appendChild($this->dom->createElement('RELATIVE_FORM_ID'));
		$this->elBillHead->appendChild($this->dom->createElement('RELATIVE_FORM_STATUS'));
		$this->elBillHead->appendChild($this->dom->createElement('INPUT_DATE'));
		$this->elBillHead->appendChild($this->dom->createElement('INPUT_NO'));
		$this->elBillHead->appendChild($this->dom->createElement('FORM_STATUS'));
		$this->elBillHead->appendChild($this->dom->createElement('D_DATE'));
		$this->elBillHead->appendChild($this->dom->createElement('CHK_DATE'));
		$this->elBillHead->appendChild($this->dom->createElement('CHK_STATUS'));
		$this->elBillHead->appendChild($this->dom->createElement('AUDIT_DATE'));
		$this->elBillHead->appendChild($this->dom->createElement('CAN_BINDING_DATE'));
		$this->elBillHead->appendChild($this->dom->createElement('CAN_CHANNEL_DATE'));
		$this->elBillHead->appendChild($this->dom->createElement('DEDUC_DATE'));
		$this->elBillHead->appendChild($this->dom->createElement('COP_GB_CODE', $this->fmtRow['fml_receiver_id']));
		$this->elBillHead->appendChild($this->dom->createElement('EMC_EPORTCARD_ID'));
		$this->elBillHead->appendChild($this->dom->createElement('SIGN'));
		$this->elBillHead->appendChild($this->dom->createElement('DESTINATION_PORT', $this->sbaRow['country_id']));
		$this->elBillHead->appendChild($this->dom->createElement('TURN_NO'));
		$this->elBillHead->appendChild($this->dom->createElement('CUS_CODE', $this->fmtRow['outbound_trade_co']));
		$this->elBillHead->appendChild($this->dom->createElement('CUS_NAME', $this->fmtRow['outbound_trade_name']));
		/*$this->elBillHead->appendChild($this->dom->createElement('CUS_CODE', $this->customerRow['cus_code']));
		$this->elBillHead->appendChild($this->dom->createElement('CUS_NAME', $this->customerRow['cus_name']));*/
		$this->elBillHead->appendChild($this->dom->createElement('DECLARE_REMARK'));
		$this->elDeclaration->appendChild($this->elBillHead);
	}
	
	/**
	 * 创建WAREHOUSE_BILL_CONTAINER节点
	 * @return DOMElement
	 */
	private function createBillContainer() {
		$elBillContainer = $this->dom->createElement('WAREHOUSE_BILL_CONTAINER');
		$elBillContainer->appendChild($this->dom->createElement('FORM_ID', $this->formID));
		$elBillContainer->appendChild($this->dom->createElement('CONTA_ID', $this->sbaRow['conta_id']));
		$elBillContainer->appendChild($this->dom->createElement('CONTA_MODEL', $this->sbaRow['conta_model']));
		$elBillContainer->appendChild($this->dom->createElement('CONTA_WT', $this->sbaRow['conta_wt']));
		$this->elBillHead->appendChild($elBillContainer);		
	}
	
	/**
	 * 创建WAREHOUSE_BILL_LIST节点
	 * @param int $no
	 * @param array $info
	 * @return DOMElement
	 */
	private function createBillList($no, $info) {
		$elBillList = $this->dom->createElement('WAREHOUSE_BILL_LIST');
		$elBillList->appendChild($this->dom->createElement('FORM_ID', $this->formID));
		$elBillList->appendChild($this->dom->createElement('G_NO', $no));
		$elBillList->appendChild($this->dom->createElement('GOODS_ID', $info['goods_id']));
		$elBillList->appendChild($this->dom->createElement('MERGER_G_NO', $no));
		$elBillList->appendChild($this->dom->createElement('MERGER_MODE', 1));	//固定传1
		$elBillList->appendChild($this->dom->createElement('CODE_TS', $info['hs_code']));
		$elBillList->appendChild($this->dom->createElement('G_NAME_CN', $info['hs_goods_name']));
		$hemList = Service_HsElementMap::getByCondition(array('product_id'=>$info['product_id']), 'hem_detail');
		$elements = array();
		foreach($hemList as $hemRow) {
			$hem_detail = trim($hemRow['hem_detail']);
			$elements[] = $hem_detail ? $hem_detail : '/';
		}
		$elBillList->appendChild($this->dom->createElement('G_MODEL', implode('|',$elements)));
		$elBillList->appendChild($this->dom->createElement('G_NAME_EN', ''));
		//$QTY = round($info['hum_quantity_law'] * $info['quantity'], 3);
		//$QTY = round($info['hum_quantity_law'], 3);
		$QTY = $info['hum_quantity_law'];
		/* $elBillList->appendChild($this->dom->createElement('G_QTY', $QTY));
		$elBillList->appendChild($this->dom->createElement('G_UNIT', $info['pu_code_law'])); */
		$elBillList->appendChild($this->dom->createElement('G_QTY', $info['quantity']));
		$elBillList->appendChild($this->dom->createElement('G_UNIT', $info['pu_code']));
		//$DECL_PRICE = sprintf("%.4f", $info['product_declared_value']/$info['hum_quantity_law']);
		$total_price = sprintf("%.2f", $info['total_price']);
		$DECL_PRICE = sprintf("%.4f", $total_price/$info['quantity']);
		$elBillList->appendChild($this->dom->createElement('DECL_PRICE', $DECL_PRICE));
		$elBillList->appendChild($this->dom->createElement('CURR', $this->kvCurrency[$info['currency_code']]));		
		$elBillList->appendChild($this->dom->createElement('QTY_1', $QTY));
		$elBillList->appendChild($this->dom->createElement('UNIT_1', $info['pu_code_law']));
		$hum_quantity_second =  $info['pu_code_second'] ? $info['hum_quantity_second'] : '';
		$elBillList->appendChild($this->dom->createElement('QTY_2', $hum_quantity_second));
		$elBillList->appendChild($this->dom->createElement('UNIT_2', $info['pu_code_second']));
		$elBillList->appendChild($this->dom->createElement('ORIGIN_COUNTRY', '110'));	//固定110
		$elBillList->appendChild($this->dom->createElement('DUTY_MODE', '3'));	//固定3
		$elBillList->appendChild($this->dom->createElement('USE_TO', '11'));	//固定11
		$elBillList->appendChild($this->dom->createElement('NOTE_S', ''));
		$elBillList->appendChild($this->dom->createElement('CAR_NO', ''));
		$elBillList->appendChild($this->dom->createElement('URM_NO', ''));
		$elBillList->appendChild($this->dom->createElement('BIND_DATE', ''));
		$elBillList->appendChild($this->dom->createElement('CHANNEL_DATE', ''));
		/* $decl_total = sprintf("%.2f", $info['product_declared_value']*$info['quantity']);
		$elBillList->appendChild($this->dom->createElement('DECL_TOTAL', $decl_total)); */
		$elBillList->appendChild($this->dom->createElement('DECL_TOTAL', $total_price));
		//总单总价
		$this->totalPrice += $total_price;
		return $elBillList;
	}
	
	/**
	 * 生成XML文档
	 * @param string $path
	 * @return int|string
	 */
	public function generate($path='') {
		if(empty($this->productList)) return false;
		$this->createMessage();
		$this->createHead();
		$this->createDeclaration();
		$this->createBillHead();
		$no = 0;
		foreach($this->productList as $product) {
			++$no;
			$this->elBillHead->appendChild($this->createBillList($no, $product));
		}
		$this->createBillContainer();
		$nodeList = $this->elBillHead->getElementsByTagName('NOTE_S');
		if($nodeList->length == 0) return false;
		$consignee = '收货人：'.$this->sbaRow['consignee'];
		$total = '总价：'.sprintf("%.2f", $this->totalPrice);
		$nodeList->item(0)->nodeValue = $consignee.'  '.$total;
		if($path) return $this->dom->save($path);
		return $this->dom->saveXML();
	}
	
}
