<?php
class Service_ProductRecordProcess
{	
	private $productList = array();
	
	public function __construct($productList) {
		$this->productList = $productList;
	}
	
	/**
	 * 本地文件路径
	 * @author solar
	 * @return string
	 */
	public function getBasePath() {
		return APPLICATION_PATH.'/../data/ftp';
	}	
		
	/**
	 * 添加商品备案记录
	 * @author solar
	 * @return int|string
	 */
	public function addGoodsRecord() {
		$fmtRow = Service_FtpMessageType::getByField('QHW', 'fmt_code');
		$relativePath = $fmtRow['fmt_folder'].'/'.date('Y/m/d');
		$absolutePath = $this->getBasePath().$relativePath;
		if(!file_exists($absolutePath)) {
			mkdir($absolutePath, 0777, true);
		}
		$xmlProcess = new Service_ProductXmlProcess($this->productList);
		$result = $xmlProcess->generate($absolutePath);
		if($result===false) return '生成XML文件失败';
		$row['fmt_code'] = 'QHW';
		$row['message_id'] = $xmlProcess->messageID;
		$row['fpr_path'] = $relativePath.'/'.$xmlProcess->messageID.'.xml';
		$row['fpr_add_time'] = date('Y-m-d H:i:s');
		$id = Service_FtpProductRecord::add($row);
		return $id > 0 ? intval($id) : '添加备案记录失败';
	}
	
	/**
	 * 发送消息文件到FTP服务器
	 * @author solar
	 * @param int $fpr_id
	 * @return boolean
	 */
	public function ftpSendRecord($fpr_id) {
		$result = true;
		$fprRow = Service_FtpProductRecord::getByField($fpr_id);
		$fmtRow = Service_FtpMessageType::getByField($fprRow['fmt_code'], 'fmt_code');
		$file_name = $fprRow['message_id'].'.xml';
		$remote_file = $fmtRow['fmt_folder'].'/'.$file_name;
		$backup_file = $fmtRow['fmt_folder'].'/backup/'.$file_name;
		$local_file = $this->getBasePath().$fprRow['fpr_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_FtpProductRecord::update(array('fpr_status'=>2), $fpr_id);
		else {
			$fprUpdate['fpr_failed_count'] = $fprRow['fpr_failed_count'] + 1;
			$fprUpdate['fpr_status'] = 1;
			Service_FtpProductRecord::update($fprUpdate, $fpr_id);
		}
		return $result;
	}
	
	/**
	 * 商品备案
	 * @author solar
	 * @return array
	 */
	public function recordGoods() {
		$result = array('ask'=>0 ,'message'=>'');
		$fpr_id = $this->addGoodsRecord();
		if(!is_int($fpr_id)) {
			$result['message'] = $fpr_id;
			return $result;
		}		
		if($this->ftpSendRecord($fpr_id)===false) {
			$result['message'] = 'FTP发送备案文件失败';
			return $result;
		}
		$result['ask'] = 1;
		return $result;
	}
	
}
