package cn.ibizlab.core.extensions.service;

import cn.ibizlab.core.dict.extensions.service.DictDstService;
import cn.ibizlab.core.extensions.domain.BaseRequest;
import cn.ibizlab.core.extensions.domain.SqlResultsMQMsg;
import cn.ibizlab.core.extensions.util.ExpiryMap;
import cn.ibizlab.core.extensions.util.LocalMsgResultProducerService;
import cn.ibizlab.core.lite.extensions.domain.FieldObj;
import cn.ibizlab.core.lite.extensions.domain.ModelObj;
import cn.ibizlab.core.rule.domain.ExecLog;
import cn.ibizlab.core.rule.domain.ExecResult;
import cn.ibizlab.core.rule.service.IExecLogService;
import cn.ibizlab.core.rule.service.IExecResultService;
import cn.ibizlab.util.dict.CodeList;
import cn.ibizlab.util.helper.CachedBeanCopier;
import cn.ibizlab.util.helper.DataObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.kie.api.KieBase;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieRepository;
import org.kie.api.builder.Message;
import org.kie.api.definition.KiePackage;
import org.kie.api.definition.rule.Rule;
import org.kie.api.io.Resource;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.rule.FactHandle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;

/**
 *  规则服务对象接口
 */
@Service
@Primary
@Slf4j
public class BaseEntityServiceImpl implements BaseEntityService
{
	public static final String Tag_SaveResults = "SAVERESULTS";
	public static final String Tag_DeleteResults = "DELETEESULTS";
	public static final String Tag_EngineId = "engineId";
	public static final String Tag_Batch_SyncRun = "SYNCRUN";

	public BaseEntityServiceImpl()
	{
		System.setProperty("drools.dateformat", "yyyy/MM/dd HH:mm:ss");
		KieServices ks = KieServices.Factory.get();
		KieContainer kContainer = ks.getKieClasspathContainer();
	}

	@Value("${defaultResultDataSource:default}")
	protected String Default_ResultDataSource;

	@Autowired
	@Lazy
	private LocalMsgResultProducerService localMsgResultProducerService;

	@Value("${ibiz.resultsBatchSend:true}")
	protected boolean resultsBatchSend;

	@Value("${defaultResultTableName:IBZRULERESULT}")
	protected String Default_ResultTableName;
	@Value("${ibiz.expirationDays:7}")
	protected int expirationDays;

