Index: src/main/java/com/novaone/common/CommonInfo.java
===================================================================
--- src/main/java/com/novaone/common/CommonInfo.java	(revision 31350)
+++ src/main/java/com/novaone/common/CommonInfo.java	(revision 31351)
@@ -75,6 +75,11 @@
     
     // 抓取状态 15 由于数据变更，已不符合支付规则
     public static final String GRAB_STATUS_DATACHANGE_NOTRULEENGINE = "15";
+    
+    /***********自动生成规则使用************/
+    // 抓取状态 16 drl规则文件生成异常
+    public static final String DRL_RULE_GENERATE_ERROR = "16";
+    
 
     // 水果通用 是
     public static final String FRESHPORT_COMMON_YES = "Y";
@@ -294,4 +299,20 @@
         depositDwList.add("上海神骋报关代理有限公司");
         depositDwList.add("深圳欧恒国际物流有限公司");
     }
+    
+	public static final String drlPrefixStrFormal = System.getProperty("user.dir") + "/";//要有一个固定的drl目录
+  
+  	// 正式环境或者本地环境都会保存到当前项目根目录。drools读取文件目录必须是/分隔符
+  	public static final String drlPrefixStr = drlPrefixStrFormal.replaceAll("\\\\", "/");
+  	
+  	// drl，临时文件名称
+  	public static final String drlTempFileName = "taxPayment-temp.drl";
+  	
+  	// drl，正式文件名称
+  	public static final String drlFormalFileName = "taxPayment.drl";
+  	
+  	// drl文件头
+  	public static final String drlFileHeader = "package com.novaone;\n" + 
+			"import com.novaone.entity.RuleDTO;\n" + 
+			"global java.util.HashMap map;\n";
 }
Index: src/main/java/com/novaone/control/ApiControl.java
===================================================================
--- src/main/java/com/novaone/control/ApiControl.java	(revision 31350)
+++ src/main/java/com/novaone/control/ApiControl.java	(revision 31351)
@@ -20,6 +20,7 @@
 import com.novaone.common.CommonInfo;
 import com.novaone.service.GrabPayService;
 import com.novaone.service.RequisitionService;
+import com.novaone.service.RuleService;
 import com.novaone.util.CommonUtils;
 import com.novaone.util.HttpUtil;
 import com.novaone.util.OkHttpUtil;
@@ -372,4 +373,46 @@
         historyService.insertOrUpdate(rdv.getHistories());
         return rdv;
     }
+    
+    @RequestMapping("/api/getRule")
+    public JsonModel getRule(HttpServletRequest request) {
+        log.info("begin------/api/getRule--------");
+        JsonModel j = new JsonModel();
+        try {
+        	String ywbh = request.getParameter("ywbh");
+            List<String> ywbhs = new ArrayList<String>();
+        	if(ywbh.contains(",")) {
+        		ywbhs = Arrays.asList(ywbh.split(","));
+        	}else {
+        		ywbhs.add(ywbh);
+        	}
+            grabPayService.doCheckRuleNotBgsj(ywbhs);
+            j.setCode(CommonInfo.ERRCODE_SUCCESS);
+            j.setDes(CommonInfo.RESTFUL_API_SUCCESS);
+        } catch (Exception e) {
+            log.info("/api/getRule 异常信息", e);
+            j.setCode(CommonInfo.ERRCODE_NOTDATA);
+            j.setDes("更新失败");
+        }
+        log.info("end------/api/getRule--------");
+        return j;
+    }
+    @Resource
+    private RuleService ruleService;
+    @RequestMapping("/api/doRuleGenerator")
+    public JsonModel doRuleGenerator() {
+    	JsonModel j = new JsonModel();
+    	j.setCode(CommonInfo.ERRCODE_NOTDATA);
+        j.setDes(CommonInfo.RESTFUL_API_FALSE);
+        try {
+        	boolean f = ruleService.generateRules();
+        	if(f){
+        		j.setCode(CommonInfo.ERRCODE_SUCCESS);
+                j.setDes(CommonInfo.RESTFUL_API_SUCCESS);
+        	}
+        } catch (Exception e) {
+            log.info("/api/getRule 异常信息", e);
+        }
+    	return j;
+    }
 }
