<?php
class Service_ShipBatchMessageProcess
{	
	/**
	 * 本地文件路径
	 * @author solar
	 * @return string
	 */
	public function getBasePath() {
		return APPLICATION_PATH.'/../data/ftp';
	}
	/**
	 * 接收文件夹本地路径
	 * @author solar
	 * @return string
	 */
	public function getOutboundReceivePath() {
		$absolutePath = $this->getBasePath().'/outbound_receive/'.date('Y/m/d');
		if(!file_exists($absolutePath)) {
			mkdir($absolutePath, 0777, true);
		}
		return $absolutePath;
	}
	
	/**
	 * @author william-fan
	 * @todo 读取远程xml数据
	 */
	public function getSendResult(){
		$fmtRow = Service_FtpMessageType::getByField('MCK', 'fmt_code');
		$connect = ftp_connect($fmtRow['fmt_host']);
		$is_login = ftp_login($connect, $fmtRow['fmt_username'], $fmtRow['fmt_password']);
		if(!$is_login) return '登录FTP服务器失败';
		$receivePath = $this->getOutboundReceivePath();
		$paths = ftp_nlist($connect, '/outbound_send/backup');
		//echo $receivePath;
		//print_r($paths);
		foreach($paths as $remote_path) {
			$path_info = pathinfo($remote_path);
			//exit('000');
			//print_r($path_info);
			
			/* if(!isset($path_info['extension']) || strtolower($path_info['extension'])!='xml') continue;
			$code = $path_info['filename'];
			$local_path = $receivePath.'/'.$path_info['basename']; */
			
			//$is_get = ftp_get($connect, $local_path, $remote_path, FTP_BINARY);
			
			$xmlString = self::ftp_get_contents($connect, $remote_path);
			$xmlget = simplexml_load_string($xmlString);
			
			
			
			//print_r($xmlget);
			
			$HeadObj = $xmlget->Head;
			$HeadObjData = Common_Common::objectToArray($HeadObj);
			//print_r($HeadObjData);
			
			$MessageID = $HeadObjData['MessageID'];
			$FunctionCode = $HeadObjData['FunctionCode'];
			$MessageType = $HeadObjData['MessageType'];
			$SenderID = $HeadObjData['SenderID'];
			$ReceiverID = $HeadObjData['ReceiverID'];
			$SendTime = $HeadObjData['SendTime'];
			$Version = $HeadObjData['Version'];
			
			
			$Head = array(
				'MessageID'=>$MessageID,
				'FunctionCode'=>$FunctionCode,
				'MessageType'=>$MessageType,
				'SenderID'=>$SenderID,
				'ReceiverID'=>$ReceiverID,
				'SendTime'=>$SendTime,
				'Version'=>$Version						
			);
			
			//$
			$DeclarationObj = $xmlget->Declaration->WAREHOUSE_BILL_HEAD;
			
			$DeclarationObjData = Common_Common::objectToArray($DeclarationObj);
			
			//print_r($DeclarationObjData);

			$sbmbhArr = array(
				'SERIAL_NO'=>$DeclarationObjData['SERIAL_NO'],
				'FORM_ID'=>$DeclarationObjData['FORM_ID'],
				'DECL_PORT'=>$DeclarationObjData['DECL_PORT'],
				'I_E_PORT'=>$DeclarationObjData['I_E_PORT'],
				'I_E_MODE'=>$DeclarationObjData['I_E_MODE'],
				'PS_TYPE'=>$DeclarationObjData['PS_TYPE'],
				'RELATIVE_FORM_TYPE'=>$DeclarationObjData['RELATIVE_FORM_TYPE'],
				'FORM_TYPE'=>$DeclarationObjData['FORM_TYPE'],
				'EMS_NO'=>$DeclarationObjData['EMS_NO'],
				'EMS_COP_NO'=>$DeclarationObjData['EMS_COP_NO'],
				'TRAF_NAME'=>$DeclarationObjData['TRAF_NAME'],
				'VOYAGE_NO'=>$DeclarationObjData['VOYAGE_NO'],
				'BILL_NO'=>$DeclarationObjData['BILL_NO'],
				'GROSS_WT'=>$DeclarationObjData['GROSS_WT'],
				'NET_WT'=>$DeclarationObjData['NET_WT'],
				'PACK_NO'=>$DeclarationObjData['PACK_NO'],
				'WRAP_TYPE'=>$DeclarationObjData['WRAP_TYPE'],
				'I_E_DATE'=>$DeclarationObjData['I_E_DATE'],
				'TRAF_MODE'=>$DeclarationObjData['TRAF_MODE'],
				'TRADE_CO'=>$DeclarationObjData['TRADE_CO'],
				'TRADE_NAME'=>$DeclarationObjData['TRADE_NAME'],
				'TRADE_MODE'=>$DeclarationObjData['TRADE_MODE'],
				'TRANS_MODE'=>$DeclarationObjData['TRANS_MODE'],
				'AGENT_CODE'=>$DeclarationObjData['AGENT_CODE'],
				'AGENT_NAME'=>$DeclarationObjData['AGENT_NAME'],
				'TRADE_COUNTRY'=>$DeclarationObjData['TRADE_COUNTRY'],
				'OWNER_CODE'=>$DeclarationObjData['OWNER_CODE'],
				'OWNER_NAME'=>$DeclarationObjData['OWNER_NAME'],
				'NOTE_S'=>$DeclarationObjData['NOTE_S'],
				'RELATIVE_FORM_ID'=>$DeclarationObjData['RELATIVE_FORM_ID'],
				'RELATIVE_FORM_STATUS'=>$DeclarationObjData['RELATIVE_FORM_STATUS'],
				'INPUT_DATE'=>$DeclarationObjData['INPUT_DATE'],
				'INPUT_NO'=>$DeclarationObjData['INPUT_NO'],
				'FORM_STATUS'=>$DeclarationObjData['FORM_STATUS'],
				'D_DATE'=>$DeclarationObjData['D_DATE'],
				'CHK_DATE'=>$DeclarationObjData['CHK_DATE'],
				'CHK_STATUS'=>$DeclarationObjData['CHK_STATUS'],
				'AUDIT_DATE'=>$DeclarationObjData['AUDIT_DATE'],
				'CAN_BINDING_DATE'=>$DeclarationObjData['CAN_BINDING_DATE'],
				'CAN_CHANNEL_DATE'=>$DeclarationObjData['CAN_CHANNEL_DATE'],
				'DEDUC_DATE'=>$DeclarationObjData['DEDUC_DATE'],
				'COP_GB_CODE'=>$DeclarationObjData['COP_GB_CODE'],
				'EMC_EPORTCARD_ID'=>$DeclarationObjData['EMC_EPORTCARD_ID'],
				'SIGN'=>$DeclarationObjData['SIGN'],
				'DESTINATION_PORT'=>$DeclarationObjData['DESTINATION_PORT'],
				'TURN_NO'=>$DeclarationObjData['TURN_NO'],
				'CUS_CODE'=>$DeclarationObjData['CUS_CODE'],
				'CUS_NAME'=>$DeclarationObjData['CUS_NAME'],
				'DECLARE_REMARK'=>$DeclarationObjData['DECLARE_REMARK'],
				'BILL_CONTAINER_FORM_ID'=>$DeclarationObjData['WAREHOUSE_BILL_CONTAINER']['FORM_ID'],
				'BILL_CONTAINER_CONTA_ID'=>$DeclarationObjData['WAREHOUSE_BILL_CONTAINER']['CONTA_ID'],
				'BILL_CONTAINER_CONTA_MODEL'=>$DeclarationObjData['WAREHOUSE_BILL_CONTAINER']['CONTA_MODEL'],
				'BILL_CONTAINER_CONTA_WT'=>$DeclarationObjData['WAREHOUSE_BILL_CONTAINER']['CONTA_WT'],	
			);
			//print_r($sbmbhArr);
			//exit;
			//ship_batch_message_bill_list
			$sbmblArr = array();
			
			$warehouseBillLists = $DeclarationObjData['WAREHOUSE_BILL_LIST'];
			if(!isset($warehouseBillLists[0])){
				$warehouseBillLists = array($warehouseBillLists);	
			}
			
			$result = self::shipMessageProcess($DeclarationObjData['FORM_ID'],$Head,$sbmbhArr,$warehouseBillLists);
			print_r($result);
			//exit;
			
		}
		@ftp_close($connect);
		return true;
	}
	/**
	 * @author william-fan
	 * @todo 用于读取ftp_message_sendlist数据
	 */
	public function getftpMessageSendResult(){
		$db =  Common_Common::getAdapter();
		$sql = "select * from ftp_message_sendlist";
		
	}
	public static function ftp_get_contents ($conn_id, $filename) {
		//Create temp handler:
		$tempHandle = fopen('php://temp', 'r+');
		//Get file from FTP:
		if (@ftp_fget($conn_id, $tempHandle, $filename, FTP_ASCII, 0)) {
			rewind($tempHandle);
			return stream_get_contents($tempHandle);
		} else {
			return false;
		}
	}
	/**
	 * @author william-fan
	 * @todo 用于添加数据
	 */
	public static function shipMessageProcess($sb_code,$sbmhArr,$sbmbhArr,$warehouseBillLists){
		$db = Common_Common::getAdapter();
		$db->beginTransaction();
		try {
			$sbmbhInfo = Service_ShipBatchMessageBillHead::getByField($sb_code,'FORM_ID');
			if(!empty($sbmbhInfo)){
				throw new Exception("该出区单已保存数据");
			}
			
			//ship_batch_message_header
			//$sbmhArr
			$shipBatch = Service_ShipBatch::getByField($sb_code,'sb_code');
			if(empty($shipBatch) || $shipBatch['sb_status']=='0'){
				throw new Exception("出区单{$sb_code}不存在,或者为草稿状态");
			}
			
			$sbmh_id=Service_ShipBatchMessageHeader::add($sbmhArr);
			if(!$sbmh_id){
				throw new Exception("添加出区报文头出错");	
			}
			//ship_batch_message_bill_head
			$sbmbhArr['sbmh_id'] = $sbmh_id;
			
			$sbmbh_id = Service_ShipBatchMessageBillHead::add($sbmbhArr);
			if(!$sbmbh_id){
				throw new Exception("添加出区报文声明头出错");
			}
			//ship_batch_message_bill_list
			if(!empty($warehouseBillLists)){
				foreach ($warehouseBillLists as $key=>$list){
					//ship_batch_message_bill_list
					$sbmblArr = array(
						'FORM_ID'=>$list['FORM_ID'],
						'G_NO'=>$list['G_NO'],
						'GOODS_ID'=>$list['GOODS_ID'],
						'MERGER_G_NO'=>$list['MERGER_G_NO'],
						'MERGER_MODE'=>$list['MERGER_MODE'],
						'CODE_TS'=>$list['CODE_TS'],
						'G_NAME_CN'=>$list['G_NAME_CN'],
						'G_MODEL'=>$list['G_MODEL'],
						'G_NAME_EN'=>$list['G_NAME_EN'],
						'G_QTY'=>$list['G_QTY'],
						'G_UNIT'=>$list['G_UNIT'],
						'DECL_PRICE'=>$list['DECL_PRICE'],
						'CURR'=>$list['CURR'],
						'QTY_1'=>$list['QTY_1'],
						'UNIT_1'=>$list['UNIT_1'],
						'QTY_2'=>$list['QTY_2'],
						'UNIT_2'=>$list['UNIT_2'],
						'ORIGIN_COUNTRY'=>$list['ORIGIN_COUNTRY'],
						'DUTY_MODE'=>$list['DUTY_MODE'],
						'USE_TO'=>$list['USE_TO'],
						'NOTE_S'=>$list['NOTE_S'],
						'CAR_NO'=>$list['CAR_NO'],
						'URM_NO'=>$list['URM_NO'],
						'BIND_DATE'=>$list['BIND_DATE'],
						'CHANNEL_DATE'=>$list['CHANNEL_DATE'],
						'DECL_TOTAL'=>$list['DECL_TOTAL'],
					);
					$sbmblArr['sbmbh_id'] = $sbmbh_id;
					if(!Service_ShipBatchMessageBillList::add($sbmblArr)){
						throw new Exception("出区报文声明表体");
					}
				}
			}else{
				throw new Exception("产品信息错误！");
			}
			//$condition = array(), $type = '*', $pageSize = 0, $page = 1, $orderBy = ""
			$condition = array(
				'sb_code'=>$sb_code		
			);	
			$shipbatchDetail = Service_ShipBatchDetail::getByCondition($condition,'*');
			$shipbatchOrderProductArr = array();
			if(!empty($shipbatchDetail)){
				foreach($shipbatchDetail as $ksd=>$vsd){
					$conditionsd = array(
						'ob_no'=>$vsd['ob_no']		
					);
					$shipoutboundDetail=Service_OutboundBagDetail::getByCondition($conditionsd,'*');
					if(!empty($shipoutboundDetail)){

						foreach ($shipoutboundDetail as $ksobd=>$vsobd){
							$orderProductCondition = array(
								'order_code'=>$vsobd['order_code']
							);
							$orderProducts = Service_OrderProduct::getByCondition($orderProductCondition,"*");
							if(!empty($orderProducts)){
								foreach ($orderProducts as $kop=>$vop){
									//ship_batch_order_product
									
									$product = Service_Product::getByField($vop['product_id']);
									if(empty($product)){
										throw new Exception("产品{$vop['product_id']}不存在");
									}
									$hum = Service_HsUom::getByField($product['hs_code'],'hs_code');
									if(empty($hum)){
										throw new Exception("海关申报单位{$product['hs_code']}不存在");
									}
									$hsuomap = Service_HsUomMap::getByField($vop['product_id'],'product_id');
									if(empty($hsuomap)){
										throw new Exception("产品{$vop['product_id']}法定数量不存在");
									}
									
									
									$hsElementCondition = array(
										'product_id'=>$vop['product_id']
									);
									$hselementMaps = Service_HsElementMap::getByCondition($hsElementCondition,'*');
									if(empty($hselementMaps)){
										throw new Exception("无产品和海关编码对于关系");
									}
                                    $hsString = '';
                                    foreach($hselementMaps as $khsm=>$vhsm){
                                        $hsString.=$vhsm['hem_detail'].'|';
                                    }
									/* $puInfo = Service_ProductUom::getByField($vop['product_id'],'product_id');
									if(empty($puInfo)){
                                        throw new Exception("产品{$vop['product_id']}无产品单位");
                                    } */
									
									$shipbatchOrderProduct = array(
										'sb_code'=>$sb_code,
										'order_code'=>$vop['order_code'],
										'product_id'=>$vop['product_id'],
										'product_barcode'=>$vop['product_barcode'],
										'op_quantity'=>$vop['op_quantity'],
										'product_weight'=>$product['product_weight'],
										'pu_code_law'=>$hum['pu_code_law'],
										'hum_quantity_law'=>$hsuomap['hum_quantity_law'],
										'pu_code_second'=>$hum['pu_code_second'],
										'hum_quantity_second'=>$hum['hum_quantity_second']?$hum['hum_quantity_second']:"",
										'hs_goods_name'=>$product['hs_goods_name'],
										'hs_code'=>$product['hs_code'],	
										'pu_code'=>$product['pu_code'],
                                        'hem_detail'=>$hsString,
										'goods_id'=>$product['goods_id'],
										'op_id'=>$vop['op_id']		
									);
									$sbop_id=Service_ShipBatchOrderProduct::add($shipbatchOrderProduct);
									if(!$sbop_id){
										throw new Exception("添加出区单和订单产品关联出错");
									}
								}
							}else{
								
							}
						}
					}else{
						throw new Exception("袋子无关联订单");
					}
				}
			}else{
				throw new Exception("该出区单无详情");
			}
			$result = array("ask"=>1,"message"=>"成功添加出区报文",'sb_code'=>$sb_code);
			$db->commit();
			//$db->rollBack();
		}catch (Exception $e){
			$result = array("ask"=>0,"message"=>$e->getMessage(),'sb_code'=>$sb_code);
			$db->rollBack();
		}
		return $result;
	}
	
	
}
