global class EmailComeBackListen implements Messaging.InboundEmailHandler {
    global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {
    	//从标题中截取出关联信息
		System.debug('SWO邮件回复监听');
		String id = '';
		String type = '';
		if(String.isNotBlank(email.subject)){
			System.debug('email.subject:'+email.subject);
			List<String> str = email.subject.split('~');
			if(str!=null && str.size()!=0){
				//截取邮件关联信息，查询邮件关联对象，判断是否跳过邮件服务
				String name = str[1];
				System.debug('name:'+name);
				//SWO 的邮件返回
				if(name.startsWith('S')){
					type = 'S';
					name = name.substring(name.indexOf(':')+1,name.length());
					if(String.isNotBlank(name)){
						System.debug('name:'+name);
						List<SWO__c> swoList = [select Id,notSaveEmail__c,Name from SWO__c where Name=:name];
						if (swoList!=null && swoList.size()!=0) {
							id = swoList[0].Id;
							System.debug('回复监听id：'+id);
							System.debug('SWO邮件回复监听:'+swoList[0].notSaveEmail__c);
							if(swoList[0].notSaveEmail__c){
								System.debug('跳过邮件服务监听');
								swoList[0].notSaveEmail__c = false;
								update swoList[0];
								return null;
							}
						}	
					}
				}
				//Case 的邮件返回
				if(name.startsWith('C')){
					type = 'C';
					System.debug('Case 的邮件返回');
					name = name.substring(name.indexOf(':')+1, name.length());
					if(String.isNotBlank(name)){
						List<User_FaultInfo__c> caseList = [select Id,notSaveEmail__c,Name from User_FaultInfo__c where Name=:name];
						System.debug('caseList:'+caseList);
						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;
							}
						}
					}
				}
				//报价的邮件返回
				if(name.startsWith('Q')){
					type = 'Q';
					name = name.substring(name.indexOf(':')+1, name.length());
					if(String.isNotBlank(name)){
						List<Quotes__c> quotesList = [select Id,notSaveEmail__c,Name from Quotes__c where Name=:name];
						if (quotesList!=null && quotesList.size()!=0) {
							id = quotesList[0].Id;
							System.debug('Quoteses邮件回复监听:'+quotesList[0].notSaveEmail__c);
							if(quotesList[0].notSaveEmail__c){
								System.debug('跳过邮件服务监听');
								quotesList[0].notSaveEmail__c = false;
								update quotesList[0];
								return null;
							}
						}
					}
				}
				if (String.isNotBlank(id)) {
					createEmail(email,id,type);
				}
			}
		}
		Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
		//createEmail(email,id);
		//SendEmail();
		result.success = true;
		return result;
	}

	public void createEmail(Messaging.InboundEmail email,String id,String type){
		Mail_Merge__c mailMerge = new Mail_Merge__c();
		mailMerge.RECORD__c = id;
		//邮件标题
		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 = '';
		}
		if(type == 'S'){
			mailMerge.SWO__c = id;
			mailMerge.RECORD_TYPE__c = 'SWO';
		}
		if(type == 'C'){
			mailMerge.CaseF__c = id;
			mailMerge.RECORD_TYPE__c = 'Case';
		}
		if(type == 'Q'){
			mailMerge.Quotes__c = id;
			mailMerge.RECORD_TYPE__c = 'Quotes';
		}
		//发件人地址
		mailMerge.FROM__c = email.fromAddress;
		//收件人地址
		mailMerge.RECIPIENT__c = getAddresses(email.toAddresses);
		//抄送人
		mailMerge.CC__c = getAddresses(email.ccAddresses);

		setAllMember(mailMerge,email.toAddresses,email.ccAddresses);
		//邮件信息
		mailMerge.MESSAGE__c = email.plainTextBody;
		//收取回复邮件时间
		mailMerge.DATE__c = Datetime.now();

		mailMerge.TYPE__c = 'reply';
		
		mailMerge.EMAIL_SENT__c = 'YES';

		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 setAllMember(Mail_Merge__c mailMerge,List<String> toAddress,List<String> ccAddresses){
		mailMerge.ALL_MEMBER__c = '';
		mailMerge.ALL_MEMBER_NAME__c = '';
        mailMerge.ALL_MEMBER_TYPE__c = '';
		if(toAddress !=null && toAddress.size()!=0){
			for(String str : toAddress){
				//邮件地址之间用“;”隔开，发送邮件页会用“;”分割字符串
				mailMerge.ALL_MEMBER__c = mailMerge.ALL_MEMBER__c + str + ';';
				//名字暂时都用“-”，邮件页面分割出“-”会用空代替
				mailMerge.ALL_MEMBER_NAME__c = mailMerge.ALL_MEMBER_NAME__c + '-;';
				mailMerge.ALL_MEMBER_TYPE__c = mailMerge.ALL_MEMBER_TYPE__c + 'to;';
			}
		}
		if(ccAddresses !=null && ccAddresses.size()!=0){
			for(String str : ccAddresses){
				if(str.startsWith('email@') || str.equals('') || str.equals('')){
					continue;
				}
				//邮件地址之间用“;”隔开，发送邮件页会用“;”分割字符串
				mailMerge.ALL_MEMBER__c = mailMerge.ALL_MEMBER__c + str + ';';
				//名字暂时都用“-”，邮件页面分割出“-”会用空代替
				mailMerge.ALL_MEMBER_NAME__c = mailMerge.ALL_MEMBER_NAME__c + '-;';
				mailMerge.ALL_MEMBER_TYPE__c = mailMerge.ALL_MEMBER_TYPE__c + 'cc;';
			}
		}
	}
	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;
		}
	} 
}