Index: src/main/java/com/novaone/entity/RuleDTO.java
===================================================================
--- src/main/java/com/novaone/entity/RuleDTO.java	(revision 0)
+++ src/main/java/com/novaone/entity/RuleDTO.java	(revision 31351)
@@ -0,0 +1,23 @@
+package com.novaone.entity;
+
+import lombok.Data;
+
+@Data
+public class RuleDTO {
+	private int id;
+	private String khbm;
+	private String jdrbm;
+	private String bm;
+	private String spdl;
+	private String sdttbm;
+	private String jydwbm;
+	private String ywxz;
+	private String ysfs;
+	private String fszl;
+	private String crtTime;
+	private String priority;
+	private String enable;
+	private String remark;
+	private String beginTime;
+	private String endTime;
+}
Index: src/main/java/com/novaone/fdao/HddzMapper.java
===================================================================
--- src/main/java/com/novaone/fdao/HddzMapper.java	(revision 31350)
+++ src/main/java/com/novaone/fdao/HddzMapper.java	(revision 31351)
@@ -8,6 +8,7 @@
 import com.novaone.entity.Bg;
 import com.novaone.entity.Hddz;
 import com.novaone.entity.PayDetail;
+import com.novaone.entity.RuleDTO;
 import com.novaone.entity.Ruleparam;
 
 import io.lettuce.core.dynamic.annotation.Param;
@@ -39,8 +40,11 @@
     //批量更新支付校验时间为1
     void updateNeedZdjs(@Param("list") List<String> list);
     
-    //批量更新支付校验时间为0
+    //批量更新支付校验时间为3
     void updateNotZdjs(@Param("list") List<String> list);
+    
+    //批量更新支付校验时间为2
+    void updateNotZdjsClear(@Param("list") List<String> list);
 
     @Select("select hgbh from yw_bg where zdjsbz = '1'  and sjzfzt  = '0' and LEN(hgbh) = 18")
     List<String> selectAllRpaPayData();
@@ -57,4 +61,15 @@
     void updatePayStatus(Bg bg);
     
     List<String> listUpdTaxStatus();
+    
+    /**
+     * 
+     * @Title: getActivityRuleList
+     * @Description: 读取Rule表数据
+     * @param: @return   
+     * @return: List<RuleDTO>
+     * @author gubj  
+     * @date 2022年6月7日 上午10:00:03
+     */
+    List<RuleDTO> getActivityRuleList();
 }
Index: src/main/java/com/novaone/fdao/Mapper/HddzMapper.xml
===================================================================
--- src/main/java/com/novaone/fdao/Mapper/HddzMapper.xml	(revision 31350)
+++ src/main/java/com/novaone/fdao/Mapper/HddzMapper.xml	(revision 31351)
@@ -89,13 +89,20 @@
 		  #{ywbh}
 		</foreach>
 	</update>
-<!-- 	    批量更新支付校验时间为3 3表示不需要自动支付，且已校验过的 0表示默认状态，暂不需要自动支付，但没有真正校验过是否真的不需要自动支付-->
+<!-- 	    批量更新支付校验时间为3 3表示不需要自动支付，且已校验过的(但是本条数据不一定是不垫付，只是没有规则) 0表示默认状态，暂不需要自动支付，但没有真正校验过是否真的不需要自动支付-->
 	<update id="updateNotZdjs" >
 		update yw_bg set zdjsbz  = '3' where ywbh in 
 		<foreach collection="list" item="ywbh" index="index" open="(" close=")" separator=",">
 		  #{ywbh}
 		</foreach>
 	</update>
+<!-- 	    批量更新支付校验时间为2 2表示不需要自动支付（有规则，明确表示不需要自动垫付的） 0表示默认状态，暂不需要自动支付，但没有真正校验过是否真的不需要自动支付-->
+	<update id="updateNotZdjsClear" >
+		update yw_bg set zdjsbz  = '2' where ywbh in 
+		<foreach collection="list" item="ywbh" index="index" open="(" close=")" separator=",">
+		  #{ywbh}
+		</foreach>
+	</update>
 	<!-- 	补录支付失败的和已审结但是没有缴税期限的实际支付状态 -->
 <!-- 这里的条件应该再加一个dycksjzfzt is not null -->
 	<select id="getDyckSjzfzt" resultType="com.novaone.entity.PayDetail">
@@ -175,7 +182,14 @@
 		<![CDATA[ 
 		SELECT ywbh FROM yw_bg
 		WHERE
-			sjzfzt = '0' and ygsjzt='1' and sjycqzzx = '0' and zdjsbz  = '1'
+			sjzfzt = '0' and ygsjzt='1' and  ISNULL(sjycqzzx, '') != '1' and zdjsbz  = '1'
 			]]>
 	</select>
