johnswang
2021-04-19 b6cfc585d1a31d71ad2f393b09076304f65589a1
完善自动作业任务;完善分享名片的二维码
4个文件已添加
12个文件已修改
1191 ■■■■■ 已修改文件
src/com/yc/sdk/shopping/action/WxNotice.java 9 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/com/yc/sdk/shopping/action/api/Poster.java 41 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/com/yc/sdk/shopping/action/jiazhuang/PanicBuying.java 21 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/com/yc/sdk/shopping/action/jiazhuang/PanicBuyingOrder.java 32 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/com/yc/sdk/shopping/action/jiazhuang/PanicBuyingSchedule.java 23 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/com/yc/sdk/shopping/action/jiazhuang/task/PanicBuyingTask.java 592 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/com/yc/sdk/shopping/action/jiazhuang/task/PanicBuyingTaskIfc.java 57 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/com/yc/sdk/shopping/action/jiazhuang/task/PanicBuyingTaskTest.java 81 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/com/yc/sdk/shopping/entity/PanicBuyingOrderEntity.java 3 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/com/yc/sdk/shopping/entity/SettingEntity.java 10 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/com/yc/sdk/shopping/filter/TaskFilter.java 39 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/com/yc/sdk/shopping/service/SettingImpl.java 3 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/com/yc/sdk/shopping/service/panicBuying/PanicBuyingIfc.java 24 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/com/yc/sdk/shopping/service/panicBuying/PanicBuyingImpl.java 106 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/com/yc/sdk/shopping/service/panicBuying/PanicBuyingOrderIfc.java 10 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/com/yc/sdk/shopping/service/panicBuying/PanicBuyingOrderImpl.java 140 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/com/yc/sdk/shopping/action/WxNotice.java
@@ -24,6 +24,8 @@
import com.yc.multiData.MultiDataSource;
import com.yc.multiData.SpObserver;
import com.yc.sdk.miniapp.action.MaSendTemplateMsg;
import com.yc.sdk.shopping.action.jiazhuang.task.PanicBuyingTask;
import com.yc.sdk.shopping.action.jiazhuang.task.PanicBuyingTaskIfc;
import com.yc.sdk.shopping.entity.CancelOrderEntity;
import com.yc.sdk.shopping.entity.OrderEntity;
import com.yc.sdk.shopping.entity.SettingEntity;
@@ -67,6 +69,8 @@
    PanicBuyingOrderIfc panicBuyingOrderIfc;
    @Autowired
    PersonalAuthenticationIfc personalAuthenticationIfc;
    @Autowired
    PanicBuyingTaskIfc panicBuyingTaskIfc ;
    
    @RequestMapping("/shopping/pay/notice/{appid}/{wx}/{formid}/wxordernotice.do")
    /**
@@ -205,6 +209,11 @@
                //家装巴士: 活动订单 
                if (formid!=null && formid.intValue() == 710806) {
                    state = panicBuyingOrderIfc.doPostPanicBuyingOrder(result.getOutTradeNo());
                    if (state) {
                        //停止到期未支付的任务,防止将订单状态改为 -200
                        String taskName = panicBuyingTaskIfc.getTaskNameForPayingExpiredDate(dataSourceEntity.getDbId(), result.getOutTradeNo());
                        panicBuyingTaskIfc.stopTask(taskName) ;  //停止任务
                    }
                }
                
                //家装巴士: 个人认证 
src/com/yc/sdk/shopping/action/api/Poster.java
@@ -8,6 +8,7 @@
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.yc.utils.SessionKey;
import org.apache.commons.io.FileUtils;
@@ -73,22 +74,24 @@
     */
    @GetMapping("/getQrCodeForPoster.do")
    public void getQrCodeForPoster(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        JsonObject json = new JsonObject();
        JsonObject errJson = new JsonObject();
        //CallBackMessage callBackMessage=new CallBackMessage();
        String openId = (session.getAttribute(SessionKey.WEIXIN_OPENID) == null ? "": (String) session.getAttribute(SessionKey.WEIXIN_OPENID));
        
        String fromUserId = request.getParameter(SettingKey.FROMUSERID) ;
        if (fromUserId == null||"".equals(fromUserId)) {
            errJson.addProperty("warning","请传递 FromUserId 参数【/getQrCodeForPoster.do】");
        //QrCodeType : 10 商城首页 , 20 我的名片,30 商品明细,40 直播间,50 优惠劵,60 关于我们, 70 抢购商品明细, 80 活动明细
        String qrCodeType = request.getParameter("QrCodeType") ;
        if (qrCodeType == null||"".equals(qrCodeType)) {
            errJson.addProperty("warning","请传递 QrCodeType 参数【/getQrCodeForPoster.do】");
            json.add("error", errJson);
            this.printJson(response, json.toString());
            return ;
        }
        //QrCodeType : 10 商城首页 , 20 我的名片,30 商品明细,40 直播间,50 优惠劵,60 关于我们
        String qrCodeType = request.getParameter("QrCodeType") ;
        if (qrCodeType == null||"".equals(qrCodeType)) {
            errJson.addProperty("warning","请传递 QrCodeType 参数【/getQrCodeForPoster.do】");
        String fromUserId = request.getParameter(SettingKey.FROMUSERID) ;
        if (!qrCodeType.equals("80")&& (fromUserId == null||"".equals(fromUserId))) {
            errJson.addProperty("warning","请传递 FromUserId 参数【/getQrCodeForPoster.do】");
            json.add("error", errJson);
            this.printJson(response, json.toString());
            return ;
@@ -138,7 +141,15 @@
            this.printJson(response, json.toString());
            return ;
        }
        String docCode = request.getParameter(SettingKey.DOCCODE) ;
        if (qrCodeType.equals("80") && (docCode == null||"".equals(docCode))) {
            errJson.addProperty("warning","获取【活动】二维码时必须传递 doccode 参数【/getQrCodeForPoster.do】");
            json.add("error", errJson);
            this.printJson(response, json.toString());
            return ;
        }
        String referralsOpenId = request.getParameter(SettingKey.ReferralsOpenId);   //导购的 openid
        
        String qrCodeParameter = "" ;
        switch(qrCodeType) {
@@ -153,6 +164,13 @@
                break;
            case "70":
                qrCodeParameter = depositDocCode+";"+ depositRowId ;
                break;
            case "80":
                if (referralsOpenId!=null&&!"".equals(referralsOpenId)) {
                    fromUserId = referralsOpenId;
                }else {
                    fromUserId = openId;
                }
                break;
            default:
                qrCodeParameter = "" ;
@@ -217,6 +235,9 @@
                case "70":
                    pathUrl = "pages/detailEvents/detailEvents?"+ SettingKey.MATCODE + "=" + matCode+"&DepositDocCode="+depositDocCode +"&DepositRowId="+depositRowId+"&"+SettingKey.FROMUSERID+"="+fromUserId;
                    break;    
                case "80":  //活动
                    pathUrl = "pages/detail/detail?"+SettingKey.DOCCODE+"=" + docCode + "&" + SettingKey.ReferralsOpenId + "=" + referralsOpenId ;
                    break;
                default:
                    pathUrl = "pages/index/index?"+SettingKey.FROMUSERID+"="+fromUserId ;
                    break ;
@@ -273,7 +294,7 @@
                    this.printJson(response, json.toString());
                    return ;
            }else {
                    errJson.addProperty("warning","保存直播间二维码失败【/getQrCodeForPoster.do】");
                    errJson.addProperty("warning","保存二维码失败【/getQrCodeForPoster.do】");
                    json.add("error", errJson);
                    this.printJson(response, json.toString());
                    return ;
src/com/yc/sdk/shopping/action/jiazhuang/PanicBuying.java
@@ -4,6 +4,7 @@
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
@@ -31,6 +32,7 @@
import com.yc.factory.FactoryBean;
import com.yc.multiData.MultiDataSource;
import com.yc.multiData.SpObserver;
import com.yc.sdk.shopping.action.jiazhuang.task.PanicBuyingTaskIfc;
import com.yc.sdk.shopping.entity.PanicBuyingEntity;
import com.yc.sdk.shopping.entity.PanicBuyingOrderEntity;
import com.yc.sdk.shopping.entity.PanicBuyingPamareterEntity;
@@ -61,6 +63,8 @@
    PanicBuyingOrderIfc panicBuyingOrderIfc;    
    @Autowired
    ShoppingImageDataIfc imgData;
    @Autowired
    PanicBuyingTaskIfc panicBuyingTaskIfc ;
    
    /**
     * 上传附件 到秒杀表 CoverImage 和 Images 字段 
@@ -290,6 +294,14 @@
            this.printJson(response, json.toString());
            return;    
        }
        Date currentDate = new Date();
        if (effectiveEndDate.getTime() <= currentDate.getTime()) {
            errJson.addProperty("warning", "结束时间不能小于系统当前时间["+ sdf.format(currentDate)+"]");
            json.add("error", errJson);
            this.printJson(response, json.toString());
            return;
        }
        if (panicBuyingEntity.getSellerList()==null||panicBuyingEntity.getSellerList().size()==0) {
            errJson.addProperty("warning", "必须至少选择一位营销人员");
            json.add("error", errJson);
@@ -343,16 +355,21 @@
                json.addProperty("historyDocCode", historyDocCode);
            }
            
            //执行定时任务,用于修改活动状态
            panicBuyingTaskIfc.addStatusTask(dataSourceEntity, docCode);
            json.addProperty("DocCode", docCode);
            json.addProperty("state", "success");
            this.printJson(response, json.toString());
            return;
        } catch (DataAccessException e) {
            e.printStackTrace();
            errJson.addProperty("warning", (e.getCause()!=null?e.getCause().getMessage(): e.getMessage()));
            json.add("error", errJson);
            this.printJson(response, json.toString());
            return;
        }catch (Exception e ){
            e.printStackTrace();
            errJson.addProperty("warning", (e.getCause()!=null?e.getCause().getMessage(): e.getMessage()));
            json.add("error", errJson);
            this.printJson(response, json.toString());
@@ -1722,8 +1739,8 @@
            break;
        }
        orderEntityJsonObject.addProperty("formName", formName);  //活动名称
        orderEntityJsonObject.addProperty("isShowContinueButton", orderEntity.getStatus()!=null&&orderEntity.getStatus().intValue()==3);  //是否显示继续活动按钮
        orderEntityJsonObject.addProperty("isShowStopButton", orderEntity.getStatus()!=null&&orderEntity.getStatus().intValue()==2);    //是否显示停止活动按钮
        orderEntityJsonObject.addProperty("isShowContinueButton", orderEntity.getEffectiveStartDateBalance() <=0 && orderEntity.getEffectiveEndDateBalance() >=0 && orderEntity.getStatus().intValue()==3);  //是否显示继续活动按钮
        orderEntityJsonObject.addProperty("isShowStopButton", orderEntity.getEffectiveStartDateBalance() <=0 && orderEntity.getEffectiveEndDateBalance() >=0 && orderEntity.getStatus().intValue()==2);    //是否显示停止活动按钮
        if (orderEntity.getFormId()!=null && orderEntity.getFormId().intValue() == 710804) {   //如果是团购活动,则显示 园购成功 和 团购失败
            orderEntityJsonObject.addProperty("isShowGroupBuyingSuccessButton", orderEntity.getStatus()!=null&&orderEntity.getStatus().intValue()==0?true:false); //是否显示团购成功按钮 
            orderEntityJsonObject.addProperty("isShowGroupBuyingFailedButton", orderEntity.getStatus()!=null&&orderEntity.getStatus().intValue()==0?true:false);  //是否显示团购失败按钮
src/com/yc/sdk/shopping/action/jiazhuang/PanicBuyingOrder.java
@@ -36,6 +36,7 @@
import com.yc.sdk.miniapp.entity.MaSettingEntity;
import com.yc.sdk.miniapp.service.MaSettingIfc;
import com.yc.sdk.shopping.action.Wxtransactions;
import com.yc.sdk.shopping.action.jiazhuang.task.PanicBuyingTaskIfc;
import com.yc.sdk.shopping.entity.AddressEntity;
import com.yc.sdk.shopping.entity.ConfirmEntity;
import com.yc.sdk.shopping.entity.CurrencyEntity;
@@ -85,6 +86,8 @@
    MatCodeIfc matCodeIfc;
    @Autowired
    ShoppingImageDataIfc imgData;
    @Autowired
    PanicBuyingTaskIfc panicBuyingTaskIfc ;
    
    @RequestMapping(params = "m=saveOrder")
    public void saveOrder(@RequestBody SaveOrderParamters saveOrderParamters , HttpServletRequest request, HttpServletResponse response) {
@@ -147,9 +150,11 @@
            if (saveOrderParamters.getBalancePayAmount()!=null) confirmEntity.setBalancePayAmount(saveOrderParamters.getBalancePayAmount());
            
            DocCodeStateEntity docCodeStateEntity = panicBuyingOrderIfc.saveOrder(confirmEntity);
            if (docCodeStateEntity != null) {
                //到期未支付的,是定时取消订单
                panicBuyingTaskIfc.addCancelOrderTaskForPayingExpired( dataSourceEntity,docCodeStateEntity.getDocCode()) ;
                //--增加处理单据确认后生成二维码,线程处理
                ThreadPoolTaskScheduler threadPoolTaskScheduler = (ThreadPoolTaskScheduler) FactoryBean.getBean("threadPoolTaskScheduler");
                threadPoolTaskScheduler.execute(new QrCodeRunable(docCodeStateEntity.getFormId(), docCodeStateEntity.getFormType(),docCodeStateEntity.getDocCode()
@@ -937,8 +942,29 @@
            DataSourceEntity dataSourceEntity = MultiDataSource.getDataSourceMap( request) ;
            SpObserver.setDBtoInstance("_"+dataSourceEntity.getDbId());//切换数据源
            //SettingEntity settingEntity = settingIfc.getSettingEntity() ;
            panicBuyingOrderIfc.deleteExpiredOrder(docCode);
            PanicBuyingOrderEntity panicBuyingOrderEntity = panicBuyingOrderIfc.getOrderHeaderEntity(docCode);
            if (panicBuyingOrderEntity != null) {
                if (panicBuyingOrderEntity.getDocStatus().intValue() == -200) {
                    errJson.addProperty("warning", "已取消");
                    json.add("error", errJson);
                    this.printJson(response, json.toString());
                    return;
                }
                if (panicBuyingOrderEntity.getDocStatus().intValue() == 100) {
                    errJson.addProperty("warning", "订单已支付,不能取消");
                    json.add("error", errJson);
                    this.printJson(response, json.toString());
                    return;
                }
                if (panicBuyingOrderEntity.getDocStatus().intValue() != 0) {
                    errJson.addProperty("warning", "订单不是待支付状态,不能取消");
                    json.add("error", errJson);
                    this.printJson(response, json.toString());
                    return;
                }
                panicBuyingOrderIfc.deletePayingExpiredOrder(docCode);
            }
            json.addProperty("state", "success");
            this.printJson(response, json.toString());
            return;
src/com/yc/sdk/shopping/action/jiazhuang/PanicBuyingSchedule.java
@@ -23,6 +23,12 @@
import com.yc.sdk.shopping.service.panicBuying.PanicBuyingOrderIfc;
@Service
@Deprecated
/**
 * 暂时停用,使用 PanicBuyingTask.java 代替
 * @author johnswang
 *
 */
public class PanicBuyingSchedule  implements ApplicationListener<ContextRefreshedEvent> {
    protected final Logger log = LoggerFactory.getLogger(this.getClass());
    @Override
@@ -33,19 +39,19 @@
        String isPanicBuyingRunSchedule = AttachmentConfig.get("isPanicBuyingRunSchedule");//只在设置了定时任务的服务器上运行
        
        if ("1".equals(isPanicBuyingRunSchedule)) {
            ThreadPoolTaskScheduler threadPoolTaskScheduler = (ThreadPoolTaskScheduler) FactoryBean.getBean("threadPoolTaskScheduler");
            //ThreadPoolTaskScheduler threadPoolTaskScheduler = (ThreadPoolTaskScheduler) FactoryBean.getBean("threadPoolTaskScheduler");
            //每1分钟更新一次活动状态: 已开始 或 已结束
            threadPoolTaskScheduler.scheduleWithFixedDelay(new UpdatePanicBuyingStatus(),
                    Instant.now().plusMillis(TimeUnit.MINUTES.toMillis(3)), Duration.ofMinutes(1));//1分钟执行一次
            //threadPoolTaskScheduler.scheduleWithFixedDelay(new UpdatePanicBuyingStatus(),
            //        Instant.now().plusMillis(TimeUnit.MINUTES.toMillis(3)), Duration.ofMinutes(1));//1分钟执行一次
            
            //每1分钟更新一次 取消支付已过期的所有订单
            threadPoolTaskScheduler.scheduleWithFixedDelay(new DeleteExpiredOrder(),
                    Instant.now().plusMillis(TimeUnit.MINUTES.toMillis(3)), Duration.ofMinutes(1));//1分钟执行一次
            //threadPoolTaskScheduler.scheduleWithFixedDelay(new DeleteExpiredOrder(),
            //        Instant.now().plusMillis(TimeUnit.MINUTES.toMillis(3)), Duration.ofMinutes(1));//1分钟执行一次
        }
    }
    
    /**
     * 更新活动状态: 已开始 或 已结束
     * 更新所有活动单据状态: 已开始 或 已结束
     * @author johnswang
     *
     */
@@ -88,7 +94,7 @@
                SpObserver.setDBtoInstance("_" + dbid);
                
                PanicBuyingIfc panicBuyingIfc = (PanicBuyingIfc) FactoryBean.getBean("PanicBuyingImpl");
                panicBuyingIfc.updatePanicBuyingStatueBySchedule();
                panicBuyingIfc.updatePanicBuyingStatusBySchedule();
                log.info(dataSourceEntity.getSystemDescribe() + " 自动更新小程序活动状态...结束执行");
            }catch (RuntimeException r){
             throw r;
@@ -99,7 +105,6 @@
                SpObserver.setDBtoInstance();
            }
        }
    }
    
    /**
@@ -147,7 +152,7 @@
                
                PanicBuyingOrderIfc panicBuyingOrderIfc = (PanicBuyingOrderIfc) FactoryBean.getBean("PanicBuyingOrderImpl");
                //清除支付已过期的订单
                panicBuyingOrderIfc.deleteExpiredOrder();
                panicBuyingOrderIfc.deletePayingExpiredOrder();
                log.info(dataSourceEntity.getSystemDescribe() + " 自动更新小程序活动状态...结束执行");
            }catch (RuntimeException r){
             throw r;
src/com/yc/sdk/shopping/action/jiazhuang/task/PanicBuyingTask.java
New file
@@ -0,0 +1,592 @@
package com.yc.sdk.shopping.action.jiazhuang.task;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;
import org.apache.tools.ant.taskdefs.Sleep;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Scope;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;
import com.yc.api.schedule.ScheduleUtils;
import com.yc.entity.AttachmentConfig;
import com.yc.entity.DataSourceEntity;
import com.yc.factory.FactoryBean;
import com.yc.multiData.MultiDataSource;
import com.yc.multiData.SpObserver;
import com.yc.sdk.shopping.entity.PanicBuyingEntity;
import com.yc.sdk.shopping.entity.PanicBuyingOrderEntity;
import com.yc.sdk.shopping.service.panicBuying.PanicBuyingIfc;
import com.yc.sdk.shopping.service.panicBuying.PanicBuyingOrderIfc;
@Service("PanicBuyingTask")
@Scope("prototype")
public class PanicBuyingTask implements ApplicationListener<ContextRefreshedEvent> , PanicBuyingTaskIfc{
    //private String cron;
    //private ScheduledFuture future;
    protected Logger log = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;
    // 线程存储器
    public static ConcurrentHashMap<String, ScheduledFuture<?>> task = new ConcurrentHashMap<String, ScheduledFuture<?>>();
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        if (contextRefreshedEvent.getApplicationContext().getParent() == null) {
            return;
        }
        String isPanicBuyingRunSchedule = AttachmentConfig.get("isPanicBuyingRunSchedule");//只在设置了定时任务的服务器上运行
        if ("1".equals(isPanicBuyingRunSchedule)) {
            ThreadPoolTaskScheduler threadPoolTaskScheduler = (ThreadPoolTaskScheduler) FactoryBean.getBean("threadPoolTaskScheduler");
          //每1分钟更新一次活动状态: 已开始 或 已结束   ,暂时不用此方法,因为太消耗系统资源,用 InitStatusTask 方法代替
          //  threadPoolTaskScheduler.scheduleWithFixedDelay(new UpdatePanicBuyingStatus(),
          //          Instant.now().plusMillis(TimeUnit.MINUTES.toMillis(3)), Duration.ofMinutes(1));//1分钟执行一次
            //启动时执行一次,初始化所有需要更新状态的活动单据
            threadPoolTaskScheduler.execute(new InitStatusTask());
          //每1分钟更新一次 取消支付已过期的所有订单, 暂时不用此方法,因为太消耗系统资源,用 InitCancelOrderTask 方法代替
           // threadPoolTaskScheduler.scheduleWithFixedDelay(new CancelOrderForPayingExpired(),
           //         Instant.now().plusMillis(TimeUnit.MINUTES.toMillis(3)), Duration.ofMinutes(1));//1分钟执行一次
            //启动时执行一次,初始化所有过期未支付的活动订单,将订单状态改为 -200
            threadPoolTaskScheduler.execute(new InitCancelOrderTask()) ;
        }
    }
    @Override
    public void addStatusTask(DataSourceEntity dataSourceEntity,String docCode) {
        try {
            SpObserver.setDBtoInstance("_" + dataSourceEntity.getDbId());
            PanicBuyingIfc panicBuyingIfc = (PanicBuyingIfc) FactoryBean.getBean("PanicBuyingImpl");
            PanicBuyingEntity panicBuyingEntity = panicBuyingIfc.getPanicBuyingHeaderByTask( docCode);
            if (panicBuyingEntity != null) {
                addStatusTask( dataSourceEntity,  panicBuyingEntity);
            }
        }catch (RuntimeException r){
            throw r;
        }catch (Exception ex){
            ex.printStackTrace();
            log.info(dataSourceEntity.getSystemDescribe()+":"+ (ex.getCause()!=null?ex.getCause().getMessage():  ex.getMessage()));
        }finally {
            SpObserver.setDBtoInstance();
        }
    }
    @Override
    public void addStatusTask(DataSourceEntity dataSourceEntity,PanicBuyingEntity  panicBuyingEntity) {
        if (panicBuyingEntity == null)  return ;
           //String cron = "0/1 * * * * ?";
           //String cron = "0/10 * * * * ?";
           //System.out.println(Thread.currentThread().getName());
           //String name = Thread.currentThread().getName();、
           String taskNameForStart = dataSourceEntity.getDbId()+"_"+panicBuyingEntity.getDocCode()+"_EffectiveStartDate";
           String taskNameForStop = dataSourceEntity.getDbId()+"_"+panicBuyingEntity.getDocCode() + "_EffectiveEndDate";
           stopTask(taskNameForStart);  //停止已经存在的任务
           stopTask(taskNameForStop);  //停止已经存在的任务
           //根据活动开始时间加入任务,到活动开始时将状态改为“进行中”
           if (panicBuyingEntity.getEffectiveStartDateBalance() >= 0) {
               String cron = getTaskSchedule(panicBuyingEntity.getEffectiveStartDate());
               //增加新的任务
               ScheduledFuture<?> future = threadPoolTaskScheduler.schedule(new UpdateStatusTask(dataSourceEntity,panicBuyingEntity.getDocCode(),taskNameForStart,true), new CronTrigger(cron));
               PanicBuyingTask.task.put(taskNameForStart, future);
               System.out.println("任务["+taskNameForStart+"]已添加!");
           }
           //根据活动结束时间加入任务,到活动结束时将状态改为“已停止”
           if (panicBuyingEntity.getEffectiveEndDateBalance() >= 0) {
               String cron = getTaskSchedule(panicBuyingEntity.getEffectiveEndDate());
               //增加新的任务
               ScheduledFuture<?> future = threadPoolTaskScheduler.schedule(new UpdateStatusTask(dataSourceEntity,panicBuyingEntity.getDocCode(),taskNameForStop,false), new CronTrigger(cron));
               PanicBuyingTask.task.put(taskNameForStop, future);
               System.out.println("任务["+taskNameForStop+"]已添加!");
           }
     }
    @Override
    public void addCancelOrderTaskForPayingExpired(DataSourceEntity dataSourceEntity,String docCode) {
        try {
            SpObserver.setDBtoInstance("_" + dataSourceEntity.getDbId());
            PanicBuyingOrderIfc panicBuyingOrderIfc = (PanicBuyingOrderIfc) FactoryBean.getBean("PanicBuyingOrderImpl");
            PanicBuyingOrderEntity  panicBuyingOrderEntity = panicBuyingOrderIfc.getOrderHeaderEntity(docCode);
            if (panicBuyingOrderEntity != null) {
                addCancelOrderTaskForPayingExpired( dataSourceEntity,  panicBuyingOrderEntity);
            }
        }catch (RuntimeException r){
            throw r;
        }catch (Exception ex){
            ex.printStackTrace();
            log.info(dataSourceEntity.getSystemDescribe()+":"+ (ex.getCause()!=null?ex.getCause().getMessage():  ex.getMessage()));
        }finally {
            SpObserver.setDBtoInstance();
        }
     }
    @Override
    public void addCancelOrderTaskForPayingExpired(DataSourceEntity dataSourceEntity,PanicBuyingOrderEntity  panicBuyingOrderEntity) {
        if (panicBuyingOrderEntity == null)  return ;
           //String cron = "0/1 * * * * ?";
           //String cron = "0/10 * * * * ?";
           //System.out.println(Thread.currentThread().getName());
           //String name = Thread.currentThread().getName();、
           String taskName = getTaskNameForPayingExpiredDate(dataSourceEntity.getDbId(),panicBuyingOrderEntity.getDocCode());
           stopTask(taskName);  //停止已经存在的任务
           //根据活动开始时间加入任务,到活动开始时将状态改为“进行中”
           if (panicBuyingOrderEntity.getPayableSecondBalance() >= 0) {
               String cron = getTaskSchedule(panicBuyingOrderEntity.getPayingExpiredDate());
               //增加新的任务
               ScheduledFuture<?> future = threadPoolTaskScheduler.schedule(new CancelOrderTask(dataSourceEntity,panicBuyingOrderEntity.getDocCode(),taskName), new CronTrigger(cron));
               PanicBuyingTask.task.put(taskName, future);
               System.out.println("任务["+taskName+"]已添加!");
           }
     }
    /**
     * 输出过期未支付的订单任务名称 :  taskName ,  用于定时任务执行
     * @param dbId
     * @param docCode
     * @return
     */
    @Override
    public String getTaskNameForPayingExpiredDate(Integer dbId,String docCode) {
        return (dbId+"_" + docCode + "_PayingExpiredDate" ) ;
    }
    /**
     * 输出 CronTrigger 配置格式:格式: [秒] [分] [小时] [日] [月] [周] [年]
     * 参考:https://blog.csdn.net/yangxiaoer1/article/details/80678563
     * @param date
     * @return
     */
    private String getTaskSchedule(Date date) {
        if (date == null) {
            return null;
        }
        // yyyy-MM-dd HH:mm:ss
        //SimpleDateFormat sdf2 = new SimpleDateFormat("2 m H d M ? yyyy") ;   //到期2秒后开始执行,如果加上年份,则会报错:spring cron expression must consist of 6 fields
        SimpleDateFormat sdf2 = new SimpleDateFormat("0 m H d M ?") ;   //到期0秒后开始执行
        String cron = sdf2.format(date);
        //System.out.println("cron:" + cron);
        return cron;
    }
    /**
     * 停止任务
     * @param taskName
     */
    @Override
    public void stopTask(String taskName) {
        try {
            ScheduledFuture<?> future = task.get(taskName) ;
            if (future == null) {
                //log.warn("任务[{}]已不在调度中,无法停止!", taskName);
                //System.out.println("任务[" + taskName + "]已不在调度中,无法停止!");
            } else {
                future.cancel(true);
                while (!future.isCancelled()) {
                    //Thread.sleep(200);    //延时200毫秒
                    future.cancel(true);
                }
                task.remove(taskName);
                log.info("任务[{}]已被停止!", taskName);
                System.out.println( "任务[" + taskName + "]已被停止!");
            }
        } catch (Exception e) {
            System.out.println("停止任务["+taskName+"]时出现意外,原因:" + e.getMessage());
            throw e;
        }
     }
    /**
     * 停止任务
     * @param taskName
     */
    @Override
    public void stopAllTask() {
        try {
            task.forEach((taskName, future) -> {
                if (future == null) {
                    //log.warn("任务[{}]已不在调度中,无法停止!", taskName);
                    //System.out.println("任务[" + taskName + "]已不在调度中,无法停止!");
                } else {
                    future.cancel(true);
                    while (!future.isCancelled()) {
                        System.out.println( "正在尝试停止任务[" + taskName + "]...!");
                        future.cancel(true);
                    }
                    task.remove(taskName);
                    log.info("任务[{}]已被停止!", taskName);
                    System.out.println( "任务[" + taskName + "]已被停止!");
                }
            });
        } catch (Exception e) {
            System.out.println("停止所有任务时出现意外,原因:" + e.getMessage());
            throw e;
        }
     }
    /**
     * 活动开始任务
     * @author johnswang
     *
     */
    private class UpdateStatusTask implements Runnable {
           final  DataSourceEntity dataSourceEntity;
           final String docCode ;
           final String taskName ;
           final boolean isUpdateEffectiveStartDate;
           SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") ;
           public UpdateStatusTask(DataSourceEntity dataSourceEntity,String docCode,String taskName,boolean isUpdateEffectiveStartDate) {
                this.dataSourceEntity = dataSourceEntity;
                this.docCode = docCode;
                this.taskName = taskName;
                this.isUpdateEffectiveStartDate = isUpdateEffectiveStartDate ;
           }
           @Override
           public void run() {
               try {
                    String dbid = dataSourceEntity.getDbId() + "";
                    log.info(dataSourceEntity.getSystemDescribe() + " 自动更新小程序活动状态["+docCode+"]...开始执行");
                    SpObserver.setDBtoInstance("_" + dbid);
                    PanicBuyingIfc panicBuyingIfc = (PanicBuyingIfc) FactoryBean.getBean("PanicBuyingImpl");
                    panicBuyingIfc.updateStatusByEffectiveDate(docCode,isUpdateEffectiveStartDate);  //更新为“进行中”状态
                    System.out.println("任务[" + taskName +"]已执行完毕");
                    log.info("任务[" + taskName +"]已执行完毕");
                    //System.out.println("已更新活动状态[任务:" + taskName +"],时间:"+ sdf2.format(new Date())+",dbid:" + dataSourceEntity.getDbId()+ ", DocCode:" + docCode);
                    stopTask( taskName);  //停止已经存在的任务
                    //log.info(dataSourceEntity.getSystemDescribe() + " 自动更新小程序活动状态["+docCode+"]...结束执行");
               }catch (RuntimeException r){
                   throw r;
               }catch (Exception ex){
                   ex.printStackTrace();
                   log.info(dataSourceEntity.getSystemDescribe()+":"+ (ex.getCause()!=null?ex.getCause().getMessage():  ex.getMessage()));
               }finally {
                   SpObserver.setDBtoInstance();
               }
           }
    }
    /**
     * 服务器启动时,遍历所有数据库,把所有活动单据加入到 task 中
     * @author johnswang
     *
     */
     public class InitStatusTask implements Runnable {
           @Override
           public void run() {
               ThreadPoolTaskExecutor threadPoolExecutor= (ThreadPoolTaskExecutor) FactoryBean.getBean("threadPoolExecutor");
                List<DataSourceEntity> dataSourceList = MultiDataSource.getDataSourceMapsByMaAppId();  //获取微信小程序所有数据源 DataSourceEntity 对象
               for (int i = 0;dataSourceList!=null&& i < dataSourceList.size(); i++) {
                   DataSourceEntity dataSourceEntity = dataSourceList.get(i);
                   //非托管系统跳过执行
                   if(ScheduleUtils.isOnbusPlatform(dataSourceEntity)){ continue;}
                   try {
                       //一个系统开一个线程
                       threadPoolExecutor.execute(new InitStatusTaskThread(dataSourceEntity ));
                      // Thread.sleep(10000);//暂停10秒,避免过多的并发
                   } catch (Exception e) {
                       e.printStackTrace();
                   }
               }
           }
     }
     /**
      * 服务器启动时,把当前数据库,把所有活动单据加入到 task 中
      * @author johnswang
      *
      */
     public class InitStatusTaskThread implements Runnable {
           final  DataSourceEntity dataSourceEntity;
           //SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") ;
           public InitStatusTaskThread(DataSourceEntity dataSourceEntity) {
                this.dataSourceEntity = dataSourceEntity;
           }
           @Override
           public void run() {
               try {
                    String dbid = dataSourceEntity.getDbId() + "";
                    SpObserver.setDBtoInstance("_" + dbid);
                    PanicBuyingIfc panicBuyingIfc = (PanicBuyingIfc) FactoryBean.getBean("PanicBuyingImpl");
                    List<PanicBuyingEntity>panicBuyingList = panicBuyingIfc.getPanicBuyingByTask();
                    for (int i = 0;panicBuyingList!=null&& i < panicBuyingList.size(); i++) {
                        addStatusTask(dataSourceEntity, panicBuyingList.get(i));
                    }
               }catch (RuntimeException r){
                   throw r;
               }catch (Exception ex){
                   ex.printStackTrace();
                   log.info(dataSourceEntity.getSystemDescribe()+":"+ (ex.getCause()!=null?ex.getCause().getMessage():  ex.getMessage()));
               }finally {
                   SpObserver.setDBtoInstance();
               }
           }
     }
        /**
         * 活动开始任务
         * @author johnswang
         *
         */
        private class CancelOrderTask implements Runnable {
               final  DataSourceEntity dataSourceEntity;
               final String docCode ;
               final String taskName ;
               SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") ;
               public CancelOrderTask(DataSourceEntity dataSourceEntity,String docCode,String taskName) {
                    this.dataSourceEntity = dataSourceEntity;
                    this.docCode = docCode;
                    this.taskName = taskName;
               }
               @Override
               public void run() {
                   try {
                        String dbid = dataSourceEntity.getDbId() + "";
                        log.info(dataSourceEntity.getSystemDescribe() + " 自动更新小程序活动订单状态["+docCode+"]...开始执行");
                        SpObserver.setDBtoInstance("_" + dbid);
                        PanicBuyingOrderIfc panicBuyingOrderIfc = (PanicBuyingOrderIfc) FactoryBean.getBean("PanicBuyingOrderImpl");
                        panicBuyingOrderIfc.deletePayingExpiredOrder(docCode);  //取消当前订单,将订单状态更新为 -200
                        System.out.println("任务[" + taskName +"]已执行完毕");
                        log.info( "任务[" + taskName +"]已执行完毕");
                        stopTask( taskName);  //停止已经存在的任务
                       // log.info(dataSourceEntity.getSystemDescribe() + " 自动更新小程序活动订单状态["+docCode+"]...结束执行");
                   }catch (RuntimeException r){
                       log.info(dataSourceEntity.getSystemDescribe()+":"+ (r.getCause()!=null?r.getCause().getMessage():  r.getMessage()));
                       System.out.println(dataSourceEntity.getSystemDescribe()+":"+ (r.getCause()!=null?r.getCause().getMessage():  r.getMessage()));
                       throw r;
                   }catch (Exception e){
                       e.printStackTrace();
                       System.out.println(dataSourceEntity.getSystemDescribe()+":"+ (e.getCause()!=null?e.getCause().getMessage():  e.getMessage()));
                       log.info(dataSourceEntity.getSystemDescribe()+":"+ (e.getCause()!=null?e.getCause().getMessage():  e.getMessage()));
                   }finally {
                       SpObserver.setDBtoInstance();
                   }
               }
        }
        /**
         * 服务器启动时,遍历所有数据库,把所有活动单据加入到 task 中
         * @author johnswang
         *
         */
         public class InitCancelOrderTask implements Runnable {
               @Override
               public void run() {
                   ThreadPoolTaskExecutor threadPoolExecutor= (ThreadPoolTaskExecutor) FactoryBean.getBean("threadPoolExecutor");
                    List<DataSourceEntity> dataSourceList = MultiDataSource.getDataSourceMapsByMaAppId();  //获取微信小程序所有数据源 DataSourceEntity 对象
                   for (int i = 0;dataSourceList!=null&& i < dataSourceList.size(); i++) {
                       DataSourceEntity dataSourceEntity = dataSourceList.get(i);
                       //非托管系统跳过执行
                       if(ScheduleUtils.isOnbusPlatform(dataSourceEntity)){ continue;}
                       try {
                           //一个系统开一个线程
                           threadPoolExecutor.execute(new InitCancelOrderTaskThread(dataSourceEntity ));
                          // Thread.sleep(10000);//暂停10秒,避免过多的并发
                       } catch (Exception e) {
                           e.printStackTrace();
                       }
                   }
               }
         }
         /**
          * 服务器启动时,把当前数据库,把所有活动单据加入到 task 中
          * @author johnswang
          *
          */
         public class InitCancelOrderTaskThread implements Runnable {
               final  DataSourceEntity dataSourceEntity;
               //SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") ;
               public InitCancelOrderTaskThread(DataSourceEntity dataSourceEntity) {
                    this.dataSourceEntity = dataSourceEntity;
               }
               @Override
               public void run() {
                   try {
                        String dbid = dataSourceEntity.getDbId() + "";
                        SpObserver.setDBtoInstance("_" + dbid);
                        PanicBuyingOrderIfc panicBuyingOrderIfc = (PanicBuyingOrderIfc) FactoryBean.getBean("PanicBuyingOrderImpl");
                        List<PanicBuyingOrderEntity>panicBuyingOrderList = panicBuyingOrderIfc.getOrderHeaderListForPayingExpired();
                        for (int i = 0;panicBuyingOrderList!=null&& i < panicBuyingOrderList.size(); i++) {
                            if (panicBuyingOrderList.get(i).getPayableSecondBalance().doubleValue() <= 0) {
                                panicBuyingOrderIfc.deletePayingExpiredOrder(panicBuyingOrderList.get(i).getDocCode());  //立即取消当前订单,将订单状态更新为 -200
                            }else {
                                addCancelOrderTaskForPayingExpired(dataSourceEntity, panicBuyingOrderList.get(i));   //排期取消前订单,将订单状态更新为 -200
                            }
                        }
                   }catch (RuntimeException r){
                       throw r;
                   }catch (Exception ex){
                       ex.printStackTrace();
                       log.info(dataSourceEntity.getSystemDescribe()+":"+ (ex.getCause()!=null?ex.getCause().getMessage():  ex.getMessage()));
                   }finally {
                       SpObserver.setDBtoInstance();
                   }
               }
         }
     /**
      * 取消支付已过期的所有活动订单
      * @author johnswang
      *
      */
     @Deprecated
     private class CancelOrderForPayingExpired implements Runnable {
            @Override
            public void run() {
                //System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "自动更新小程序活动状态(新版小程序)...");
                //log.info("启动定时自动更新小程序活动状态(新版小程序).....");
                ThreadPoolTaskExecutor threadPoolExecutor= (ThreadPoolTaskExecutor) FactoryBean.getBean("threadPoolExecutor");
                List<DataSourceEntity> dataSourceList = MultiDataSource.getDataSourceMapsByMaAppId();  //获取微信小程序所有数据源 DataSourceEntity 对象
               for (int i = 0;dataSourceList!=null&& i < dataSourceList.size(); i++) {
                   DataSourceEntity dataSourceEntity = dataSourceList.get(i);
                   //非托管系统跳过执行
                   if(ScheduleUtils.isOnbusPlatform(dataSourceEntity)){ continue;}
                   try {
                       //一个系统开一个线程
                       threadPoolExecutor.execute(new CancelOrderForPayingExpiredThread(dataSourceEntity ));
                      // Thread.sleep(10000);//暂停10秒,避免过多的并发
                   } catch (Exception e) {
                       e.printStackTrace();
                   }
               }
            }
     }
     /**
      * 取消支付已过期的所有活动订单
      * @author johnswang
      *
      */
     @Deprecated
     private class CancelOrderForPayingExpiredThread implements Runnable {
            final  DataSourceEntity dataSourceEntity;
            public CancelOrderForPayingExpiredThread(DataSourceEntity dataSourceEntity) {
                this.dataSourceEntity = dataSourceEntity;
            }
            @Override
            public void run() {
                try {
                    String dbid = dataSourceEntity.getDbId() + "";
                    log.info(dataSourceEntity.getSystemDescribe() + " 自动更新小程序活动状态...开始执行");
                    SpObserver.setDBtoInstance("_" + dbid);
                    PanicBuyingOrderIfc panicBuyingOrderIfc = (PanicBuyingOrderIfc) FactoryBean.getBean("PanicBuyingOrderImpl");
                    //清除支付已过期的订单
                    panicBuyingOrderIfc.deletePayingExpiredOrder();
                    log.info(dataSourceEntity.getSystemDescribe() + " 自动更新小程序活动状态...结束执行");
                }catch (RuntimeException r){
                 throw r;
                }catch (Exception ex){
                    ex.printStackTrace();
                    log.info(dataSourceEntity.getSystemDescribe()+":"+ (ex.getCause()!=null?ex.getCause().getMessage():  ex.getMessage()));
                }finally {
                    SpObserver.setDBtoInstance();
                }
            }
     }
     /**
      * 更新所有活动单据状态: 已开始 或 已结束,暂时停用
      * @author johnswang
      *
      */
     @Deprecated
     private  class UpdateStatusForAllOrders implements Runnable {
            @Override
            public void run() {
                //System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "自动更新小程序活动状态(新版小程序)...");
                //log.info("启动定时自动更新小程序活动状态(新版小程序).....");
                ThreadPoolTaskExecutor threadPoolExecutor= (ThreadPoolTaskExecutor) FactoryBean.getBean("threadPoolExecutor");
                List<DataSourceEntity> dataSourceList = MultiDataSource.getDataSourceMapsByMaAppId();  //获取微信小程序所有数据源 DataSourceEntity 对象
               for (int i = 0;dataSourceList!=null&& i < dataSourceList.size(); i++) {
                   DataSourceEntity dataSourceEntity = dataSourceList.get(i);
                   //非托管系统跳过执行
                   if(ScheduleUtils.isOnbusPlatform(dataSourceEntity)){ continue;}
                   try {
                       //一个系统开一个线程
                       threadPoolExecutor.execute(new UpdateStatusForAllOrdersThread(dataSourceEntity ));
                      // Thread.sleep(10000);//暂停10秒,避免过多的并发
                   } catch (Exception e) {
                       e.printStackTrace();
                   }
               }
            }
     }
      /**
       * 更新所有活动单据状态: 已开始 或 已结束
       * @author johnswang
       *
       */
     @Deprecated
     private class UpdateStatusForAllOrdersThread implements Runnable {
            final  DataSourceEntity dataSourceEntity;
            public UpdateStatusForAllOrdersThread(DataSourceEntity dataSourceEntity) {
                this.dataSourceEntity = dataSourceEntity;
            }
            @Override
            public void run() {
                try {
                    String dbid = dataSourceEntity.getDbId() + "";
                    log.info(dataSourceEntity.getSystemDescribe() + " 自动更新小程序活动状态...开始执行");
                    SpObserver.setDBtoInstance("_" + dbid);
                    PanicBuyingIfc panicBuyingIfc = (PanicBuyingIfc) FactoryBean.getBean("PanicBuyingImpl");
                    panicBuyingIfc.updatePanicBuyingStatusBySchedule();
                    log.info(dataSourceEntity.getSystemDescribe() + " 自动更新小程序活动状态...结束执行");
                }catch (RuntimeException r){
                 throw r;
                }catch (Exception ex){
                    ex.printStackTrace();
                    log.info(dataSourceEntity.getSystemDescribe()+":"+ (ex.getCause()!=null?ex.getCause().getMessage():  ex.getMessage()));
                }finally {
                    SpObserver.setDBtoInstance();
                }
            }
      }
}
src/com/yc/sdk/shopping/action/jiazhuang/task/PanicBuyingTaskIfc.java
New file
@@ -0,0 +1,57 @@
package com.yc.sdk.shopping.action.jiazhuang.task;
import com.yc.entity.DataSourceEntity;
import com.yc.sdk.shopping.entity.PanicBuyingEntity;
import com.yc.sdk.shopping.entity.PanicBuyingOrderEntity;
public interface PanicBuyingTaskIfc {
    /**
     * 为每个单据设一个定时任务,到时间则更新他的状态为“进行中”或“已结束”
     * @param dataSourceEntity
     * @param panicBuyingEntity
     */
    public void addStatusTask(DataSourceEntity dataSourceEntity, PanicBuyingEntity  panicBuyingEntity);
    /**
     * 为每个单据设一个定时任务,到时间则更新他的状态为“进行中”或“已结束”
     * @param dataSourceEntity
     * @param docCode
     */
    public void addStatusTask(DataSourceEntity dataSourceEntity, String docCode);
    /**
     * 取消到期未支付的活动订单,将活动订单状态改为 -200
     * @param dataSourceEntity
     * @param panicBuyingOrderEntity
     */
    public void addCancelOrderTaskForPayingExpired(DataSourceEntity dataSourceEntity,
            PanicBuyingOrderEntity panicBuyingOrderEntity);
    /**
     * 取消到期未支付的活动订单,将活动订单状态改为 -200
     * @param dataSourceEntity
     * @param docCode
     */
    public void addCancelOrderTaskForPayingExpired(DataSourceEntity dataSourceEntity, String docCode);
    /**
     * 获取到期未支付的活动订单的 “任务名字”
     * @param dbId
     * @param docCode
     * @return
     */
    public String getTaskNameForPayingExpiredDate(Integer dbId, String docCode);
    /**
     * 停止单个任务
     * @param taskName
     */
    public void stopTask(String taskName);
    /**
     * 停止所有任务
     */
    public void stopAllTask();
}
src/com/yc/sdk/shopping/action/jiazhuang/task/PanicBuyingTaskTest.java
New file
@@ -0,0 +1,81 @@
package com.yc.sdk.shopping.action.jiazhuang.task;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.yc.action.BaseAction;
import com.yc.entity.DataSourceEntity;
import com.yc.multiData.MultiDataSource;
import com.yc.multiData.SpObserver;
import com.yc.sdk.shopping.entity.PanicBuyingEntity;
@Controller
@RequestMapping("/shopping/panicBuyingTaskTest.do")
public class PanicBuyingTaskTest  extends BaseAction {
    @Autowired
    PanicBuyingTaskIfc panicBuyingTaskIfc ;
    @RequestMapping(params = "m=startCron")
    public void getAddressList(HttpServletRequest request, HttpServletResponse response) {
        JsonObject json = new JsonObject();
        JsonObject errJson = new JsonObject();
        String docCode = request.getParameter("doccode");
        try {
            DataSourceEntity dataSourceEntity = MultiDataSource.getDataSourceMap( request) ;
            SpObserver.setDBtoInstance("_"+dataSourceEntity.getDbId());//切换数据源
            PanicBuyingEntity panicBuyingEntity = new PanicBuyingEntity();
            panicBuyingEntity.setDocCode(docCode);
            panicBuyingTaskIfc.addStatusTask(dataSourceEntity, panicBuyingEntity);
            json.addProperty("state", "success");
            this.printJson(response, json.toString());
            return;
        }catch(DataAccessException e ) {
            errJson.addProperty("warning", e.getCause() != null ?e.getCause().getMessage():e.getMessage());
            json.add("error", errJson);
            this.printJson(response, json.toString());
            return;
        }catch(Exception e){
            errJson.addProperty("warning", (e.getCause()!=null?e.getCause().getMessage(): e.getMessage()));
            json.add("error", errJson);
            this.printJson(response, json.toString());
            return;
        }finally {
            SpObserver.setDBtoInstance();
        }
    }
    @RequestMapping(params = "m=getTaskList")
    public void getTaskList(HttpServletRequest request, HttpServletResponse response) {
        JsonObject json = new JsonObject();
        JsonObject errJson = new JsonObject();
        try {
            JsonArray jsonArray = new JsonArray();
            PanicBuyingTask.task.forEach((taskName, future) -> {
                //System.out.println(key + ":" + value);
                jsonArray.add(taskName);
            });
            json.add("list", jsonArray);
            json.addProperty("state", "success");
            this.printJson(response, json.toString());
            return;
        }catch(DataAccessException e ) {
            errJson.addProperty("warning", e.getCause() != null ?e.getCause().getMessage():e.getMessage());
            json.add("error", errJson);
            this.printJson(response, json.toString());
            return;
        }catch(Exception e){
            errJson.addProperty("warning", (e.getCause()!=null?e.getCause().getMessage(): e.getMessage()));
            json.add("error", errJson);
            this.printJson(response, json.toString());
            return;
        }
    }
}
src/com/yc/sdk/shopping/entity/PanicBuyingOrderEntity.java
@@ -44,7 +44,8 @@
    private Date postDate = null ;
    private Integer isAllowPayable = 0 ;  //是否可支付 isAllowPayable 状态: 0.不能支付,1.可支付,2.已支付 ,3.正在退款,4.已退款,5.无需支付
    private Date preSendDate ;
    private Long payableSecondBalance ;
    private Long payableSecondBalance ;   //支付到计时秒数
    private Date payingExpiredDate;  //支付过期时间
    private String deliveryMethod ;
    private Integer heXiaoStatus ;
    private String heXiaoStatusName ;