	public void saveResult(ModelObj param, String RULEID,String RULECODE, String RULENAME, String RU_EXECRESULTNAME, FieldObj BUSINESSCAT, Integer RETVALUE, FieldObj KEYVALUEFIELD, FieldObj DOMAINSFIELD,FieldObj DIMFIELD,
						   FieldObj METRICFIELD, FieldObj TIMEFIELD, FieldObj EXT1FIELD, FieldObj EXT2FIELD)
	{
		ExecResult result=new ExecResult();
		result.setRuleId(RULEID);
		result.setRuleName(RULENAME);
		result.setName(RU_EXECRESULTNAME);
		result.setRetValue(RETVALUE);

		if(KEYVALUEFIELD==null)
			KEYVALUEFIELD=param.getEmpty();
		if(DIMFIELD==null)
			DIMFIELD=param.getEmpty();

		result.setKeyValueField(KEYVALUEFIELD.getValue(param.getRowKey()));

		if(1==RETVALUE)
		{
			if(DOMAINSFIELD==null)
				DOMAINSFIELD=param.getEmpty();
			if(BUSINESSCAT==null)
				BUSINESSCAT=param.getEmpty();
			if(METRICFIELD==null)
				METRICFIELD=param.getEmpty();
			if(TIMEFIELD==null)
				TIMEFIELD=param.getEmpty();
			if(EXT1FIELD==null)
				EXT1FIELD=param.getEmpty();
			if(EXT2FIELD==null)
				EXT2FIELD=param.getEmpty();

			result.setSystemId(DataObject.getStringValue(param.get("systemid"),null));
			if((!BUSINESSCAT.getDataModelName().equals(DIMFIELD.getDataModelName()))||BUSINESSCAT.isSingle()||DIMFIELD.isSingle())
				result.setBusinessCat(BUSINESSCAT.getValue(String.class,null));

			if((!METRICFIELD.getDataModelName().equals(DIMFIELD.getDataModelName()))||METRICFIELD.isSingle()||DIMFIELD.isSingle())
				result.setMetricField(METRICFIELD.getDecimal());
			else
				result.setMetricField(new BigDecimal(1));

			if((!TIMEFIELD.getDataModelName().equals(DIMFIELD.getDataModelName()))||TIMEFIELD.isSingle()||DIMFIELD.isSingle())
				result.setTimeField(TIMEFIELD.getValue(Timestamp.class, null));

			if((!DOMAINSFIELD.getDataModelName().equals(DIMFIELD.getDataModelName()))||DOMAINSFIELD.isSingle()||DIMFIELD.isSingle())
				result.setDomainsField(DOMAINSFIELD.getValue(String.class, null));

			if((!EXT1FIELD.getDataModelName().equals(DIMFIELD.getDataModelName()))||EXT1FIELD.isSingle()||DIMFIELD.isSingle()) {
				String ext1=EXT1FIELD.getValues();
				if(ext1.length()>330)
					ext1=ext1.substring(0,330)+"...";
				if(!StringUtils.isEmpty(ext1))
					result.setExt1Field(ext1);
			}

			if((!EXT2FIELD.getDataModelName().equals(DIMFIELD.getDataModelName()))||EXT2FIELD.isSingle()||DIMFIELD.isSingle()) {
				String ext2=EXT2FIELD.getValues();
				if(ext2.length()>330)
					ext2=ext2.substring(0,330)+"...";
				if(!StringUtils.isEmpty(ext2))
					result.setExt2Field(ext2);
			}
		}else{
			if(BUSINESSCAT==null)
				BUSINESSCAT=param.getEmpty();
			if((!BUSINESSCAT.getDataModelName().equals(DIMFIELD.getDataModelName()))||BUSINESSCAT.isSingle()||DIMFIELD.isSingle())
				result.setBusinessCat(BUSINESSCAT.getValue(String.class,null));
		}


		Object resultDataSource = Default_ResultDataSource;
		Object resultTableName = Default_ResultTableName;
		if(param.get("resultDataSource")!=null){
			resultDataSource = param.get("resultDataSource");
		}
		if(param.get("resultTableName")!=null){
			resultTableName = param.get("resultTableName");
		}
		if(!StringUtils.isEmpty(param.get("resultTopic"))){
			Object resultTopic = param.get("resultTopic");
			if (!StringUtils.isEmpty(resultTopic)){
				result.set("resultTopic", resultTopic);
			}
		}
		result.set(Tag_EngineId,param.get(Tag_EngineId));
		result.set("resultDataSource", resultDataSource);
		result.set("resultTableName", resultTableName);

		if(DIMFIELD.isEmpty())
			return;

		List dims = null;
		if(DIMFIELD.getValue() instanceof List){
			dims = (List)DIMFIELD.getValue();
		}else {
			dims = new ArrayList();
			dims.add(DIMFIELD.getValue());
		}
		for(int i=0;i<dims.size();i++){
			Object obj = dims.get(i);

			result.setDimField(DataObject.getStringValue(obj,null));
			if(StringUtils.isEmpty(result.getDimField()))
				continue;

			ExecResult result2=null;
			if(DIMFIELD.isMultiple())
			{
				result2=new ExecResult();
				CachedBeanCopier.copy(result, result2);
			}
			else
				result2=result;



			if(KEYVALUEFIELD.getDataModelName().equals(DIMFIELD.getDataModelName())&&KEYVALUEFIELD.getCount()==DIMFIELD.getCount()&&DIMFIELD.isMultiple())
				result2.setBusinessCat(KEYVALUEFIELD.getItemValue(i,String.class,param.getRowKey()));


			if(result2.getRetValue()==1)
			{

				if(BUSINESSCAT.getDataModelName().equals(DIMFIELD.getDataModelName())&&BUSINESSCAT.getCount()==DIMFIELD.getCount()&&DIMFIELD.isMultiple())
					result2.setBusinessCat(BUSINESSCAT.getItemValue(i,String.class,null));

				if(METRICFIELD.getDataModelName().equals(DIMFIELD.getDataModelName())&&METRICFIELD.getCount()==DIMFIELD.getCount()&&DIMFIELD.isMultiple())
					result2.setMetricField(METRICFIELD.getItemDecimal(i));

				if(result2.getMetricField()==null)
					continue;

				if(TIMEFIELD.getDataModelName().equals(DIMFIELD.getDataModelName())&&TIMEFIELD.getCount()==DIMFIELD.getCount()&&DIMFIELD.isMultiple())
					result2.setTimeField(TIMEFIELD.getItemValue(i,Timestamp.class, null));

				if(result2.getTimeField()==null)
					continue;

				if(DOMAINSFIELD.getDataModelName().equals(DIMFIELD.getDataModelName())&&DOMAINSFIELD.getCount()==DIMFIELD.getCount()&&DIMFIELD.isMultiple())
					result2.setDomainsField(DOMAINSFIELD.getItemValue(i,String.class,result2.getDimField()));

				if(result2.getDomainsField()==null)
					result2.setDomainsField(result2.getDimField());


				if(EXT1FIELD.getDataModelName().equals(DIMFIELD.getDataModelName())&&EXT1FIELD.getCount()==DIMFIELD.getCount()&&DIMFIELD.isMultiple()) {
					String ext1=EXT1FIELD.getItemValue(i,String.class,"");
					if(ext1.length()>330)
						ext1=ext1.substring(0,330)+"...";
					if(!StringUtils.isEmpty(ext1))
						result2.setExt1Field(ext1);
				}
				if(EXT2FIELD.getDataModelName().equals(DIMFIELD.getDataModelName())&&EXT2FIELD.getCount()==DIMFIELD.getCount()&&DIMFIELD.isMultiple()) {
					String ext2=EXT2FIELD.getItemValue(i,String.class,"");
					if(ext2.length()>330)
						ext2=ext2.substring(0,330)+"...";
					if(!StringUtils.isEmpty(ext2))
						result2.setExt2Field(ext2);
				}

				result2.setId(result2.getDefaultKey(true).toString());
				result2.setRuleId(RULECODE);
				this.addResults(param,Tag_SaveResults,result2);
			}
			else
			{
				if(BUSINESSCAT.getDataModelName().equals(DIMFIELD.getDataModelName())&&BUSINESSCAT.getCount()==DIMFIELD.getCount()&&DIMFIELD.isMultiple())
					result2.setBusinessCat(BUSINESSCAT.getItemValue(i,String.class,null));
				result2.setId(result2.getDefaultKey(true).toString());
				result2.setRuleId(RULECODE);
				this.addResults(param,Tag_DeleteResults,result2);
			}
		}
	}



