global class CaseEmailComeBackListen implements Messaging.InboundEmailHandler {
   global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {
    	System.debug('进入Case回复邮件监听');
    	String id = '';
		if(String.isNotBlank(email.subject)){
			List<String> str = email.subject.split('~');
			if(str!=null && str.size()!=0){
				//截取邮件关联信息，查询邮件关联对象，判断是否跳过邮件服务
				String name = str[1];
				if(String.isNotBlank(name)){
					List<User_FaultInfo__c> caseList = [select Id,notSaveEmail__c,Name from User_FaultInfo__c where Name=:name];
					if(caseList!=null && caseList.size()!=0){
						id = caseList[0].Id;
						System.debug('Case邮件回复监听:'+caseList[0].notSaveEmail__c);
						if(caseList[0].notSaveEmail__c){
							System.debug('跳过邮件服务监听');
							caseList[0].notSaveEmail__c = false;
							update caseList[0];
							return null;
						}
					}
				}
			}
		}
		Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
		createEmail(email,id);
		//SendEmail();
		result.success = true;
		return result;
	} 
	public void createEmail(Messaging.InboundEmail email,String id){
		Mail_Merge__c mailMerge = new Mail_Merge__c();
		//邮件标题
		if(String.isNotBlank(email.subject)){
			mailMerge.SUBJECTCOPY__c = email.subject;
			List<String> str = email.subject.split('~');
			if(str!=null && str.size()!=0){
				mailMerge.SUBJECT__c = str[0];
				mailMerge.Name = str[0];
			}
		}else{
			mailMerge.SUBJECTCOPY__c = '';
			mailMerge.SUBJECT__c = '';
			mailMerge.Name = '';
		}
		mailMerge.CaseF__c = id;
		mailMerge.RECORD_TYPE__c = 'Case';
		//发件人地址
		mailMerge.FROM__c = email.fromAddress;
		//收件人地址
		mailMerge.RECIPIENT__c = getAddresses(email.toAddresses);
		//抄送人
		mailMerge.CC__c = getAddresses(email.ccAddresses);
		//邮件信息
		mailMerge.MESSAGE__c = email.plainTextBody;
		//收取回复邮件时间
		mailMerge.DATE__c = Date.today();

		mailMerge.TYPE__c = 'reply';
		
		insert mailMerge;
		//保存邮件附件
		saveFile(email.binaryAttachments,mailMerge.Id);
	}

	public String getAddresses(List<String> addresses){
		String returnStr = '';
		if(addresses!=null && addresses.size()!=0){
			for(String str:addresses){
				returnStr += str+';';
			}
		}
		return returnStr;
	}

	public void saveFile(List<Messaging.InboundEmail.BinaryAttachment> binaryAttachments,String Id){
		if (binaryAttachments != null && binaryAttachments.size()!=0) {
			List<Attachment> attachmentList = new List<Attachment>();
			for(Messaging.InboundEmail.BinaryAttachment emailFile : binaryAttachments){
				Attachment attachment = new Attachment();
				attachment.Name = emailFile.fileName;
				attachment.Body = emailFile.body;
				attachment.ParentId = Id;
				attachmentList.add(attachment);
			}
			insert attachmentList;
		}
	} 
}