public with sharing class CampaignMemberTriggerHandler extends Oly_TriggerHandler {
	private Map<Id, CampaignMember__c> newMap;
	private Map<Id, CampaignMember__c> oldMap;
	private List<CampaignMember__c> newList;
	private List<CampaignMember__c> oldList;
	public CampaignMemberTriggerHandler() {
		this.newMap = (Map<Id, CampaignMember__c>) Trigger.newMap;
		this.oldMap = (Map<Id, CampaignMember__c>) Trigger.oldMap;
		this.newList = (List<CampaignMember__c>) Trigger.new;
		this.oldList = (List<CampaignMember__c>) Trigger.old;
	}

	protected override void afterInsert() {
		updateCampaigntoContact();
	}

	protected override void afterUpdate() {
		updateCampaigntoContact();
	}
	protected override void BeforeDelete() {

		removeCampaigntoContact();
	}
	protected override void afterUndelete() {
		updateCampaigntoContact();

	}


	private void updateCampaigntoContact() {
		this.newlist =
		    [select id, Contact_ID__c, Campaign__c from CampaignMember__c
		     where Campaign__r.recordType.DeveloperName = 'ServiceEngineerTraining' and id in: newlist];
		list<Contact> updateContactlist = new list<Contact>();
		for (CampaignMember__c temCM : newlist) {
			updateContactlist.add(new Contact(id = temCM.Contact_ID__c, Campaign__c = temCM.Campaign__c, IsEndoscope__c = '是'));
		}
		if (updateContactlist.size() > 0) {
			ControllerUtil.updateSObjectContact(updateContactlist);
		}

	}
	private void removeCampaigntoContact() {
		this.oldList = [select id, Contact_ID__c, Campaign__c from CampaignMember__c
		                where Campaign__r.recordType.DeveloperName = 'ServiceEngineerTraining' and id in: oldList];
		list<id> oldContactIdlist = new list<id>();
		for (CampaignMember__c temCM : oldList) {
			oldContactIdlist.add( temCM.Contact_ID__c);
		}
		Map<id, contact> oldContactmap = new Map<id, contact>(
		    [select id, Campaign__c
		     from contact
		     where Campaign__c != null
		     and id in: oldContactIdlist]);
		list<Contact> updateContactlist = new list<Contact>();
		for (CampaignMember__c temCM : oldList) {
			Contact oldContact = oldContactmap.get(temCM.Contact_ID__c);
			if (oldContact != null && temCM.Campaign__c != null
			        && oldContact.Campaign__c.equals(temCM.Campaign__c)) {
				updateContactlist.add(new Contact(id = temCM.Contact_ID__c, Campaign__c = null, IsEndoscope__c = null));
			}
		}
		if (updateContactlist.size() > 0) {
			ControllerUtil.updateSObjectContact(updateContactlist);
		}

	}

}