<?php
class Service_FtpMessageProcess
{	
	/**
	 * 本地文件路径
	 * @author solar
	 * @return string
	 */
	public function getBasePath() {
		return APPLICATION_PATH.'/../data/ftp';
	}
		
	/**
	 * 添加发送消息
	 * @author solar
	 * @param string $sb_code
	 * @return int
	 */
	public function addSendMessage($sb_code) {
		$fileName = $sb_code.'.xml';
		$relativePath = '/outbound_send/'.date('Y/m/d');
		$absolutePath = $this->getBasePath().$relativePath;
		if(!file_exists($absolutePath)) {
			mkdir($absolutePath, 0777, true);
		}
		$obxProcess = new Service_OutBillXmlProcess($sb_code);
		$result = $obxProcess->generate($absolutePath.'/'.$fileName);
		if($result===false) return 0;
		$sbaRow=Service_ShipBatchAttribute::getByField($sb_code,'sb_code');
		 if ($sbaRow['form_type']=='E2F') {
                 $row['fmt_code'] = 'ZCCQ';
          }else{
              $row['fmt_code'] = 'MCK';
           }
		//$row['fmt_code'] = 'MCK';
		$row['fmt_type'] = 'BSG011';
		$row['refercence_no'] = $sb_code;
		$row['fml_path'] = $relativePath.'/'.$fileName;
		$row['fml_add_time'] = date('Y-m-d H:i:s');
		$row['fml_status'] = 1;
		$row['fml_send_time'] = $obxProcess->sendtime;
		return Service_FtpMessageSendlist::add($row);		
	}
	
	public function updateSendMessage($row) {
		$fileName = $row['refercence_no'].'.xml';
		$relativePath = '/outbound_send/'.date('Y/m/d');
		$absolutePath = $this->getBasePath().$relativePath;
		if(!file_exists($absolutePath)) {
			mkdir($absolutePath, 0777, true);
		}
		$obxProcess = new Service_SpOutBillXmlProcess($row['refercence_no']);
		$result = $obxProcess->generate($absolutePath.'/'.$fileName);
		if($result===false) return false;
		$aUpdate['fml_path'] = $relativePath.'/'.$fileName;
		$aUpdate['fml_update_time'] = date('Y-m-d H:i:s');
		$aUpdate['fml_send_time'] = $obxProcess->sendtime;
		return Service_FtpMessageSendlist::update($aUpdate, $row['fml_id']);
	}
	
	/**
	 * 发送消息文件到FTP服务器
	 * @author solar
	 * @param $fml_id
	 * @return boolean
	 */
	public function ftpSendMessage($fml_id) {
		$result = true;
		$fmsRow = Service_FtpMessageSendlist::getByField($fml_id);
		$fmtRow = Service_FtpMessageType::getByField($fmsRow['fmt_code'], 'fmt_code');
		$file_name = $fmsRow['refercence_no'].'.xml';
		$remote_file = $fmtRow['fmt_folder'].'/'.$file_name;
		$backup_file = $fmtRow['fmt_folder'].'/backup/'.$file_name;
		$local_file = $this->getBasePath().$fmsRow['fml_path'];
		$connect = ftp_connect($fmtRow['fmt_host']);
		$is_login = ftp_login($connect, $fmtRow['fmt_username'], $fmtRow['fmt_password']);
		if(!$is_login) return false;
		while(true) {
			if(ftp_put($connect, $remote_file, $local_file, FTP_BINARY) == false) {
				$result = false;
				break;
			}
			if(ftp_put($connect, $backup_file, $local_file, FTP_BINARY) == false) {
				$result = false;
			}
			break;
		}
		@ftp_close($connect);
		if($result === true) Service_FtpMessageSendlist::update(array('fml_status'=>2), $fml_id);
		else {
			$fmsUpdate['fml_failed_count'] = $fmsRow['fml_failed_count'] + 1;
			$fmsUpdate['fml_status'] = 1;
			Service_FtpMessageSendlist::update($fmsUpdate, $fml_id);
		}
		return $result;
	}
	