+<!-- 	获取Rule所有数据 -->
+	<select id="getActivityRuleList" resultType="com.novaone.entity.RuleDTO">
+		<![CDATA[ 
+			select flag_id id,khbm,jdrbm,bm,spdl,sdttbm,jydwbm,ywxz,ysfs,fszl,crt_time crtTime,priority,enable,remark,begin_time beginTime,end_time endTime 
+			from jn_auto_tax_config where enable = 'Y' order by flag_id
+			]]>
+	</select>
 </mapper>
\ No newline at end of file
Index: src/main/java/com/novaone/service/RuleService.java
===================================================================
--- src/main/java/com/novaone/service/RuleService.java	(revision 0)
+++ src/main/java/com/novaone/service/RuleService.java	(revision 31351)
@@ -0,0 +1,18 @@
+package com.novaone.service;
+
+import java.util.List;
+
+import com.novaone.entity.RuleDTO;
+
+
+/**
+ * 规则生成接口
+ * @author gubj
+ *
+ */
+public interface RuleService {
+
+	List<RuleDTO> getActivityRuleList();
+	
+	boolean generateRules() throws Exception;
+}
Index: src/main/java/com/novaone/service/impl/GrabPayServiceImpl.java
===================================================================
--- src/main/java/com/novaone/service/impl/GrabPayServiceImpl.java	(revision 31350)
+++ src/main/java/com/novaone/service/impl/GrabPayServiceImpl.java	(revision 31351)
@@ -12,14 +12,14 @@
 import java.util.concurrent.TimeUnit;
 import java.util.stream.Collectors;
 
-import javax.annotation.PostConstruct;
 import javax.annotation.Resource;
 
 import org.kie.api.KieServices;
-import org.kie.api.builder.KieScanner;
-import org.kie.api.builder.ReleaseId;
-import org.kie.api.runtime.KieContainer;
+import org.kie.api.builder.KieBuilder;
+import org.kie.api.builder.KieFileSystem;
+import org.kie.api.builder.KieModule;
 import org.kie.api.runtime.KieSession;
+import org.kie.internal.io.ResourceFactory;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.data.redis.core.StringRedisTemplate;
 import org.springframework.stereotype.Service;
@@ -28,7 +28,6 @@
 
 import com.alibaba.fastjson.JSON;
 import com.alibaba.fastjson.JSONObject;
-import com.freshport.tax_payment.TaxPayment;
 import com.novaone.common.CommonInfo;
 import com.novaone.dao.BgdMapper;
 import com.novaone.entity.ApiQuota;
@@ -39,6 +38,7 @@
 import com.novaone.entity.PayMain;
 import com.novaone.entity.PayRecord;
 import com.novaone.entity.PubHoliday;
+import com.novaone.entity.RuleDTO;
 import com.novaone.entity.Ruleparam;
 import com.novaone.fdao.HddzMapper;
 import com.novaone.service.GrabPayService;
@@ -63,8 +63,6 @@
 	
 	@Resource
     private StringRedisTemplate stringRedisTemplate;
-	
-    private KieContainer kContainer;
     
     @Value("${STARTNOTPAYDATE}")
     private String startNotPayDate;
@@ -75,15 +73,6 @@
     @Value("${NOTPAYDATESTATUS}")
     private String notPayDateStatus;
 	