src/com/yc/sdk/shopping/entity/SettingEntity.java
@@ -228,6 +228,16 @@
    private boolean isShowElectronicVoucherButton ; //是否显示电子兑换劵
    private Double personalAuthenticationAmount ; //个人认证金额
    
    private Integer paymentCountdown ;  //支付倒计时分钟
    public Integer getPaymentCountdown() {
        return paymentCountdown;
    }
    public void setPaymentCountdown(Integer paymentCountdown) {
        this.paymentCountdown = paymentCountdown;
    }
    public Double getPersonalAuthenticationAmount() {
        return personalAuthenticationAmount;
    }
src/com/yc/sdk/shopping/filter/TaskFilter.java
New file
@@ -0,0 +1,39 @@
package com.yc.sdk.shopping.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.yc.factory.FactoryBean;
import com.yc.sdk.shopping.action.jiazhuang.task.PanicBuyingTaskIfc;
@Component
public class TaskFilter  implements Filter {
    private  final Logger log = LoggerFactory.getLogger(this.getClass());
    @Override
    public void doFilter(ServletRequest rep, ServletResponse resp,
            FilterChain chain) throws IOException, ServletException {
    }
    @Override
    public void destroy() {
        PanicBuyingTaskIfc panicBuyingTaskIfc = (PanicBuyingTaskIfc) FactoryBean.getBean("PanicBuyingTask");
        panicBuyingTaskIfc.stopAllTask();
        System.out.println("----------定时任务服务已停止----------");
    }
    @Override
    public void init(FilterConfig arg0) throws ServletException {
        System.out.println("----------定时任务服务已启动----------");
    }
}
src/com/yc/sdk/shopping/service/SettingImpl.java
@@ -139,7 +139,7 @@
                + " a.ParallelNumberForInnerMenuOnHomePage,a.isShowPoster,a.isAllowSelectDeliveryMethod,a.DeliveryMethod,\n"
                + " a.isShowLiveBannerPhotoOnHomePage,a.LiveBannerPhoto,a.isShowBannerPhotoOnHomePageForLiveUser, \n"
                + " a.isStartupPriceSubsystem,a.PriceSubsystemMemberLevels,a.isStartupBalancePay,\n"
                + " a.isShowBuyingButton,a.isShowElectronicVoucherButton,a.PersonalAuthenticationAmount \n"
                + " a.isShowBuyingButton,a.isShowElectronicVoucherButton,a.PersonalAuthenticationAmount,a.PaymentCountdown \n"
                + " from t714001 a left join t110601 b on a.DefaultShopCcCode = b.CcCode  \n"
                + " left join t714030 c on a.CountryId = c.CountryId \n"
                + " left join t110202 d on a.ProvinceZoneId = d.ZoneId \n" 
