admin
2019-11-20 8b2191df2f7d94aa299bd43dcbe97c94e5a61bbd
fanli/src/main/java/com/yeshi/fanli/service/impl/order/OrderProcessServiceImpl.java
@@ -2,7 +2,6 @@
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
@@ -10,24 +9,38 @@
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.yeshi.utils.NumberUtil;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.Producer;
import com.aliyun.openservices.ons.api.SendResult;
import com.aliyun.openservices.ons.api.transaction.LocalTransactionExecuter;
import com.aliyun.openservices.ons.api.transaction.TransactionProducer;
import com.aliyun.openservices.ons.api.transaction.TransactionStatus;
import com.google.gson.Gson;
import com.yeshi.fanli.dao.mybatis.HongBaoV2Mapper;
import com.yeshi.fanli.dao.mybatis.UserInfoMapper;
import com.yeshi.fanli.dao.mybatis.money.UserMoneyDetailMapper;
import com.yeshi.fanli.dao.mybatis.order.HongBaoOrderMapper;
import com.yeshi.fanli.dao.mybatis.order.OrderMapper;
import com.yeshi.fanli.dao.mybatis.taobao.TaoBaoWeiQuanOrderMapper;
import com.yeshi.fanli.dto.HongBao;
import com.yeshi.fanli.dto.mq.order.OrderTopicTagEnum;
import com.yeshi.fanli.dto.mq.order.body.OrderMQMsg;
import com.yeshi.fanli.dto.mq.order.body.OrderMoneyRecievedMQMsg;
import com.yeshi.fanli.dto.order.CommonOrderAddResultDTO;
import com.yeshi.fanli.entity.bus.user.HongBaoV2;
import com.yeshi.fanli.entity.bus.user.Order;
import com.yeshi.fanli.entity.bus.user.UserExtraTaoBaoInfo;
import com.yeshi.fanli.entity.bus.user.UserInfo;
import com.yeshi.fanli.entity.elme.ElmeHongBaoOrderMap;
import com.yeshi.fanli.entity.elme.ElmeOrder;
import com.yeshi.fanli.entity.jd.JDOrder;
import com.yeshi.fanli.entity.jd.JDOrderItem;
import com.yeshi.fanli.entity.money.UserMoneyDetail;
@@ -39,35 +52,45 @@
import com.yeshi.fanli.entity.taobao.TaoBaoUnionConfig;
import com.yeshi.fanli.entity.taobao.TaoBaoWeiQuanDrawBack;
import com.yeshi.fanli.entity.taobao.TaoBaoWeiQuanOrder;
import com.yeshi.fanli.exception.HongBaoException;
import com.yeshi.fanli.exception.OrderItemException;
import com.yeshi.fanli.exception.TaoBaoWeiQuanException;
import com.yeshi.fanli.exception.money.OrderMoneySettleException;
import com.yeshi.fanli.exception.money.UserMoneyDetailException;
import com.yeshi.fanli.exception.order.CommonOrderException;
import com.yeshi.fanli.exception.order.HongBaoException;
import com.yeshi.fanli.exception.order.OrderItemException;
import com.yeshi.fanli.exception.order.TaoBaoWeiQuanException;
import com.yeshi.fanli.exception.user.UserAccountException;
import com.yeshi.fanli.log.LogHelper;
import com.yeshi.fanli.service.inter.elme.ElmeHongBaoOrderMapService;
import com.yeshi.fanli.service.inter.elme.ElmeOrderService;
import com.yeshi.fanli.service.inter.hongbao.AccountDetailsHongBaoMapService;
import com.yeshi.fanli.service.inter.hongbao.HongBaoV2Service;
import com.yeshi.fanli.service.inter.msg.UserMoneyMsgNotificationService;
import com.yeshi.fanli.service.inter.money.UserMoneyService;
import com.yeshi.fanli.service.inter.money.msg.UserMoneyMsgNotificationService;
import com.yeshi.fanli.service.inter.money.tb.TaoBaoWeiQuanDrawBackService;
import com.yeshi.fanli.service.inter.order.CommonOrderService;
import com.yeshi.fanli.service.inter.order.HongBaoV2Service;
import com.yeshi.fanli.service.inter.order.LostOrderService;
import com.yeshi.fanli.service.inter.order.OrderMoneySettleService;
import com.yeshi.fanli.service.inter.order.OrderProcessService;
import com.yeshi.fanli.service.inter.order.jd.JDOrderService;
import com.yeshi.fanli.service.inter.order.pdd.PDDOrderService;
import com.yeshi.fanli.service.inter.order.tb.TaoBaoOrderService;
import com.yeshi.fanli.service.inter.taobao.TaoBaoBuyRelationMapService;
import com.yeshi.fanli.service.inter.taobao.TaoBaoOrderService;
import com.yeshi.fanli.service.inter.taobao.TaoBaoUnionConfigService;
import com.yeshi.fanli.service.inter.taobao.TaoBaoWeiQuanDrawBackService;
import com.yeshi.fanli.service.inter.user.UserExtraTaoBaoInfoService;
import com.yeshi.fanli.service.inter.user.UserMoneyService;
import com.yeshi.fanli.service.inter.user.UserSystemCouponService;
import com.yeshi.fanli.service.inter.user.tb.UserExtraTaoBaoInfoService;
import com.yeshi.fanli.util.CMQManager;
import com.yeshi.fanli.util.Constant;
import com.yeshi.fanli.util.MoneyBigDecimalUtil;
import com.yeshi.fanli.util.StringUtil;
import com.yeshi.fanli.util.TaoBaoConstant;
import com.yeshi.fanli.util.TimeUtil;
import com.yeshi.fanli.util.cmq.PlaceOrderCMQManager;
import com.yeshi.fanli.util.factory.UserMoneyDetailFactory;
import com.yeshi.fanli.util.jd.JDApiUtil;
import com.yeshi.fanli.util.pinduoduo.PinDuoDuoApiUtil;
import com.yeshi.fanli.util.taobao.TaoKeOrderApiUtil;
import com.yeshi.fanli.util.rocketmq.MQMsgBodyFactory;
import com.yeshi.fanli.util.rocketmq.MQTagConstant;
import com.yeshi.fanli.util.rocketmq.MQTopicName;
@Service
public class OrderProcessServiceImpl implements OrderProcessService {
@@ -122,6 +145,52 @@
   @Resource
   private HongBaoV2Service hongBaoV2Service;
   @Resource
   private JDOrderService jdOrderService;
   @Resource
   private PDDOrderService pddOrderService;
   @Resource(name = "orderTransactionProducer")
   private TransactionProducer orderTransactionProducer;
   @Resource(name = "producer")
   private Producer producer;
   @Resource
   private OrderMoneySettleService orderMoneySettleService;
   /**
    * 是否是分享订单
    *
    * @param order
    * @return
    */
   private boolean isShareOrder(TaoBaoOrder order) {
      List<TaoBaoUnionConfig> configList = taoBaoUnionConfigService.getConfigByTypeCache(PidUser.TYPE_FANLI_ANDROID);
      String pid = String.format("mm_%s_%s_%s", configList.get(0).getAccountId(), order.getSourceMediaId(),
            order.getAdPositionId());
      if (!StringUtil.isNullOrEmpty(order.getSpecialId())
            || pid.equalsIgnoreCase(TaoBaoConstant.TAOBAO_RELATION_AS_SPECIAL_PID)) {// 设置渠道ID当做会员运营ID的位置ID
         return false;
      } else if (!StringUtil.isNullOrEmpty(order.getRelationId())) {
         return true;
      } else {
         // 通过红包查询
         CommonOrder commonOrder = commonOrderService.selectBySourceTypeAndTradeId(Constant.SOURCE_TYPE_TAOBAO,
               order.getTradeId());
         if (commonOrder != null) {
            HongBaoOrder hongBaoOrder = hongBaoOrderMapper.selectByCommonOrderId(commonOrder.getId());
            if (hongBaoOrder != null && hongBaoOrder.getHongBaoV2() != null
                  && hongBaoOrder.getHongBaoV2().getType() == HongBaoV2.TYPE_SHARE_GOODS) {
               return true;
            }
         }
         return false;
      }
   }
   @Override
   public synchronized void processOrder(Map<String, List<TaoBaoOrder>> orders) {
@@ -227,6 +296,7 @@
   @Override
   public void fanli() {
      LogHelper.test("处理返利到账");
      // 获取主红包
      List<HongBaoV2> hongBaoList = hongBaoV2Mapper.listCanBalanceHongBaoByType(HongBaoV2.TYPE_ZIGOU, 1000);
      //
@@ -293,7 +363,7 @@
      // 查询最新的红包数据
      hb1 = hongBaoV2Mapper.selectByPrimaryKeyForUpdate(hb1.getId());
      // 正常用户才能到账
      UserInfo mainUser = userInfoMapper.selectByPrimaryKey(hb1.getUserInfo().getId());
      UserInfo mainUser = userInfoMapper.selectAvailableByPrimaryKey(hb1.getUserInfo().getId());
      if (mainUser == null || mainUser.getState() != UserInfo.STATE_NORMAL) {
         return;
      }
@@ -304,12 +374,15 @@
         return;
      }
      // 灰度测试中,京东/拼多多不返利
      if (hongBaoOrder.getCommonOrder() == null
            || hongBaoOrder.getCommonOrder().getSourceType() == Constant.SOURCE_TYPE_JD
            || hongBaoOrder.getCommonOrder().getSourceType() == Constant.SOURCE_TYPE_PDD) {
      if (hongBaoOrder.getCommonOrder() == null) {
         return;
      }
      // 如果是拼多多/京东维权则返回,不需要返利
      if ((hongBaoOrder.getCommonOrder().getSourceType() == Constant.SOURCE_TYPE_PDD
            || hongBaoOrder.getCommonOrder().getSourceType() == Constant.SOURCE_TYPE_JD)
            && hongBaoOrder.getCommonOrder().getState() == CommonOrder.STATE_WQ)
         return;
      if (hongBaoOrder.getCommonOrder() != null
            && hongBaoOrder.getCommonOrder().getSourceType() == Constant.SOURCE_TYPE_TAOBAO) {
@@ -325,144 +398,61 @@
            return;
      }
      // 查询同一订单号的红包
      List<CommonOrder> orderList = commonOrderService.listBySourceTypeAndOrderId(
            hongBaoOrder.getCommonOrder().getSourceType(), hongBaoOrder.getCommonOrder().getOrderNo());
      List<HongBaoV2> hongBaoList = new ArrayList<>();
      Map<Long, BigDecimal> userMoney = new HashMap<>();
      Map<Long, List<HongBaoV2>> userHongBao = new HashMap<>();
      Map<Long, Integer> userGoodsCount = new HashMap<>();
      // Map<Long, BigDecimal> userPayMent = new HashMap<>();
      for (CommonOrder co : orderList) {
         hongBaoOrder = hongBaoOrderMapper.selectByCommonOrderId(co.getId());
         hongBaoList.add(hongBaoOrder.getHongBaoV2());
         Long uid = co.getUserInfo().getId();
         if (userGoodsCount.get(uid) == null)
            userGoodsCount.put(uid, co.getCount());
         else
            userGoodsCount.put(uid, Integer.valueOf(co.getCount() + userGoodsCount.get(uid)));
         // if (userPayMent.get(uid) == null)
         // userPayMent.put(uid, new BigDecimal(0));
         // if (co.getState() == CommonOrder.STATE_JS)
         // userPayMent.put(uid,
         // userPayMent.get(uid).add(co.getSettlement()));
         // else
         // userPayMent.put(uid, userPayMent.get(uid).add(co.getPayment()));
      }
      for (HongBaoV2 hb : hongBaoList) {
         long currentTimeMillis = System.currentTimeMillis();
         if (hb.getState() != HongBao.STATE_SHIXIAO) {
            // 设置为已返利
            // 处理主红包
            if (hb.getState() != HongBaoV2.STATE_SHIXIAO && hb.getState() != HongBaoV2.STATE_YILINGQU
                  && hb.getType() == HongBaoV2.TYPE_ZIGOU) {
               // 如果红包没被领取
               Long uid = hb.getUserInfo().getId();
               HongBaoV2 updateHongBao = new HongBaoV2();
               updateHongBao.setId(hb.getId());
               updateHongBao.setState(HongBaoV2.STATE_YILINGQU);
               updateHongBao.setGetTime(new Date(currentTimeMillis));
               hongBaoV2Mapper.updateByPrimaryKeySelective(updateHongBao);
               if (userMoney.get(uid) == null)
                  userMoney.put(uid, hb.getMoney());
               else
                  userMoney.put(uid, userMoney.get(uid).add(hb.getMoney()));
               // 添加红包到用户
               if (userHongBao.get(uid) == null)
                  userHongBao.put(uid, new ArrayList<>());
               userHongBao.get(uid).add(hb);
            }
      // 查询该订单之前是否有到账
      List<HongBaoOrder> list = hongBaoOrderMapper.listByOrderIdAndSourceType(
            hongBaoOrder.getCommonOrder().getOrderNo(), hongBaoOrder.getCommonOrder().getSourceType());
      List<Long> hongBaoIdList = new ArrayList<>();
      if (list != null) {
         for (HongBaoOrder ho : list) {
            hongBaoIdList.add(ho.getHongBaoV2().getId());
         }
      }
      Iterator<Long> its = userMoney.keySet().iterator();
      while (its.hasNext()) {
         // 将自己添加到用户
         Long uid = its.next();
         BigDecimal money = userMoney.get(uid);
         UserMoneyDetail userMoneyDetail = null;
         // 插入新版资金明细
         try {
            // 此处不用订单号做唯一性索引
            userMoneyDetail = UserMoneyDetailFactory.createFanLi(uid, hongBaoOrder.getCommonOrder().getOrderNo(),
                  hongBaoOrder.getCommonOrder().getSourceType(), null, money);
         } catch (UserMoneyDetailException e1) {
            try {
               LogHelper.errorDetailInfo(e1, "订单号:" + hongBaoOrder.getCommonOrder().getOrderNo(), "");
            } catch (Exception e2) {
               e2.printStackTrace();
            }
      List<HongBaoV2> allHongBaoList = hongBaoV2Mapper.listByIds(hongBaoIdList);
      boolean first = true;
      for (HongBaoV2 v2 : allHongBaoList)
         if (v2.getState() == HongBaoV2.STATE_YILINGQU) {
            first = false;
            break;
         }
         userMoneyService.addUserMoney(uid, money, userMoneyDetail);
         // 添加资金明细与红包的映射关系
         for (HongBaoV2 v2 : userHongBao.get(uid)) {
            accountDetailsHongBaoMapService.saveAccountDetailsHongBaoMap(v2.getId(), userMoneyDetail.getId());
         }
         // 站内信+推送
         UserInfo user = userInfoMapper.selectByPKey(uid);
         // 新版通知
         userMoneyMsgNotificationService.fanliOrderReceived(uid, hongBaoOrder.getCommonOrder().getOrderNo(),
               hongBaoOrder.getCommonOrder().getSourceType(), userGoodsCount.get(uid), money, user.getMyHongBao());
      }
      // 通知免单到账
      // 自购到账事务消息
      OrderMoneyRecievedMQMsg mqMsg = new OrderMoneyRecievedMQMsg(OrderMoneyRecievedMQMsg.TYPE_ZIGOU,
            mainUser.getId(), hongBaoOrder.getCommonOrder().getSourceType(),
            hongBaoOrder.getCommonOrder().getOrderNo(), null, new Date(),0);
      mqMsg.setOrderFirst(first);
      Message msg = MQMsgBodyFactory.create(MQTopicName.TOPIC_ORDER, OrderTopicTagEnum.orderFanLiActual,
            mqMsg);
      String key = mainUser.getId() + "-" + UUID.randomUUID().toString();
      msg.setKey(key);
      try {
         userSystemCouponService.updateStateByArrivalAccount(hongBaoOrder.getCommonOrder().getOrderNo());
      } catch (Exception e) {
         e.printStackTrace();
      }
      // 维权扣款(2018-08-05后开始实行)
      if (hongBaoOrder.getCommonOrder().getSettleTime() != null && hongBaoOrder.getCommonOrder().getSettleTime()
            .getTime() >= TimeUtil.convertToTimeTemp("2018-08-05", "yyyy-MM-dd")) {
         try {
            if (hongBaoOrder.getCommonOrder().getSourceType() == Constant.SOURCE_TYPE_TAOBAO)
               taoBaoWeiQuanDrawBackService.doWeiQuanFanli(hongBaoOrder.getCommonOrder().getOrderNo());
         } catch (TaoBaoWeiQuanException e) {
            if (e.getCode() == TaoBaoWeiQuanException.CODE_NEDD_UPDATE_ORDER) {
               List<TaoBaoOrder> olist = taoBaoOrderService
                     .getTaoBaoOrderByOrderId(hongBaoOrder.getCommonOrder().getOrderNo());
               if (olist != null && olist.size() > 0) {
                  long time = TimeUtil.convertToTimeTemp(olist.get(0).getCreateTime(), "yyyy-MM-dd HH:mm:ss");
                  olist = TaoKeOrderApiUtil.getTaoBaoAllOrder(TimeUtil.getGernalTime(time, "yyyy-MM-dd HH:mm:ss"),
                        TaoBaoConstant.TAOBAO_AUTH_APPKEY, TaoBaoConstant.TAOBAO_AUTH_APPSECRET);
                  List<TaoBaoOrder> thirdOList = TaoKeOrderApiUtil.getTaoBaoThirdAllOrder(
                        TimeUtil.getGernalTime(time, "yyyy-MM-dd HH:mm:ss"), 30, 1,
                        TaoBaoConstant.TAOBAO_AUTH_APPKEY, TaoBaoConstant.TAOBAO_AUTH_APPSECRET);
                  if (thirdOList != null && thirdOList.size() > 0)
                     olist.addAll(thirdOList);
                  if (olist != null && olist.size() > 0) {
                     for (int i = 0; i < olist.size(); i++) {
                        if (!olist.get(i).getOrderId()
                              .equalsIgnoreCase(hongBaoOrder.getCommonOrder().getOrderNo())) {// 删除无关订单
                           olist.remove(i);
                           i--;
                        }
                     }
                     taoBaoOrderService.addTaoBaoOrderList(olist);
                  }
         orderTransactionProducer.send(msg, new LocalTransactionExecuter() {
            @Override
            public TransactionStatus execute(Message arg0, Object arg1) {
               try {
                  orderMoneySettleService.ziGouSettle(hongBaoOrder.getCommonOrder().getOrderNo(),
                        hongBaoOrder.getCommonOrder().getSourceType(), key);
                  return TransactionStatus.CommitTransaction;
               } catch (Exception e) {
                  return TransactionStatus.RollbackTransaction;
               }
            } else
               throw new TaoBaoWeiQuanException(e.getCode(), e.getMsg());
         }
            }
         }, null);
      } catch (Exception e) {
         LogHelper.mqError(e.getMessage(), msg.getTopic(), msg.getTag(), new Gson().toJson(mqMsg));
      }
   }
   @Override
   public void weiQuanOrder(List<TaoBaoWeiQuanOrder> orderList) {
      if (orderList != null)
         for (TaoBaoWeiQuanOrder order : orderList) {
            if (order.getState().contains("维权成功")) {
               CMQManager.getInstance().addWeiQuanOrderMsg(order);
            try {
               if (order.getState().contains("维权成功")) {
                  CMQManager.getInstance().addWeiQuanOrderMsg(order);
               }
            } catch (Exception e) {
               LogHelper.error("维权订单加入到队列出错:" + order != null ? new Gson().toJson(order) : null);
            }
         }
   }
@@ -531,278 +521,48 @@
      }
   }
   private HongBaoV2 filterWeiQuanINGHongBao(HongBaoV2 hongBao) {
      long hbId = hongBao.getId();
      if (hongBao.getParent() != null) {
         hbId = hongBao.getParent().getId();
      }
      HongBaoOrder hongbaoOrder = hongBaoOrderMapper.selectByHongBaoId(hbId);
      if (hongbaoOrder == null)
         return null;
      List<TaoBaoWeiQuanOrder> taoBaoWeiQuanList = taoBaoWeiQuanOrderMapper
            .selectListByOrderIdAndState(hongbaoOrder.getCommonOrder().getOrderNo(), "维权创建");
      List<TaoBaoWeiQuanOrder> taoBaoWeiQuanList1 = taoBaoWeiQuanOrderMapper
            .selectListByOrderIdAndState(hongbaoOrder.getCommonOrder().getOrderNo(), "等待处理");
      if ((taoBaoWeiQuanList != null && taoBaoWeiQuanList.size() > 0)
            || (taoBaoWeiQuanList1 != null && taoBaoWeiQuanList1.size() > 0)) {
         return null;
      }
      return hongBao;
   }
   @Override
   @Transactional
   public void fanliInvaiteAndShare(Long uid) throws TaoBaoWeiQuanException {
      /**
       * 处理邀请赚订单
       */
      // 查询UID的邀请赚订单
      List<Integer> types = new ArrayList<>();
      types.add(HongBaoV2.TYPE_YIJI);
      types.add(HongBaoV2.TYPE_ERJI);
      List<HongBaoV2> hongBaoList = hongBaoV2Mapper.listCanBalanceHongBaoByTypeAndUid(types, uid, 1000);
      // 灰度测试中,京东/拼多多订单分享/邀请订单不返利
      for (int i = 0; i < hongBaoList.size(); i++) {
         HongBaoV2 item = hongBaoList.get(i);
         if (item.getType() == HongBaoV2.TYPE_SHARE_GOODS) {
         } else {
            item = item.getParent();
         }
         if (item != null) {
            HongBaoOrder hongBaoOrder = hongBaoOrderMapper.selectByHongBaoId(item.getId());
            if (hongBaoOrder != null && hongBaoOrder.getCommonOrder() != null) {
               CommonOrder co = hongBaoOrder.getCommonOrder();
               if (co.getSourceType() == Constant.SOURCE_TYPE_JD
                     || co.getSourceType() == Constant.SOURCE_TYPE_PDD) {
                  hongBaoList.remove(i);
                  i--;
               } else {// 上级用户不是正常用户,订单均不能到账
                  UserInfo userInfo = userInfoMapper.selectByPrimaryKey(item.getUserInfo().getId());
                  if (userInfo == null || userInfo.getState() != UserInfo.STATE_NORMAL) {
                     hongBaoList.remove(i);
                     i--;
                  }
               }
            }
         }
      }
      List<Long> hbIdList = new ArrayList<>();
      BigDecimal invitemoney = new BigDecimal(0);
      Set<String> inviteOrders = new HashSet<>();
      int inviteGoodsCount = 0;
      // 需要判断退款的订单号
      Set<String> drawBackOrders = new HashSet<String>();
      for (HongBaoV2 hongBao : hongBaoList) {
         hongBao = filterWeiQuanINGHongBao(hongBao);
         if (hongBao == null)
            continue;
         hongBao = hongBaoV2Mapper.selectByPrimaryKeyForUpdate(hongBao.getId());
         if (hongBao.getState() == HongBaoV2.STATE_BUKELINGQU || hongBao.getState() == HongBaoV2.STATE_KELINGQU) {
            invitemoney = invitemoney.add(hongBao.getMoney());
            HongBaoV2 updateHongBao = new HongBaoV2();
            updateHongBao.setId(hongBao.getId());
            updateHongBao.setGetTime(new Date());
            updateHongBao.setState(HongBaoV2.STATE_YILINGQU);
            updateHongBao.setUpdateTime(new Date());
            hongBaoV2Mapper.updateByPrimaryKeySelective(updateHongBao);
            // 添加到红包返利记录集合
            hbIdList.add(hongBao.getId());
            // 2018-08-05 过后的订单才处理维权
            HongBaoOrder hongBaoOrder = hongBaoOrderMapper.selectByHongBaoId(hongBao.getParent().getId());
            inviteGoodsCount += hongBaoOrder.getCommonOrder().getCount();
            inviteOrders.add(hongBaoOrder.getCommonOrder().getOrderNo());
            Date balanceTime = hongBaoOrder.getCommonOrder().getSettleTime();
            if (balanceTime != null
                  && balanceTime.getTime() >= TimeUtil.convertToTimeTemp("2018-08-05", "yyyy-MM-dd")) {
               if (!StringUtil.isNullOrEmpty(hongBaoOrder.getCommonOrder().getOrderNo()))
                  drawBackOrders.add(hongBaoOrder.getCommonOrder().getOrderNo());
            }
         }
      }
      /**
       * 处理一级二级分享赚(属于邀请赚类型)
       */
      List<HongBaoV2> totalHongBaoList = new ArrayList<>();
      // 查询UID的二级或者三级分享赚订单
      // TODO 暂时查询10000条数据,后面再做分页
      types.clear();
      types.add(HongBaoV2.TYPE_SHARE_YIJI);
      types.add(HongBaoV2.TYPE_SHARE_ERJI);
      List<HongBaoV2> hbList = hongBaoV2Mapper.listCanBalanceHongBaoByTypeAndUid(types, uid, 10000);
      if (hbList != null && hbList.size() > 0)
         totalHongBaoList.addAll(hbList);
      for (HongBaoV2 hb : totalHongBaoList) {
         if (hb.getState() == HongBaoV2.STATE_BUKELINGQU || hb.getState() == HongBaoV2.STATE_KELINGQU) {
            hb = filterWeiQuanINGHongBao(hb);
            if (hb == null)
               continue;
            invitemoney = invitemoney.add(hb.getMoney());
            HongBaoV2 updateHongBao = new HongBaoV2();
            updateHongBao.setId(hb.getId());
            updateHongBao.setGetTime(new Date());
            updateHongBao.setState(HongBaoV2.STATE_YILINGQU);
            updateHongBao.setUpdateTime(new Date());
            hongBaoV2Mapper.updateByPrimaryKeySelective(updateHongBao);
            // 添加到红包返利记录集合
            hbIdList.add(hb.getId());
            HongBaoOrder hongBaoOrder = hongBaoOrderMapper.selectByHongBaoId(hb.getParent().getId());
            inviteGoodsCount += hongBaoOrder.getCommonOrder().getCount();
            inviteOrders.add(hongBaoOrder.getCommonOrder().getOrderNo());
            if (!StringUtil.isNullOrEmpty(hongBaoOrder.getCommonOrder().getOrderNo()))
               drawBackOrders.add(hongBaoOrder.getCommonOrder().getOrderNo());
         }
      }
      // 邀请赚到账
      if (invitemoney.compareTo(new BigDecimal(0)) > 0) {
      try {
         orderMoneySettleService.inviteSettleTB(uid);
      } catch (OrderMoneySettleException e) {
         e.printStackTrace();
      }
      if (1 > 0)
         return;
         // 添加新版详情记录
         try {
            // 查询邀请赚的有效订单,失效订单,维权订单
            Calendar ca = Calendar.getInstance();
            Date maxDate = new Date(TimeUtil
                  .convertToTimeTemp(ca.get(Calendar.YEAR) + "-" + (ca.get(Calendar.MONTH) + 1), "yyyy-M"));
            ca.add(Calendar.MONTH, -1);
            Date minDate = new Date(TimeUtil
                  .convertToTimeTemp(ca.get(Calendar.YEAR) + "-" + (ca.get(Calendar.MONTH) + 1), "yyyy-M"));
            long validCount = hongBaoV2Mapper.countInviteOrderCountByUidAndSettleTime(uid, CommonOrder.STATE_JS,
                  minDate, maxDate);
            long weiQuanCount = hongBaoV2Mapper.countInviteOrderCountByUidAndSettleTime(uid, CommonOrder.STATE_WQ,
                  minDate, maxDate);
            long invalidCount = hongBaoV2Mapper.countInviteOrderCountByUidAndSettleTime(uid, CommonOrder.STATE_SX,
                  minDate, maxDate);
            UserMoneyDetail userMoneyDetail = UserMoneyDetailFactory.createInvite(uid, Constant.SOURCE_TYPE_TAOBAO,
                  (int) validCount, (int) weiQuanCount, (int) invalidCount, invitemoney, new Date());
            // 增加资金
            userMoneyService.addUserMoney(uid, invitemoney, userMoneyDetail);
            // 添加到红包返利记录集合
            accountDetailsHongBaoMapService.saveAccountDetailsHongBaoMap(hbIdList, userMoneyDetail.getId());
         } catch (UserMoneyDetailException e) {
            try {
               LogHelper.errorDetailInfo(e);
            } catch (Exception e1) {
               e1.printStackTrace();
            }
         }
         // 新版通知
         userMoneyMsgNotificationService.inviteOrderReceived(uid, Constant.SOURCE_TYPE_TAOBAO, inviteOrders.size(),
               inviteGoodsCount, invitemoney, userInfoMapper.selectByPKey(uid).getMyHongBao());
         for (String orderId : drawBackOrders)
            taoBaoWeiQuanDrawBackService.doWeiQuanInvite(orderId);
      try {
         orderMoneySettleService.inviteSettleJD(uid);
      } catch (OrderMoneySettleException e) {
         e.printStackTrace();
      }
      hbIdList.clear();
      drawBackOrders.clear();
      /**
       * 处理分享赚
       */
      int shareGoodsCount = 0;
      Set<String> shareOrders = new HashSet<>();
      BigDecimal sharemoney = new BigDecimal(0);
      // 查询UID的分享赚订单
      types.clear();
      types.add(HongBaoV2.TYPE_SHARE_GOODS);
      List<HongBaoV2> hongBaoShareList = hongBaoV2Mapper.listCanBalanceHongBaoByTypeAndUid(types, uid, 10000);
      for (HongBaoV2 hongBao : hongBaoShareList) {
         hongBao = hongBaoV2Mapper.selectByPrimaryKeyForUpdate(hongBao.getId());
         hongBao = filterWeiQuanINGHongBao(hongBao);
         if (hongBao == null)
            continue;
         if (hongBao.getState() == HongBaoV2.STATE_BUKELINGQU || hongBao.getState() == HongBaoV2.STATE_KELINGQU) {
            sharemoney = sharemoney.add(hongBao.getMoney());
            HongBaoV2 updateHongBao = new HongBaoV2();
            updateHongBao.setId(hongBao.getId());
            updateHongBao.setGetTime(new Date());
            updateHongBao.setState(HongBao.STATE_YILINGQU);
            updateHongBao.setUpdateTime(new Date());
            hongBaoV2Mapper.updateByPrimaryKeySelective(updateHongBao);
            // 添加到红包返利记录集合
            hbIdList.add(hongBao.getId());
            // 2018-08-05 过后的订单才处理维权
            Date balanceTime = null;
            HongBaoOrder hongBaoOrder = hongBaoOrderMapper.selectByHongBaoId(hongBao.getId());
            if (hongBaoOrder != null) {
               balanceTime = hongBaoOrder.getCommonOrder().getSettleTime();
               shareGoodsCount += hongBaoOrder.getCommonOrder().getCount();
            }
            shareOrders.add(hongBaoOrder.getCommonOrder().getOrderNo());
            if (balanceTime != null
                  && balanceTime.getTime() >= TimeUtil.convertToTimeTemp("2018-08-05", "yyyy-MM-dd")) {
               drawBackOrders.add(hongBaoOrder.getCommonOrder().getOrderNo());
            }
         }
      try {
         orderMoneySettleService.inviteSettlePDD(uid);
      } catch (OrderMoneySettleException e) {
         e.printStackTrace();
      }
      /**
       * 分享赚到账
       */
      if (sharemoney.compareTo(new BigDecimal(0)) > 0) {
         // 添加新版详情记录
         try {
            // 计算本月的有效订单,失效订单,维权订单
            Calendar ca = Calendar.getInstance();
            Date maxDate = new Date(TimeUtil
                  .convertToTimeTemp(ca.get(Calendar.YEAR) + "-" + (ca.get(Calendar.MONTH) + 1), "yyyy-M"));
            ca.add(Calendar.MONTH, -1);
            Date minDate = new Date(TimeUtil
                  .convertToTimeTemp(ca.get(Calendar.YEAR) + "-" + (ca.get(Calendar.MONTH) + 1), "yyyy-M"));
            long validCount = hongBaoV2Mapper.countShareOrderCountByUidAndSettleTime(uid, CommonOrder.STATE_JS,
                  minDate, maxDate);
            long weiQuanCount = hongBaoV2Mapper.countShareOrderCountByUidAndSettleTime(uid, CommonOrder.STATE_WQ,
                  minDate, maxDate);
            long invalidCount = hongBaoV2Mapper.countShareOrderCountByUidAndSettleTime(uid, CommonOrder.STATE_SX,
                  minDate, maxDate);
            UserMoneyDetail userMoneyDetail = UserMoneyDetailFactory.createShare(uid, Constant.SOURCE_TYPE_TAOBAO,
                  (int) validCount, (int) weiQuanCount, (int) invalidCount, sharemoney, new Date());
            // 添加资金
            userMoneyService.addUserMoney(uid, sharemoney, userMoneyDetail);
            // 添加到红包返利记录集合
            accountDetailsHongBaoMapService.saveAccountDetailsHongBaoMap(hbIdList, userMoneyDetail.getId());
         } catch (UserMoneyDetailException e) {
            try {
               LogHelper.errorDetailInfo(e);
            } catch (Exception e1) {
               e1.printStackTrace();
            }
         }
         // 新版通知
         userMoneyMsgNotificationService.shareOrderReceived(uid, Constant.SOURCE_TYPE_TAOBAO, shareOrders.size(),
               shareGoodsCount, sharemoney, userInfoMapper.selectByPrimaryKey(uid).getMyHongBao());
         for (String orderId : drawBackOrders)
            taoBaoWeiQuanDrawBackService.doWeiQuanShare(orderId);
      // 分享赚到账
      try {
         orderMoneySettleService.shareSettleTB(uid);
      } catch (OrderMoneySettleException e) {
         e.printStackTrace();
      }
      try {
         orderMoneySettleService.shareSettleJD(uid);
      } catch (OrderMoneySettleException e) {
         e.printStackTrace();
      }
      try {
         orderMoneySettleService.shareSettlePDD(uid);
      } catch (OrderMoneySettleException e) {
         e.printStackTrace();
      }
   }
   @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
@@ -824,10 +584,20 @@
         // 原来不存在订单
         Long uid = null;
         if (oldOrder == null) {
            PidUser pidUser = null;// pidUserMapper.selectByPid(pid);
            if (pidUser != null) {
               uid = pidUser.getUid();
            Long targetUid = null;
            if (pid.equalsIgnoreCase(TaoBaoConstant.TAOBAO_RELATION_AS_SPECIAL_PID)
                  && !StringUtil.isNullOrEmpty(orderList.get(0).getRelationId())) {
               targetUid = taoBaoBuyRelationMapService.selectUidByRelationId(orderList.get(0).getRelationId());
            } else if (!StringUtil.isNullOrEmpty(orderList.get(0).getSpecialId())) {
               UserExtraTaoBaoInfo info = userExtraTaoBaoInfoService
                     .getBySpecialId(orderList.get(0).getSpecialId());
               if (info != null && info.getUser() != null)
                  targetUid = info.getUser().getId();
            }
            if (targetUid != null) {
               uid = targetUid;
               // 插入到Order中
               // 添加到订单中去
               Order order = new Order();
@@ -841,36 +611,8 @@
               // 加入到订单表
               orderMapper.insertSelective(order);
               oldOrder = order;
            } else {
               Long targetUid = null;
               if (pid.equalsIgnoreCase(TaoBaoConstant.TAOBAO_RELATION_AS_SPECIAL_PID)
                     && !StringUtil.isNullOrEmpty(orderList.get(0).getRelationId())) {
                  targetUid = taoBaoBuyRelationMapService.selectUidByRelationId(orderList.get(0).getRelationId());
               } else if (!StringUtil.isNullOrEmpty(orderList.get(0).getSpecialId())) {
                  UserExtraTaoBaoInfo info = userExtraTaoBaoInfoService
                        .getBySpecialId(orderList.get(0).getSpecialId());
                  if (info != null && info.getUser() != null)
                     targetUid = info.getUser().getId();
               }
               if (targetUid != null) {
                  uid = targetUid;
                  // 插入到Order中
                  // 添加到订单中去
                  Order order = new Order();
                  order.setBeizhu("PID返利订单");
                  order.setCreatetime(System.currentTimeMillis());
                  order.setOrderId(orderId);
                  order.setOrderType(1);
                  order.setState(Order.STATE_YIZHIFU);
                  order.setUserInfo(new UserInfo(uid));
                  order.setVersion(2);
                  // 加入到订单表
                  orderMapper.insertSelective(order);
                  oldOrder = order;
               }
            }
         } else {
            uid = oldOrder.getUserInfo().getId();
         }
@@ -905,11 +647,20 @@
         orderMapper.updateByPrimaryKeySelective(updateOrder);
         // 用第一个子订单锁定用户
         List<CommonOrder> commonOrderList = null;
         List<CommonOrderAddResultDTO> commonOrderList = null;
         try {
            commonOrderList = commonOrderService.addTaoBaoOrder(orderList, uid);
            hongBaoV2Service.addHongBao(commonOrderList, HongBaoV2.TYPE_ZIGOU);
            addHongBaoWithMQ(commonOrderList, orderId, uid, Constant.SOURCE_TYPE_TAOBAO, HongBaoV2.TYPE_ZIGOU);
            if (isCommonOrderAllAdd(commonOrderList)) {
               Order order = new Order();
               order.setOrderId(orderId);
               order.setOrderType(Constant.SOURCE_TYPE_TAOBAO);
               order.setUserInfo(new UserInfo(uid));
               try {
                  PlaceOrderCMQManager.getInstance().addPlaceOrderMsg(order);
               } catch (Exception e) {
               }
            }
         } catch (CommonOrderException e) {
            try {
               LogHelper.errorDetailInfo(e, "addTaoBaoOrder或addHongBao出错", "订单号:" + orderId);
@@ -922,21 +673,12 @@
   @Override
   public void processShareGoodsOrderNew(String orderId, List<TaoBaoOrder> orderList) {
      List<TaoBaoUnionConfig> configList = taoBaoUnionConfigService.getConfigByTypeCache(PidUser.TYPE_FANLI_ANDROID);
      if (orderList != null && orderList.size() > 0) {
         String pid = String.format("mm_%s_%s_%s", configList.get(0).getAccountId(),
               orderList.get(0).getSourceMediaId(), orderList.get(0).getAdPositionId());
         // 原来不存在订单
         Long uid = null;
         PidUser pidUser = null; // pidUserMapper.selectByPid(pid);-PID机制移除
         if (pidUser != null)
            uid = pidUser.getUid();
         else {
            UserExtraTaoBaoInfo info = userExtraTaoBaoInfoService.getByRelationId(orderList.get(0).getRelationId());
            if (info != null && info.getUser() != null)
               uid = info.getUser().getId();
         }
         UserExtraTaoBaoInfo info = userExtraTaoBaoInfoService.getByRelationId(orderList.get(0).getRelationId());
         if (info != null && info.getUser() != null)
            uid = info.getUser().getId();
         // 尚未找到和PID对应的用户
         if (uid == null) {
            // 通过红包查询
@@ -957,23 +699,51 @@
         // 用第一个子订单锁定用户
         try {
            List<CommonOrder> commonOrders = commonOrderService.addTaoBaoOrder(orderList, uid);
            hongBaoV2Service.addHongBao(commonOrders, HongBaoV2.TYPE_SHARE_GOODS);
            List<CommonOrderAddResultDTO> commonOrders = commonOrderService.addTaoBaoOrder(orderList, uid);
            addHongBaoWithMQ(commonOrders, orderId, uid, Constant.SOURCE_TYPE_TAOBAO, HongBaoV2.TYPE_SHARE_GOODS);
            if (isCommonOrderAllAdd(commonOrders)) {
               Order order = new Order();
               order.setOrderId(orderId);
               order.setOrderType(Constant.SOURCE_TYPE_TAOBAO);
               order.setUserInfo(new UserInfo(uid));
               try {
                  PlaceOrderCMQManager.getInstance().addPlaceOrderMsg(order);
               } catch (Exception e) {
               }
            }
         } catch (CommonOrderException e) {
            e.printStackTrace();
         } catch (HongBaoException e1) {
            e1.printStackTrace();
         }
      }
   }
   /**
    * 是否为分享订单
    *
    * @param order
    * @return
    */
   private boolean isShareOrder(JDOrder order) {
      if (order == null || order.getOrderItemList() == null || order.getOrderItemList().size() == 0)
         return false;
      Long positionId = order.getOrderItemList().get(0).getPositionId();
      if (positionId == JDApiUtil.POSITION_SHARE) {// 分享订单
         return true;
      }
      return false;
   }
   @Override
   public void processJDOrder(JDOrder order) {
      if (order == null || order.getOrderItemList() == null || order.getOrderItemList().size() == 0)
         return;
      // 拆单的不做处理
      if (order.getValidCode() == 2)
         return;
      String uidStr = order.getExt1();
      Long uid = null;
      if (!StringUtil.isNullOrEmpty(uidStr))
      if (!StringUtil.isNullOrEmpty(uidStr) && NumberUtil.isNumeric(uidStr))
         uid = Long.parseLong(uidStr);
      Long positionId = order.getOrderItemList().get(0).getPositionId();
      if (positionId == JDApiUtil.POSITION_FANLI)// 返利订单
@@ -1016,7 +786,7 @@
      // 加入订单
      Order oldOrder = orderMapper.selectOrderByOrderIdAndOrderType(jdOrder.getOrderId() + "",
            Constant.SOURCE_TYPE_JD);
      if (uid == null && oldOrder.getBeizhu().contains("补单"))
      if (uid == null && oldOrder != null && oldOrder.getBeizhu() != null && oldOrder.getBeizhu().contains("补单"))
         uid = oldOrder.getUserInfo().getId();
      if (uid == null)
@@ -1045,15 +815,21 @@
      }
      try {
         List<CommonOrder> commonOrderList = commonOrderService.addJDOrder(jdOrder, uid);
         hongBaoV2Service.addHongBao(commonOrderList, HongBaoV2.TYPE_ZIGOU);
      } catch (CommonOrderException e) {
         try {
            LogHelper.errorDetailInfo(e, "addJDOrder或addHongBao出错", "订单号:" + jdOrder.getOrderId());
         } catch (Exception e1) {
            e1.printStackTrace();
         List<CommonOrderAddResultDTO> commonOrderList = commonOrderService.addJDOrder(jdOrder, uid);
         addHongBaoWithMQ(commonOrderList, jdOrder.getOrderId() + "", uid, Constant.SOURCE_TYPE_JD,
               HongBaoV2.TYPE_ZIGOU);
         if (isCommonOrderAllAdd(commonOrderList)) {
            Order order = new Order();
            order.setOrderId(jdOrder.getOrderId() + "");
            order.setOrderType(Constant.SOURCE_TYPE_JD);
            order.setUserInfo(new UserInfo(uid));
            try {
               PlaceOrderCMQManager.getInstance().addPlaceOrderMsg(order);
            } catch (Exception e) {
            }
         }
      } catch (HongBaoException e) {
      } catch (CommonOrderException e) {
         try {
            LogHelper.errorDetailInfo(e, "addJDOrder或addHongBao出错", "订单号:" + jdOrder.getOrderId());
         } catch (Exception e1) {
@@ -1069,23 +845,42 @@
    * @param uid
    */
   @Transactional
   private void processShareJDOrder(JDOrder order, Long uid) {
   private void processShareJDOrder(JDOrder jdOrder, Long uid) {
      try {
         List<CommonOrder> commonOrderList = commonOrderService.addJDOrder(order, uid);
         hongBaoV2Service.addHongBao(commonOrderList, HongBaoV2.TYPE_SHARE_GOODS);
         List<CommonOrderAddResultDTO> commonOrderList = commonOrderService.addJDOrder(jdOrder, uid);
         addHongBaoWithMQ(commonOrderList, jdOrder.getOrderId() + "", uid, Constant.SOURCE_TYPE_JD,
               HongBaoV2.TYPE_SHARE_GOODS);
         if (isCommonOrderAllAdd(commonOrderList)) {
            Order order = new Order();
            order.setOrderId(jdOrder.getOrderId() + "");
            order.setOrderType(Constant.SOURCE_TYPE_JD);
            order.setUserInfo(new UserInfo(uid));
            try {
               PlaceOrderCMQManager.getInstance().addPlaceOrderMsg(order);
            } catch (Exception e) {
            }
         }
      } catch (CommonOrderException e) {
         try {
            LogHelper.errorDetailInfo(e, "addJDOrder或addHongBao出错", "订单号:" + order.getOrderId());
         } catch (Exception e1) {
            e1.printStackTrace();
         }
      } catch (HongBaoException e) {
         try {
            LogHelper.errorDetailInfo(e, "addJDOrder或addHongBao出错", "订单号:" + order.getOrderId());
            LogHelper.errorDetailInfo(e, "addJDOrder或addHongBao出错", "订单号:" + jdOrder.getOrderId());
         } catch (Exception e1) {
            e1.printStackTrace();
         }
      }
   }
   /**
    * 是否是分享赚订单
    *
    * @param order
    * @return
    */
   private boolean isShareOrder(PDDOrder pddOrder) {
      String positionId = pddOrder.getpId();
      if (PinDuoDuoApiUtil.PID_SHARE.equalsIgnoreCase(positionId))
         return true;
      else
         return false;
   }
   /**
@@ -1131,7 +926,7 @@
      // 加入订单
      Order oldOrder = orderMapper.selectOrderByOrderIdAndOrderType(pddOrder.getOrderSn(), Constant.SOURCE_TYPE_PDD);
      if (uid == null && oldOrder.getBeizhu().contains("补单"))
      if (uid == null && oldOrder != null && oldOrder.getBeizhu() != null && oldOrder.getBeizhu().contains("补单"))
         uid = oldOrder.getUserInfo().getId();
      if (uid == null)
@@ -1161,15 +956,20 @@
      try {
         List<PDDOrder> pddOrderList = new ArrayList<>();
         pddOrderList.add(pddOrder);
         List<CommonOrder> commonOrderList = commonOrderService.addPDDOrder(pddOrderList, uid);
         hongBaoV2Service.addHongBao(commonOrderList, HongBaoV2.TYPE_ZIGOU);
      } catch (CommonOrderException e) {
         try {
            LogHelper.errorDetailInfo(e, "addPDDOrder或addHongBao出错", "订单号:" + pddOrder.getOrderSn());
         } catch (Exception e1) {
            e1.printStackTrace();
         List<CommonOrderAddResultDTO> commonOrderList = commonOrderService.addPDDOrder(pddOrderList, uid);
         addHongBaoWithMQ(commonOrderList, pddOrder.getOrderSn(), uid, Constant.SOURCE_TYPE_PDD,
               HongBaoV2.TYPE_ZIGOU);
         if (isCommonOrderAllAdd(commonOrderList)) {
            Order order = new Order();
            order.setOrderId(pddOrder.getOrderSn());
            order.setOrderType(Constant.SOURCE_TYPE_PDD);
            order.setUserInfo(new UserInfo(uid));
            try {
               PlaceOrderCMQManager.getInstance().addPlaceOrderMsg(order);
            } catch (Exception e) {
            }
         }
      } catch (HongBaoException e) {
      } catch (CommonOrderException e) {
         try {
            LogHelper.errorDetailInfo(e, "addPDDOrder或addHongBao出错", "订单号:" + pddOrder.getOrderSn());
         } catch (Exception e1) {
@@ -1185,24 +985,262 @@
    * @param uid
    */
   @Transactional
   private void processSharePDDOrder(PDDOrder order, Long uid) {
   private void processSharePDDOrder(PDDOrder pddOrder, Long uid) {
      try {
         List<PDDOrder> pddOrderList = new ArrayList<>();
         pddOrderList.add(order);
         List<CommonOrder> commonOrderList = commonOrderService.addPDDOrder(pddOrderList, uid);
         hongBaoV2Service.addHongBao(commonOrderList, HongBaoV2.TYPE_SHARE_GOODS);
         pddOrderList.add(pddOrder);
         List<CommonOrderAddResultDTO> commonOrderList = commonOrderService.addPDDOrder(pddOrderList, uid);
         addHongBaoWithMQ(commonOrderList, pddOrder.getOrderSn(), uid, Constant.SOURCE_TYPE_PDD,
               HongBaoV2.TYPE_SHARE_GOODS);
         if (isCommonOrderAllAdd(commonOrderList)) {
            Order order = new Order();
            order.setOrderId(pddOrder.getOrderSn());
            order.setOrderType(Constant.SOURCE_TYPE_PDD);
            order.setUserInfo(new UserInfo(uid));
            try {
               PlaceOrderCMQManager.getInstance().addPlaceOrderMsg(order);
            } catch (Exception e) {
            }
         }
      } catch (CommonOrderException e) {
         try {
            LogHelper.errorDetailInfo(e, "addJDOrder或addHongBao出错", "订单号:" + order.getOrderId());
         } catch (Exception e1) {
            e1.printStackTrace();
         }
      } catch (HongBaoException e) {
         try {
            LogHelper.errorDetailInfo(e, "addJDOrder或addHongBao出错", "订单号:" + order.getOrderId());
            LogHelper.errorDetailInfo(e, "addJDOrder或addHongBao出错", "订单号:" + pddOrder.getOrderId());
         } catch (Exception e1) {
            e1.printStackTrace();
         }
      }
   }
   @Override
   public void repairCommonOrderByByTaoBaoOrder(String orderId) {
      // 根据订单号查询淘宝订单
      List<TaoBaoOrder> orderList = taoBaoOrderService.getTaoBaoOrderByOrderId(orderId);
      if (orderList != null)
         for (TaoBaoOrder order : orderList) {
            // 根据交易ID查询常规订单
            CommonOrder commonOrder = commonOrderService.selectBySourceTypeAndTradeId(Constant.SOURCE_TYPE_TAOBAO,
                  order.getTradeId());
            // 修复orderby
            if (commonOrder != null) {
               CommonOrder update = new CommonOrder(commonOrder.getId());
               update.setOrderBy(order.getOrderBy());
               update.setUpdateTime(new Date());
               commonOrderService.updateByPrimaryKeySelective(update);
            }
         }
   }
   @Override
   public boolean isShareOrder(CommonOrder commonOrder) {
      switch (commonOrder.getSourceType()) {
      case Constant.SOURCE_TYPE_TAOBAO:
         return isShareOrder(taoBaoOrderService.selectByTradeId(commonOrder.getTradeId()));
      case Constant.SOURCE_TYPE_JD:
         return isShareOrder(jdOrderService.selectDetailByOrderId(Long.parseLong(commonOrder.getOrderNo())));
      case Constant.SOURCE_TYPE_PDD:
         return isShareOrder(pddOrderService.selectByOrderSn(commonOrder.getOrderNo()).get(0));
      }
      return false;
   }
   /**
    * 转为普通订单
    *
    * @param dtoList
    * @return
    */
   private List<CommonOrder> convertCommonOrder(List<CommonOrderAddResultDTO> dtoList) {
      List<CommonOrder> commonOrderList = new ArrayList<>();
      if (dtoList != null)
         for (CommonOrderAddResultDTO dto : dtoList)
            commonOrderList.add(dto.getCommonOrder());
      return commonOrderList;
   }
   /**
    * 是否全是增加
    *
    * @param list
    * @return
    */
   private boolean isCommonOrderAllAdd(List<CommonOrderAddResultDTO> list) {
      if (list == null || list.size() == 0)
         return false;
      int addCount = 0;
      if (list != null)
         for (CommonOrderAddResultDTO dto : list) {
            if (dto.getType() == CommonOrderAddResultDTO.TYPE_ADD)
               addCount++;
         }
      if (addCount == list.size())
         return true;
      else
         return false;
   }
   @Transactional(rollbackFor = Exception.class)
   public void invalidHongBaoV2AndGiveGodenCorn(Long hongBaoId, Long uid, String orderId, int sourceType,
         String beiZhu) throws Exception {
      HongBaoV2 v2 = new HongBaoV2(hongBaoId);
      v2.setState(HongBaoV2.STATE_SHIXIAO);
      v2.setBeizhu(beiZhu);
      v2.setUpdateTime(new Date());
      hongBaoV2Service.updateByPrimaryKeySelective(v2);
      List<HongBaoV2> children = hongBaoV2Service.listChildrenById(hongBaoId);
      if (children != null)
         for (HongBaoV2 child : children) {
            HongBaoV2 update = new HongBaoV2(child.getId());
            update.setState(HongBaoV2.STATE_SHIXIAO);
            update.setBeizhu(beiZhu);
            update.setUpdateTime(new Date());
            hongBaoV2Service.updateByPrimaryKeySelective(update);
         }
      userSystemCouponService.systemGiveRewardCoupon(uid, 1, orderId, sourceType, "因商家违约未能结算返利或商家已经关店");
   }
   @Transactional
   @Override
   public void doTaoBaoSellerNotPaid(TaoBaoOrder order) {
      // 根据交易ID查询
      if (!StringUtil.isNullOrEmpty(order.getTradeId())) {
         List<CommonOrder> commonOrderList = commonOrderService
               .listBySourceTypeAndTradeId(Constant.SOURCE_TYPE_TAOBAO, order.getTradeId());
         if (commonOrderList != null)
            // 查询主订单
            for (CommonOrder commonOrder : commonOrderList) {
            // 查询主红包
            HongBaoOrder hongBaoOrder = hongBaoOrderMapper.selectByCommonOrderId(commonOrder.getId());
            if (hongBaoOrder != null && hongBaoOrder.getHongBaoV2() != null) {
            if (hongBaoOrder.getHongBaoV2().getState() == HongBaoV2.STATE_BUKELINGQU) {
            // 订单失效,赠送金币
            try {
            invalidHongBaoV2AndGiveGodenCorn(hongBaoOrder.getHongBaoV2().getId(), hongBaoOrder.getHongBaoV2().getUserInfo().getId(), commonOrder.getOrderNo(), commonOrder.getSourceType(), "订单成功,商家未打款");
            } catch (Exception e) {
            e.printStackTrace();
            }
            }
            }
            }
      }
   }
   public void elmeFanli() {
   }
   // 饿了么订单
   @Resource
   private ElmeHongBaoOrderMapService elmeHongBaoOrderMapService;
   @Resource
   private ElmeOrderService elmeOrderService;
   /**
    * 获取饿了么可以返利的红包
    *
    * @return
    */
   @Override
   public List<HongBaoV2> getCanBalanceElmeFanliHongBao() {
      List<Integer> list = new ArrayList<>();
      list.add(HongBaoV2.TYPE_ELME);
      return hongBaoV2Mapper.listCanBalanceHongBaoByTypeAndUid(list, null, null, 0, 1000);
   }
   @Override
   @Transactional
   public void elmeFanli(Long hongBaoId) {
      // 查询详情
      HongBaoV2 hongBao = hongBaoV2Mapper.selectByPrimaryKeyForUpdate(hongBaoId);
      if (hongBao.getType() == HongBaoV2.TYPE_ELME && hongBao.getState() == HongBaoV2.STATE_KELINGQU
            && hongBao.getPreGetTime() != null && System.currentTimeMillis() > hongBao.getPreGetTime().getTime()) {// 可以到账了
         // 判断用户状态
         UserInfo user = userInfoMapper.selectByPrimaryKey(hongBao.getUserInfo().getId());
         if (user == null || user.getState() != UserInfo.STATE_NORMAL)
            return;
         ElmeHongBaoOrderMap map = elmeHongBaoOrderMapService.selectByHongBaoId(hongBaoId);
         if (map == null)
            return;
         ElmeOrder order = elmeOrderService.selectByPrimaryKey(map.getElmeOrder().getId());
         if (order == null)
            return;
         // 到账,加数据
         HongBaoV2 update = new HongBaoV2(hongBao.getId());
         update.setUpdateTime(new Date());
         update.setGetTime(new Date());
         update.setState(HongBaoV2.STATE_YILINGQU);
         hongBaoV2Mapper.updateByPrimaryKeySelective(update);
         // 增加资金
         UserMoneyDetail detail = null;
         try {
            detail = UserMoneyDetailFactory.createElmeFanLi(hongBao.getUserInfo().getId(), order.getOrderId(),
                  hongBao.getId(), hongBao.getMoney());
         } catch (UserMoneyDetailException e) {
            e.printStackTrace();
         }
         userMoneyService.addUserMoney(hongBao.getUserInfo().getId(), hongBao.getMoney(), detail);
         BigDecimal balance = userInfoMapper.selectByPrimaryKey(hongBao.getUserInfo().getId()).getMyHongBao();
         // 添加消息
         userMoneyMsgNotificationService.elmeFanli(hongBao.getUserInfo().getId(), order.getOrderId(),
               hongBao.getMoney(), balance);
      }
      // 返利到账
   }
   /**
    * 添加红包与事务消息
    *
    * @param commonOrderList
    * @param orderId
    * @param uid
    * @param sourceType
    * @param hongBaoType
    */
   @Transactional
   private void addHongBaoWithMQ(List<CommonOrderAddResultDTO> commonOrderList, String orderId, Long uid,
         int sourceType, int hongBaoType) {
      final List<CommonOrder> coList = convertCommonOrder(commonOrderList);
      int resultCode = 0;
      try {
         resultCode = hongBaoV2Service.addHongBao(coList, hongBaoType);
      } catch (HongBaoException e) {
         try {
            LogHelper.errorDetailInfo(e, "addJDOrder或addHongBao出错", "订单号:" + orderId);
         } catch (Exception e1) {
            e1.printStackTrace();
         }
      } catch (UserAccountException e) {
      }
      if (resultCode == 1) {// 只发送新增消息
         OrderMQMsg mqMsg = new OrderMQMsg(orderId, sourceType, uid, OrderMQMsg.HANDLE_TYPE_ADD,
               isCommonOrderValid(coList),0,new Date());
         Message msg = MQMsgBodyFactory.create(MQTopicName.TOPIC_ORDER, OrderTopicTagEnum.orderStatistic,
               mqMsg);
         producer.send(msg);
      }
   }
   /**
    * 订单是否有效
    *
    * @param coList
    * @return
    */
   private boolean isCommonOrderValid(List<CommonOrder> coList) {
      for (CommonOrder commonOrder : coList) {
         if (commonOrder.getState() == CommonOrder.STATE_JS || commonOrder.getState() == CommonOrder.STATE_FK
               || commonOrder.getState() == CommonOrder.STATE_WQ) {
            return true;
         }
      }
      return false;
   }
}