	/**
	 * 添加到新增或删除结果队列
	 * @param param
	 * @param tag
	 * @param result
	 */
	protected void addResults(ModelObj param, String tag, ExecResult result){
		List<ExecResult> results;
		if(param.containsKey(tag)){
			results = (List<ExecResult>)param.get(tag);
		}else{
			results = new ArrayList<>();
			param.set(tag, results);
		}
		results.add(result);
	}

	@Autowired
	private IExecResultService ruExecResultService;

	protected Hashtable<String, KieSession> setkieSession=new Hashtable<String,KieSession>();
	protected Hashtable<String,KieContainer> setKc=new Hashtable<String,KieContainer>();
	protected Hashtable<String,Integer> setRuleCount=new Hashtable<String,Integer>();

	public void printFactsMessageCount(KieSession kieSession)
	{
		Collection allHandles = kieSession.getFactHandles();

		String msg = new StringBuilder().append("\nAll facts count:").append(allHandles.size()).append("\n").toString();
		log.debug(msg);
	}

	public void printFactsMessage(KieSession kieSession)
	{
		Collection<FactHandle> allHandles = kieSession.getFactHandles();

		String msg = "\nAll facts:\n";
		for (FactHandle handle : allHandles)
			msg = new StringBuilder().append(msg).append("    ").append(kieSession.getObject(handle)).append("\n").toString();

		log.debug(msg);
	}

