package cn.component.rule.base;

import java.util.HashMap;
import java.util.Map;

import cn.orm.sqltoy.plus.Wrappers;
import cn.orm.sqltoy.plus.query.QueryWrapper;
import cn.pojo.atv.TSysFillRule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.facade.abs.IFillRuleHandler;
import cn.orm.abs.ISqlToyDao;
import cn.util.core.IsKit;
import cn.util.core.LogKit;
import cn.util.core.TypeKit;
import cn.util.string.JsonKit;

/**
 * 规则值自动生成工具类
 * @举例： 自动生成订单号；自动生成当前日期
 */
@Service
public class FillRuleUtil 
{

	@Autowired
	private ISqlToyDao daoService;

	/**
	 * @param ruleCode ruleCode
	 * @return
	 */
	public Object executeRule(String ruleCode,String formData) 
	{
		if (IsKit.isNotNullOrEmpty(ruleCode)) 
		{
			QueryWrapper<TSysFillRule> queryWrapper = Wrappers.wrapper(TSysFillRule.class)
					.eq("ruleCode", ruleCode);
			TSysFillRule entity = daoService.findOne(queryWrapper);
			if(IsKit.isNullOrEmpty(entity)) {
				LogKit.info("填值规则：" + ruleCode + " 不存在");
				return null;
			}
					//获取必要的参数
			String ruleClass = entity.getRuleClass();
			String ruleParams = entity.getRuleParams();
			Map<String, Object> paramMap = JsonKit.json2Map_jackson(ruleParams) ;
			try {
				Class<?> classObj = Class.forName(ruleClass);
				IFillRuleHandler ruleHandler = (IFillRuleHandler) classObj.getDeclaredConstructor().newInstance();
				return ruleHandler.execute(paramMap, formData);
			} catch (Exception e) {
				LogKit.info("填值规则错误：" + e);
			}
		}
		return null;
	}
}
