package nccloud.web.hrwa.waruleex.action.formula.pub;

import java.util.List;
import java.util.Map;

import nc.vo.pub.BusinessException;
import nc.vo.wa.pub.WaLoginContext;
import nccloud.commons.collections.CollectionUtils;
import nccloud.commons.lang.StringUtils;
import nccloud.web.hr.formula.HRFormulaType4Web;
import nccloud.web.hrwa.classitem.action.formula.factory.WaClassItemFormulaTransFactory;
import nccloud.web.hrwa.waruleex.action.formula.factory.WaRuleExFormulaTransFactory;
import nccloud.web.hrwa.waruleex.action.formula.factory.WaRuleExFormulaTypeFactory;

/**
 * 对公式进行转换
 * @author lenovo
 *
 */
public class TranslateFormula {

	/**
	 * 公式转换，将文本公式转为script公式
	 * @param context
	 * @param formulastr
	 * @return
	 * @throws BusinessException
	 */
	public String translateFormula(WaLoginContext context, String formulastr, String condition,String dynPara) throws BusinessException{

		if(StringUtils.isBlank(formulastr))
			return formulastr;
		Map<String, List<HRFormulaType4Web>> tableTypes = getTableTypes(context);
		// 数据库信息
		List<HRFormulaType4Web> itemList = tableTypes.get("tableList");
		if(CollectionUtils.isEmpty(itemList))
			return formulastr;
		// 数据源信息
		List<HRFormulaType4Web> soruceItemList = tableTypes.get("dsList");
		if(CollectionUtils.isEmpty(soruceItemList))
			return formulastr;
		WaRuleExFormulaTransFactory transFactory = new WaRuleExFormulaTransFactory(soruceItemList, itemList, condition,
				dynPara);
		String formula = transFactory.getScriptStr(formulastr, context);
		return formula;
	}
	
	/**
	 * 公式转换，将script公式转为文本公式
	 * @param context
	 * @param formulastr
	 * @return
	 * @throws BusinessException
	 */
	public String translateFormulaStr(WaLoginContext context, String formula,String dynPara) throws BusinessException{
		if(StringUtils.isBlank(formula))
			return formula;
		Map<String, List<HRFormulaType4Web>> tableTypes = getTableTypes(context);
		// 数据库信息
		List<HRFormulaType4Web> itemList = tableTypes.get("tableList");
		if(CollectionUtils.isEmpty(itemList))
			return formula;
		// 数据源信息
		List<HRFormulaType4Web> soruceItemList = tableTypes.get("dsList");
		if(CollectionUtils.isEmpty(soruceItemList))
			return formula;
		WaClassItemFormulaTransFactory transFactory = new WaClassItemFormulaTransFactory(soruceItemList, itemList, null,
				dynPara);
		String formulaStr = transFactory.getBusinessStr(formula, context);
		return formulaStr;
	}
	
	/**
	 * 取信息项列表
	 * @param context
	 * @return
	 * @throws BusinessException 
	 */
	private Map<String, List<HRFormulaType4Web>> getTableTypes(WaLoginContext context) throws BusinessException {
		WaRuleExFormulaTypeFactory factory = new WaRuleExFormulaTypeFactory(context);
		return factory.getFormulaTypes();
	}
}