	public void DeleteFactsMessage(KieSession kieSession)
	{
		Collection<FactHandle> allHandles = kieSession.getFactHandles();

		String msg = "\nAll facts:\n";
		for (FactHandle handle : allHandles)
			kieSession.delete(handle);
	}

	public static String prettyBuildMessage(Message msg)
	{
		return new StringBuilder().append("Message: {id=").append(msg.getId()).append(", level=").append(msg.getLevel()).append(", path=").append(msg.getPath()).append(", line=").append(msg.getLine())
				.append(", column=").append(msg.getColumn()).append(", text=\"").append(msg.getText()).append("\"}").toString();
	}

	public static String knowledgeBaseDetails(KieBase kbase)
	{
		if (kbase == null)
			return "Knowledge Base is null.";

		StringBuilder sb = new StringBuilder("Knowledge base built from the following packages:");

		Collection<KiePackage> packages = kbase.getKiePackages();
		for (KiePackage kp : packages)
		{
			sb.append(new StringBuilder().append("\n    Package: [").append(kp.getName()).append("]").toString());
			for (Rule rule : kp.getRules())
				sb.append(new StringBuilder().append("\n        Rule: [").append(rule.getName()).append("]").toString());
		}

		return sb.toString();
	}


	public void initCommonData()
	{
		try
		{

		}
		catch (Exception ex)
		{
			log.error("baseservice:initcommondata:" + ex.getMessage());
		}
	}


	@Value("${ibiz.rulepath:}")
	private String drlpath;


	public void reset(String keyC)
	{
		if(setKc.containsKey(keyC))
		{
			try
			{
				setKc.get(keyC).dispose();
			}
			catch (Exception ex){}

			setKc.remove(keyC);
		}
	}
	public String initRule(List<String> rulefilelist,String keyC)
	{
		String strRt="";
		try
		{
			initCommonData();
			String strResId= "RES"+ IdWorker.getIdStr();
			KieContainer kContainer=null;
			if(setKc.containsKey(keyC))
			{
				kContainer=setKc.get(keyC);
			}

			else{
				KieServices ks = KieServices.Factory.get();
				KieRepository kr = ks.getRepository();

				KieFileSystem kfs = ks.newKieFileSystem();

				for (String rulefile : rulefilelist)
				{

					log.debug(new StringBuilder().append("init rule file: rules/").append(rulefile).toString());
					//Resource rs = ks.getResources().newClassPathResource(new StringBuilder().append("rules/").append(rulefile).toString());
					String path=(new StringBuilder().append(rulefile).toString());
					Resource rs = ks.getResources().newFileSystemResource(path.replace("\\","/"),"UTF-8");



					kfs.write(rs);
				}

				KieBuilder kb = ks.newKieBuilder(kfs);
				kb.buildAll();
				if (kb.getResults().hasMessages(new Message.Level[] { Message.Level.ERROR }))
				{
					List<Message> errors = kb.getResults().getMessages(new Message.Level[] { Message.Level.ERROR });
					StringBuilder sb = new StringBuilder("Errors:");
					for (Message msg : errors)
					{
						sb.append(new StringBuilder().append("\n  ").append(prettyBuildMessage(msg)).toString());
					}

					log.error(new StringBuilder().append("build rule failed:").append(sb.toString()).toString());
					return "";
				}

				log.info(new StringBuilder().append("KieServices built: ").append(toString()).toString());

				kContainer = ks.newKieContainer(kr.getDefaultReleaseId());
				setKc.put(keyC, kContainer);
			}


			KieSession kieSession = kContainer.newKieSession();

			kieSession.setGlobal("BaseService", this);


			setkieSession.put(strResId,kieSession);
			setRuleCount.put(strResId,rulefilelist.size());
			strRt=strResId;

		}
		catch (Exception e)
		{
			log.error(e.toString());

			return "";
		}

		return strRt;
	}



