package com.artfess.bpm.listener;

import com.artfess.base.cache.annotation.CacheEvict;
import com.artfess.base.constants.CacheKeyConst;
import com.artfess.base.util.AppUtil;
import com.artfess.bpm.api.event.BpmDefinitionDelEvent;
import com.artfess.bpm.api.model.process.def.BpmDefinition;
import com.artfess.bpm.api.service.BpmDefinitionAccessor;
import com.artfess.bpm.natapi.def.NatProDefinitionService;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class BpmDefinitionListener implements ApplicationListener<BpmDefinitionDelEvent>{

	@Resource
	NatProDefinitionService natProDefinitionService;
	@Resource
	BpmDefinitionAccessor bpmDefinitionAccessor;

	@Override
	public void onApplicationEvent(BpmDefinitionDelEvent endEvent) {
		BpmDefinition bpmDef=(BpmDefinition) endEvent.getSource();
		delFromCache(bpmDef);
	}

	/**
	 * 清除缓存。
	 * @param defId
	 * void
	 */
	private void delFromCache(BpmDefinition def){
		String bpmnDefId=def.getBpmnDefId();
		String defId=def.getDefId();

		BpmDefinitionListener bean = AppUtil.getBean(getClass());

		bean.delByDefId(defId);
		bean.delByBpmnDefId(bpmnDefId);
		bean.delByFlowKey(def.getDefKey());

		natProDefinitionService.clearCacheByBpmnDefId(bpmnDefId);
		bpmDefinitionAccessor.clean(defId);
	}

	@CacheEvict(value = CacheKeyConst.EIP_BPM_DEFINITION, key = "#defId", ignoreException = false)
	protected void delByDefId(String defId) {}

	@CacheEvict(value = CacheKeyConst.EIP_BPM_DEFINITION_BPMN_ID, key = "#bpmnDefId", ignoreException = false)
	protected void delByBpmnDefId(String bpmnDefId) {}

	@CacheEvict(value = CacheKeyConst.EIP_BPM_DEFINITION_FLOW_KEY, key = "#flowKey", ignoreException = false)
	protected void delByFlowKey(String flowKey) {}
}