@@ -418,6 +418,7 @@
            set.setShowBuyingButton(map.get("isShowBuyingButton") != null &&map.get("isShowBuyingButton").equals(1)?true:false );
            set.setShowElectronicVoucherButton(map.get("isShowElectronicVoucherButton") != null &&map.get("isShowElectronicVoucherButton").equals(1)?true:false );
            set.setPersonalAuthenticationAmount(map.get("PersonalAuthenticationAmount") == null ? 0L : Double.parseDouble(map.get("PersonalAuthenticationAmount").toString()));
            set.setPaymentCountdown(map.get("PaymentCountdown") == null ? 0: (Integer)map.get("PaymentCountdown"));
            
            //取小程序订单提醒消息
            sql = " set nocount on \n"
src/com/yc/sdk/shopping/service/panicBuying/PanicBuyingIfc.java
@@ -178,5 +178,27 @@
     * 更新活动状态(作业自动执行,每隔1分钟执行一次)
     * @return
     */
    public Integer updatePanicBuyingStatueBySchedule();
    public Integer updatePanicBuyingStatusBySchedule();
    /**
     * 根据活动的开始时间或结束时间更新状态
     * @param docCode
     * @param  isUpdateEffectiveStartDate 是否按开始时间更新状态
     * @return
     */
    public Integer updateStatusByEffectiveDate(String docCode,boolean isUpdateEffectiveStartDate);
    /**
     * 获取活动列表给更新活动状态的任务使用
     * @return
     */
    public List<PanicBuyingEntity> getPanicBuyingByTask();
    /**
     * 获取活动明细给更新活动状态的任务使用
     * @param docCode
     * @return
     */
    public PanicBuyingEntity getPanicBuyingHeaderByTask(String docCode);
}
src/com/yc/sdk/shopping/service/panicBuying/PanicBuyingImpl.java
@@ -518,6 +518,78 @@
        
    }
    
    @Override
    public List<PanicBuyingEntity> getPanicBuyingByTask() {
        String sql = " set nocount on \n"
                + " declare @now datetime = getdate() \n"
                + " select a.DocCode,a.FormId,a.DocDate,a.CompanyId,a.CompanyName,a.DocStatus,a.DocType,a.EnterCode,a.EnterName,\n"
                + "        a.EnterDate,a.ModifyName,a.ModifyDate,a.Status,a.CcCode,a.Title,a.CoverImage,a.CoverImageUrl,a.OriginalPrice,a.SalesPrice,\n"
                + "        a.NumberOfTeam,a.EffectiveStartDate,a.EffectiveEndDate,\n"
                + "     DATEDIFF(second,@now,a.EffectiveStartDate) as EffectiveStartDateBalance,\n"
                + "     DATEDIFF(second,@now,a.EffectiveEndDate) as EffectiveEndDateBalance \n"
                + " from t710802H a \n"
                + " where a.DocStatus = 100 and a.EffectiveStartDate <= @now and a.Status = 1 \n"
                + " union \n"
                + " select a.DocCode,a.FormId,a.DocDate,a.CompanyId,a.CompanyName,a.DocStatus,a.DocType,a.EnterCode,a.EnterName,\n"
                + "        a.EnterDate,a.ModifyName,a.ModifyDate,a.Status,a.CcCode,a.Title,a.CoverImage,a.CoverImageUrl,a.OriginalPrice,a.SalesPrice,\n"
                + "        a.NumberOfTeam,a.EffectiveStartDate,a.EffectiveEndDate,\n"
                + "     DATEDIFF(second,@now,a.EffectiveStartDate) as EffectiveStartDateBalance,\n"
                + "     DATEDIFF(second,@now,a.EffectiveEndDate) as EffectiveEndDateBalance \n"
                + " from t710802H a \n"
                + " where a.DocStatus = 100 and a.EffectiveEndDate <= @now and a.Status = 2 \n" ;
        try {
            List<Map<String, Object>> list = this.jdbcTemplate.queryForList(sql, new Object[] {}) ;
            List<PanicBuyingEntity> panicBuyingList = new ArrayList<PanicBuyingEntity>();
            for (int i = 0;list!= null && i < list.size(); i++) {
                Map<String, Object> map = list.get(i) ;
                panicBuyingList.add(getPanicBuyingEntity(map)) ;
            }
            return panicBuyingList ;
        }catch(DataAccessException e ) {
            if (e instanceof EmptyResultDataAccessException){
                return null ;
            }else {
                 throw e ;
            }
        }catch(Exception e){
            e.printStackTrace();
            throw e;
        }
    }
    @Override
    public PanicBuyingEntity getPanicBuyingHeaderByTask(String docCode) {
        String sql = " set nocount on \n"
                + " declare @now datetime = getdate(),@DocCode varchar(20) = ? \n"
                + " select a.DocCode,a.FormId,a.DocDate,a.CompanyId,a.CompanyName,a.DocStatus,a.DocType,a.EnterCode,a.EnterName,\n"
                + "        a.EnterDate,a.ModifyName,a.ModifyDate,a.Status,a.CcCode,a.Title,a.CoverImage,a.CoverImageUrl,a.OriginalPrice,a.SalesPrice,\n"
                + "        a.NumberOfTeam,a.EffectiveStartDate,a.EffectiveEndDate,\n"
                + "     DATEDIFF(second,@now,a.EffectiveStartDate) as EffectiveStartDateBalance,\n"
                + "     DATEDIFF(second,@now,a.EffectiveEndDate) as EffectiveEndDateBalance \n"
                + " from t710802H a \n"
                + " where a.DocCode = @DocCode  \n" ;
        try {
            Map<String, Object> map = this.jdbcTemplate.queryForMap(sql, new Object[] {docCode}) ;
            if (map !=null) {
                return getPanicBuyingEntity(map) ;
            }else {
                return null;
            }
        }catch(DataAccessException e ) {
            if (e instanceof EmptyResultDataAccessException){
                return null ;
            }else {
                 throw e ;
            }
        }catch(Exception e){
            e.printStackTrace();
            throw e;
        }
    }
    
    @Override
    public PanicBuyingEntity saveSharedTraceRecord(String refCode,String openId) {
@@ -827,7 +899,39 @@
    }
    
    @Override
    public Integer updatePanicBuyingStatueBySchedule() {
    public Integer updateStatusByEffectiveDate(String docCode,boolean isUpdateEffectiveStartDate) {
        String sql = " set nocount on \n"
                + " declare @DocCode varchar(20) = ?,@now datetime = getdate() \n"
                + " declare @myrowcount int \n";
        if (isUpdateEffectiveStartDate) {
            sql += " update a set Status = 2 from t710802H a \n"
                + " where a.DocCode = @DocCode and a.DocStatus = 100 \n"
                + " and a.EffectiveStartDate <= @now and a.Status = 1 \n";
        }else {
            sql +=  " update a set Status = 3 from t710802H a \n"
                + " where a.DocCode = @DocCode and a.DocStatus = 100 \n"
                + " and a.EffectiveEndDate <= @now and a.Status = 2 \n";
        }
        sql +=  " set @myrowcount = isnull(@myrowcount,0) + @@rowcount \n"
            + " select @myrowcount as myrowcount \n" ;
        try {
            Integer ret = this.jdbcTemplate.queryForObject(sql, new Object[] {docCode},Integer.class) ;
            return ret ;
        }catch(DataAccessException e ) {
            if (e instanceof EmptyResultDataAccessException){
                return null ;
            }else {
                 throw e ;
            }
        }catch(Exception e){
            e.printStackTrace();
            throw e;
        }
    }
    @Override
    public Integer updatePanicBuyingStatusBySchedule() {
        String sql = " set nocount on \n"
                + " declare @now datetime = getdate() \n"
                + " declare @myrowcount int \n"
src/com/yc/sdk/shopping/service/panicBuying/PanicBuyingOrderIfc.java
@@ -139,14 +139,20 @@
     * 取消支付已过期的所有订单
     * @return
     */
    public Integer deleteExpiredOrder();
    public Integer deletePayingExpiredOrder();
    /**
     * 取消待支付单个订单
     * @param docCode
     * @return
     */
    public Integer deleteExpiredOrder(String docCode);
    public Integer deletePayingExpiredOrder(String docCode);
    /**
     * 取起草状态的订单,如果已经支付过期,则立即将它改为 -200 状态,如果还未过期,则加入排期任务,到点时再执行“过期”程序
     * @return
     */
    public List<PanicBuyingOrderEntity> getOrderHeaderListForPayingExpired();
}
src/com/yc/sdk/shopping/service/panicBuying/PanicBuyingOrderImpl.java
@@ -374,11 +374,6 @@
    public List<PanicBuyingOrderEntity> getOrderHeaderListForMe(String cltCode) {
        String sql = " set nocount on \n"
                + " declare  @UserCode varchar(50) = ? \n" 
                + " declare @GenerateOrderProcess int ,@PaymentCountdown int = 30 \n"
                + " declare @DefaultShopCcCode varchar(50),@isStartupLeagueShopCcCode int \n"
                + " select @GenerateOrderProcess = GenerateOrderProcess,@PaymentCountdown = isnull(PaymentCountdown,0), \n"
                + "     @DefaultShopCcCode = DefaultShopCcCode ,@isStartupLeagueShopCcCode = isStartupLeagueShopCcCode \n"
                + " from t714001 \n"
                + " select a.DocCode,a.FormID,a.DocDate,a.DocType,a.RefCode,a.RefFormId,a.RefFormType,a.CcCode,a.CcName,a.CltCode,a.CltCode, \n" 
                + "    a.CltName,a.LinkMan,a.Telephone,a.PropertyAddress,a.FullAddress,a.FullAddressName,a.Street,\n" 
@@ -388,7 +383,8 @@
                + "       b.BalancePayAmount,b.WeiXinPayAmount, \n" 
                + "       a.EnterCode,a.EnterName ,a.EnterDate,a.PostCode,a.PostName,a.PostDate,\n" 
                + "       a.isAllowPayable,a.PreSendDate, \n" 
                + "       DATEDIFF(SECOND,getdate(),  DATEADD(MINUTE,@PaymentCountdown,a.EnterDate))  as PayableSecondBalance,\n"
                + "       DATEDIFF(SECOND,getdate(), a.PayingExpiredDate)  as PayableSecondBalance,\n"
                + "    a.PayingExpiredDate, \n"
                + "       a.DeliveryMethod,\n"
                + "    case when isnull(a.Digit,0) <> 0 and isnull(a.Digit,0) = isnull(a.HeXiaoDigit,0) then 1 else 0 end as HeXiaoStatus, \n"
                + "       case when isnull(a.Digit,0) <> 0 and isnull(a.Digit,0) = isnull(a.HeXiaoDigit,0) then '已核销' else '待核销' end as HeXiaoStatusName, \n"
@@ -436,15 +432,9 @@
    
    @Override
    public List<PanicBuyingOrderEntity> getOrderHeaderListForPanicBuyingDocCode(String panicByingDocCode,String searchKey) {
    public List<PanicBuyingOrderEntity> getOrderHeaderListForPayingExpired() {
        String sql = " set nocount on \n"
                + " declare  @PanicByingDocCode varchar(50) = ?,@SearchKey varchar(50) = ? \n"
                + " declare @GenerateOrderProcess int ,@PaymentCountdown int = 30 \n"
                + " declare @DefaultShopCcCode varchar(50),@isStartupLeagueShopCcCode int \n"
                + " select @GenerateOrderProcess = GenerateOrderProcess,@PaymentCountdown = isnull(PaymentCountdown,0), \n"
                + "     @DefaultShopCcCode = DefaultShopCcCode ,@isStartupLeagueShopCcCode = isStartupLeagueShopCcCode \n"
                + " from t714001 \n"
                + " declare @now datetime = getdate() \n"
                + " select a.DocCode,a.FormID,a.DocDate,a.DocType,a.RefCode,a.RefFormId,a.RefFormType,a.CcCode,a.CcName,a.CltCode,a.CltCode, \n" 
                + "    a.CltName,a.LinkMan,a.Telephone,a.PropertyAddress,a.FullAddress,a.FullAddressName,a.Street,\n" 
                + "       a.Digit,a.Price,a.Amount,a.TransCosts,a.ReduceMoney,a.HandlingCharges,a.PayableAmount,  \n" 
@@ -453,7 +443,69 @@
                + "       b.BalancePayAmount,b.WeiXinPayAmount, \n" 
                + "       a.EnterCode,a.EnterName ,a.EnterDate,a.PostCode,a.PostName,a.PostDate,\n" 
                + "       a.isAllowPayable,a.PreSendDate, \n" 
                + "       DATEDIFF(SECOND,getdate(),  DATEADD(MINUTE,@PaymentCountdown,a.EnterDate))  as PayableSecondBalance,\n"
                + "       DATEDIFF(SECOND,@now,  a.PayingExpiredDate)  as PayableSecondBalance,\n"
                + "    a.PayingExpiredDate, \n"
                + "       a.DeliveryMethod,\n"
                + "    case when isnull(a.Digit,0) <> 0 and isnull(a.Digit,0) = isnull(a.HeXiaoDigit,0) then 1 else 0 end as HeXiaoStatus, \n"
                + "       case when isnull(a.Digit,0) <> 0 and isnull(a.Digit,0) = isnull(a.HeXiaoDigit,0) then '已核销' else '待核销' end as HeXiaoStatusName, \n"
                + "    e.Title,e.CoverImage,e.CoverImageUrl,e.OriginalPrice,e.SalesPrice,\n"
                + "       e.NumberOfTeam,e.EffectiveStartDate,e.EffectiveEndDate,\n"
                + "    DATEDIFF(second,@now,e.EffectiveStartDate) as EffectiveStartDateBalance,\n"
                + "    DATEDIFF(second,@now,e.EffectiveEndDate) as EffectiveEndDateBalance,\n"
                + "    e.Quantity,e.RestrictBuyingQuantity,e.FreeId,f.FreeName,f.isRequiredAddress,e.TransCosts,e.Description,e.Images,e.ImagesUrl,\n"
                + "    e.Status as PanicBuyingStatus,e.VisiteTimes,e.SharedTimes,e.OrderTimes,a.SellerId,a.SellerName,a.SellerTelephone, \n"
                + "    a.OpenId,g.WeiXinAvatarUnid,g.Headimgurl,a.TuiHuoRuKuDigit,a.QrCode \n"
                + " from t710806H a  \n"
                + " left join (select a.doccode ,sum(case when a.PayType = '2' then isnull(a.PayAmount,0) else 0 end) as BalancePayAmount, \n"
                + "     sum(case when a.PayType = '1' then isnull(a.PayAmount,0) else 0 end )  as WeiXinPayAmount \n"
                + "     from t710806D a join t710806H b on a.DocCode = b.DocCode \n"
                + "     where b.DocStatus = 0 \n"
                + "     group by a.doccode ) b on a.DocCode = b.DocCode \n"
                + " left join t110703 c on a.hdcurrency = c.currency \n"
                + " join t110203 d on a.CltCode = d.CltCode  \n"
                + " left join t710802H e on a.RefCode = e.DocCode \n"
                + " left join t714034 f on a.FreeId = f.FreeId \n"
                + " left join t730102 g on a.OpenId = g.OpenId"
                + " where a.DocStatus = 0  \n"
                + " order by a.DocDate desc,a.DocCode desc ; \n";
        List<Map<String,Object>> list = null ;
        try {
            list =  this.jdbcTemplate.queryForList(sql,new Object[] { } ) ;
            List<PanicBuyingOrderEntity> orderList = new ArrayList<PanicBuyingOrderEntity>();
            for (int i = 0;list!=null&& i < list.size(); i++) {
                orderList.add(getPanicBuyingOrderEntity(list.get(i)));
            }
            return orderList ;
        }catch(DataAccessException e ) {
            if (e instanceof EmptyResultDataAccessException){
                return null ;
            }else {
                 throw e ;
            }
        }catch(Exception e){
            e.printStackTrace();
            throw e;
        }
    }
    @Override
    public List<PanicBuyingOrderEntity> getOrderHeaderListForPanicBuyingDocCode(String panicByingDocCode,String searchKey) {
        String sql = " set nocount on \n"
                + " declare  @PanicByingDocCode varchar(50) = ?,@SearchKey varchar(50) = ? \n"
                + " select a.DocCode,a.FormID,a.DocDate,a.DocType,a.RefCode,a.RefFormId,a.RefFormType,a.CcCode,a.CcName,a.CltCode,a.CltCode, \n"
                + "    a.CltName,a.LinkMan,a.Telephone,a.PropertyAddress,a.FullAddress,a.FullAddressName,a.Street,\n"
                + "       a.Digit,a.Price,a.Amount,a.TransCosts,a.ReduceMoney,a.HandlingCharges,a.PayableAmount,  \n"
                + "       a.DocStatusName,a.HDCurrency,c.Meno as CurrencySign,c.CurrencyIsoCode, \n"
                + "       d.Email,a.HDMemo,a.DocStatus, \n"
                + "       b.BalancePayAmount,b.WeiXinPayAmount, \n"
                + "       a.EnterCode,a.EnterName ,a.EnterDate,a.PostCode,a.PostName,a.PostDate,\n"
                + "       a.isAllowPayable,a.PreSendDate, \n"
                + "       DATEDIFF(SECOND,getdate(),  a.PayingExpiredDate)  as PayableSecondBalance,\n"
                + "    a.PayingExpiredDate, \n"
                + "       a.DeliveryMethod,\n"
                + "    case when isnull(a.Digit,0) <> 0 and isnull(a.Digit,0) = isnull(a.HeXiaoDigit,0) then 1 else 0 end as HeXiaoStatus, \n"
                + "       case when isnull(a.Digit,0) <> 0 and isnull(a.Digit,0) = isnull(a.HeXiaoDigit,0) then '已核销' else '待核销' end as HeXiaoStatusName, \n"
@@ -548,6 +600,7 @@
        orderEntity.setIsAllowPayable(map.get("isAllowPayable")== null?0:(Integer)map.get("isAllowPayable") );
        orderEntity.setPreSendDate(map.get("PreSendDate")== null?null:(Date)map.get("PreSendDate") );
        orderEntity.setPayableSecondBalance(map.get("PayableSecondBalance")== null?0L:(Long.parseLong( map.get("PayableSecondBalance").toString())) );
        orderEntity.setPayingExpiredDate(map.get("PayingExpiredDate")== null?null:(Date) map.get("PayingExpiredDate"));
        orderEntity.setDeliveryMethod(map.get("DeliveryMethod")== null?"":(String)map.get("DeliveryMethod")  );
        orderEntity.setHeXiaoStatus(map.get("HeXiaoStatus")== null?0:(Integer)map.get("HeXiaoStatus")  );
        orderEntity.setHeXiaoStatusName(map.get("HeXiaoStatusName")== null?"":(String)map.get("HeXiaoStatusName")  );
@@ -624,12 +677,6 @@
    public PanicBuyingOrderEntity getOrderHeaderEntity(String docCode) {
        String sql = " set nocount on \n"
                + " declare  @DocCode varchar(50) = ? \n" 
                + " declare @GenerateOrderProcess int ,@PaymentCountdown int = 30 \n"
                + " declare @DefaultShopCcCode varchar(50),@isStartupLeagueShopCcCode int \n"
                + " select @GenerateOrderProcess = GenerateOrderProcess,@PaymentCountdown = isnull(PaymentCountdown,0), \n"
                + "     @DefaultShopCcCode = DefaultShopCcCode ,@isStartupLeagueShopCcCode = isStartupLeagueShopCcCode \n"
                + " from t714001 \n"
                + " select a.DocCode,a.FormID,a.DocDate,a.DocType,a.RefCode,a.RefFormId,a.RefFormType,a.CcCode,a.CcName,a.CltCode, \n" 
                + "    a.CltName,a.LinkMan,a.Telephone,a.PropertyAddress,a.FullAddress,a.FullAddressName,a.Street,\n" 
                + "       a.Digit,a.Price,a.Amount,a.TransCosts,a.ReduceMoney,a.HandlingCharges,a.PayableAmount,  \n" 
@@ -638,7 +685,8 @@
                + "       b.BalancePayAmount,b.WeiXinPayAmount, \n" 
                + "       a.EnterCode,a.EnterName ,a.EnterDate,a.PostCode,a.PostName,a.PostDate,\n" 
                + "       a.isAllowPayable,a.PreSendDate, \n" 
                + "       DATEDIFF(SECOND,getdate(),  DATEADD(MINUTE,@PaymentCountdown,a.EnterDate))  as PayableSecondBalance,\n"
                + "       DATEDIFF(SECOND,getdate(),  a.PayingExpiredDate)  as PayableSecondBalance,\n"
                + "    a.PayingExpiredDate, \n"
                + "       a.DeliveryMethod,\n"
                + "    case when isnull(a.Digit,0) <> 0 and isnull(a.Digit,0) = isnull(a.HeXiaoDigit,0) then 1 else 0 end as HeXiaoStatus, \n"
                + "       case when isnull(a.Digit,0) <> 0 and isnull(a.Digit,0) = isnull(a.HeXiaoDigit,0) then '已核销' else '待核销' end as HeXiaoStatusName, \n"
@@ -681,28 +729,17 @@
    }
    
    @Override
    public Integer deleteExpiredOrder(String docCode) {
    public Integer deletePayingExpiredOrder(String docCode) {
        String sql = " set nocount on \n"
                + " declare @DocCode varchar(20) = ?,@DocStatus int \n"
                + " declare @PaymentCountdown int = 30 ,@myrowcount int \n"
                + " declare @DocCode varchar(20),@RefCode varchar(20),@RefFormId int,@Digit money \n"
                + " select @PaymentCountdown = isnull(PaymentCountdown,0) from t714001 \n"
                + " declare cancelOrderCur cursor for \n"
                + " select @RefCode = a.RefCode,@RefFormId = a.RefFormId,@Digit = a.Digit , @DocStatus = a.DocStatus \n"
                + " declare @RefCode varchar(20),@RefFormId int,@Digit money , @PayableSecondBalance bigint \n"
                + " select @RefCode = a.RefCode,@RefFormId = a.RefFormId,@Digit = a.Digit , @DocStatus = a.DocStatus, \n"
                + "    @PayableSecondBalance = DATEDIFF(SECOND,getdate(),  a.PayingExpiredDate ) \n"
                + " from t710806H a \n"
                + " where a.DocCode = @DocCode \n"
                //+ " and DATEDIFF(SECOND,getdate(),  DATEADD(MINUTE,@PaymentCountdown,a.EnterDate)) <=0 \n"
                + " if isnull(@DocStatus,0) = -200 \n"
                + " begin \n"
                + "     raiserror('已取消',16,1) \n"
                + "     return \n"
                + " end \n"
                + " if isnull(@DocStatus,0) = 100 \n"
                + " begin \n"
                + "     raiserror('订单已支付,不能取消',16,1) \n"
                + "     return \n"
                + " end \n"
                + " if isnull(@DocStatus,0) = 0 \n"
                + " if isnull(@DocStatus,0) = 0 and isnull(@PayableSecondBalance,0) <=0 \n"
                + "    and not exists(select 1 from t151705H a where a.OutTradeNo = @DocCode ) \n"
                + " begin \n"
                + "    if isnull(@RefFormId,0) = 710802 \n"
                + "    begin \n"
@@ -730,27 +767,28 @@
    }
    
    @Override
    public Integer deleteExpiredOrder() {
    public Integer deletePayingExpiredOrder() {
        String sql = " set nocount on \n"
                + " declare @PaymentCountdown int = 30 ,@myrowcount int \n"
                + " declare @DocCode varchar(20),@RefCode varchar(20),@RefFormId int,@Digit money \n" 
                + " select @PaymentCountdown = isnull(PaymentCountdown,0) from t714001 \n"
                + " declare cancelOrderCur cursor for \n"
                + " select a.DocCode ,a.RefCode,a.RefFormId,a.Digit \n"
                + " from t710806H a \n"
                + " where a.DocStatus = 0 \n"
                + " and DATEDIFF(SECOND,getdate(),  DATEADD(MINUTE,@PaymentCountdown,a.EnterDate)) <=0 \n"
                + " and DATEDIFF(SECOND,getdate(),  a.PayingExpiredDate) <=0 \n"
                + " open cancelOrderCur \n"
                + " fetch next from cancelOrderCur into @DocCode , @RefCode ,@RefFormId, @Digit \n"
                + " while @@fetch_status = 0 \n"
                + " begin \n"
                + "    if isnull(@RefFormId,0) = 710802 \n"
                + "    if  not exists(select 1 from t151705H a where a.OutTradeNo = @DocCode ) \n"
                + "    begin \n"
                + "       update a set Quantity = isnull(a.Quantity,0) - isnull(@Digit,0) \n"
                + "       from t710802H a where a.DocCode = @RefCode \n"
                + "       if isnull(@RefFormId,0) = 710802 \n"
                + "       begin \n"
                + "          update a set Quantity = isnull(a.Quantity,0) - isnull(@Digit,0) \n"
                + "          from t710802H a where a.DocCode = @RefCode \n"
                + "       end \n"
                + "       update a set DocStatus = -200 from t710806H a where a.DocCode = @DocCode \n"
                + "       select @myrowcount = isnull(@myrowcount,0) + 1 \n]"
                + "    end \n"
                + "    update a set DocStatus = -200 from t710806H a where a.DocCode = @DocCode \n"
                + "    select @myrowcount = isnull(@myrowcount,0) + 1 \n"
                + "    fetch next from cancelOrderCur into @DocCode , @RefCode , @RefFormId,@Digit"
                + " end \n"
                + " close cancelOrderCur \n"
@@ -891,8 +929,6 @@
                + " declare @AccountsReceivableAcctCode varchar(20),@FeeAmountAcctCode varchar(20)\n" 
                + " declare @Balance money ,@msg varchar(2000)\n" 
                + " declare @myrowcount int ,@myerror int \n"
                + " declare @PaymentCountdown int = 30 ,@PayableSecondBalance bigint \n"
                + " select @PaymentCountdown = isnull(PaymentCountdown,0) from t714001 \n"
                + " select @AccountsReceivableAcctCode = AccountsReceivableAcctCode ,\n" 
                + "       @FeeAmountAcctCode=BankCostAcctCode  \n" 
                + " from t111601 \n" 
@@ -903,7 +939,7 @@
                + " end \n" 
                + " select @currency=a.hdcurrency ,@CltCode = a.CltCode , @CompanyId = a.CompanyId, \n"
                + "   @PayableSecondBalance = DATEDIFF(SECOND,getdate(),  DATEADD(MINUTE,@PaymentCountdown,a.EnterDate)) \n"
                + "   @PayableSecondBalance = DATEDIFF(SECOND,getdate(),  a.PayingExpiredDate ) \n"
                + " from t710806H a \n" 
                + " where doccode = @DocCode\n" 
                + " select @myrowcount = @@ROWCOUNT ,@myerror = @@ERROR \n"