	public void processRule(ModelObj entity, String strCurKeyValue,String strResId) throws Exception
	{
		if(!setkieSession.containsKey(strResId))
		{
			log.error("Service规则容器查找失败：" + strResId);
			throw new Exception("Service规则容器查找失败：" + strResId);
		}
		KieSession kieSession=setkieSession.get(strResId);

		int rulescount=setRuleCount.get(strResId);
		FactHandle fireHandle = kieSession.insert(entity);


		int rulesFired = 0;

		printFactsMessageCount(kieSession);

		// for (int iloop = 0; iloop < this.rulescount; ++iloop)
		// {
		try
		{
			rulesFired = kieSession.fireAllRules(rulescount);
		}
		catch (Exception e)
		{
			log.error("Service规则执行错误：" + e.toString());

			throw e;
		}
		finally
		{
			try
			{
				kieSession.delete(fireHandle);
			}
			catch (Exception ex){}




		}
		// }
		log.info(new StringBuilder().append("Service，Process ").append(rulesFired).append(" rules for record.\n").toString());



	}


	@Autowired
	protected IExecLogService ruExecLogService;
	public ExecLog processAll(BaseRequest msg)
	{

		ExecLog execlog=new ExecLog();
		execlog.setId(msg.getId());
		execlog.setRunBody(msg.toString());

		StringBuilder strErrorInfo=new StringBuilder();
		int count = 0;
		int errorcount = 0;

		String strResId=initRule(msg.getRules(),msg.getBatch());
		if (StringUtils.isEmpty(strResId))
		{
			strErrorInfo.append("准备rule文件错误");
			strErrorInfo.append("\r\n");
			execlog.setRetCode(2);
			execlog.setCnt(count);
			execlog.setSucc(errorcount);
			execlog.setRunResult(strErrorInfo.toString());
			ruExecLogService.update(execlog);
			return execlog;
		}

		List<ExecResult> saveDatas = new ArrayList<>();
		List<ExecResult> deleteDatas = new ArrayList<>();
		try
		{


			for (ModelObj modelObj : msg.getDatas())
			{
				try
				{

					count++;
					modelObj.set("BATCH",msg.getBatch());
					modelObj.set(Tag_EngineId, msg.getEngineId());
					modelObj.set("systemid",msg.getSystemid());
					if(!StringUtils.isEmpty(msg.getResultDataSource())){
						modelObj.set("resultDataSource", msg.getResultDataSource());
					}
					if(!StringUtils.isEmpty(msg.getResultTableName())){
						modelObj.set("resultTableName", msg.getResultTableName());
					}
					if(!StringUtils.isEmpty(msg.getResultTopic())){
						modelObj.set("resultTopic", msg.getResultTopic());
					}

					processRule(modelObj, modelObj.getRowKey(),strResId);
					List<ExecResult> saveExecResultList = (List<ExecResult>) modelObj.get(Tag_SaveResults);
					List<ExecResult> deleteExecResultList = (List<ExecResult>) modelObj.get(Tag_DeleteResults);
					// 设置符合规则条件的数据集合
					if(msg.getBatch().startsWith(Tag_Batch_SyncRun) && saveExecResultList != null && saveExecResultList.size() > 0){
						msg.getResults().addAll(saveExecResultList);
					}
					if (resultsBatchSend){
						if (saveExecResultList != null && saveExecResultList.size()>0){
							saveDatas.addAll(saveExecResultList);
						}
						if (deleteExecResultList != null && deleteExecResultList.size()>0){
							deleteDatas.addAll(deleteExecResultList);
						}
					}else {
						SqlResultsMQMsg sqlResultsMQMsg = new SqlResultsMQMsg();
						sqlResultsMQMsg.setMsgId(msg.getId());
						if (saveExecResultList != null && saveExecResultList.size()>0){
							sqlResultsMQMsg.setSaveDatas(saveExecResultList);
						}
						if (deleteExecResultList != null && deleteExecResultList.size()>0){
							sqlResultsMQMsg.setDeleteDatas(deleteExecResultList);
						}
						if(!StringUtils.isEmpty(msg.getResultDataSource())){
							sqlResultsMQMsg.setResultDataSource(msg.getResultDataSource());
						}
						if(!StringUtils.isEmpty(msg.getResultTableName())){
							sqlResultsMQMsg.setResultTableName(msg.getResultTableName());
						}
						localMsgResultProducerService.sendEngineResultsMsg(sqlResultsMQMsg);
					}
				}
				catch (Exception e)
				{
					errorcount++;
					log.error("Service错误，加载数据详细信息：" + modelObj.getRowKey() + "," + e.getMessage());
					if (strErrorInfo.toString().length() <= 5000)
					{
						strErrorInfo.append("加载数据详细信息：" + modelObj.getRowKey() + ",错误：" + e.getMessage());
						strErrorInfo.append("\r\n");
						if (e.getCause() != null && e.getCause().getMessage() != null)
						{
							strErrorInfo.append(e.getCause().getMessage());
							strErrorInfo.append("\r\n");
						}

					}

				}

			}
			if (resultsBatchSend && (saveDatas.size() > 0 || deleteDatas.size() > 0)){
				SqlResultsMQMsg sqlResultsMQMsg = new SqlResultsMQMsg();
				sqlResultsMQMsg.setMsgId(msg.getId());
				if(!StringUtils.isEmpty(msg.getResultDataSource())){
					sqlResultsMQMsg.setResultDataSource(msg.getResultDataSource());
				}
				if(!StringUtils.isEmpty(msg.getResultTableName())){
					sqlResultsMQMsg.setResultTableName(msg.getResultTableName());
				}
				sqlResultsMQMsg.setSaveDatas(saveDatas);
				sqlResultsMQMsg.setDeleteDatas(deleteDatas);
				localMsgResultProducerService.sendEngineResultsMsg(sqlResultsMQMsg);
			}






		}
		catch(Exception e)
		{
			log.error("Service读取BaseRequest错误:" + e.toString());
			strErrorInfo.append("读取BaseRequest错误:" + e.getMessage());
			strErrorInfo.append("\r\n");
			if (e.getCause() != null && e.getCause().getMessage() != null)
			{
				strErrorInfo.append(e.getCause().getMessage());
				strErrorInfo.append("\r\n");
			}


			execlog.setRetCode(1);
			execlog.setCnt(count);
			if (errorcount == 0)
				execlog.setSucc(0);
			else
				execlog.setSucc(count-errorcount);
			execlog.setRunResult(strErrorInfo.toString());
			ruExecLogService.update(execlog);
			return execlog;
		}
		finally
		{
			saveDatas.clear();
			deleteDatas.clear();
			if(setkieSession.containsKey(strResId))
			{
				KieSession kieSession=setkieSession.get(strResId);
				try
				{
					kieSession.dispose();
				}
				catch (Exception ex){}
				setkieSession.remove(strResId);
				setRuleCount.remove(strResId);
			}
			//自动构建数据，清楚规则引擎缓存数据
			if(msg.isAutoRun()){
				reset(msg.getBatch());
			}

		}

		log.info(new StringBuilder().append("Service成功，process successfully:").append(msg.toString()).toString());
		strErrorInfo.append("Service成功，process successfully\r\n");





		execlog.setCnt(count);
		execlog.setSucc(count-errorcount);
		if(execlog.getCnt()==0)
			execlog.setRetCode(3);
		else
			execlog.setRetCode(0);
		execlog.setRunResult(strErrorInfo.toString());
		this.ruExecLogService.update(execlog);
		return execlog;
	}