-    @PostConstruct
-    private void setEnv() {
-        KieServices ks = KieServices.Factory.get();
-        ReleaseId releaseId = ks.newReleaseId("com.freshport", "tax_payment", "LATEST");
-        kContainer = ks.newKieContainer(releaseId);
-        KieScanner kieScanner = ks.newKieScanner(kContainer);
-        kieScanner.start(10000L);
-    }
-
 	@Transactional(propagation = Propagation.REQUIRES_NEW )
 	@Override
 	public void insertErrorData(String bgdh, String status, String msg) {
@@ -640,7 +629,6 @@
 		try {
 			if(CommonUtils.isEmpty(rp) || (!CommonUtils.isEmpty(rp) && rp.size() > 1)) {
 				log.info("listRp" + JSON.toJSONString(rp));
-//				grabPayService.insertErrorData(ywbh, CommonInfo.GRAB_STATUS_RULEENGINE_ERROR, "该单号未匹配到唯一规则数据");
 			}else {
 				resultMap = callRuleEngine(rp.get(0));
 			}
@@ -700,6 +688,8 @@
     	List<PayDetail> detail_t = new ArrayList<PayDetail>();
     	//未匹配列表
     	List<String> detail_t_not = new ArrayList<String>();
+    	//明确规则不垫付
+    	List<String> detail_t_not_clear = new ArrayList<String>();
     	
     	for (PayDetail payDetail : directDetail) {
 			if(listMain_t.contains(payDetail.getBgdh())) {
@@ -710,28 +700,33 @@
 				// 1、申报单位或者收发货必须至少有一个是我司
 				// 2、如果申报单位是我司，直接放到bill_main
 				// 3、如果是申报单位不是我司且收发货单位是我司，直接放到pay_sfh_main
-				// 4、校验规则时单独判断是否强制支付，与通过规则同级
+				// 4、校验规则时单独判断是否强制支付，如果强制支付，则与通过规则同级
 				
 				if(!resultMap.isEmpty()) {
-					//获取银行账号
-					String account = getYhzhByZfdw(payDetail);
-					if(!CommonUtils.isEmpty(account)) {
-						// 银行账号
-						payDetail.setYhzh(account);
-						// 规则编号
-						payDetail.setRuleid(resultMap.get("rule") + "");
-						// 获取agreementId (执行c1指令)
-						String agreementId = grabPayService.grabSeqNoData(payDetail);
-						if(CommonUtils.isEmpty(agreementId)) {
-							// agreementId为空，停止执行
-							log.info("获取agreementId失败："+JSON.toJSONString(payDetail));
-							continue;
+					if("Y".equals(resultMap.get("fszl"))) {
+						//获取银行账号
+						String account = getYhzhByZfdw(payDetail);
+						if(!CommonUtils.isEmpty(account)) {
+							// 银行账号
+							payDetail.setYhzh(account);
+							// 规则编号
+							payDetail.setRuleid(resultMap.get("rule") + "");
+							// 获取agreementId (执行c1指令)
+							String agreementId = grabPayService.grabSeqNoData(payDetail);
+							if(CommonUtils.isEmpty(agreementId)) {
+								// agreementId为空，停止执行
+								log.info("获取agreementId失败："+JSON.toJSONString(payDetail));
+								continue;
+							}
+							payDetail.setAgreementid(agreementId);
+							//设置id等
+							payDetail.setId(UUID.randomUUID().toString());
+							payDetail.setCrt_time(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
+							detail_t.add(payDetail);
 						}
-						payDetail.setAgreementid(agreementId);
-						//设置id等
-						payDetail.setId(UUID.randomUUID().toString());
-						payDetail.setCrt_time(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
-						detail_t.add(payDetail);
+					}else {
+						// 明确规则不垫付
+						detail_t_not_clear.add(payDetail.getBgdh());
 					}
 				}else {
 					//没有匹配上规则
@@ -746,11 +741,21 @@
     		List<String> l = grabPayService.getBeforMatch(detail_t_not);
 			if(l != null && !l.isEmpty()) {
 				log.info("由于数据原因，已不符合支付规则::"+JSON.toJSONString(l));
-				//预警 
+				//更新水果通状态并预警 
 				hddzMapper.updateNotZdjs(l);
 				grabPayService.insertErrorData(detail_t_not.get(0), CommonInfo.GRAB_STATUS_DATACHANGE_NOTRULEENGINE, "由于数据原因，已不符合支付规则");
 			}
     	}
+    	if(!detail_t_not_clear.isEmpty()) {
+    		//看是不是有之前匹配上的数据
+    		List<String> l = grabPayService.getBeforMatch(detail_t_not_clear);
+    		if(l != null && !l.isEmpty()) {
+    			log.info("由于规则原因，已不符合支付规则::"+JSON.toJSONString(l));
+    			//更新水果通状态并预警 
+    			hddzMapper.updateNotZdjsClear(l);
+    			grabPayService.insertErrorData(detail_t_not_clear.get(0), CommonInfo.GRAB_STATUS_DATACHANGE_NOTRULEENGINE, "由于规则原因，该数据由垫付转为不垫付");
+    		}
+    	}
     	return detail_t;
     }
 	/**
@@ -773,6 +778,7 @@
     	}
     	return main_pay;
     }
+	
 	 /**
      * 
      * @Title: test
@@ -782,16 +788,26 @@
      * @author gubj  
      * @date 2021年8月20日 下午1:59:57
      */
-    private HashMap callRuleEngine(Ruleparam rp) throws Exception {
-        KieSession kieSession = kContainer.newKieSession();
-        TaxPayment tp = new TaxPayment();
-        tp.setKhjc(rp.getKhjc());
-        tp.setJdr(rp.getJdr());
-        tp.setSplx(rp.getSplx());
-        tp.setSdtt(rp.getSdtt());
-        tp.setJydw(rp.getJydw());
+    private static HashMap callRuleEngine(Ruleparam rp) throws Exception {
+    	
+    	// 构建KieSession, 这部分写法是固定的
+	    KieServices kieServices = KieServices.Factory.get();
+	    KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
+	    kieFileSystem.write(ResourceFactory.newFileResource(CommonInfo.drlPrefixStr + CommonInfo.drlFormalFileName));
+	    KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem);
+	    kieBuilder.buildAll();
+	    KieModule kieModule = kieBuilder.getKieModule();
+	    KieSession kieSession = kieServices.newKieContainer(kieModule.getReleaseId()).newKieSession();
+    	
+	    RuleDTO tp = new RuleDTO();
+        tp.setKhbm(rp.getKhjc());
+        tp.setJdrbm(rp.getJdr());
+        tp.setSpdl(rp.getSplx());
+        tp.setSdttbm(rp.getSdtt());
+        tp.setJydwbm(rp.getJydw());
         tp.setYwxz(rp.getYwxz());
         tp.setYsfs(rp.getYsfs());
+        tp.setBm(rp.getBm());
         HashMap map = new HashMap();
         kieSession.setGlobal("map", map);
         kieSession.insert(tp);
@@ -810,12 +826,19 @@
     	List<String> updateNeedZdjs = new ArrayList<String>();
     	//保存不需要自动缴税的
     	List<String> updateNotZdjs = new ArrayList<String>();
+    	//保存不需要自动缴税的且有规则的
+    	List<String> updateNotZdjsClear = new ArrayList<String>();
     	for(String s : listString) {
     		try {
     			Map<String,String> resultMap = grabPayService.callRuleEngine(s);
     			if(!resultMap.isEmpty()) {
-    				//规则通过
-    				updateNeedZdjs.add(s);
+    				if("Y".equals(resultMap.get("fszl"))) {
+    					//规则通过，垫付
+        				updateNeedZdjs.add(s);
+    				}else {
+    					//规则明确表示不垫付
+    					updateNotZdjsClear.add(s);
+    				}
     			}else {
     				//规则不通过
     				updateNotZdjs.add(s);
@@ -829,9 +852,13 @@
         	hddzMapper.updateNeedZdjs(updateNeedZdjs);
     	}
     	if(!updateNotZdjs.isEmpty()) {
-    		//更新不通过的状态
+    		//更新没有规则的状态
         	hddzMapper.updateNotZdjs(updateNotZdjs);
     	}
+    	if(!updateNotZdjsClear.isEmpty()) {
+    		//更新有明确规则不垫付的状态
+    		hddzMapper.updateNotZdjsClear(updateNotZdjsClear);
+    	}
     }
     /*************测试用的方法，先保留*************/
     public List<String> getAll(){
Index: src/main/java/com/novaone/service/impl/RuleServiceIml.java
===================================================================
--- src/main/java/com/novaone/service/impl/RuleServiceIml.java	(revision 0)
+++ src/main/java/com/novaone/service/impl/RuleServiceIml.java	(revision 31351)
@@ -0,0 +1,357 @@
+package com.novaone.service.impl;
+
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.lang.reflect.Method;
+import java.text.SimpleDateFormat;
+import java.time.LocalDateTime;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+import javax.annotation.Resource;
+
+import org.drools.template.ObjectDataCompiler;
+import org.kie.api.KieServices;
+import org.kie.api.builder.KieBuilder;
+import org.kie.api.builder.KieFileSystem;
+import org.kie.api.builder.KieModule;
+import org.kie.api.runtime.KieSession;
+import org.kie.internal.io.ResourceFactory;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Propagation;
+import org.springframework.transaction.annotation.Transactional;
+
+import com.alibaba.fastjson.JSONObject;
+import com.novaone.common.CommonInfo;
+import com.novaone.entity.RuleDTO;
+import com.novaone.fdao.HddzMapper;
+import com.novaone.service.GrabPayService;
+import com.novaone.service.RuleService;
+import com.novaone.util.CommonUtils;
+
+import lombok.extern.slf4j.Slf4j;
+
+@Slf4j
+@Service("RuleService")
+public class RuleServiceIml implements RuleService{
+	
+	
+	@Resource
+	private RuleService ruleService;
+	
+	@Resource
+	private GrabPayService grabPayService;
+	
+	@Resource
+	private HddzMapper hddzMapper;
+	
+	/**
+	 * 获取规则数据
+	 */
+	@Override
+	@Transactional(propagation = Propagation.NOT_SUPPORTED)
+	public List<RuleDTO> getActivityRuleList() {
+		return hddzMapper.getActivityRuleList();
+	}
+
+	/**
+	 * 生成规则
+	 */
+	@Override
+	public boolean generateRules() throws Exception{
+		boolean flag = false;
+		// 拿数据
+		List<RuleDTO> ruleDTOs = ruleService.getActivityRuleList();
+		if(null == ruleDTOs || ruleDTOs.isEmpty()) {
+			// 没有数据
+		}else {
+			try {
+				log.info("generateRules开始时间：：："+LocalDateTime.now());
+				CopyOnWriteArrayList<String> ruleDrls = new CopyOnWriteArrayList<String>();
+				ruleDTOs.parallelStream().forEach(l->{
+		            try {
+		            	ruleDrls.add(applyRuleTemplate(l));
+		            } catch (Exception e) {
+		                e.printStackTrace();
+		            }
+		        });
+		        //规则的加载
+		        createOrRefreshDrl(ruleDrls);
+		        flag = !flag;
+		        log.info("结束时间：：："+LocalDateTime.now());
+			} catch (Exception e) {
+				log.info("生成规则出现异常",e);
+				System.err.println(e);
+				// 规则生成异常
+				grabPayService.insertErrorData("", CommonInfo.DRL_RULE_GENERATE_ERROR, "drl文件规则生成异常");
+				throw e;
+			}
+		}
+		return flag;
+	}
+    /**
+     * 
+     * @Title: applyRuleTemplate
+     * @Description: 根据Rule生成drl的String
+     * @param: @param ruleDTO
+     * @param: @return
+     * @param: @throws Exception   
+     * @return: String
+     * @author gubj  
+     * @date 2022年5月25日 上午10:21:20
+     */
+    private String applyRuleTemplate(RuleDTO ruleDTO) throws Exception{
+    	// 格式化
+        Map<String, Object> data = prepareData(ruleDTO);
+        ObjectDataCompiler objectDataCompiler = new ObjectDataCompiler();
+        // 模板文件生成drl String
+        return objectDataCompiler.compile(Arrays.asList(data), 
+        		Thread.currentThread().getContextClassLoader().getResourceAsStream("give-reward-rule-template.drt"));
+    }
+    /**
+     * 
+     * @Title: prepareData
+     * @Description: 根据Rule生成drl的map data
+     * @param: @param ruleDTO
+     * @param: @return
+     * @param: @throws Exception   
+     * @return: Map<String,Object>
+     * @author gubj  
+     * @date 2022年5月25日 上午10:21:11
+     */
+    protected Map<String, Object> prepareData(RuleDTO ruleDTO) throws Exception{
+        Map<String, Object> data = new HashMap<>();
+        RuleDTO rule = ruleDTO;
+        data.put("ruleCode", rule.getId());//id
+        data.put("beginTime", CommonUtils.stringToStringFormat(ruleDTO.getBeginTime(), "dd-MMM-yyyy"));//开始时间（一定不为空）
+        if(ruleDTO.getEndTime() == null) {
+        	data.put("endTime", null);//结束时间
+        }else {
+        	data.put("endTime", CommonUtils.stringToStringFormat(ruleDTO.getEndTime(), "dd-MMM-yyyy"));//结束时间
+        }
+        data.put("priority", rule.getPriority());//优先级
+        //组装rule
+        data.put("rules", getRules(rule));
+        data.put("fszl", rule.getFszl());
+        data.put("enable", "Y".equals(rule.getEnable()));
+        return data;
+    }
+    /**
+     * 
+     * @Title: getRules
+     * @Description: 仅生成规则字符串
+     * @param: @param rule
+     * @param: @return   
+     * @return: String
+     * @author gubj  
+     * @date 2022年5月24日 下午6:04:13
+     */
+    private String getRules(RuleDTO rule) throws Exception{
+    	String stringRule = "RuleDTO(";
+    	String[] filedArr = {"khbm","jdrbm","bm","spdl","sdttbm","jydwbm","ywxz","ysfs"};
+		for(String s : filedArr) {
+			if(!CommonUtils.isEmpty(getGetMethodInvoke(rule, s))) {
+             	stringRule += getGetMethodName(rule, s) + "==\""+getGetMethodInvoke(rule, s)+"\" && ";
+			}
+		}
+    	return stringRule.substring(0,stringRule.length()-3) + ")";
+    }
+    /**
+     * 
+     * @Title: getGetMethodInvoke
+     * @Description: 根据字段名字拿到get方法值
+     * @param: @param ob
+     * @param: @param name
+     * @param: @return
+     * @param: @throws Exception   
+     * @return: Object
+     * @author gubj  
+     * @date 2022年5月19日 下午5:11:14
+     */
+	public static Object getGetMethodInvoke(Object ob , String name)throws Exception{
+		Method[] m = ob.getClass().getMethods();
+		for(int i = 0;i < m.length;i++){
+			if(("get"+name).toLowerCase().equals(m[i].getName().toLowerCase())){
+				return m[i].invoke(ob);
+			}
+		}
+		return null;
+	}
+	/**
+	 * 
+	 * @Title: getGetMethodName
+	 * @Description: 根据字段名字获取方法名字
+	 * @param: @param ob
+	 * @param: @param name
+	 * @param: @return
+	 * @param: @throws Exception   
+	 * @return: Object
+	 * @author gubj  
+	 * @date 2022年5月20日 上午10:33:21
+	 */
+	public static Object getGetMethodName(Object ob , String name)throws Exception{
+		Method[] m = ob.getClass().getMethods();
+		for(int i = 0;i < m.length;i++){
+			if(("get"+name).toLowerCase().equals(m[i].getName().toLowerCase())){
+				return m[i].getName() + "()";
+			}
+		}
+		return null;
+	}
+
+    /**
+     * 
+     * @Title: createOrRefreshDrl
+     * @Description: 根据String格式生成drl结构的规则写入文件
+     * @param: @param rules   
+     * @return: void
+     * @author gubj  
+     * @throws Exception 
+     * @date 2022年5月25日 上午10:21:51
+     */
+    private void createOrRefreshDrl(List<String> rules) throws Exception {
+    	System.err.println(rules.size());
+        try {
+        	// 1、先备份之前的规则
+        	copyFileToFolder(CommonInfo.drlFormalFileName, CommonInfo.drlPrefixStr + "drlbackup");
+        	// 2、清空temp规则文件
+        	writeFileNull(CommonInfo.drlPrefixStr + CommonInfo.drlTempFileName);
+        	// 3、将规则写入temp文件
+	        bufferedWriterTest(CommonInfo.drlPrefixStr + CommonInfo.drlTempFileName, CommonInfo.drlFileHeader);
+	        for (String str : rules) {
+				bufferedWriterTest(CommonInfo.drlPrefixStr + CommonInfo.drlTempFileName,  str);
+	        }
+	        // 4、校验temp文件
+	        if(testTempRule() == -1) {
+	        	// 出现异常，给出预警
+	        	grabPayService.insertErrorData("", CommonInfo.DRL_RULE_GENERATE_ERROR, "程序生成drl校验文件异常");
+	        }else {
+	        	// 5、将temp文件内容替换到正式文件
+	        	writeFileNull(CommonInfo.drlPrefixStr + CommonInfo.drlFormalFileName);
+	        	bufferedWriterTest(CommonInfo.drlPrefixStr + CommonInfo.drlFormalFileName, CommonInfo.drlFileHeader);
+	        	for (String str : rules) {
+					bufferedWriterTest(CommonInfo.drlPrefixStr + CommonInfo.drlFormalFileName,  str);
+		        }
+	        }
+        } catch (Exception e) {
+        	grabPayService.insertErrorData("", CommonInfo.DRL_RULE_GENERATE_ERROR, "程序生成drl文件异常");
+        	log.info("程序生成drl文件异常",e);
+			e.printStackTrace();
+			throw e;
+		}
+    }
+
+    /**
+     * 
+     * @Title: bufferedWriterTest
+     * @Description: 写入文件
+     * @param: @param filepath
+     * @param: @param content
+     * @param: @throws IOException   
+     * @return: void
+     * @author gubj  
+     * @date 2022年5月24日 下午6:06:27
+     */
+    private static void bufferedWriterTest(String filepath, String content) throws IOException { 
+        try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filepath, true))) { 
+            bufferedWriter.write(content); 
+        } 
+    }
+    /**
+     * 
+     * @Title: copyFileToFolder
+     * @Description: 复制文件至指定目录
+     * @param: @param srcFileName
+     * @param: @param destDir   
+     * @return: void
+     * @author gubj  
+     * @throws Exception 
+     * @date 2022年5月25日 上午11:14:49
+     */
+    public static void copyFileToFolder(String srcFileName, String destDir) throws Exception {
+        //组装成一个目录文件
+        String dirFile = destDir + "/" + srcFileName + "-" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
+        int index;
+        byte[] bytes = new byte[1024];
+        try {
+        	File file = new File(CommonInfo.drlPrefixStr + CommonInfo.drlFormalFileName);
+            FileInputStream input = new FileInputStream(file);
+        	
+            FileOutputStream outputStream = new FileOutputStream(dirFile);
+            while ((index = input.read(bytes)) != -1) {
+                outputStream.write(bytes, 0, index);
+                outputStream.flush();
+            }
+            outputStream.close();
+            input.close();
+        } catch (Exception e) {
+            System.err.println("备份规则文件时异常 " + e.getMessage());
+            throw e;
+        }
+    }
+    /**
+     * 
+     * @Title: writeFileNull
+     * @Description: 清空文件内容
+     * @param: @param srcFileName
+     * @param: @throws Exception   
+     * @return: void
+     * @author gubj  
+     * @date 2022年5月25日 下午3:05:54
+     */
+    public static void writeFileNull(String srcFileName) throws Exception{
+    	File f = new File (srcFileName);
+    	FileWriter fw = new FileWriter (f);
+    	fw.write("");
+    	fw.flush();
+    	fw.close();
+    }
+    /**
+     * 
+     * @Title: testTempRule
+     * @Description: 测试规则文件是否正常使用
+     * @param: @return   
+     * @return: int
+     * @author gubj  
+     * @date 2022年5月25日 下午3:05:38
+     */
+    @SuppressWarnings("unchecked")
+	public static int testTempRule() {
+	    // 构建KieSession, 这部分写法是固定的
+	    KieServices kieServices = KieServices.Factory.get();
+	    KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
+	    kieFileSystem.write(ResourceFactory.newFileResource(CommonInfo.drlPrefixStr + CommonInfo.drlTempFileName));
+	    KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem);
+	    kieBuilder.buildAll();
+	    KieModule kieModule = kieBuilder.getKieModule();
+	    KieSession kieSession = kieServices.newKieContainer(kieModule.getReleaseId()).newKieSession();
+
+	    // 构建实体类对象
+	    RuleDTO tp = new RuleDTO();
+	    tp.setKhbm("10040472");
+	    tp.setJdrbm("40010712");
+	    tp.setSpdl("新鲜水果");
+	    tp.setSdttbm("10040472");
+	    tp.setJydwbm("40010608");
+	    tp.setYwxz("代理");
+	    tp.setYsfs("陆运");
+	    HashMap<String, String> map = new HashMap<String, String>();
+        kieSession.setGlobal("map", map);
+        kieSession.insert(tp);
+        kieSession.fireAllRules();
+        HashMap<String, String> resultMap = (HashMap<String, String>) kieSession.getGlobal("map");
+        System.out.println("temp测试规则：：：：callRuleEngine参数:"+JSONObject.toJSONString(tp) + "==规则匹配信息:" + resultMap.toString());
+        if(map.isEmpty()) {
+        	return -1;
+        }
+        return tp.getId();
+	}
+}
Index: src/main/java/com/novaone/util/CommonUtils.java
===================================================================
--- src/main/java/com/novaone/util/CommonUtils.java	(revision 31350)
+++ src/main/java/com/novaone/util/CommonUtils.java	(revision 31351)
@@ -162,6 +162,11 @@
             return false;
         }
     }
+    public static String stringToStringFormat(String date, String format) throws Exception{
+    	SimpleDateFormat sf = new SimpleDateFormat(format);
+		return sf.format(new SimpleDateFormat("yyyy-MM-dd").parse(date));
+
+    }
     /**
      * 将map转成控制指令参数
      * @Title: getOrderParam
Index: src/main/resources/give-reward-rule-template.drt
===================================================================
--- src/main/resources/give-reward-rule-template.drt	(revision 0)
+++ src/main/resources/give-reward-rule-template.drt	(revision 31351)
@@ -0,0 +1,31 @@
+template header
+
+rule
+ruleCode
+priority
+beginTime
+endTime
+priority
+enable
+fszl
+rules
+
+template "judge condition"
+
+rule "judge_@{ruleCode}"
+no-loop true            //只检查一次
+lock-on-active true
+activation-group "rule"
+salience @{priority}    //值越大 ，优先级越高
+date-effective "@{beginTime}"
+date-expires "@{endTime}"
+enabled @{enable}
+
+when
+	$s : @{rules};
+then
+	update($s);
+	map.put("fszl", "@{fszl}");
+	map.put("rule", "@{ruleCode}");
+end
+end template
\ No newline at end of file