	/**
	 * 接收文件夹本地路径
	 * @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;
	}
	
	/**
	 * 检查出库单FTP接收文件夹
	 * @author solar
	 * @return true|string
	 */
	public function ftpOutboundReceive() {
		$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_receive');
		foreach($paths as $remote_path) {
			$path_info = pathinfo($remote_path);
			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);
			if(!$is_get) {
				$this->addReceiveMessage($code, $local_path, 1, 1);
				ftp_rename($connect, $remote_path, '/outbound_receive/failed/'.$path_info['basename']);
				continue;				
			}
			$sbRet = $this->updateShipBatch($code);
			if($sbRet!==true) {				
				$this->addReceiveMessage($code, $local_path, 1, 1);
				ftp_rename($connect, $remote_path, '/outbound_receive/failed/'.$path_info['basename']);
				continue;	
			}
			$this->addReceiveMessage($code, $local_path, 2);
			ftp_delete($connect, $remote_path);
		}
		@ftp_close($connect);
		return true;
	}
	
	/**
	 * 添加出库单接受消息
	 * @author solar
	 * @param string $code
	 * @param string $path
	 * @param int $status
	 * @param int $failed_count
	 * @return int
	 */
	public function addReceiveMessage($code, $path, $status, $failed_count=0) {
		$row['fmt_code'] = 'MCK';
		$row['fmt_type'] = 'BSG011';
		$row['refercence_no'] = $code;
		$row['fmr_path'] = $path;
		$row['fmr_failed_count'] = $failed_count;
		$row['fmr_status'] = $status;
		$row['fmr_add_time'] = date('Y-m-d H:i:s');
		return Service_FtpMessageReceivelist::add($row);
	}
	
	/**
	 * 修改出货总单为已审核状态
	 * @author solar
	 * @param string $sb_code
	 * @return true|string
	 */
	public function updateShipBatch($sb_code) {
		$aShipBatch = Service_ShipBatch::getByField($sb_code, 'sb_code');
		if(empty($aShipBatch)) return '出货总单号['.$sb_code.']不存在';
		if(intval($aShipBatch['sb_status']) !==1) return '出货总单号['.$sb_code.']不是已完成状态';
		$uShipBatch['sb_status'] = 2;
		$uShipBatch['sb_update_time'] = date('Y-m-d H:i:s');
		$affect = Service_ShipBatch::update($uShipBatch, $sb_code, 'sb_code');
		if($affect > 0) {
			$sblRow['sb_id'] = $aShipBatch['sb_id'];
			$sblRow['sb_code'] = $aShipBatch['sb_code'];
			$sblRow['sbl_type'] = 1;
			$sblRow['user_id'] = Service_User::getUserId();
			$sblRow['sbl_status_from'] = 1;
			$sblRow['sbl_status_to'] = 2;
			$sblRow['sbl_note'] = '扫描FTP服务器outbound_receive文件夹';
			$sblRow['sbl_add_time'] = date('Y-m-d H:i:s');
			$sblRow['sbl_ip'] = Common_Common::getIP();
			Service_ShipBatchLog::add($sblRow);
			return true;
		} else return '出货总单号['.$sb_code.']更新失败';
	}

    public function updateSummaryOrderMessage($sendRow){
        $fileName = $sendRow['invt_no'].'.xml';
        $relativePath = '/order/'.date('Y/m/d');
        $absolutePath = $this->getBasePath().$relativePath;
        if(!file_exists($absolutePath)) {
            mkdir($absolutePath, 0777, true);
        }
        $obxProcess = new Service_OrderXmlProcess($sendRow);
        $result = $obxProcess->generate($absolutePath.'/'.$fileName);
        if($result===false) return 0;
        $row['cmbl_xml_path'] = $relativePath.'/'.$fileName;
        return Service_OrderSendList::update($row,$sendRow['osl_id'],"osl_id");
    }
	
}