	@Autowired
	@Lazy
	private DictDstService dictDstService;

	private ExpiryMap<String,CodeList> codelistMap=new ExpiryMap<>();

	public CodeList getCodeListCatalog(String dictname)
	{

		CodeList codeList = codelistMap.get(dictname);
		if(codeList==null)
		{
			codeList=dictDstService.getCodeListCatalog(dictname);
			if(codeList!=null)
				codelistMap.put(dictname,codeList);
		}
		return codeList;

	}

	/**
	 * 清理过期的KieContainer，默认超过七天即认为过期失效
	 */
	@Override
	public void cleanExpirationKieContainer(){
	    int beforeSize = this.setKc.size();
	    if (beforeSize == 0){
	    	return;
		}
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
		SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd");
		long curTime = 0L;
		try {
			curTime = simpleDateFormat2.parse(LocalDate.now().toString()).getTime();
		} catch (ParseException e) {
			e.printStackTrace();
			log.error(String.format("获取当前日期时间戳异常，原因：",e.getMessage()));
			return;
		}
		long timeDifference = this.expirationDays * 24 * 60 * 60 * 1000;
		Iterator<String> iterator = this.setKc.keySet().iterator();
		while (iterator.hasNext()) {
			// 构建批次信息，如：20230214140921[高检-信访辅助（规则专用）]-cnt-10
			String bacth = iterator.next();
			if (!StringUtils.isEmpty(bacth) && bacth.length() > 8){
				try{
					String strBatchTime = bacth.substring(0,8);
					long batchTime = simpleDateFormat.parse(strBatchTime).getTime();
					if ((curTime - batchTime) > timeDifference){
						try{
							this.setKc.get(bacth).dispose();
						}catch (Exception ex){
							ex.printStackTrace();
							log.error(String.format("setKc.get(iterator).dispose()异常，原因：" + ex.getMessage()));
						}
						iterator.remove();
						log.info(String.format("[batch]：%1$s，是否被清除：是",bacth));
					}else {
						log.info(String.format("[batch]：%1$s，是否被清除：否",bacth));
					}
				}catch (Exception e){
					e.printStackTrace();
					log.error(String.format("比较构建批次[batch]：%1$s，是否过期异常，原因：%2$s",bacth,e.getMessage()));
				}
			}else {
				log.info(String.format("[batch]：%1$s，是否被清除：否",bacth));
			}
		}
        int afterSize = this.setKc.size();
        log.info(String.format("清理过期setKc完成，过期时间(天)：%1$s，清理前setKc大小：%2$s，清理后setKc大小：%3$s，清理setKc数：%4$s",this.expirationDays,beforeSize,afterSize,(beforeSize - afterSize) ));
	}

	@Override
	public void cleanKieContainer() {
		int beforeSize = this.setKc.size();
		if (beforeSize == 0){
			return;
		}
		Iterator<String> iterator = this.setKc.keySet().iterator();
		while (iterator.hasNext()) {
			// 构建批次信息，如：20230214140921[高检-信访辅助（规则专用）]-cnt-10
			String bacth = iterator.next();
			try{
				this.setKc.get(bacth).dispose();
			}catch (Exception ex){
				ex.printStackTrace();
				log.error(String.format("--cleanKieContainer--setKc.get(iterator).dispose()异常，[batch]：%1$s，原因：%2$s" ,bacth,ex.getMessage()));
			}
			iterator.remove();
			log.info(String.format("--cleanKieContainer--[batch]：%1$s，已被清除。",bacth));
		}
		int afterSize = this.setKc.size();
		log.info(String.format("--cleanKieContainer--执行完成，清理前setKc大小：%1$s，清理后setKc大小：%2$s，清理setKc数：%3$s",beforeSize,afterSize,(beforeSize - afterSize) ));
	}
}