package nc.bs.mmpub.setanalysis.bp;

import nc.bs.mmpub.setanalysis.bp.log.SaMemoryBP;
import nc.bs.mmpub.setanalysis.bp.utils.SaLogger;
import nc.bs.mmpub.setanalysis.proxy.SaServiceProxy;
import nc.vo.mmpub.setanalysis.entity.AggAnalysisVO;
import nc.vo.mmpub.setanalysis.entity.SaContext;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFDateTime;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;
import nc.bs.mmpub.setanalysis.bp.rule.analysisAfterCheckRule;
import nc.vo.mmpub.setanalysis.entity.SaAnalysisVO;
import nc.vo.mmpub.setanalysis.utils.SaMeasureUtil;
import nc.bs.mmpub.setanalysis.bp.utils.SaScaleUtil;
import nc.bs.mmpub.setanalysis.bp.utils.SaVOUtils;

public class SetAnalysisBP {
	private SaContext context;

	public SetAnalysisBP(SaContext context) {
		this.context = context;
	}

	public AggAnalysisVO[] doSetAnalysis() {
		try {
			addBeforeRule();
			SaLogger.init();
			UFDateTime tstarttime1 = new UFDateTime();
			SaLogger.debug("0.分析开始^^^^^^^^^^^^^^^^^^^^^^^^^^");

			createMd5Function();

			UFDateTime tstarttime2 = new UFDateTime();
			SaLogger.debug("1.收集数据");
			SaMemoryBP.printMemory();
			SaServiceProxy.getAnalysisService().gather_RequiresNew(this.context);
			SaLogger.debug("数据收集共耗时:" + SaLogger.getRunTime(tstarttime2));

			UFDateTime tstarttime3 = new UFDateTime();
			SaLogger.debug("2.执行匹配开始");
			SaServiceProxy.getAnalysisService().match_RequiresNew(this.context);
			SaLogger.debug("匹配共耗时:" + SaLogger.getRunTime(tstarttime3));

			UFDateTime tstarttime4 = new UFDateTime();
			SaLogger.debug("3.反算齐套开始");
			SaServiceProxy.getAnalysisService().multiStorey_RequiresNew(this.context);
			SaLogger.debug("反算齐套结束,共耗时:" + SaLogger.getRunTime(tstarttime4));
			SaMemoryBP.printMemory();
			this.result(this.context.getAggs());
			// 分析后调用回写，齐套率计算方式已调整，此处不用，注释analysisAfterCheckRule
			// this.analysisAfterCheckRule();
			SaLogger.debug("齐套分析算法结束,共耗时:" + SaLogger.getRunTime(tstarttime1));
			return this.context.getAggs();
		} catch (BusinessException e) {
			ExceptionUtils.wrappException(e);
			SaLogger.error(e.getMessage());

			return null;
		}
	}

	private void result(AggAnalysisVO[] aggs) {
		SaScaleUtil scale = new SaScaleUtil();
		SaAnalysisVO[] savos = SaVOUtils.construcVOs(aggs);
		scale.setScaleSuperVOs(savos, "cmeasureid", new String[] { "nsetsnum" });
		SaMeasureUtil.setAnalysisAssNum(aggs);
	}

	private void printMemory(String operation) {
		long totalMemory = Runtime.getRuntime().totalMemory() / 1024L / 1024L;
		long freeMemory = Runtime.getRuntime().freeMemory() / 1024L / 1024L;
		SaLogger.debug(operation + ":totalMemory->" + operation + "MB,freeMemory->" + totalMemory + "MB");
	}

	private void createMd5Function() {
		(new SaFunctionBP()).createMD5();
	}

	private void addBeforeRule() {

	}

	private void analysisAfterCheckRule() {
		(new analysisAfterCheckRule()).process(this.context.getAggs());
	}
}
