yujian
2020-05-09 7e7db2fa55a9a3af46d4fd8ede0dee147f101d64
fanli/src/main/java/com/yeshi/fanli/service/impl/order/CommonOrderServiceImpl.java
@@ -1,1637 +1,2190 @@
package com.yeshi.fanli.service.impl.order;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.yeshi.utils.DateUtil;
import org.yeshi.utils.entity.DateInfo;
import org.yeshi.utils.taobao.TbImgUtil;
import com.yeshi.fanli.dao.mybatis.order.CommonOrderGoodsMapper;
import com.yeshi.fanli.dao.mybatis.order.CommonOrderMapper;
import com.yeshi.fanli.dao.mybatis.order.CommonOrderTradeIdMapMapper;
import com.yeshi.fanli.dao.mybatis.taobao.TaoBaoWeiQuanOrderMapper;
import com.yeshi.fanli.dto.order.CommonOrderAddResultDTO;
import com.yeshi.fanli.dto.pdd.PDDGoodsDetail;
import com.yeshi.fanli.entity.accept.AcceptData;
import com.yeshi.fanli.entity.bus.user.HongBaoV2;
import com.yeshi.fanli.entity.bus.user.UserInfo;
import com.yeshi.fanli.entity.bus.user.UserSystemCouponRecord;
import com.yeshi.fanli.entity.goods.CommonGoods;
import com.yeshi.fanli.entity.jd.JDGoods;
import com.yeshi.fanli.entity.jd.JDOrder;
import com.yeshi.fanli.entity.jd.JDOrderItem;
import com.yeshi.fanli.entity.order.CommonOrder;
import com.yeshi.fanli.entity.order.CommonOrderGoods;
import com.yeshi.fanli.entity.order.CommonOrderTradeIdMap;
import com.yeshi.fanli.entity.order.HongBaoOrder;
import com.yeshi.fanli.entity.order.InviteOrderSubsidy;
import com.yeshi.fanli.entity.pdd.PDDOrder;
import com.yeshi.fanli.entity.system.SystemCoupon.CouponTypeEnum;
import com.yeshi.fanli.entity.taobao.TaoBaoGoodsBrief;
import com.yeshi.fanli.entity.taobao.TaoBaoOrder;
import com.yeshi.fanli.entity.taobao.TaoBaoWeiQuanOrder;
import com.yeshi.fanli.exception.order.CommonOrderException;
import com.yeshi.fanli.exception.taobao.TaobaoGoodsDownException;
import com.yeshi.fanli.log.LogHelper;
import com.yeshi.fanli.service.inter.common.JumpDetailV2Service;
import com.yeshi.fanli.service.inter.config.ConfigService;
import com.yeshi.fanli.service.inter.config.SystemCouponService;
import com.yeshi.fanli.service.inter.goods.CommonGoodsService;
import com.yeshi.fanli.service.inter.order.CommonOrderService;
import com.yeshi.fanli.service.inter.order.HongBaoOrderService;
import com.yeshi.fanli.service.inter.order.HongBaoV2Service;
import com.yeshi.fanli.service.inter.order.InviteOrderSubsidyService;
import com.yeshi.fanli.service.inter.user.UserSystemCouponRecordService;
import com.yeshi.fanli.service.inter.user.UserSystemCouponService;
import com.yeshi.fanli.service.inter.user.vip.UserVIPInfoService;
import com.yeshi.fanli.util.Constant;
import com.yeshi.fanli.util.MoneyBigDecimalUtil;
import com.yeshi.fanli.util.StringUtil;
import com.yeshi.fanli.util.TimeUtil;
import com.yeshi.fanli.util.VersionUtil;
import com.yeshi.fanli.util.account.UserUtil;
import com.yeshi.fanli.util.factory.CommonOrderGoodsFactory;
import com.yeshi.fanli.util.factory.goods.CommonOrderFactory;
import com.yeshi.fanli.util.jd.JDApiUtil;
import com.yeshi.fanli.util.jd.JDUtil;
import com.yeshi.fanli.util.pinduoduo.PinDuoDuoApiUtil;
import com.yeshi.fanli.util.taobao.TaoBaoOrderUtil;
import com.yeshi.fanli.util.taobao.TaoBaoUtil;
import com.yeshi.fanli.util.taobao.TaoKeApiUtil;
import com.yeshi.fanli.vo.msg.ClientTextStyleVO;
import com.yeshi.fanli.vo.order.CommonOrderGoodsVO;
import com.yeshi.fanli.vo.order.CommonOrderVO;
import com.yeshi.fanli.vo.order.OrderCountVO;
import com.yeshi.fanli.vo.order.WeiQuanInfo;
import net.sf.json.JSONObject;
@Service
public class CommonOrderServiceImpl implements CommonOrderService {
   @Resource
   private CommonOrderMapper commonOrderMapper;
   @Resource
   private TaoBaoWeiQuanOrderMapper taoBaoWeiQuanOrderMapper;
   @Resource
   private CommonOrderGoodsMapper commonOrderGoodsMapper;
   @Resource
   private JumpDetailV2Service jumpDetailV2Service;
   @Resource
   private ConfigService configService;
   @Resource
   private UserSystemCouponService userSystemCouponService;
   @Resource
   private UserSystemCouponRecordService userSystemCouponRecordService;
   @Resource
   private SystemCouponService systemCouponService;
   @Resource
   private HongBaoV2Service hongBaoV2Service;
   @Resource
   private CommonOrderTradeIdMapMapper commonOrderTradeIdMapMapper;
   @Resource
   private CommonGoodsService commonGoodsService;
   @Resource
   private HongBaoOrderService hongBaoOrderService;
   @Resource
   private InviteOrderSubsidyService inviteOrderSubsidyService;
   @Resource
   private UserVIPInfoService userVIPInfoService;
   // 奖励订单图片
   public final static String PIC_REWARD = "http://img.flqapp.com/resource/order/order_state_reward.png";
   // 免单状态图片
   public final static String PIC_FREE_ON = "http://img.flqapp.com/resource/order/order_state_freeing.png";
   public final static String PIC_FREE_FAIL = "http://img.flqapp.com/resource/order/order_state_free_fail.png";
   public final static String PIC_FREE_SUCCEED = "http://img.flqapp.com/resource/order/order_state_free_suc.png";
   @Override
   public int insert(CommonOrder record) {
      return commonOrderMapper.insert(record);
   }
   @Override
   public int insertSelective(CommonOrder record) {
      return commonOrderMapper.insertSelective(record);
   }
   @Override
   public int updateByPrimaryKeySelective(CommonOrder record) {
      return commonOrderMapper.updateByPrimaryKeySelective(record);
   }
   @Override
   public int updateByPrimaryKey(CommonOrder record) {
      return commonOrderMapper.updateByPrimaryKey(record);
   }
   @Override
   public int deleteByPrimaryKey(Long id) {
      return commonOrderMapper.deleteByPrimaryKey(id);
   }
   @Override
   public CommonOrder selectByPrimaryKey(Long id) {
      return commonOrderMapper.selectByPrimaryKey(id);
   }
   @Override
   public List<CommonOrderVO> listGroupOrderNoByUid(long start, int count, Long uid, Integer state, Integer type,
         Integer orderState, String orderNo, String startTime, String endTime, Integer dateType, Integer source)
         throws CommonOrderException {
      return commonOrderMapper.listUserOrder(start, count, uid, state, type, orderState, orderNo, startTime, endTime,
            dateType, source);
   }
   @Override
   public long countGroupOrderNoByUid(Long uid, Integer state, Integer type, Integer orderState, String orderNo,
         String startTime, String endTime, Integer dateType, Integer source) throws CommonOrderException {
      return commonOrderMapper.countUserOrder(uid, state, type, orderState, orderNo, startTime, endTime, dateType,
            source);
   }
   @Override
   public List<CommonOrderVO> getOrderByUid(AcceptData acceptData, Integer page, Long uid, Integer state, Integer type,
         Integer orderState, String orderNo, String startTime, String endTime, Integer dateType, Integer source)
         throws CommonOrderException, Exception {
      int pageSize = Constant.PAGE_SIZE;
      List<CommonOrderVO> listOrder = listGroupOrderNoByUid((page - 1) * pageSize, pageSize, uid, state, type,
            orderState, orderNo, startTime, endTime, dateType, source);
      // 订单信息为空
      if (listOrder == null || listOrder.size() == 0) {
         listOrder = new ArrayList<CommonOrderVO>();
         return listOrder;
      }
      // 商品信息
      List<CommonOrderVO> listGoods = commonOrderMapper.listOrderGoodsInfo(listOrder);
      // 订单商品为空
      if (listGoods == null || listGoods.size() == 0) {
         return listOrder;
      }
      // 数据加工重新组织
      orderInfoFactory(acceptData, listOrder, listGoods, uid);
      // listDataFactory(acceptData, listOrder, listGoods, uid);
      return listOrder;
   }
   /**
    * 订单: 免单标识 奖励标识
    *
    * @param order
    * @param hasRewardCoupon
    * @param hongBaoState
    * @param list
    * @param signList
    */
   public void setSystemCouponRecord(CommonOrderVO order, boolean hasRewardCoupon,   Integer hongBaoState,
         Integer hongBaoType, List<UserSystemCouponRecord> list, List<String> signList,
         Long uid, AcceptData acceptData) {
      // 是否免单商品
      boolean freeOrder = false;
      // 是否奖励成功
      boolean rewardSuccess = false;
      if (list != null && list.size() > 0) {
         for (UserSystemCouponRecord couponRecord : list) {
            // 订单号匹配
            if (order.getOrderNo().equals(couponRecord.getOrderNo())) {
               Integer state = couponRecord.getState();
               String systemCouponType = couponRecord.getCouponType();
               // 奖励订单: 且成功
               if (CouponTypeEnum.rebatePercentCoupon.name().equals(systemCouponType)
                     && UserSystemCouponRecord.STATE_SUCCESS == state) {
                  rewardSuccess = true;
                  signList.add(PIC_REWARD); // 加入奖励成功图片
               } else if (CouponTypeEnum.freeCoupon.name().equals(systemCouponType)
                     || CouponTypeEnum.welfareFreeCoupon.name().equals(systemCouponType)
                     || CouponTypeEnum.freeCouponBuy.name().equals(systemCouponType)) {
                  if (UserSystemCouponRecord.STATE_FREE_ON == state) {
                     // 免单中
                     freeOrder = true;
                     signList.add(PIC_FREE_ON);
                  } else if (UserSystemCouponRecord.STATE_SUCCESS == state) {
                     // 免单成功
                     freeOrder = true;
                     signList.add(PIC_FREE_SUCCEED);
                  } else if (UserSystemCouponRecord.STATE_FAIL_RULE == state
                        || UserSystemCouponRecord.STATE_FAIL_DRAWBACK == state) {
                     // 规则不匹配、退款
                     freeOrder = true;
                     signList.add(PIC_FREE_FAIL);
                  }
               }
               break;
            }
         }
      }
      // 订单标识
      order.setSignList(signList);
      int type = 1; // 1 常规跳转页面 2弹出选项(奖励券)
      boolean rewardOrder = false;
      if (VersionUtil.greaterThan_2_1(acceptData.getPlatform(), acceptData.getVersion())) {
         if (rewardSuccess) {
            rewardOrder = true; // 以前版本奖励成功 的显示入口
         }
         // 已到账的返利订单、非会员可使用奖励券
         if (!freeOrder && HongBaoV2.TYPE_ZIGOU == hongBaoType && HongBaoV2.STATE_YILINGQU == hongBaoState
               && !userVIPInfoService.isVIP(uid)) {
            type = 2;
            rewardOrder = true;
         }
      } else if (hasRewardCoupon && !freeOrder && HongBaoV2.TYPE_ZIGOU == hongBaoType
               && HongBaoV2.STATE_YILINGQU == hongBaoState && !userVIPInfoService.isVIP(uid)) {
          // 有可用的奖励券 、非免单订单 、且已到账的 、返利订单、 非超级会员
         type = 2;
         rewardOrder = true;
      }
      // 维权订单 不可使用
      Integer orderState = order.getState();
      if(CommonOrder.STATE_WQ == orderState) {
         rewardOrder = false;
      }
      if (rewardOrder) {
         try {
            boolean newEdition = false;
            String num = null;
            String unit = null;
            boolean canUse = false;
            // 版本区分:2.1  奖励券倒计时
            if (VersionUtil.greaterThan_2_1(acceptData.getPlatform(), acceptData.getVersion())) {
               Date thirdCreateTime = order.getThirdCreateTime();
               Date accountTime = order.getAccountTime();
               if (thirdCreateTime != null && accountTime != null) {
                  long downOrderTime = thirdCreateTime.getTime();
                  long limitDate = TimeUtil.parse(Constant.COUPON_REWARD_TIME).getTime();
                  if (downOrderTime > limitDate) {
                     newEdition = true;
                     Date endDay = DateUtil.plusDayDate(Constant.COUPON_REWARD_LIMIT_DAY, accountTime);
                     long currentTime = java.lang.System.currentTimeMillis();
                     if (endDay.getTime() > currentTime) {
                        DateInfo dateInfo = DateUtil.dateDiff3(currentTime, endDay.getTime());
                        if (dateInfo != null) {
                           if (dateInfo.getDay() > 0) {
                              canUse = true;
                              unit = "天";
                              num = dateInfo.getDay().toString();
                           }
                           if (!canUse && dateInfo.getHour() > 0) {
                              canUse = true;
                              unit = "小时";
                              num = dateInfo.getHour().toString();
                           }
                           if (!canUse && dateInfo.getMinute() > 0) {
                              canUse = true;
                              unit = "分";
                              num = dateInfo.getMinute().toString();
                           }
                           if (!canUse && dateInfo.getSecond() > 0) {
                              canUse = true;
                              unit = "秒";
                              num = dateInfo.getSecond().toString();
                           }
                        }
                     }
                  }
               }
            }
            if (newEdition && !canUse) {
               // 新版不可使用
            } else {
               Map<String, Object> rewardMap = new HashMap<String, Object>();
               ClientTextStyleVO rewardStyleVO = new ClientTextStyleVO();
               rewardStyleVO.setColor("#E5005C");
               rewardStyleVO.setBottomColor("#FFDCEA");
               if (!newEdition) {
                  if (VersionUtil.greaterThan_2_1(acceptData.getPlatform(), acceptData.getVersion())) {
                     rewardStyleVO.setContent("使用奖励券 >");
                  } else {
                     rewardStyleVO.setContent("返利奖励 >");
                  }
               } else if (canUse) {
                  rewardStyleVO.setContent("使用奖励券");
                  ClientTextStyleVO txt1 = new ClientTextStyleVO();
                  txt1.setContent("剩");
                  txt1.setColor("#666666");
                  txt1.setBottomColor("#FFDCEA");
                  ClientTextStyleVO txt2 = new ClientTextStyleVO();
                  txt2.setContent(num);
                  txt2.setColor("#E5005C");
                  txt2.setBottomColor("#FFDCEA");
                  txt2.setFontSize("1.33");
                  ClientTextStyleVO txt3 = new ClientTextStyleVO();
                  txt3.setContent(unit + "关闭 >");
                  txt3.setColor("#666666");
                  txt3.setBottomColor("#FFDCEA");
                  List<ClientTextStyleVO> ticking = new ArrayList<ClientTextStyleVO>();
                  ticking.add(txt1);
                  ticking.add(txt2);
                  ticking.add(txt3);
                  rewardMap.put("ticking", ticking);
               }
               rewardMap.put("text", rewardStyleVO);
               Map<String, Object> jumpLink = new HashMap<String, Object>();
               jumpLink.put("orderNo", order.getOrderNo());
               jumpLink.put("goodsType", order.getSourceType() + "");
               Map<String, Object> jump = new HashMap<String, Object>();
               jump.put("type", type);
               jump.put("params", jumpLink);
               jump.put("jumpDetail", jumpDetailV2Service.getByTypeCache("rewardCouponDetail"));
               rewardMap.put("jump", jump);
               order.setRewardDetail(rewardMap);
            }
         } catch (Exception e) {
            e.printStackTrace();
         }
      }
      if (freeOrder) {
         ClientTextStyleVO rewardStyleVO = new ClientTextStyleVO();
         // 返利、免单详情
         rewardStyleVO.setContent("免单详情 >");
         rewardStyleVO.setColor("#E5005C");
         rewardStyleVO.setBottomColor("#FFDCEA");
         Map<String, Object> jumpLink = new HashMap<String, Object>();
         jumpLink.put("orderNo", order.getOrderNo());
         if (VersionUtil.greaterThan_1_6_0(acceptData.getPlatform(), acceptData.getVersion())) {
            jumpLink.put("goodsType", order.getSourceType() + "");
         }
         Map<String, Object> jump = new HashMap<String, Object>();
         jump.put("type", 1); // 页面跳转
         jump.put("params", jumpLink);
         jump.put("jumpDetail", jumpDetailV2Service.getByTypeCache("freeCouponDetail"));
         Map<String, Object> rewardMap = new HashMap<String, Object>();
         rewardMap.put("text", rewardStyleVO);
         rewardMap.put("jump", jump);
         order.setRewardDetail(rewardMap);
      }
   }
   /**
    * 订单信息加工
    *
    * @param acceptData
    * @param listOrder
    * @param listGoods
    * @param uid
    */
   public void orderInfoFactory(AcceptData acceptData, List<CommonOrderVO> listOrder, List<CommonOrderVO> listGoods,
         Long uid) throws Exception {
      List<String> listTB = new ArrayList<String>();
      List<String> listJD = new ArrayList<String>();
      List<String> listPDD = new ArrayList<String>();
      for (CommonOrderVO commonOrderVO : listOrder) {
         Integer sourceType = commonOrderVO.getSourceType();
         if (sourceType == null) {
            continue;
         } else if (sourceType == Constant.SOURCE_TYPE_TAOBAO) {
            listTB.add(commonOrderVO.getOrderNo());
         } else if (sourceType == Constant.SOURCE_TYPE_JD) {
            listJD.add(commonOrderVO.getOrderNo());
         } else if (sourceType == Constant.SOURCE_TYPE_PDD) {
            listPDD.add(commonOrderVO.getOrderNo());
         }
      }
      List<UserSystemCouponRecord> listRecordTB = null;
      if (listTB.size() > 0) {
         listRecordTB = userSystemCouponRecordService.getRecordByOrderNoList(Constant.SOURCE_TYPE_TAOBAO, listTB);
      }
      List<UserSystemCouponRecord> listRecordJD = null;
      if (listJD.size() > 0) {
         listRecordJD = userSystemCouponRecordService.getRecordByOrderNoList(Constant.SOURCE_TYPE_JD, listJD);
      }
      List<UserSystemCouponRecord> listRecordPDD = null;
      if (listPDD.size() > 0) {
         listRecordPDD = userSystemCouponRecordService.getRecordByOrderNoList(Constant.SOURCE_TYPE_PDD, listPDD);
      }
      SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd HH:mm");
      SimpleDateFormat formatday = new SimpleDateFormat("yyyy.MM.dd");
      // 2019.8.1开始返回维权信息
      Date august = TimeUtil.parse("2019-08-01");
      // 是否存在奖励券
      boolean hasRewardCoupon = userSystemCouponService.getValidRebateCoupon(uid);
      // 需要查询是否为VIP的用户ID,只有邀请订单才需要查询
      List<Long> needSelectVIPUidList = new ArrayList<>();
      for (CommonOrderVO order : listOrder) {
         if (order.getHongBaoType() == HongBaoV2.TYPE_YIJI || order.getHongBaoType() == HongBaoV2.TYPE_ERJI
               || order.getHongBaoType() == HongBaoV2.TYPE_SHARE_ERJI
               || order.getHongBaoType() == HongBaoV2.TYPE_SHARE_ERJI)
            needSelectVIPUidList.add(Long.parseLong(order.getUserId()));
      }
      Map<Long, Boolean> vipUserMap = userVIPInfoService.listByUids(needSelectVIPUidList);
      // 设置是否为vip订单
      for (CommonOrderVO order : listOrder) {
         if (order.getHongBaoType() == HongBaoV2.TYPE_YIJI || order.getHongBaoType() == HongBaoV2.TYPE_ERJI
               || order.getHongBaoType() == HongBaoV2.TYPE_SHARE_ERJI
               || order.getHongBaoType() == HongBaoV2.TYPE_SHARE_ERJI) {
            if (vipUserMap.get(Long.parseLong(order.getUserId())) != null
                  && vipUserMap.get(Long.parseLong(order.getUserId())) == true)
               order.setVipOrder(true);
            else
               order.setVipOrder(false);
         } else
            order.setVipOrder(false);
         if(order.isVipOrder())
            order.setVipOrderDesc("订单来源:由超级会员的粉丝产生");
      }
      for (CommonOrderVO order : listOrder) {
         String orderNo = order.getOrderNo();
         Integer sourceType = order.getSourceType();
         // 商品信息组合
         for (CommonOrderVO commonOrder : listGoods) {
            CommonOrderGoods goods = commonOrder.getCommonOrderGoods();
            if (goods == null) {
               continue;
            }
            if (sourceType.equals(commonOrder.getSourceType()) && orderNo.equals(commonOrder.getOrderNo())) {
               CommonOrderGoodsVO commonGoodsVO = new CommonOrderGoodsVO();
               PropertyUtils.copyProperties(commonGoodsVO, goods);
               commonGoodsVO.setGoodsType(sourceType);
               // 淘宝商品图片处理
               String picture = commonGoodsVO.getPicture();
               if (sourceType == Constant.SOURCE_TYPE_TAOBAO && !StringUtil.isNullOrEmpty(picture)
                     && !picture.contains("320x320")) {
                  commonGoodsVO.setPicture(TbImgUtil.getTBSize320Img(picture));
               }
               // 购买数量
               commonGoodsVO.setActualCount(commonOrder.getTotalCount() + "件");
               // 实付款
               BigDecimal totalSettlement = commonOrder.getTotalSettlement();
               if (totalSettlement == null || totalSettlement.compareTo(new BigDecimal(0)) <= 0) {
                  totalSettlement = commonOrder.getTotalPayment();
               }
               commonGoodsVO.setActualPay("付款金额:¥" + totalSettlement);
               Integer hongBaoType = order.getHongBaoType();
               // 邀请订单信息保护
               if (HongBaoV2.TYPE_YAOQING == hongBaoType || HongBaoV2.TYPE_YIJI == hongBaoType
                     || HongBaoV2.TYPE_ERJI == hongBaoType || HongBaoV2.TYPE_SHARE_YIJI == hongBaoType
                     || HongBaoV2.TYPE_SHARE_ERJI == hongBaoType) {
                  Map<String, String> titleMap = new HashMap<String, String>();
                  titleMap.put("content", "为保障用户隐私,商品信息已隐藏!");
                  titleMap.put("fontColor", "#888888");
                  titleMap.put("bottomColor", "#E9E9E9");
                  commonGoodsVO.setTitle(null);
                  commonGoodsVO.setGoodsTitle(titleMap);
               }
               // 订单类型为空时 已商品类为准
               Integer orderType = order.getOrderType();
               if (orderType == null) {
                  String shopType = commonGoodsVO.getShopType();
                  if (CommonOrderGoodsVO.TYPE_TAOBAO.equalsIgnoreCase(shopType)) {
                     order.setOrderType(1);
                  } else if (CommonOrderGoodsVO.TYPE_TMALL.equalsIgnoreCase(shopType)) {
                     order.setOrderType(2);
                  }
               }
               order.getListOrderGoods().add(commonGoodsVO);
            }
         }
         Date thirdCreateTime = order.getThirdCreateTime();
         if (thirdCreateTime != null) {
            order.setDownTime("下单时间:" + format.format(thirdCreateTime));
            order.setObtainTime(thirdCreateTime.getTime());
         }
         Date settleTime = order.getSettleTime();
         if (settleTime != null) {
            order.setReceiveTime("收货时间:" + format.format(settleTime));
         }
         // 订单类型
         if (sourceType == Constant.SOURCE_TYPE_TAOBAO) {
            Integer orderType = order.getOrderType();
            if (orderType == null)
               order.setOrderType(1);
         } else if (sourceType == Constant.SOURCE_TYPE_JD) {
            order.setOrderType(3);
         } else if (sourceType == Constant.SOURCE_TYPE_PDD) {
            order.setOrderType(4);
         }
         /* 订单状态 转换处理 */
         String orderStateContent = "";
         Map<String, String> orderStateMap = new HashMap<String, String>();
         // 订单状态
         Integer orderState = order.getState();
         // 红包状态
         Integer hongBaoState = order.getHongBaoState();
         Integer stateWholeOrder = order.getStateWholeOrder();
         if (CommonOrder.STATE_WHOLE_ORDER_BUFENYOUXIAO == stateWholeOrder) {
            // 整个订单部分失效:判断真实状态 订单、红包
            CommonOrderVO buFenOrder = commonOrderMapper.getBuFenOrderState(uid, order.getOrderNo());
            if (buFenOrder != null) {
               // 有效的订单状态
               orderState = buFenOrder.getState();
               // 有效的红包状态
               hongBaoState = buFenOrder.getHongBaoState();
            }
         }
         BigDecimal hongBao = order.getHongBao();
         if (hongBao == null) {
            hongBao = new BigDecimal(0);
         }
         if (CommonOrder.STATE_FK == orderState) {
            orderStateContent = "已付款";
         } else if (CommonOrder.STATE_JS == orderState) {
            orderStateContent = "已收货";
         } else if (CommonOrder.STATE_SX == orderState) {
            orderStateContent = "未付款/已退款";
         } else if (CommonOrder.STATE_WQ == orderState) {
            orderStateContent = "已售后";
            if (sourceType != null && sourceType == Constant.SOURCE_TYPE_TAOBAO) {
               /* 订单维权 判断是否全部维权 */
               List<TaoBaoWeiQuanOrder> listWQ = taoBaoWeiQuanOrderMapper
                     .selectListByOrderIdAndState(order.getOrderNo(), "维权成功");
               boolean isPart = false;// 默认失效
               BigDecimal weiQuanMoney = getWeiQuanMoney(listWQ, sourceType, uid);
               if (!VersionUtil.greaterThan_1_6_0(acceptData.getPlatform(), acceptData.getVersion())) {
                  if (isPart) {
                     hongBaoState = HongBaoV2.STATE_BUFENSHIXIAO; // 部分失效
                  } else {
                     hongBaoState = HongBaoV2.STATE_SHIXIAO; // 全部失效
                  }
               } else {
                  // 2019.8.1 返回维权信息
                  if (settleTime != null && august != null && settleTime.getTime() > august.getTime()) {
                     orderStateContent = "售后成功";
                     WeiQuanInfo weiQuanInfo = new WeiQuanInfo();
                     weiQuanInfo.setOldHongBao("¥" + hongBao.setScale(2, BigDecimal.ROUND_DOWN).toString());
                     weiQuanInfo
                           .setWqHongBao("售后:-¥" + weiQuanMoney.setScale(2, BigDecimal.ROUND_DOWN).toString());
                     hongBao = MoneyBigDecimalUtil.sub(hongBao, weiQuanMoney);
                     order.setWeiQuanInfo(weiQuanInfo);
                  }
               }
            }
         }
         orderStateMap.put("content", orderStateContent);
         orderStateMap.put("fontColor", "#666666");
         order.setOrderState(orderStateMap);
         String hongbaoInfo = "";
         // 订单标识
         List<String> signList = new ArrayList<String>();
         /* 订单返利类型 转换 */
         Integer hongBaoType = order.getHongBaoType();
         if (HongBaoV2.TYPE_ZIGOU == hongBaoType || 2 == hongBaoType) {
            // 自购
            hongbaoInfo = "返利";
            order.setOrderOrigin("1");
            order.setHongBaoTypePic(CommonOrder.TYPE_FANLI);
            signList.add(CommonOrder.TYPE_FANLI);
         } else if (HongBaoV2.TYPE_SHARE_GOODS == hongBaoType) {
            // 分享
            hongbaoInfo = "奖金";
            order.setOrderOrigin("2");
            order.setHongBaoTypePic(CommonOrder.TYPE_SHARE);
            signList.add(CommonOrder.TYPE_SHARE);
         } else if (HongBaoV2.TYPE_SHARE_YIJI == hongBaoType || HongBaoV2.TYPE_SHARE_ERJI == hongBaoType) {
            // 下级的分享订单: 显示邀请
            hongbaoInfo = "奖金";
            order.setOrderOrigin("3");
            order.setHongBaoTypePic(CommonOrder.TYPE_INVITE);
            signList.add(CommonOrder.TYPE_INVITE);
         } else if (HongBaoV2.TYPE_YAOQING == hongBaoType || HongBaoV2.TYPE_YIJI == hongBaoType
               || HongBaoV2.TYPE_ERJI == hongBaoType) {
            // 邀请订单
            hongbaoInfo = "奖金";
            order.setOrderOrigin("3");
            order.setHongBaoTypePic(CommonOrder.TYPE_INVITE);
            signList.add(CommonOrder.TYPE_INVITE);
            // 版本区分:2-0-2
            if (VersionUtil.greaterThan_2_1(acceptData.getPlatform(), acceptData.getVersion())) {
               InviteOrderSubsidy orderSubsidy = inviteOrderSubsidyService.getByOrderNoAndType(uid,
                     order.getOrderNo(), sourceType);
               if (orderSubsidy != null) {
                  ClientTextStyleVO subsidyInfo = new ClientTextStyleVO();
                  subsidyInfo.setContent("(补贴¥" + orderSubsidy.getMoney() + ")");
                  if (orderSubsidy.getState() == InviteOrderSubsidy.STATE_SUBSIDIZED) {
                     subsidyInfo.setColor("#E5005C");
                  } else {
                     subsidyInfo.setColor("#888888");
                  }
                  order.setSubsidy(subsidyInfo);
                  // 解释信息(问号)
                  List<String> subsidyList = new ArrayList<String>();
                  subsidyList.add("额外补贴能否获得由系统算法自动判断,人为无法干涉;");
                  subsidyList.add("额外补贴到账时间以及金额请以实际到账为准;");
                  subsidyList.add("额外补贴产生后将会在消息-资金消息中提醒你。");
                  order.setSubsidyList(subsidyList);
               }
            }
         }
         String hongBaoDate = null;
         String hongBaoState_Str = "";
         String hongbaoInfoFontColor = "#E5005C";
         /* 红包状态 转换 */
         String stateContent = "";
         String stateFontColor = "#E5005C";
         Integer orderHongBaoState = null;
         if (HongBaoV2.STATE_KELINGQU == hongBaoState || HongBaoV2.STATE_BUKELINGQU == hongBaoState) {
            orderHongBaoState = 1;
            stateContent = "未到账";
            hongBaoState_Str = "预估";
            Date preAccountTime = order.getPreAccountTime();
            if (preAccountTime != null) {
               hongBaoDate = "预计到账时间:" + formatday.format(preAccountTime);
            }
         } else if (HongBaoV2.STATE_YILINGQU == hongBaoState) {
            orderHongBaoState = 3;
            stateContent = "已到账";
            Date accountTime = order.getAccountTime();
            if (accountTime != null) {
               hongBaoDate = "到账时间:" + formatday.format(accountTime);
            }
         } else if (HongBaoV2.STATE_BUFENSHIXIAO == hongBaoState) {
            stateContent = "部分失效";
            orderHongBaoState = 3;
            Date accountTime = order.getAccountTime();
            if (accountTime != null) {
               hongBaoDate = "到账时间:" + formatday.format(accountTime);
            }
         } else if (HongBaoV2.STATE_SHIXIAO == hongBaoState) {
            orderHongBaoState = 4;
            stateContent = "已失效";
            hongbaoInfoFontColor = "#888888";
         }
         order.setHongBaoState(orderHongBaoState);
         order.setHongBaoDate(hongBaoDate);
         if (!StringUtil.isNullOrEmpty(order.getStateDesc())) {
            stateContent = stateContent + "-" + order.getStateDesc();
         }
         Map<String, String> stateMap = new HashMap<String, String>();
         stateMap.put("content", stateContent);
         stateMap.put("fontColor", stateFontColor);
         order.setAccountState(stateMap);
         hongbaoInfo = hongBaoState_Str + hongbaoInfo;
         Map<String, String> hongBaoMap = new HashMap<String, String>();
         hongBaoMap.put("content", hongbaoInfo + " ¥" + hongBao.setScale(2, BigDecimal.ROUND_DOWN).toString());
         hongBaoMap.put("fontColor", hongbaoInfoFontColor);
         order.setHongBaoInfo(hongBaoMap);
         // 非自购的订单 不显示返利、免单详情
         if (HongBaoV2.TYPE_ZIGOU != hongBaoType) {
            order.setSignList(signList);
         } else {
            // 奖励订单、免单 使用记录
            if (sourceType == null) {
               setSystemCouponRecord(order, hasRewardCoupon, hongBaoState, hongBaoType, null,
                     signList, uid, acceptData);
            } else if (sourceType == Constant.SOURCE_TYPE_TAOBAO) {
               setSystemCouponRecord(order, hasRewardCoupon, hongBaoState, hongBaoType,
                     listRecordTB, signList, uid, acceptData);
            } else if (sourceType == Constant.SOURCE_TYPE_JD) {
               setSystemCouponRecord(order, hasRewardCoupon, hongBaoState, hongBaoType,
                     listRecordJD, signList, uid, acceptData);
            } else if (sourceType == Constant.SOURCE_TYPE_PDD) {
               setSystemCouponRecord(order, hasRewardCoupon, hongBaoState, hongBaoType,
                     listRecordPDD, signList, uid, acceptData);
            }
         }
         // 分享、邀请 隐藏订单号
         if (HongBaoV2.TYPE_SHARE_GOODS == hongBaoType || HongBaoV2.TYPE_YAOQING == hongBaoType
               || HongBaoV2.TYPE_YIJI == hongBaoType || HongBaoV2.TYPE_ERJI == hongBaoType
               || HongBaoV2.TYPE_SHARE_YIJI == hongBaoType || HongBaoV2.TYPE_SHARE_ERJI == hongBaoType) {
            order.setOrderNo(UserUtil.filterOrderId(order.getOrderNo()));
         }
      }
   }
   @Override
   public Map<String, BigDecimal> countHistoryOrder(Long uid, Integer day, Integer source) {
      return commonOrderMapper.countHistoryOrder(uid, day, source);
   }
   @Override
   public OrderCountVO getOrderCount(Long uid, Integer day, Integer source) {
      return commonOrderMapper.getOrderCount(uid, day, source);
   }
   @Override
   public long countBonusOrderNumber(Long uid, Integer type, Integer day, String startTime, String endTime,
         Integer source) {
      return commonOrderMapper.countBonusOrderNumber(uid, type, day, startTime, endTime, source);
   }
   @Override
   public BigDecimal countBonusOrderMoney(Long uid, Integer type, Integer day, String startTime, String endTime,
         Integer source) {
      return commonOrderMapper.countBonusOrderMoney(uid, type, day, startTime, endTime, source);
   }
   @Override
   public Map<String, Object> countBonusOrderMoneyAndNumber(Long uid, Integer type, Integer day, String startTime,
         String endTime, Integer source) {
      return commonOrderMapper.countBonusOrderMoneyAndNumber(uid, type, day, startTime, endTime, source);
   }
   @Override
   public Long countUserOrderToApp(Long uid, Integer type, String startTime, String endTime, Integer day,
         Integer source, Integer state, Integer stateOrder) {
      return commonOrderMapper.countUserOrderToApp(uid, type, startTime, endTime, day, source, state, stateOrder);
   }
   private BigDecimal getWeiQuanMoney(List<TaoBaoWeiQuanOrder> listWQ, int sourceType, Long uid) {
      BigDecimal weiQuanMoney = new BigDecimal(0);
      if (listWQ != null && listWQ.size() > 0) {
         for (TaoBaoWeiQuanOrder weiQuanOrder : listWQ) {
            String tradeId = weiQuanOrder.getOrderItemId();
            // 查询红包
            List<String> tradeList = new ArrayList<>();
            tradeList.add(tradeId);
            List<HongBaoV2> hongBaoList = hongBaoV2Service.listBySourceTypeAndTradeIdListAndUid(sourceType, uid,
                  tradeList);
            if (hongBaoList != null && hongBaoList.size() > 0) {
               CommonOrder commonOrder = commonOrderMapper.selectBySourceTypeAndTradeId(sourceType, tradeId);
               if (commonOrder != null && commonOrder.getSettlement().compareTo(new BigDecimal(0)) > 0) {
                  BigDecimal wqMoney = MoneyBigDecimalUtil
                        .mul(hongBaoList.get(0).getMoney(), weiQuanOrder.getMoney())
                        .divide(commonOrder.getSettlement(), 2, BigDecimal.ROUND_UP);
                  if (wqMoney.compareTo(hongBaoList.get(0).getMoney()) > 0)
                     wqMoney = hongBaoList.get(0).getMoney();
                  weiQuanMoney = weiQuanMoney.add(wqMoney);
               }
            }
         }
      }
      return weiQuanMoney;
   }
   @Override
   public List<CommonOrder> listBySourceTypeAndOrderId(int sourceType, String orderId) {
      return commonOrderMapper.listBySourceTypeAndOrderNo(sourceType, orderId);
   }
   @Transactional
   @Override
   public List<CommonOrderAddResultDTO> addTaoBaoOrder(List<TaoBaoOrder> taoBaoOrders, Long uid)
         throws CommonOrderException {
      List<CommonOrderAddResultDTO> commonOrderList = new ArrayList<>();
      // 判断所有的订单状态
      int invalidCount = 0;
      for (TaoBaoOrder tb : taoBaoOrders) {
         if ("订单失效".equalsIgnoreCase(tb.getOrderState())) {
            invalidCount++;
         }
      }
      // 获取整体订单的状态
      int wholeOrderState = 0;
      if (taoBaoOrders.size() == invalidCount)
         wholeOrderState = CommonOrder.STATE_WHOLE_ORDER_SHIXIAO;
      else if (invalidCount == 0)
         wholeOrderState = CommonOrder.STATE_WHOLE_ORDER_YOUXIAO;
      else
         wholeOrderState = CommonOrder.STATE_WHOLE_ORDER_BUFENYOUXIAO;
      for (TaoBaoOrder taoBaoOrder : taoBaoOrders) {
         CommonOrder newCommonOrder = TaoBaoOrderUtil.convert(taoBaoOrder);
         CommonOrderGoods cog = new CommonOrderGoods();
         cog.setGoodsId(taoBaoOrder.getAuctionId() + "");
         cog.setGoodsType(Constant.SOURCE_TYPE_TAOBAO);
         newCommonOrder.setCommonOrderGoods(cog);
         newCommonOrder.setStateWholeOrder(wholeOrderState);
         // 订单商品插入
         List<CommonOrderGoods> commonGoodsList = commonOrderGoodsMapper.listByGoodsIdAndGoodsType(cog.getGoodsId(),
               cog.getGoodsType());
         if (commonGoodsList.size() <= 0)// 不存在就插入商品
         {
            TaoBaoGoodsBrief taoBaoGoods = null;
            try {
               taoBaoGoods = TaoKeApiUtil.getSimpleGoodsInfo(taoBaoOrder.getAuctionId());
            } catch (TaobaoGoodsDownException e) {
               e.printStackTrace();
               LogHelper.errorDetailInfo(e, "AUCTIONID:" + taoBaoOrder.getAuctionId(), "");
               try {
                  taoBaoGoods = TaoBaoUtil.getSimpleGoodsBrief(taoBaoOrder.getAuctionId());
               } catch (Exception e1) {
                  CommonGoods commonGoods = commonGoodsService.getCommonGoodsByGoodsIdAndGoodsType(
                        taoBaoOrder.getAuctionId(), Constant.SOURCE_TYPE_TAOBAO);
                  if (commonGoods != null)
                     taoBaoGoods = TaoBaoUtil.convert(commonGoods);
               }
            }
            if (taoBaoGoods != null) {
               cog = CommonOrderGoodsFactory.create(taoBaoGoods);
            }
            cog.setCreateTime(new Date());
            cog.setUpdateTime(new Date());
            commonOrderGoodsMapper.insertSelective(cog);
         }
         newCommonOrder.setUserInfo(new UserInfo(uid));
         commonOrderList.add(addCommonOrder(newCommonOrder));
      }
      return commonOrderList;
   }
   @Transactional
   @Override
   public List<CommonOrderAddResultDTO> addPDDOrder(List<PDDOrder> pddOrderList, Long uid)
         throws CommonOrderException {
      List<CommonOrderAddResultDTO> commonOrderList = new ArrayList<>();
      // 判断所有的订单状态
      int invalidCount = 0;
      for (PDDOrder order : pddOrderList) {
         if (order.getOrderStatus() == -1 || order.getOrderStatus() == 4 || order.getOrderStatus() == 8) {
            invalidCount++;
         }
      }
      // 获取整体订单的状态
      int wholeOrderState = 0;
      if (pddOrderList.size() == invalidCount)
         wholeOrderState = CommonOrder.STATE_WHOLE_ORDER_SHIXIAO;
      else if (invalidCount == 0)
         wholeOrderState = CommonOrder.STATE_WHOLE_ORDER_YOUXIAO;
      else
         wholeOrderState = CommonOrder.STATE_WHOLE_ORDER_BUFENYOUXIAO;
      for (PDDOrder pddOrder : pddOrderList) {
         CommonOrder newCommonOrder = CommonOrderFactory.create(pddOrder);
         CommonOrderGoods cog = new CommonOrderGoods();
         cog.setGoodsId(pddOrder.getGoodsId() + "");
         cog.setGoodsType(Constant.SOURCE_TYPE_PDD);
         newCommonOrder.setCommonOrderGoods(cog);
         newCommonOrder.setStateWholeOrder(wholeOrderState);
         // 订单商品插入
         List<CommonOrderGoods> commonGoodsList = commonOrderGoodsMapper.listByGoodsIdAndGoodsType(cog.getGoodsId(),
               cog.getGoodsType());
         if (commonGoodsList.size() <= 0)// 不存在就插入商品
         {
            PDDGoodsDetail pddGoods = null;
            pddGoods = PinDuoDuoApiUtil.getGoodsDetail(Long.parseLong(cog.getGoodsId()));
            if (pddGoods != null) {
               cog = CommonOrderGoodsFactory.create(pddGoods);
            }
            cog.setCreateTime(new Date());
            cog.setUpdateTime(new Date());
            commonOrderGoodsMapper.insertSelective(cog);
            newCommonOrder.setCommonOrderGoods(cog);
         } else {
         }
         newCommonOrder.setUserInfo(new UserInfo(uid));
         commonOrderList.add(addCommonOrder(newCommonOrder));
      }
      return commonOrderList;
   }
   @Transactional
   @Override
   public List<CommonOrderAddResultDTO> addJDOrder(JDOrder jdOrder, Long uid) throws CommonOrderException {
      List<CommonOrderAddResultDTO> commonOrderList = new ArrayList<>();
      // 判断所有的订单状态
      int invalidCount = 0;
      for (JDOrderItem tb : jdOrder.getOrderItemList()) {
         if (tb.getValidCode() < 16) {
            invalidCount++;
         }
      }
      // 获取整体订单的状态
      int wholeOrderState = 0;
      if (jdOrder.getOrderItemList().size() == invalidCount)
         wholeOrderState = CommonOrder.STATE_WHOLE_ORDER_SHIXIAO;
      else if (invalidCount == 0)
         wholeOrderState = CommonOrder.STATE_WHOLE_ORDER_YOUXIAO;
      else
         wholeOrderState = CommonOrder.STATE_WHOLE_ORDER_BUFENYOUXIAO;
      List<JDOrderItem> orderItemList = jdOrder.getOrderItemList();
      jdOrder.setOrderItemList(null);
      for (JDOrderItem itemOrder : orderItemList) {
         itemOrder.setOrder(jdOrder);
         CommonOrder newCommonOrder = CommonOrderFactory.create(itemOrder);
         CommonOrderGoods cog = new CommonOrderGoods();
         cog.setGoodsId(itemOrder.getSkuId() + "");
         cog.setGoodsType(Constant.SOURCE_TYPE_JD);
         newCommonOrder.setCommonOrderGoods(cog);
         newCommonOrder.setStateWholeOrder(wholeOrderState);
         // 订单商品插入
         List<CommonOrderGoods> commonGoodsList = commonOrderGoodsMapper.listByGoodsIdAndGoodsType(cog.getGoodsId(),
               cog.getGoodsType());
         if (commonGoodsList.size() <= 0)// 不存在就插入商品
         {
            JDGoods goods = JDApiUtil.getGoodsDetail(itemOrder.getSkuId());
            if (goods == null) {
               goods = JDUtil.getGoodsFromWeb(itemOrder.getSkuId());
            }
            if (goods == null) {
               goods = new JDGoods();
               goods.setSkuName(itemOrder.getSkuName());
               goods.setPrice(itemOrder.getPrice());
               goods.setSkuId(itemOrder.getSkuId());
            }
            if (goods != null) {
               cog = CommonOrderGoodsFactory.create(goods);
            }
            cog.setCreateTime(new Date());
            cog.setUpdateTime(new Date());
            commonOrderGoodsMapper.insertSelective(cog);
         } else {
         }
         newCommonOrder.setUserInfo(new UserInfo(uid));
         commonOrderList.add(addCommonOrder(newCommonOrder));
      }
      return commonOrderList;
   }
   /**
    * 添加订单
    *
    * @param commonOrder
    */
   @Transactional
   private CommonOrderAddResultDTO addCommonOrder(CommonOrder commonOrder) throws CommonOrderException {
      // 判断商品是否存在
      if (commonOrder == null)
         throw new CommonOrderException(1, "订单为空");
      if (commonOrder.getUserInfo() == null)
         throw new CommonOrderException(2, "订单用户为空");
      if (commonOrder.getCommonOrderGoods() == null || commonOrder.getCommonOrderGoods().getGoodsId() == null
            || commonOrder.getCommonOrderGoods().getGoodsType() == null)
         throw new CommonOrderException(3, "订单商品为空");
      // 不存在就插入,存在就不管
      CommonOrderGoods goods = commonOrder.getCommonOrderGoods();
      // 之前不存在于数据库
      if (commonOrder.getCommonOrderGoods().getId() == null) {
         List<CommonOrderGoods> commonGoodsList = commonOrderGoodsMapper
               .listByGoodsIdAndGoodsType(goods.getGoodsId(), goods.getGoodsType());
         if (commonGoodsList == null || commonGoodsList.size() < 1) {// 不存在
            commonOrderGoodsMapper.insertSelective(goods);
         } else {// 存在
            goods = commonGoodsList.get(0);
         }
         if (goods.getId() == null)
            throw new CommonOrderException(4, "商品插入失败");
         commonOrder.setCommonOrderGoods(goods);
      }
      CommonOrder oldCommonOrder = null;
      if (!StringUtil.isNullOrEmpty(commonOrder.getTradeId()))
         oldCommonOrder = commonOrderMapper.selectBySourceTypeAndTradeId(commonOrder.getSourceType(),
               commonOrder.getTradeId());
      else {
         throw new CommonOrderException(10, "交易ID为空");
      }
      if (oldCommonOrder == null)// 新增
      {
         commonOrder.setCreateTime(new Date());
         commonOrderMapper.insertSelective(commonOrder);
         // 插入映射,保证交易ID的完整性
         commonOrderTradeIdMapMapper.insertSelective(new CommonOrderTradeIdMap(commonOrder.getId(),
               commonOrder.getTradeId(), new Date(), commonOrder.getSourceType()));
         return new CommonOrderAddResultDTO(commonOrder, CommonOrderAddResultDTO.TYPE_ADD);
      } else {// 修改
         // 非京东已经结算,已经失效,状态未改变的订单不处理
         if ((oldCommonOrder.getState() == CommonOrder.STATE_JS
               && oldCommonOrder.getSourceType() != Constant.SOURCE_TYPE_JD)
               || oldCommonOrder.getState() == CommonOrder.STATE_SX
               || oldCommonOrder.getState() == CommonOrder.STATE_WQ
               || (oldCommonOrder.getState().intValue() == commonOrder.getState())) {
            return new CommonOrderAddResultDTO(oldCommonOrder, CommonOrderAddResultDTO.TYPE_NOUPDATE);
         }
         // 交易ID一致才修改
         if (commonOrder.getTradeId() != null
               && commonOrder.getTradeId().equalsIgnoreCase(oldCommonOrder.getTradeId())) {
            CommonOrder updateCommonOrder = new CommonOrder(oldCommonOrder.getId());
            updateCommonOrder.seteIncome(commonOrder.geteIncome());
            updateCommonOrder.setEstimate(commonOrder.getEstimate());
            updateCommonOrder.setPayment(commonOrder.getPayment());
            updateCommonOrder.setSettlement(commonOrder.getSettlement());
            updateCommonOrder.setSettleTime(commonOrder.getSettleTime());
            updateCommonOrder.setState(commonOrder.getState());
            updateCommonOrder.setStateWholeOrder(commonOrder.getStateWholeOrder());
            updateCommonOrder.setUpdateTime(new Date());
            updateCommonOrder.setTradeId(commonOrder.getTradeId());
            commonOrderMapper.updateByPrimaryKeySelective(updateCommonOrder);
            return new CommonOrderAddResultDTO(commonOrderMapper.selectByPrimaryKey(updateCommonOrder.getId()),
                  CommonOrderAddResultDTO.TYPE_UPDATE);
         } else
            return new CommonOrderAddResultDTO(oldCommonOrder, CommonOrderAddResultDTO.TYPE_NOUPDATE);
      }
   }
   @Override
   public long countByUidAndOrderStateWithOrderBalanceTime(Long uid, int state, Date minDate, Date maxDate) {
      return commonOrderMapper.countByUidAndOrderStateWithOrderBalanceTime(uid, state, minDate, maxDate);
   }
   @Override
   public List<CommonOrderVO> listQueryByUid(long start, int count, Long uid, Integer state, Integer type,
         Integer orderState, String orderNo, String startTime, String endTime, Integer dateType)
         throws CommonOrderException {
      List<CommonOrderVO> list = commonOrderMapper.listQueryByUid(start, count, uid, state, type, orderState, orderNo,
            startTime, endTime, dateType);
      if (list == null) {
         list = new ArrayList<CommonOrderVO>();
      }
      if (list.size() == 0) {
         return list;
      }
      SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
      for (CommonOrderVO order : list) {
         // 下单时间
         Date thirdCreateTime = order.getThirdCreateTime();
         if (thirdCreateTime != null) {
            order.setDownTime(format.format(thirdCreateTime));
         }
         // 收货时间
         Date settleTime = order.getSettleTime();
         if (settleTime != null) {
            order.setReceiveTime(format.format(settleTime));
         }
         // 到账时间
         Date accountTime = order.getAccountTime();
         if (accountTime != null) {
            order.setHongBaoDate(format.format(accountTime));
         }
         BigDecimal settlement = order.getSettlement();
         if (settlement != null && settlement.compareTo(new BigDecimal(0)) > 0) {
            order.setPayment(settlement); // 实际付款金额
         }
         /* 订单返利类型 转换 */
         Integer hongBaoType = order.getHongBaoType();
         if (HongBaoV2.TYPE_ZIGOU == hongBaoType || 2 == hongBaoType) {
            // 自购
            order.setHongBaoType(1);
         } else if (HongBaoV2.TYPE_SHARE_GOODS == hongBaoType) {
            // 分享
            order.setHongBaoType(2);
         } else if (HongBaoV2.TYPE_YAOQING == hongBaoType || HongBaoV2.TYPE_YIJI == hongBaoType
               || HongBaoV2.TYPE_ERJI == hongBaoType || HongBaoV2.TYPE_SHARE_YIJI == hongBaoType
               || HongBaoV2.TYPE_SHARE_ERJI == hongBaoType) {
            // 邀请
            order.setHongBaoType(3);
         }
         Integer hongBaoState = order.getHongBaoState();
         if (HongBaoV2.STATE_KELINGQU == hongBaoState || HongBaoV2.STATE_BUKELINGQU == hongBaoState) {
            // 未到账
            order.setHongBaoState(1);
         } else if (HongBaoV2.STATE_YILINGQU == hongBaoState) {
            // 已到账
            order.setHongBaoState(2);
         } else if (HongBaoV2.STATE_SHIXIAO == hongBaoState) {
            // 已失效
            order.setHongBaoState(3);
         }
      }
      return list;
   }
   @Override
   public long countQueryByUid(Long uid, Integer state, Integer type, Integer orderState, String orderNo,
         String startTime, String endTime, Integer dateType) throws CommonOrderException {
      return commonOrderMapper.countQueryByUid(uid, state, type, orderState, orderNo, startTime, endTime, dateType);
   }
   @Override
   public List<CommonOrderVO> listQuery(long start, int count, Integer keyType, String key, Integer state,
         Integer type, Integer orderState, String startTime, String endTime, Integer source, List<Long> listShopId,
         List<Long> listGoodsId, Date minTime, BigDecimal money) throws CommonOrderException {
      List<CommonOrderVO> list = null;
      if (StringUtil.isNullOrEmpty(key) || keyType == 1) {// 搜索框无值或者按订单号搜索时都只搜索主订单
         list = commonOrderMapper.listQueryWithNoChild(start, count, keyType, key, state, type, orderState,
               startTime, endTime, source);
      } else {
         list = commonOrderMapper.listQuery(start, count, keyType, key, state, type, orderState, startTime, endTime,
               source, listShopId, listGoodsId, minTime, money);
      }
      if (list == null) {
         list = new ArrayList<CommonOrderVO>();
      }
      if (list.size() == 0) {
         return list;
      }
      List<String> listTB = new ArrayList<String>();
      List<String> listJD = new ArrayList<String>();
      List<String> listPDD = new ArrayList<String>();
      for (CommonOrderVO commonOrderVO : list) {
         Integer sourceType = commonOrderVO.getSourceType();
         if (sourceType == null) {
            continue;
         } else if (sourceType == Constant.SOURCE_TYPE_TAOBAO) {
            listTB.add(commonOrderVO.getOrderNo());
         } else if (sourceType == Constant.SOURCE_TYPE_JD) {
            listJD.add(commonOrderVO.getOrderNo());
         } else if (sourceType == Constant.SOURCE_TYPE_PDD) {
            listPDD.add(commonOrderVO.getOrderNo());
         }
      }
      List<UserSystemCouponRecord> listRecordTB = null;
      if (listTB.size() > 0) {
         listRecordTB = userSystemCouponRecordService.getRecordByOrderNoList(Constant.SOURCE_TYPE_TAOBAO, listTB);
      }
      List<UserSystemCouponRecord> listRecordJD = null;
      if (listJD.size() > 0) {
         listRecordJD = userSystemCouponRecordService.getRecordByOrderNoList(Constant.SOURCE_TYPE_JD, listJD);
      }
      List<UserSystemCouponRecord> listRecordPDD = null;
      if (listPDD.size() > 0) {
         listRecordPDD = userSystemCouponRecordService.getRecordByOrderNoList(Constant.SOURCE_TYPE_PDD, listPDD);
      }
      SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
      for (CommonOrderVO order : list) {
         // 下单时间
         Date thirdCreateTime = order.getThirdCreateTime();
         if (thirdCreateTime != null) {
            order.setDownTime(format.format(thirdCreateTime));
         }
         // 收货时间
         Date settleTime = order.getSettleTime();
         if (settleTime != null) {
            order.setReceiveTime(format.format(settleTime));
         }
         // 到账时间
         Date accountTime = order.getAccountTime();
         if (accountTime != null) {
            order.setHongBaoDate(format.format(accountTime));
         }
         BigDecimal settlement = order.getSettlement();
         if (settlement != null && settlement.compareTo(new BigDecimal(0)) > 0) {
            order.setPayment(settlement); // 实际付款金额
         }
         /* 订单返利类型 转换 */
         Integer hongBaoType = order.getHongBaoType();
         if (HongBaoV2.TYPE_ZIGOU == hongBaoType || 2 == hongBaoType) {
            // 自购
            order.setHongBaoType(1);
         } else if (HongBaoV2.TYPE_SHARE_GOODS == hongBaoType) {
            // 分享
            order.setHongBaoType(2);
         } else if (HongBaoV2.TYPE_YAOQING == hongBaoType || HongBaoV2.TYPE_YIJI == hongBaoType
               || HongBaoV2.TYPE_ERJI == hongBaoType || HongBaoV2.TYPE_SHARE_YIJI == hongBaoType
               || HongBaoV2.TYPE_SHARE_ERJI == hongBaoType) {
            // 邀请
            order.setHongBaoType(3);
         }
         Integer hongBaoState = order.getHongBaoState();
         if (HongBaoV2.STATE_KELINGQU == hongBaoState || HongBaoV2.STATE_BUKELINGQU == hongBaoState) {
            // 未到账
            order.setHongBaoState(1);
         } else if (HongBaoV2.STATE_YILINGQU == hongBaoState) {
            // 已到账
            order.setHongBaoState(2);
         } else if (HongBaoV2.STATE_SHIXIAO == hongBaoState) {
            // 已失效
            order.setHongBaoState(3);
         }
         List<HongBaoV2> listhb = hongBaoV2Service.listChildrenById(order.getHongbaoId());
         if (listhb != null && listhb.size() > 0) {
            if (listhb.size() == 1) {
               UserInfo userInfo = listhb.get(0).getUserInfo();
               if (userInfo != null) {
                  order.setLevelOneId(userInfo.getId() + "");
                  order.setLevelOneMoney(listhb.get(0).getMoney() + "");
               }
            } else if (listhb.size() == 2) {
               UserInfo userInfo = listhb.get(0).getUserInfo();
               if (userInfo != null) {
                  order.setLevelOneId(userInfo.getId() + "");
                  order.setLevelOneMoney(listhb.get(0).getMoney() + "");
               }
               UserInfo userInfo2 = listhb.get(1).getUserInfo();
               if (userInfo2 != null) {
                  order.setLevelTwoId(userInfo2.getId() + "");
                  order.setLevelTwoMoney(listhb.get(1).getMoney() + "");
               }
            }
         }
         Integer sourceType = order.getSourceType();
         // 奖励订单、免单 使用记录
         if (sourceType == null) {
         } else if (sourceType == Constant.SOURCE_TYPE_TAOBAO && listRecordTB != null && listRecordTB.size() > 0) {
            for (UserSystemCouponRecord couponRecord : listRecordTB) {
               if (order.getOrderNo().equals(couponRecord.getOrderNo())) {
                  String systemCouponType = couponRecord.getCouponType();
                  Integer couponState = couponRecord.getState();
                  if (CouponTypeEnum.freeCoupon.name().equals(systemCouponType)
                        || CouponTypeEnum.welfareFreeCoupon.name().equals(systemCouponType)
                        || CouponTypeEnum.freeCouponBuy.name().equals(systemCouponType)) {
                     if (UserSystemCouponRecord.STATE_SUCCESS == couponState) {
                        // 免单成功
                        order.setOtherState(2);
                     } else if (UserSystemCouponRecord.STATE_FREE_ON == couponState) {
                        order.setOtherState(1);
                     }
                  }
                  break;
               }
            }
         } else if (sourceType == Constant.SOURCE_TYPE_JD && listRecordJD != null && listRecordJD.size() > 0) {
            for (UserSystemCouponRecord couponRecord : listRecordJD) {
               if (order.getOrderNo().equals(couponRecord.getOrderNo())) {
                  String systemCouponType = couponRecord.getCouponType();
                  Integer couponState = couponRecord.getState();
                  if (CouponTypeEnum.freeCoupon.name().equals(systemCouponType)
                        || CouponTypeEnum.welfareFreeCoupon.name().equals(systemCouponType)
                        || CouponTypeEnum.freeCouponBuy.name().equals(systemCouponType)) {
                     if (UserSystemCouponRecord.STATE_SUCCESS == couponState) {
                        // 免单成功
                        order.setOtherState(2);
                     } else if (UserSystemCouponRecord.STATE_FREE_ON == couponState) {
                        order.setOtherState(1);
                     }
                  }
                  break;
               }
            }
         } else if (sourceType == Constant.SOURCE_TYPE_PDD && listRecordPDD != null && listRecordPDD.size() > 0) {
            for (UserSystemCouponRecord couponRecord : listRecordPDD) {
               if (order.getOrderNo().equals(couponRecord.getOrderNo())) {
                  String systemCouponType = couponRecord.getCouponType();
                  Integer couponState = couponRecord.getState();
                  if (CouponTypeEnum.freeCoupon.name().equals(systemCouponType)
                        || CouponTypeEnum.welfareFreeCoupon.name().equals(systemCouponType)
                        || CouponTypeEnum.freeCouponBuy.name().equals(systemCouponType)) {
                     if (UserSystemCouponRecord.STATE_SUCCESS == couponState) {
                        // 免单成功
                        order.setOtherState(2);
                     } else if (UserSystemCouponRecord.STATE_FREE_ON == couponState) {
                        order.setOtherState(1);
                     }
                  }
                  break;
               }
            }
         }
      }
      return list;
   }
   @Override
   public long countQuery(Integer keyType, String key, Integer state, Integer type, Integer orderState,
         String startTime, String endTime, Integer source, List<Long> listShopId, List<Long> listGoodsId,
         Date minTime, BigDecimal money) throws CommonOrderException {
      if (StringUtil.isNullOrEmpty(key) || keyType == 1) {// 搜索框无值或者按订单号搜索时都只搜索主订单
         return commonOrderMapper.countQueryWithNoChild(keyType, key, state, type, orderState, startTime, endTime,
               source);
      } else {
         return commonOrderMapper.countQuery(keyType, key, state, type, orderState, startTime, endTime, source,
               listShopId, listGoodsId, minTime, money);
      }
   }
   @Override
   public CommonOrderVO getCommonOrderByOrderNo(Long uid, String orderNo, Integer orderState, Integer sourceType)
         throws CommonOrderException {
      if (sourceType == null) {
         sourceType = Constant.SOURCE_TYPE_TAOBAO;
      }
      CommonOrderVO commonOrderVO = commonOrderMapper.getCommonOrderByOrderNo(uid, orderNo, orderState, sourceType);
      // 订单信息为空
      if (commonOrderVO == null) {
         return null;
      }
      List<CommonOrderVO> listOrder = new ArrayList<CommonOrderVO>();
      listOrder.add(commonOrderVO);
      // 商品信息
      List<CommonOrderVO> listGoods = commonOrderMapper.listOrderGoodsInfo(listOrder);
      // 订单商品为空
      if (listGoods == null || listGoods.size() == 0) {
         return null;
      }
      /* 组合商品信息 */
      for (CommonOrderVO commonOrder : listGoods) {
         CommonOrderGoods goods = commonOrder.getCommonOrderGoods();
         if (goods == null) {
            continue;
         }
         String orderNo1 = commonOrder.getOrderNo();
         Integer sourceType1 = commonOrder.getSourceType();
         String orderNo2 = commonOrderVO.getOrderNo();
         Integer sourceType2 = commonOrderVO.getSourceType();
         // 来源、订单号相同
         if (sourceType1.equals(sourceType2) && orderNo1.equals(orderNo2)) {
            // 加入商品信息
            List<CommonOrderGoodsVO> listOrderGoods = commonOrderVO.getListOrderGoods();
            CommonOrderGoodsVO commonGoodsVO = new CommonOrderGoodsVO();
            try {
               PropertyUtils.copyProperties(commonGoodsVO, goods);
            } catch (Exception e) {
               e.printStackTrace();
            }
            String picture = commonGoodsVO.getPicture();
            if (!StringUtil.isNullOrEmpty(picture) && !picture.contains("320x320")) {
               commonGoodsVO.setPicture(TbImgUtil.getTBSize320Img(picture));
            }
            Integer hongBaoType = commonOrderVO.getHongBaoType();
            // 邀请订单信息保护
            if (HongBaoV2.TYPE_YAOQING == hongBaoType || HongBaoV2.TYPE_YIJI == hongBaoType
                  || HongBaoV2.TYPE_ERJI == hongBaoType || HongBaoV2.TYPE_SHARE_YIJI == hongBaoType
                  || HongBaoV2.TYPE_SHARE_ERJI == hongBaoType) {
               Map<String, String> titleMap = new HashMap<String, String>();
               titleMap.put("content", "为保障用户隐私,商品信息已隐藏!");
               titleMap.put("fontColor", "#888888");
               titleMap.put("bottomColor", "#E9E9E9");
               commonGoodsVO.setTitle(null);
               commonGoodsVO.setGoodsTitle(titleMap);
            }
            // 购买数量
            commonGoodsVO.setActualCount(commonOrder.getTotalCount() + "件");
            BigDecimal totalSettlement = commonOrder.getTotalSettlement();
            if (totalSettlement == null || totalSettlement.compareTo(new BigDecimal(0)) <= 0) {
               totalSettlement = commonOrder.getTotalPayment();
            }
            // 实付款
            commonGoodsVO.setActualPay("付款金额:¥" + totalSettlement);
            listOrderGoods.add(commonGoodsVO);
            Integer orderType = commonOrder.getOrderType();
            if (orderType == null) {
               String shopType = commonGoodsVO.getShopType();
               if (CommonOrderGoodsVO.TYPE_TAOBAO.equalsIgnoreCase(shopType)) {
                  commonOrder.setOrderType(1);
               } else if (CommonOrderGoodsVO.TYPE_TMALL.equalsIgnoreCase(shopType)) {
                  commonOrder.setOrderType(2);
               }
            }
            break;
         }
      }
      return commonOrderVO;
   }
   @Override
   public JSONObject getRewardJumpInfo(String orderNo, Integer goodsType) {
      JSONObject map = new JSONObject();
      // 订单标识
      List<String> signList = new ArrayList<String>();
      signList.add(CommonOrder.TYPE_FANLI);
      signList.add(PIC_REWARD); // 加入奖励成功图片
      map.put("signList", signList);
      ClientTextStyleVO rewardStyleVO = new ClientTextStyleVO();
      // 奖励券进度详情
      rewardStyleVO.setContent("返利奖励 >");
      rewardStyleVO.setColor("#E5005C");
      rewardStyleVO.setBottomColor("#FFDCEA");
      Map<String, Object> jumpLink = new HashMap<String, Object>();
      jumpLink.put("orderNo", orderNo);
      jumpLink.put("goodsType", goodsType == null ? goodsType : goodsType + "");
      Map<String, Object> jump = new HashMap<String, Object>();
      jump.put("type", 1);
      jump.put("params", jumpLink);
      jump.put("jumpDetail", jumpDetailV2Service.getByTypeCache("rewardCouponDetail"));
      Map<String, Object> rewardMap = new HashMap<String, Object>();
      rewardMap.put("text", rewardStyleVO);
      rewardMap.put("jump", jump);
      map.put("rewardDetail", rewardMap);
      return map;
   }
   @Override
   public CommonOrder selectBySourceTypeAndTradeId(int sourceType, String tradeId) {
      return commonOrderMapper.selectBySourceTypeAndTradeId(sourceType, tradeId);
   }
   @Transactional
   @Override
   public void deleteErrorCommonOrder(Long coId) {
      // 查询是否返利到账
      HongBaoOrder hongBaoOrder = hongBaoOrderService.selectDetailByCommonOrderId(coId);
      if (hongBaoOrder.getHongBaoV2().getState() == HongBaoV2.STATE_YILINGQU)
         return;
      List<HongBaoV2> hongBaoList = hongBaoV2Service.listChildrenById(hongBaoOrder.getHongBaoV2().getId());
      boolean canDelete = true;
      for (HongBaoV2 child : hongBaoList)
         if (child.getState() == HongBaoV2.STATE_YILINGQU) {
            canDelete = false;
            break;
         }
      // 不能删除
      if (!canDelete)
         return;
      // 删除child
      for (HongBaoV2 child : hongBaoList)
         hongBaoV2Service.deleteByPrimaryKey(child.getId());
      // 删除主红包
      hongBaoV2Service.deleteByPrimaryKey(hongBaoOrder.getHongBaoV2().getId());
      // 删除hongbaoOrder
      hongBaoOrderService.deleteByPrimaryKey(hongBaoOrder.getId());
      // 删除CommonOrder
      commonOrderMapper.deleteByPrimaryKey(hongBaoOrder.getCommonOrder().getId());
   }
   @Override
   public List<CommonOrder> listBySourceTypeAndTradeId(int sourceType, String tradeId) {
      return commonOrderMapper.listBySourceTypeAndTradeId(sourceType, tradeId);
   }
   @Override
   public List<CommonOrder> listBySourceTypeAndStateAndThirdCrateTime(int sourceType, Integer state, Long minTime,
         Long maxTime, int page, int pageSize) {
      return commonOrderMapper.listBySourceTypeAndStateAndThirdCrateTime(sourceType, state, minTime, maxTime,
            (page - 1) * pageSize, pageSize);
   }
   @Override
   public List<CommonOrder> getByOrderNo(Long uid, String orderNO) {
      return commonOrderMapper.getByOrderNo(uid, orderNO);
   }
   @Override
   public CommonOrder selectLatestValidByUid(Long uid) {
      List<Integer> stateList = new ArrayList<>();
      stateList.add(CommonOrder.STATE_FK);
      stateList.add(CommonOrder.STATE_JS);
      List<CommonOrder> commonOrderList = commonOrderMapper.listByUid(uid, stateList, 0, 1);
      if (commonOrderList == null || commonOrderList.size() == 0)
         return null;
      return commonOrderList.get(0);
   }
   @Override
   public CommonOrderVO firstValidOrderByUid(Long uid) {
      return commonOrderMapper.firstValidOrderByUid(uid, null, null);
   }
   @Override
   public CommonOrderVO firstValidOrderByUidAndType(Long uid, Integer type) {
      return commonOrderMapper.firstValidOrderByUid(uid, type, null);
   }
   @Override
   public CommonOrderVO firstValidOrderLastMonthByUidAndType(Long uid, Integer type) {
      return commonOrderMapper.firstValidOrderByUid(uid, type, 4);
   }
   @Override
   public CommonOrder getFirstShareOrderByUid(Long uid) {
      return commonOrderMapper.getFirstShareOrderByUid(uid);
   }
   @Override
   public BigDecimal getTotalRewardMoneyByOrderNoAndSourceType(String orderNo, Integer sourceType) {
      return commonOrderMapper.getTotalRewardMoneyByOrderNoAndSourceType(orderNo, sourceType);
   }
package com.yeshi.fanli.service.impl.order;
   @Override
   public long count24HValidOrderByUid(Long uid, Date minTime) {
      return commonOrderMapper.count24HValidOrderByUid(uid, minTime);
   }
}
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.yeshi.utils.DateUtil;
import org.yeshi.utils.entity.DateInfo;
import org.yeshi.utils.taobao.TbImgUtil;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.Producer;
import com.yeshi.fanli.dao.mybatis.order.CommonOrderGoodsMapper;
import com.yeshi.fanli.dao.mybatis.order.CommonOrderMapper;
import com.yeshi.fanli.dao.mybatis.order.CommonOrderTradeIdMapMapper;
import com.yeshi.fanli.dao.mybatis.taobao.TaoBaoOrderGoodsMapper;
import com.yeshi.fanli.dao.mybatis.taobao.TaoBaoWeiQuanOrderMapper;
import com.yeshi.fanli.dto.mq.order.OrderTopicTagEnum;
import com.yeshi.fanli.dto.mq.order.body.OrderConfirmMQMsg;
import com.yeshi.fanli.dto.order.CommonOrderAddResultDTO;
import com.yeshi.fanli.dto.pdd.PDDGoodsDetail;
import com.yeshi.fanli.entity.accept.AcceptData;
import com.yeshi.fanli.entity.bus.user.HongBaoV2;
import com.yeshi.fanli.entity.bus.user.UserInfo;
import com.yeshi.fanli.entity.bus.user.UserSystemCouponRecord;
import com.yeshi.fanli.entity.bus.user.vip.UserLevelEnum;
import com.yeshi.fanli.entity.goods.CommonGoods;
import com.yeshi.fanli.entity.jd.JDGoods;
import com.yeshi.fanli.entity.jd.JDOrder;
import com.yeshi.fanli.entity.jd.JDOrderItem;
import com.yeshi.fanli.entity.order.CommonOrder;
import com.yeshi.fanli.entity.order.CommonOrderGoods;
import com.yeshi.fanli.entity.order.CommonOrderTradeIdMap;
import com.yeshi.fanli.entity.order.ESOrder;
import com.yeshi.fanli.entity.order.HongBaoOrder;
import com.yeshi.fanli.entity.order.InviteOrderSubsidy;
import com.yeshi.fanli.entity.pdd.PDDOrder;
import com.yeshi.fanli.entity.system.ConfigKeyEnum;
import com.yeshi.fanli.entity.system.SystemCoupon.CouponTypeEnum;
import com.yeshi.fanli.entity.taobao.TaoBaoGoodsBrief;
import com.yeshi.fanli.entity.taobao.TaoBaoOrder;
import com.yeshi.fanli.entity.taobao.TaoBaoOrderGoods;
import com.yeshi.fanli.entity.taobao.TaoBaoWeiQuanOrder;
import com.yeshi.fanli.exception.order.CommonOrderException;
import com.yeshi.fanli.exception.taobao.TaobaoGoodsDownException;
import com.yeshi.fanli.log.LogHelper;
import com.yeshi.fanli.log.LogManager;
import com.yeshi.fanli.log.LogType;
import com.yeshi.fanli.service.inter.common.JumpDetailV2Service;
import com.yeshi.fanli.service.inter.config.ConfigService;
import com.yeshi.fanli.service.inter.config.SystemCouponService;
import com.yeshi.fanli.service.inter.goods.CommonGoodsService;
import com.yeshi.fanli.service.inter.order.CommonOrderService;
import com.yeshi.fanli.service.inter.order.HongBaoOrderService;
import com.yeshi.fanli.service.inter.order.HongBaoV2Service;
import com.yeshi.fanli.service.inter.order.InviteOrderSubsidyService;
import com.yeshi.fanli.service.inter.user.UserInfoService;
import com.yeshi.fanli.service.inter.user.UserSystemCouponRecordService;
import com.yeshi.fanli.service.inter.user.UserSystemCouponService;
import com.yeshi.fanli.service.inter.user.invite.UserInviteService;
import com.yeshi.fanli.service.inter.user.vip.UserVIPInfoService;
import com.yeshi.fanli.service.manger.user.UserLevelManager;
import com.yeshi.fanli.util.Constant;
import com.yeshi.fanli.util.MoneyBigDecimalUtil;
import com.yeshi.fanli.util.StringUtil;
import com.yeshi.fanli.util.TimeUtil;
import com.yeshi.fanli.util.VersionUtil;
import com.yeshi.fanli.util.account.UserUtil;
import com.yeshi.fanli.util.factory.CommonOrderGoodsFactory;
import com.yeshi.fanli.util.factory.goods.CommonOrderFactory;
import com.yeshi.fanli.util.jd.JDApiUtil;
import com.yeshi.fanli.util.jd.JDUtil;
import com.yeshi.fanli.util.pinduoduo.PinDuoDuoApiUtil;
import com.yeshi.fanli.util.rocketmq.MQMsgBodyFactory;
import com.yeshi.fanli.util.rocketmq.MQTopicName;
import com.yeshi.fanli.util.taobao.TaoBaoUtil;
import com.yeshi.fanli.util.taobao.TaoKeApiUtil;
import com.yeshi.fanli.util.user.UserLevelUtil;
import com.yeshi.fanli.vo.msg.ClientTextStyleVO;
import com.yeshi.fanli.vo.order.CommonOrderGoodsVO;
import com.yeshi.fanli.vo.order.CommonOrderVO;
import com.yeshi.fanli.vo.order.HongBaoCountVO;
import com.yeshi.fanli.vo.order.OrderCountVO;
import com.yeshi.fanli.vo.order.WeiQuanInfo;
import net.sf.json.JSONObject;
@Service
public class CommonOrderServiceImpl implements CommonOrderService {
   @Resource
   private CommonOrderMapper commonOrderMapper;
   @Resource
   private TaoBaoWeiQuanOrderMapper taoBaoWeiQuanOrderMapper;
   @Resource
   private CommonOrderGoodsMapper commonOrderGoodsMapper;
   @Resource
   private JumpDetailV2Service jumpDetailV2Service;
   @Resource
   private ConfigService configService;
   @Resource
   private UserSystemCouponService userSystemCouponService;
   @Resource
   private UserSystemCouponRecordService userSystemCouponRecordService;
   @Resource
   private SystemCouponService systemCouponService;
   @Resource
   private HongBaoV2Service hongBaoV2Service;
   @Resource
   private CommonOrderTradeIdMapMapper commonOrderTradeIdMapMapper;
   @Resource
   private CommonGoodsService commonGoodsService;
   @Resource
   private HongBaoOrderService hongBaoOrderService;
   @Resource
   private InviteOrderSubsidyService inviteOrderSubsidyService;
   @Resource
   private UserVIPInfoService userVIPInfoService;
   @Resource
   private UserInfoService userInfoService;
   @Resource
   private UserInviteService userInviteService;
   @Resource
   private UserLevelManager userLevelManager;
   @Resource
   private TaoBaoOrderGoodsMapper taoBaoOrderGoodsMapper;
   @Resource(name = "producer")
   private Producer orderProducer;
   // 奖励订单图片
   public final static String PIC_REWARD = "http://img.flqapp.com/resource/order/order_state_reward.png";
   // 免单状态图片
   public final static String PIC_FREE_ON = "http://img.flqapp.com/resource/order/order_state_freeing.png";
   public final static String PIC_FREE_FAIL = "http://img.flqapp.com/resource/order/order_state_free_fail.png";
   public final static String PIC_FREE_SUCCEED = "http://img.flqapp.com/resource/order/order_state_free_suc.png";
   @Override
   public int insert(CommonOrder record) {
      return commonOrderMapper.insert(record);
   }
   @Override
   public int insertSelective(CommonOrder record) {
      return commonOrderMapper.insertSelective(record);
   }
   @Override
   public int updateByPrimaryKeySelective(CommonOrder record) {
      return commonOrderMapper.updateByPrimaryKeySelective(record);
   }
   @Override
   public int updateByPrimaryKey(CommonOrder record) {
      return commonOrderMapper.updateByPrimaryKey(record);
   }
   @Override
   public int deleteByPrimaryKey(Long id) {
      return commonOrderMapper.deleteByPrimaryKey(id);
   }
   @Override
   public CommonOrder selectByPrimaryKey(Long id) {
      return commonOrderMapper.selectByPrimaryKey(id);
   }
   @Override
   public List<CommonOrderVO> listGroupOrderNoByUid(long start, int count, Long uid, Integer state, Integer type,
         Integer orderState, String orderNo, String startTime, String endTime, Integer dateType, Integer source)
         throws CommonOrderException {
      List<Integer> listSource = new ArrayList<>();
      if (source != null) {
         listSource.add(source);
      }
      return commonOrderMapper.listUserOrder(start, count, uid, state, type, orderState, orderNo, startTime, endTime,
            dateType, listSource);
   }
   @Override
   public long countGroupOrderNoByUid(Long uid, Integer state, Integer type, Integer orderState, String orderNo,
         String startTime, String endTime, Integer dateType, List<Integer> listSource) throws CommonOrderException {
      return commonOrderMapper.countUserOrder(uid, state, type, orderState, orderNo, startTime, endTime, dateType,
            listSource);
   }
   @Override
   public List<CommonOrderVO> getOrderByUid(AcceptData acceptData, Integer page, Long uid, Integer state, Integer type,
         Integer orderState, String orderNo, String startTime, String endTime, Integer dateType,
         List<Integer> listSource) throws CommonOrderException, Exception {
      int pageSize = Constant.PAGE_SIZE;
      List<CommonOrderVO> listOrder = commonOrderMapper.listUserOrder((page - 1) * pageSize, pageSize, uid, state,
            type, orderState, orderNo, startTime, endTime, dateType, listSource);
      // 订单信息为空
      if (listOrder == null || listOrder.size() == 0) {
         listOrder = new ArrayList<CommonOrderVO>();
         return listOrder;
      }
      // 商品信息
      List<CommonOrderVO> listGoods = commonOrderMapper.listOrderGoodsInfo(listOrder);
      // 订单商品为空
      if (listGoods == null || listGoods.size() == 0) {
         return listOrder;
      }
      // 数据加工重新组织
      if (VersionUtil.greaterThan_2_1(acceptData.getPlatform(), acceptData.getVersion())) {
         orderVOFactory21(acceptData, listOrder, listGoods, uid);
      } else {
         orderVOFactory(acceptData, listOrder, listGoods, uid);
      }
      return listOrder;
   }
   /**
    * 订单信息加工
    *
    * @param acceptData
    * @param listOrder
    * @param listGoods
    * @param uid
    */
   private void orderVOFactory(AcceptData acceptData, List<CommonOrderVO> listOrder, List<CommonOrderVO> listGoods,
         Long uid) throws Exception {
      List<String> listTB = new ArrayList<String>();
      List<String> listJD = new ArrayList<String>();
      List<String> listPDD = new ArrayList<String>();
      for (CommonOrderVO commonOrderVO : listOrder) {
         Integer sourceType = commonOrderVO.getSourceType();
         if (sourceType == null) {
            continue;
         } else if (sourceType == Constant.SOURCE_TYPE_TAOBAO) {
            listTB.add(commonOrderVO.getOrderNo());
         } else if (sourceType == Constant.SOURCE_TYPE_JD) {
            listJD.add(commonOrderVO.getOrderNo());
         } else if (sourceType == Constant.SOURCE_TYPE_PDD) {
            listPDD.add(commonOrderVO.getOrderNo());
         }
      }
      List<UserSystemCouponRecord> listRecordTB = null;
      if (listTB.size() > 0) {
         listRecordTB = userSystemCouponRecordService.getRecordByOrderNoList(Constant.SOURCE_TYPE_TAOBAO, listTB);
      }
      List<UserSystemCouponRecord> listRecordJD = null;
      if (listJD.size() > 0) {
         listRecordJD = userSystemCouponRecordService.getRecordByOrderNoList(Constant.SOURCE_TYPE_JD, listJD);
      }
      List<UserSystemCouponRecord> listRecordPDD = null;
      if (listPDD.size() > 0) {
         listRecordPDD = userSystemCouponRecordService.getRecordByOrderNoList(Constant.SOURCE_TYPE_PDD, listPDD);
      }
      // 需要查询是否为VIP的用户ID,只有邀请订单才需要查询
      List<Long> needSelectVIPUidList = new ArrayList<>();
      for (CommonOrderVO order : listOrder) {
         if (order.getHongBaoType() == HongBaoV2.TYPE_YIJI || order.getHongBaoType() == HongBaoV2.TYPE_ERJI
               || order.getHongBaoType() == HongBaoV2.TYPE_SHARE_ERJI
               || order.getHongBaoType() == HongBaoV2.TYPE_SHARE_ERJI)
            needSelectVIPUidList.add(Long.parseLong(order.getUserId()));
      }
      Map<Long, Boolean> vipUserMap = userVIPInfoService.listByUids(needSelectVIPUidList);
      // 设置是否为vip订单
      for (CommonOrderVO order : listOrder) {
         if (order.getHongBaoType() == HongBaoV2.TYPE_YIJI || order.getHongBaoType() == HongBaoV2.TYPE_ERJI
               || order.getHongBaoType() == HongBaoV2.TYPE_SHARE_ERJI
               || order.getHongBaoType() == HongBaoV2.TYPE_SHARE_ERJI) {
            if (vipUserMap.get(Long.parseLong(order.getUserId())) != null
                  && vipUserMap.get(Long.parseLong(order.getUserId())) == true)
               order.setVipOrder(true);
            else
               order.setVipOrder(false);
         } else
            order.setVipOrder(false);
         if (order.isVipOrder())
            order.setVipOrderDesc("订单来源:由超级会员的粉丝产生");
      }
      SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd HH:mm");
      SimpleDateFormat formatday = new SimpleDateFormat("yyyy.MM.dd");
      // 2019.8.1开始返回维权信息
      Date august = TimeUtil.parse("2019-08-01");
      // 当前用户是否VIP
      boolean vip = userInviteService.verifyVIP(uid);
      // 是否存在奖励券
      boolean hasRewardCoupon = userSystemCouponService.getValidRebateCoupon(uid);
      for (CommonOrderVO order : listOrder) {
         String orderNo = order.getOrderNo();
         Integer sourceType = order.getSourceType();
         Integer hongBaoType = order.getHongBaoType();
         // 商品信息组合
         for (CommonOrderVO commonOrder : listGoods) {
            CommonOrderGoods goods = commonOrder.getCommonOrderGoods();
            if (goods == null) {
               continue;
            }
            if (sourceType.equals(commonOrder.getSourceType()) && orderNo.equals(commonOrder.getOrderNo())) {
               CommonOrderGoodsVO commonGoodsVO = new CommonOrderGoodsVO();
               PropertyUtils.copyProperties(commonGoodsVO, goods);
               commonGoodsVO.setGoodsType(sourceType);
               // 淘宝商品图片处理
               String picture = commonGoodsVO.getPicture();
               if (sourceType == Constant.SOURCE_TYPE_TAOBAO && !StringUtil.isNullOrEmpty(picture)
                     && !picture.contains("320x320")) {
                  commonGoodsVO.setPicture(TbImgUtil.getTBSize320Img(picture));
               }
               // 购买数量
               commonGoodsVO.setActualCount(commonOrder.getTotalCount() + "件");
               // 实付款
               BigDecimal totalSettlement = commonOrder.getTotalSettlement();
               if (totalSettlement == null || totalSettlement.compareTo(new BigDecimal(0)) <= 0) {
                  totalSettlement = commonOrder.getTotalPayment();
               }
               commonGoodsVO.setActualPay("付款金额:¥" + totalSettlement);
               // 邀请订单信息保护
               if (HongBaoV2.TYPE_YAOQING == hongBaoType || HongBaoV2.TYPE_YIJI == hongBaoType
                     || HongBaoV2.TYPE_ERJI == hongBaoType || HongBaoV2.TYPE_SHARE_YIJI == hongBaoType
                     || HongBaoV2.TYPE_SHARE_ERJI == hongBaoType) {
                  Map<String, String> titleMap = new HashMap<String, String>();
                  titleMap.put("content", "为保障用户隐私,商品信息已隐藏!");
                  titleMap.put("fontColor", "#888888");
                  titleMap.put("bottomColor", "#E9E9E9");
                  commonGoodsVO.setTitle(null);
                  commonGoodsVO.setGoodsTitle(titleMap);
               }
               // 订单类型为空时 已商品类为准
               Integer orderType = order.getOrderType();
               if (orderType == null) {
                  String shopType = commonGoodsVO.getShopType();
                  if (CommonOrderGoodsVO.TYPE_TAOBAO.equalsIgnoreCase(shopType)) {
                     order.setOrderType(1);
                  } else if (CommonOrderGoodsVO.TYPE_TMALL.equalsIgnoreCase(shopType)) {
                     order.setOrderType(2);
                  }
               }
               order.getListOrderGoods().add(commonGoodsVO);
            }
         }
         Date thirdCreateTime = order.getThirdCreateTime();
         order.setDownTime("下单时间:" + format.format(thirdCreateTime));
         order.setObtainTime(thirdCreateTime.getTime());
         Date settleTime = order.getSettleTime();
         if (settleTime != null) {
            order.setReceiveTime("收货时间:" + format.format(settleTime));
         }
         // 订单类型
         if (sourceType == Constant.SOURCE_TYPE_TAOBAO) {
            Integer orderType = order.getOrderType();
            if (orderType == null)
               order.setOrderType(1);
         } else if (sourceType == Constant.SOURCE_TYPE_JD) {
            order.setOrderType(3);
         } else if (sourceType == Constant.SOURCE_TYPE_PDD) {
            order.setOrderType(4);
         }
         /* 订单状态 转换处理 */
         String orderStateContent = "";
         Map<String, String> orderStateMap = new HashMap<String, String>();
         // 订单状态
         Integer orderState = order.getState();
         // 红包状态
         Integer hongBaoState = order.getHongBaoState();
         Integer stateWholeOrder = order.getStateWholeOrder();
         if (CommonOrder.STATE_WHOLE_ORDER_BUFENYOUXIAO == stateWholeOrder) {
            // 整个订单部分失效:判断真实状态 订单、红包
            CommonOrderVO buFenOrder = commonOrderMapper.getBuFenOrderState(uid, order.getOrderNo());
            if (buFenOrder != null) {
               // 有效的订单状态
               orderState = buFenOrder.getState();
               // 有效的红包状态
               hongBaoState = buFenOrder.getHongBaoState();
            }
         }
         BigDecimal hongBao = order.getHongBao();
         if (hongBao == null) {
            hongBao = new BigDecimal(0);
         }
         if (CommonOrder.STATE_FK == orderState) {
            orderStateContent = "已付款";
         } else if (CommonOrder.STATE_JS == orderState) {
            orderStateContent = "已收货";
         } else if (CommonOrder.STATE_SX == orderState) {
            orderStateContent = "未付款/已退款";
         } else if (CommonOrder.STATE_WQ == orderState) {
            orderStateContent = "已售后";
            if (sourceType != null && sourceType == Constant.SOURCE_TYPE_TAOBAO) {
               /* 订单维权 判断是否全部维权 */
               List<TaoBaoWeiQuanOrder> listWQ = taoBaoWeiQuanOrderMapper
                     .selectListByOrderIdAndState(order.getOrderNo(), "维权成功");
               boolean isPart = false;// 默认失效
               BigDecimal weiQuanMoney = getWeiQuanMoney(listWQ, sourceType, uid);
               if (!VersionUtil.greaterThan_1_6_0(acceptData.getPlatform(), acceptData.getVersion())) {
                  if (isPart) {
                     hongBaoState = HongBaoV2.STATE_BUFENSHIXIAO; // 部分失效
                  } else {
                     hongBaoState = HongBaoV2.STATE_SHIXIAO; // 全部失效
                  }
               } else {
                  // 2019.8.1 返回维权信息
                  if (settleTime != null && august != null && settleTime.getTime() > august.getTime()) {
                     orderStateContent = "售后成功";
                     WeiQuanInfo weiQuanInfo = new WeiQuanInfo();
                     weiQuanInfo.setOldHongBao("¥" + hongBao.setScale(2, BigDecimal.ROUND_DOWN).toString());
                     weiQuanInfo
                           .setWqHongBao("售后:-¥" + weiQuanMoney.setScale(2, BigDecimal.ROUND_DOWN).toString());
                     hongBao = MoneyBigDecimalUtil.sub(hongBao, weiQuanMoney);
                     order.setWeiQuanInfo(weiQuanInfo);
                  }
               }
            }
         }
         orderStateMap.put("content", orderStateContent);
         orderStateMap.put("fontColor", "#666666");
         order.setOrderState(orderStateMap);
         String hongbaoInfo = "";
         // 订单标识
         List<String> signList = new ArrayList<String>();
         /* 订单返利类型 转换 */
         if (HongBaoV2.TYPE_ZIGOU == hongBaoType || 2 == hongBaoType) {
            // 自购
            hongbaoInfo = "返利";
            order.setOrderOrigin("1");
            order.setHongBaoTypePic(CommonOrder.TYPE_FANLI);
            signList.add(CommonOrder.TYPE_FANLI);
         } else if (HongBaoV2.TYPE_SHARE_GOODS == hongBaoType) {
            // 分享
            hongbaoInfo = "奖金";
            order.setOrderOrigin("2");
            order.setHongBaoTypePic(CommonOrder.TYPE_SHARE);
            signList.add(CommonOrder.TYPE_SHARE);
         } else if (HongBaoV2.TYPE_SHARE_YIJI == hongBaoType || HongBaoV2.TYPE_SHARE_ERJI == hongBaoType) {
            // 下级的分享订单: 显示邀请
            hongbaoInfo = "奖金";
            order.setOrderOrigin("3");
            order.setHongBaoTypePic(CommonOrder.TYPE_INVITE);
            signList.add(CommonOrder.TYPE_INVITE);
         } else if (HongBaoV2.TYPE_YAOQING == hongBaoType || HongBaoV2.TYPE_YIJI == hongBaoType
               || HongBaoV2.TYPE_ERJI == hongBaoType) {
            // 邀请订单
            hongbaoInfo = "奖金";
            order.setOrderOrigin("3");
            order.setHongBaoTypePic(CommonOrder.TYPE_INVITE);
            signList.add(CommonOrder.TYPE_INVITE);
            // 版本区分:2-0-2
            if (VersionUtil.greaterThan_2_0_5(acceptData.getPlatform(), acceptData.getVersion())) {
               InviteOrderSubsidy orderSubsidy = inviteOrderSubsidyService.getByOrderNoAndType(uid,
                     order.getOrderNo(), sourceType);
               if (orderSubsidy != null) {
                  ClientTextStyleVO subsidyInfo = new ClientTextStyleVO();
                  subsidyInfo.setContent("(补贴¥" + orderSubsidy.getMoney() + ")");
                  if (orderSubsidy.getState() == InviteOrderSubsidy.STATE_SUBSIDIZED) {
                     subsidyInfo.setColor("#E5005C");
                  } else {
                     subsidyInfo.setColor("#888888");
                  }
                  order.setSubsidy(subsidyInfo);
                  // 解释信息(问号)
                  List<String> subsidyList = new ArrayList<String>();
                  subsidyList.add("额外补贴能否获得由系统算法自动判断,人为无法干涉;");
                  subsidyList.add("额外补贴到账时间以及金额请以实际到账为准;");
                  subsidyList.add("额外补贴产生后将会在消息-资金消息中提醒你。");
                  order.setSubsidyList(subsidyList);
               }
            }
         }
         order.setSignList(signList);
         String hongBaoDate = null;
         String hongBaoState_Str = "";
         String hongbaoInfoFontColor = "#E5005C";
         /* 红包状态 转换 */
         String stateContent = "";
         String stateFontColor = "#E5005C";
         Integer orderHongBaoState = null;
         if (HongBaoV2.STATE_KELINGQU == hongBaoState || HongBaoV2.STATE_BUKELINGQU == hongBaoState) {
            orderHongBaoState = 1;
            stateContent = "未到账";
            hongBaoState_Str = "预估";
            Date preAccountTime = order.getPreAccountTime();
            if (preAccountTime != null) {
               hongBaoDate = "预计到账时间:" + formatday.format(preAccountTime);
            }
         } else if (HongBaoV2.STATE_YILINGQU == hongBaoState) {
            orderHongBaoState = 3;
            stateContent = "已到账";
            Date accountTime = order.getAccountTime();
            if (accountTime != null) {
               hongBaoDate = "到账时间:" + formatday.format(accountTime);
            }
         } else if (HongBaoV2.STATE_BUFENSHIXIAO == hongBaoState) {
            stateContent = "部分失效";
            orderHongBaoState = 3;
            Date accountTime = order.getAccountTime();
            if (accountTime != null) {
               hongBaoDate = "到账时间:" + formatday.format(accountTime);
            }
         } else if (HongBaoV2.STATE_SHIXIAO == hongBaoState) {
            orderHongBaoState = 4;
            stateContent = "已失效";
            hongbaoInfoFontColor = "#888888";
         }
         order.setHongBaoState(orderHongBaoState);
         order.setHongBaoDate(hongBaoDate);
         if (!StringUtil.isNullOrEmpty(order.getStateDesc())) {
            stateContent = stateContent + "-" + order.getStateDesc();
         }
         Map<String, String> stateMap = new HashMap<String, String>();
         stateMap.put("content", stateContent);
         stateMap.put("fontColor", stateFontColor);
         order.setAccountState(stateMap);
         hongbaoInfo = hongBaoState_Str + hongbaoInfo;
         Map<String, String> hongBaoMap = new HashMap<String, String>();
         hongBaoMap.put("content", hongbaoInfo + " ¥" + hongBao.setScale(2, BigDecimal.ROUND_DOWN).toString());
         hongBaoMap.put("fontColor", hongbaoInfoFontColor);
         order.setHongBaoInfo(hongBaoMap);
         // 显示返利、免单详情
         if (HongBaoV2.TYPE_ZIGOU == hongBaoType) {
            // 奖励订单、免单 使用记录
            if (sourceType == null) {
               couponFactory(order, hasRewardCoupon, hongBaoState, hongBaoType, null, uid, vip, acceptData,
                     hongBao);
            } else if (sourceType == Constant.SOURCE_TYPE_TAOBAO) {
               couponFactory(order, hasRewardCoupon, hongBaoState, hongBaoType, listRecordTB, uid, vip, acceptData,
                     hongBao);
            } else if (sourceType == Constant.SOURCE_TYPE_JD) {
               couponFactory(order, hasRewardCoupon, hongBaoState, hongBaoType, listRecordJD, uid, vip, acceptData,
                     hongBao);
            } else if (sourceType == Constant.SOURCE_TYPE_PDD) {
               couponFactory(order, hasRewardCoupon, hongBaoState, hongBaoType, listRecordPDD, uid, vip,
                     acceptData, hongBao);
            }
         }
         // 邀请 隐藏订单号
         if (HongBaoV2.TYPE_YAOQING == hongBaoType || HongBaoV2.TYPE_YIJI == hongBaoType || HongBaoV2.TYPE_ERJI == hongBaoType
               || HongBaoV2.TYPE_SHARE_YIJI == hongBaoType || HongBaoV2.TYPE_SHARE_ERJI == hongBaoType) {
            order.setOrderNo(UserUtil.filterOrderId(order.getOrderNo()));
         }
      }
   }
   /**
    * 订单: 免单标识 奖励标识
    *
    * @param order
    * @param hasRewardCoupon
    * @param hongBaoState
    * @param list
    * @param signList
    */
   private void couponFactory(CommonOrderVO order, boolean hasRewardCoupon, Integer hongBaoState, Integer hongBaoType,
         List<UserSystemCouponRecord> list, Long uid, boolean vip, AcceptData acceptData, BigDecimal hongBao)
         throws Exception {
      // 是否免单商品
      boolean freeOrder = false;
      // 是否奖励成功
      boolean rewardSuccess = false;
      boolean version2_1 = VersionUtil.greaterThan_2_0_5(acceptData.getPlatform(), acceptData.getVersion());
      if (list != null && list.size() > 0) {
         for (UserSystemCouponRecord couponRecord : list) {
            int goodSource = couponRecord.getGoodSource();
            if (goodSource == 0)
               goodSource = 1;
            if (order.getOrderNo().equals(couponRecord.getOrderNo()) && goodSource == order.getSourceType()) {
               Integer state = couponRecord.getState();
               String systemCouponType = couponRecord.getCouponType();
               if (CouponTypeEnum.rebatePercentCoupon.name().equals(systemCouponType)
                     && UserSystemCouponRecord.STATE_SUCCESS == state) {
                  rewardSuccess = true;
                  if (!version2_1) {
                     // 奖励成功
                     order.getSignList().add(PIC_REWARD);
                  }
               } else if (CouponTypeEnum.freeCoupon.name().equals(systemCouponType)
                     || CouponTypeEnum.welfareFreeCoupon.name().equals(systemCouponType)
                     || CouponTypeEnum.freeCouponBuy.name().equals(systemCouponType)) {
                  if (UserSystemCouponRecord.STATE_FREE_ON == state) {
                     // 免单中
                     freeOrder = true;
                     order.getSignList().add(PIC_FREE_ON);
                  } else if (UserSystemCouponRecord.STATE_SUCCESS == state) {
                     // 免单成功
                     freeOrder = true;
                     order.getSignList().add(PIC_FREE_SUCCEED);
                  } else if (UserSystemCouponRecord.STATE_FAIL_RULE == state
                        || UserSystemCouponRecord.STATE_FAIL_DRAWBACK == state) {
                     // 规则不匹配、退款
                     freeOrder = true;
                     order.getSignList().add(PIC_FREE_FAIL);
                  }
               }
               break;
            }
         }
      }
      // 免单详情
      if (freeOrder) {
         ClientTextStyleVO rewardStyleVO = new ClientTextStyleVO();
         rewardStyleVO.setContent("免单详情 >");
         rewardStyleVO.setColor("#E5005C");
         rewardStyleVO.setBottomColor("#FFDCEA");
         Map<String, Object> jumpLink = new HashMap<String, Object>();
         jumpLink.put("orderNo", order.getOrderNo());
         if (VersionUtil.greaterThan_1_6_0(acceptData.getPlatform(), acceptData.getVersion())) {
            jumpLink.put("goodsType", order.getSourceType() + "");
         }
         Map<String, Object> jump = new HashMap<String, Object>();
         jump.put("type", 1); // 页面跳转
         jump.put("params", jumpLink);
         jump.put("jumpDetail", jumpDetailV2Service.getByTypeCache("freeCouponDetail"));
         Map<String, Object> rewardMap = new HashMap<String, Object>();
         rewardMap.put("text", rewardStyleVO);
         rewardMap.put("jump", jump);
         order.setRewardDetail(rewardMap);
      }
      // 已使用奖励券
      if (rewardSuccess) {
         ClientTextStyleVO rewardStyleVO = new ClientTextStyleVO();
         rewardStyleVO.setColor("#E5005C");
         rewardStyleVO.setBottomColor("#FFDCEA");
         if (version2_1) {
            rewardStyleVO.setContent("已使用奖励券 >");
         } else {
            rewardStyleVO.setContent("返利奖励 >");
         }
         Map<String, Object> rewardMap = new HashMap<String, Object>();
         rewardMap.put("text", rewardStyleVO);
         Map<String, Object> jumpLink = new HashMap<String, Object>();
         jumpLink.put("orderNo", order.getOrderNo());
         jumpLink.put("goodsType", order.getSourceType() + "");
         Map<String, Object> jump = new HashMap<String, Object>();
         jump.put("type", 1); // 1 常规跳转页面
         jump.put("params", jumpLink);
         jump.put("jumpDetail", jumpDetailV2Service.getByTypeCache("rewardCouponDetail"));
         rewardMap.put("jump", jump);
         order.setRewardDetail(rewardMap);
      }
      // 使用奖励券 金额额限制
      if (hongBao.compareTo(Constant.REWARD_COUPON_LIMIT_MONEY) > 0) {
         return;
      }
      // 是否可使用奖励券
      if (!rewardSuccess && !freeOrder && HongBaoV2.TYPE_ZIGOU == hongBaoType
            && HongBaoV2.STATE_YILINGQU == hongBaoState && !vip && CommonOrder.STATE_WQ != order.getState()) {
         // 下单时间
         Date thirdCreateTime = order.getThirdCreateTime();
         // 到账时间
         Date accountTime = order.getAccountTime();
         if (thirdCreateTime == null || accountTime == null)
            return;
         // 下单日期是否是符合上线日期
         long downOrderTime = thirdCreateTime.getTime();
         long limitDate = TimeUtil.convertDateToTemp(Constant.VIP_ONLINE_TIME);
         if (downOrderTime > limitDate) {
            // 2.1 开始新版
            rewardCounponLimitTime(order, accountTime);
         } else if (hasRewardCoupon) {
            // 在2.1新版上线之前订单-存在则显示奖励券可使用
            ClientTextStyleVO rewardStyleVO = new ClientTextStyleVO();
            rewardStyleVO.setColor("#E5005C");
            rewardStyleVO.setBottomColor("#FFDCEA");
            rewardStyleVO.setContent("返利奖励 >");
            Map<String, Object> jumpLink = new HashMap<String, Object>();
            jumpLink.put("orderNo", order.getOrderNo());
            jumpLink.put("goodsType", order.getSourceType() + "");
            Map<String, Object> jump = new HashMap<String, Object>();
            jump.put("type", 2); // 弹框
            jump.put("params", jumpLink);
            jump.put("jumpDetail", jumpDetailV2Service.getByTypeCache("rewardCouponDetail"));
            Map<String, Object> rewardMap = new HashMap<String, Object>();
            rewardMap.put("text", rewardStyleVO);
            rewardMap.put("jump", jump);
            order.setRewardDetail(rewardMap);
         }
      }
   }
   private void rewardCounponLimitTime(CommonOrderVO order, Date accountTime) throws Exception {
      // 倒计时验证
      Date endDay = DateUtil.plusDayDate(Constant.COUPON_REWARD_LIMIT_DAY, accountTime);
      long currentTime = java.lang.System.currentTimeMillis();
      if (endDay.getTime() <= currentTime)
         return;
      String num = null;
      String unit = null;
      boolean canUse = false;
      DateInfo dateInfo = DateUtil.dateDiff3(currentTime, endDay.getTime());
      if (dateInfo.getDay() > 0) {
         canUse = true;
         unit = "天";
         num = dateInfo.getDay().toString();
      }
      if (!canUse && dateInfo.getHour() > 0) {
         canUse = true;
         unit = "小时";
         num = dateInfo.getHour().toString();
      }
      if (!canUse && dateInfo.getMinute() > 0) {
         canUse = true;
         unit = "分";
         num = dateInfo.getMinute().toString();
      }
      if (!canUse && dateInfo.getSecond() > 0) {
         canUse = true;
         unit = "秒";
         num = dateInfo.getSecond().toString();
      }
      // 已经超时
      if (!canUse)
         return;
      Map<String, Object> rewardMap = new HashMap<String, Object>();
      ClientTextStyleVO rewardStyleVO = new ClientTextStyleVO();
      rewardStyleVO.setColor("#E5005C");
      rewardStyleVO.setBottomColor("#FFDCEA");
      rewardStyleVO.setContent("使用奖励券");
      rewardMap.put("text", rewardStyleVO);
      ClientTextStyleVO txt1 = new ClientTextStyleVO();
      txt1.setContent("剩");
      txt1.setColor("#666666");
      txt1.setBottomColor("#FFDCEA");
      ClientTextStyleVO txt2 = new ClientTextStyleVO();
      txt2.setContent(num);
      txt2.setColor("#E5005C");
      txt2.setBottomColor("#FFDCEA");
      txt2.setFontSize("1.33");
      ClientTextStyleVO txt3 = new ClientTextStyleVO();
      txt3.setContent(unit + "关闭 >");
      txt3.setColor("#666666");
      txt3.setBottomColor("#FFDCEA");
      List<ClientTextStyleVO> ticking = new ArrayList<ClientTextStyleVO>();
      ticking.add(txt1);
      ticking.add(txt2);
      ticking.add(txt3);
      rewardMap.put("ticking", ticking);
      Map<String, Object> jumpLink = new HashMap<String, Object>();
      jumpLink.put("orderNo", order.getOrderNo());
      jumpLink.put("goodsType", order.getSourceType() + "");
      Map<String, Object> jump = new HashMap<String, Object>();
      jump.put("type", 2); // 弹出框使用券
      jump.put("params", jumpLink);
      jump.put("jumpDetail", jumpDetailV2Service.getByTypeCache("rewardCouponDetail"));
      rewardMap.put("jump", jump);
      order.setRewardDetail(rewardMap);
   }
   @Override
   public Map<String, BigDecimal> countHistoryOrder(Long uid, Integer day, Integer source) {
      return commonOrderMapper.countHistoryOrder(uid, day, source);
   }
   @Override
   public OrderCountVO getOrderCount(Long uid, Integer day, List<Integer> listSource) {
      return commonOrderMapper.getOrderCount(uid, day, listSource);
   }
   @Override
   public long countBonusOrderNumber(Long uid, Integer type, Integer day, String startTime, String endTime,
         Integer source) {
      return commonOrderMapper.countBonusOrderNumber(uid, type, day, startTime, endTime, source);
   }
   @Override
   public BigDecimal countBonusOrderMoney(Long uid, Integer type, Integer day, String startTime, String endTime,
         Integer source) {
      return commonOrderMapper.countBonusOrderMoney(uid, type, day, startTime, endTime, source);
   }
   @Override
   public Map<String, Object> countBonusOrderMoneyAndNumber(Long uid, Integer type, Integer day, String startTime,
         String endTime, Integer source) {
      return commonOrderMapper.countBonusOrderMoneyAndNumber(uid, type, day, startTime, endTime, source);
   }
   @Override
   public Long countUserOrderToApp(Long uid, Integer type, String startTime, String endTime, Integer day,
         Integer source, Integer state, Integer stateOrder) {
      return commonOrderMapper.countUserOrderToApp(uid, type, startTime, endTime, day, source, state, stateOrder);
   }
   @Override
   public BigDecimal getWeiQuanMoney(List<TaoBaoWeiQuanOrder> listWQ, int sourceType, Long uid) {
      BigDecimal weiQuanMoney = new BigDecimal(0);
      if (listWQ != null && listWQ.size() > 0) {
         for (TaoBaoWeiQuanOrder weiQuanOrder : listWQ) {
            String tradeId = weiQuanOrder.getOrderItemId();
            // 查询红包
            List<String> tradeList = new ArrayList<>();
            tradeList.add(tradeId);
            List<HongBaoV2> hongBaoList = hongBaoV2Service.listBySourceTypeAndTradeIdListAndUid(sourceType, uid,
                  tradeList);
            if (hongBaoList != null && hongBaoList.size() > 0) {
               CommonOrder commonOrder = commonOrderMapper.selectBySourceTypeAndTradeId(sourceType, tradeId);
               if (commonOrder != null && commonOrder.getSettlement().compareTo(new BigDecimal(0)) > 0) {
                  BigDecimal wqMoney = MoneyBigDecimalUtil
                        .mul(hongBaoList.get(0).getMoney(), weiQuanOrder.getMoney())
                        .divide(commonOrder.getSettlement(), 2, BigDecimal.ROUND_UP);
                  if (wqMoney.compareTo(hongBaoList.get(0).getMoney()) > 0)
                     wqMoney = hongBaoList.get(0).getMoney();
                  weiQuanMoney = weiQuanMoney.add(wqMoney);
               }
            }
         }
      }
      return weiQuanMoney;
   }
   @Override
   public List<CommonOrder> listBySourceTypeAndOrderId(int sourceType, String orderId) {
      return commonOrderMapper.listBySourceTypeAndOrderNo(sourceType, orderId);
   }
   @Transactional(rollbackFor = Exception.class)
   @Override
   public List<CommonOrderAddResultDTO> addTaoBaoOrder(List<TaoBaoOrder> taoBaoOrders, Long uid)
         throws CommonOrderException {
      List<CommonOrderAddResultDTO> commonOrderList = new ArrayList<>();
      // 判断所有的订单状态
      int invalidCount = 0;
      for (TaoBaoOrder tb : taoBaoOrders) {
         if ("订单失效".equalsIgnoreCase(tb.getOrderState())) {
            invalidCount++;
         }
      }
      // 获取整体订单的状态
      int wholeOrderState = 0;
      if (taoBaoOrders.size() == invalidCount)
         wholeOrderState = CommonOrder.STATE_WHOLE_ORDER_SHIXIAO;
      else if (invalidCount == 0)
         wholeOrderState = CommonOrder.STATE_WHOLE_ORDER_YOUXIAO;
      else
         wholeOrderState = CommonOrder.STATE_WHOLE_ORDER_BUFENYOUXIAO;
      for (TaoBaoOrder taoBaoOrder : taoBaoOrders) {
         CommonOrder newCommonOrder = CommonOrderFactory.create(taoBaoOrder);
         CommonOrderGoods cog = new CommonOrderGoods();
         if ("饿了么".equalsIgnoreCase(taoBaoOrder.getOrderType())) {
            cog.setGoodsId(taoBaoOrder.getTradeId() + "");
            cog.setGoodsType(Constant.SOURCE_TYPE_ELME);
            TaoBaoOrderGoods goods = taoBaoOrderGoodsMapper.selectByTradeId(taoBaoOrder.getTradeId());
            if (goods == null) {
               cog.setPicture("http://img.flqapp.com/resource/goods/elme_picture_demo.png");
               cog.setTitle(taoBaoOrder.getTitle());
            } else {
               cog.setPicture(goods.getImg());
               cog.setTitle(goods.getTitle());
            }
            newCommonOrder.setCommonOrderGoods(cog);
         } else {
            cog.setGoodsId(taoBaoOrder.getAuctionId() + "");
            cog.setGoodsType(Constant.SOURCE_TYPE_TAOBAO);
            newCommonOrder.setCommonOrderGoods(cog);
         }
         newCommonOrder.setStateWholeOrder(wholeOrderState);
         // 订单商品插入
         List<CommonOrderGoods> commonGoodsList = commonOrderGoodsMapper.listByGoodsIdAndGoodsType(cog.getGoodsId(),
               cog.getGoodsType());
         if (commonGoodsList.size() <= 0)// 不存在就插入商品
         {
            TaoBaoGoodsBrief taoBaoGoods = null;
            if (cog.getGoodsType() != Constant.SOURCE_TYPE_ELME) {
               try {
                  taoBaoGoods = TaoKeApiUtil.getSimpleGoodsInfo(taoBaoOrder.getAuctionId());
                  LogManager.getLogger(LogType.taobaoGoods)
                        .info(String.format("订单商品分类:%s#%s#%s", taoBaoGoods.getAuctionId(),
                              taoBaoGoods.getRootCategoryName(), taoBaoGoods.getLeafName()));
               } catch (TaobaoGoodsDownException e) {
                  e.printStackTrace();
                  LogHelper.errorDetailInfo(e, "AUCTIONID:" + taoBaoOrder.getAuctionId(), "");
                  try {
                     taoBaoGoods = TaoBaoUtil.getSimpleGoodsBrief(taoBaoOrder.getAuctionId());
                     // 记录商品分类
                  } catch (Exception e1) {
                     CommonGoods commonGoods = commonGoodsService.getCommonGoodsByGoodsIdAndGoodsType(
                           taoBaoOrder.getAuctionId(), Constant.SOURCE_TYPE_TAOBAO);
                     if (commonGoods != null)
                        taoBaoGoods = TaoBaoUtil.convert(commonGoods);
                  }
               }
            }
            if (taoBaoGoods != null) {
               cog = CommonOrderGoodsFactory.create(taoBaoGoods);
            }
            cog.setCreateTime(new Date());
            cog.setUpdateTime(new Date());
            commonOrderGoodsMapper.insertSelective(cog);
         }
         newCommonOrder.setUserInfo(new UserInfo(uid));
         commonOrderList.add(addCommonOrder(newCommonOrder));
      }
      addConfirmMQMsg(commonOrderList);
      return commonOrderList;
   }
   @Transactional(rollbackFor = Exception.class)
   @Override
   public List<CommonOrderAddResultDTO> addPDDOrder(List<PDDOrder> pddOrderList, Long uid)
         throws CommonOrderException {
      List<CommonOrderAddResultDTO> commonOrderList = new ArrayList<>();
      // 判断所有的订单状态
      int invalidCount = 0;
      for (PDDOrder order : pddOrderList) {
         if (order.getOrderStatus() == -1 || order.getOrderStatus() == 4 || order.getOrderStatus() == 8) {
            invalidCount++;
         }
      }
      // 获取整体订单的状态
      int wholeOrderState = 0;
      if (pddOrderList.size() == invalidCount)
         wholeOrderState = CommonOrder.STATE_WHOLE_ORDER_SHIXIAO;
      else if (invalidCount == 0)
         wholeOrderState = CommonOrder.STATE_WHOLE_ORDER_YOUXIAO;
      else
         wholeOrderState = CommonOrder.STATE_WHOLE_ORDER_BUFENYOUXIAO;
      for (PDDOrder pddOrder : pddOrderList) {
         CommonOrder newCommonOrder = CommonOrderFactory.create(pddOrder);
         CommonOrderGoods cog = new CommonOrderGoods();
         cog.setGoodsId(pddOrder.getGoodsId() + "");
         cog.setGoodsType(Constant.SOURCE_TYPE_PDD);
         newCommonOrder.setCommonOrderGoods(cog);
         newCommonOrder.setStateWholeOrder(wholeOrderState);
         // 订单商品插入
         List<CommonOrderGoods> commonGoodsList = commonOrderGoodsMapper.listByGoodsIdAndGoodsType(cog.getGoodsId(),
               cog.getGoodsType());
         if (commonGoodsList.size() <= 0)// 不存在就插入商品
         {
            PDDGoodsDetail pddGoods = null;
            pddGoods = PinDuoDuoApiUtil.getGoodsDetail(Long.parseLong(cog.getGoodsId()));
            if (pddGoods != null) {
               cog = CommonOrderGoodsFactory.create(pddGoods);
            }
            cog.setCreateTime(new Date());
            cog.setUpdateTime(new Date());
            commonOrderGoodsMapper.insertSelective(cog);
            newCommonOrder.setCommonOrderGoods(cog);
         } else {
         }
         newCommonOrder.setUserInfo(new UserInfo(uid));
         commonOrderList.add(addCommonOrder(newCommonOrder));
      }
      addConfirmMQMsg(commonOrderList);
      return commonOrderList;
   }
   private void addConfirmMQMsg(List<CommonOrderAddResultDTO> resultList) {
      // 订单是否新增或者更新过
      boolean isAddOrUpdate = false;
      for (CommonOrderAddResultDTO dto : resultList)
         if (dto.getType() == CommonOrderAddResultDTO.TYPE_ADD
               || dto.getType() == CommonOrderAddResultDTO.TYPE_UPDATE) {
            isAddOrUpdate = true;
            break;
         }
      boolean hasSettleOrder = false;
      // 查询是否有结算的订单
      if (isAddOrUpdate) {
         for (CommonOrderAddResultDTO dto : resultList) {
            if (dto.getCommonOrder().getSettleTime() != null && dto.getCommonOrder().getSettlement() != null) {
               hasSettleOrder = true;
               break;
            }
         }
      }
      // 有结算的订单
      if (hasSettleOrder) {
         if (!Constant.IS_TEST) {
            // 统计结算金额
            BigDecimal settlement = new BigDecimal("0");
            CommonOrder firstOrder = null;
            for (CommonOrderAddResultDTO dto : resultList)
               if (dto.getCommonOrder().getSettlement() != null) {
                  settlement = settlement.add(dto.getCommonOrder().getSettlement());
                  if (firstOrder == null)
                     firstOrder = dto.getCommonOrder();
               }
            if (firstOrder != null) {
               Date placeDate = firstOrder.getThirdCreateTime();
               OrderConfirmMQMsg mqMsg = new OrderConfirmMQMsg(firstOrder.getOrderNo(), firstOrder.getSourceType(),
                     settlement, firstOrder.getUserInfo().getId(), placeDate, new Date());
               Message msg = MQMsgBodyFactory.create(MQTopicName.TOPIC_ORDER, OrderTopicTagEnum.orderConfirm,
                     mqMsg);
               orderProducer.send(msg);
            }
         }
      }
   }
   @Transactional(rollbackFor = Exception.class)
   @Override
   public List<CommonOrderAddResultDTO> addJDOrder(JDOrder jdOrder, Long uid) throws CommonOrderException {
      List<CommonOrderAddResultDTO> commonOrderList = new ArrayList<>();
      // 判断所有的订单状态
      int invalidCount = 0;
      for (JDOrderItem tb : jdOrder.getOrderItemList()) {
         if (tb.getValidCode() < 16) {
            invalidCount++;
         }
      }
      // 获取整体订单的状态
      int wholeOrderState = 0;
      if (jdOrder.getOrderItemList().size() == invalidCount)
         wholeOrderState = CommonOrder.STATE_WHOLE_ORDER_SHIXIAO;
      else if (invalidCount == 0)
         wholeOrderState = CommonOrder.STATE_WHOLE_ORDER_YOUXIAO;
      else
         wholeOrderState = CommonOrder.STATE_WHOLE_ORDER_BUFENYOUXIAO;
      List<JDOrderItem> orderItemList = jdOrder.getOrderItemList();
      jdOrder.setOrderItemList(null);
      for (JDOrderItem itemOrder : orderItemList) {
         itemOrder.setOrder(jdOrder);
         CommonOrder newCommonOrder = CommonOrderFactory.create(itemOrder);
         CommonOrderGoods cog = new CommonOrderGoods();
         cog.setGoodsId(itemOrder.getSkuId() + "");
         cog.setGoodsType(Constant.SOURCE_TYPE_JD);
         newCommonOrder.setCommonOrderGoods(cog);
         newCommonOrder.setStateWholeOrder(wholeOrderState);
         // 订单商品插入
         List<CommonOrderGoods> commonGoodsList = commonOrderGoodsMapper.listByGoodsIdAndGoodsType(cog.getGoodsId(),
               cog.getGoodsType());
         if (commonGoodsList.size() <= 0)// 不存在就插入商品
         {
            JDGoods goods = JDApiUtil.getGoodsDetail(itemOrder.getSkuId());
            if (goods == null) {
               goods = JDUtil.getGoodsFromWeb(itemOrder.getSkuId());
            }
            if (goods == null) {
               goods = new JDGoods();
               goods.setSkuName(itemOrder.getSkuName());
               goods.setPrice(itemOrder.getPrice());
               goods.setSkuId(itemOrder.getSkuId());
            }
            if (goods != null) {
               cog = CommonOrderGoodsFactory.create(goods);
            }
            cog.setCreateTime(new Date());
            cog.setUpdateTime(new Date());
            commonOrderGoodsMapper.insertSelective(cog);
         } else {
         }
         newCommonOrder.setUserInfo(new UserInfo(uid));
         commonOrderList.add(addCommonOrder(newCommonOrder));
      }
      addConfirmMQMsg(commonOrderList);
      return commonOrderList;
   }
   /**
    * 添加订单
    *
    * @param commonOrder
    */
   @Transactional(rollbackFor = Exception.class)
   private CommonOrderAddResultDTO addCommonOrder(CommonOrder commonOrder) throws CommonOrderException {
      // 判断商品是否存在
      if (commonOrder == null)
         throw new CommonOrderException(1, "订单为空");
      if (commonOrder.getUserInfo() == null)
         throw new CommonOrderException(2, "订单用户为空");
      if (commonOrder.getCommonOrderGoods() == null || commonOrder.getCommonOrderGoods().getGoodsId() == null
            || commonOrder.getCommonOrderGoods().getGoodsType() == null)
         throw new CommonOrderException(3, "订单商品为空");
      // 不存在就插入,存在就不管
      CommonOrderGoods goods = commonOrder.getCommonOrderGoods();
      // 之前不存在于数据库
      if (commonOrder.getCommonOrderGoods().getId() == null) {
         List<CommonOrderGoods> commonGoodsList = commonOrderGoodsMapper
               .listByGoodsIdAndGoodsType(goods.getGoodsId(), goods.getGoodsType());
         if (commonGoodsList == null || commonGoodsList.size() < 1) {// 不存在
            commonOrderGoodsMapper.insertSelective(goods);
         } else {// 存在
            goods = commonGoodsList.get(0);
         }
         if (goods.getId() == null)
            throw new CommonOrderException(4, "商品插入失败");
         commonOrder.setCommonOrderGoods(goods);
      }
      CommonOrder oldCommonOrder = null;
      if (!StringUtil.isNullOrEmpty(commonOrder.getTradeId()))
         oldCommonOrder = commonOrderMapper.selectBySourceTypeAndTradeId(commonOrder.getSourceType(),
               commonOrder.getTradeId());
      else {
         throw new CommonOrderException(10, "交易ID为空");
      }
      if (oldCommonOrder == null)// 新增
      {
         commonOrder.setCreateTime(new Date());
         UserLevelEnum userLevel = userLevelManager.getUserLevel(commonOrder.getUserInfo().getId(),
               commonOrder.getThirdCreateTime());
         // 查询是否为vip
         if (userLevel != null)
            commonOrder.setUrank(userLevel.getOrderRank());// VIP订单
         else {
            UserInfo user = userInfoService.selectAvailableByPrimaryKey(commonOrder.getUserInfo().getId());
            if (user != null)
               commonOrder.setUrank(user.getRank());
         }
         commonOrderMapper.insertSelective(commonOrder);
         // 插入映射,保证交易ID的完整性
         commonOrderTradeIdMapMapper.insertSelective(new CommonOrderTradeIdMap(commonOrder.getId(),
               commonOrder.getTradeId(), new Date(), commonOrder.getSourceType()));
         return new CommonOrderAddResultDTO(commonOrder, CommonOrderAddResultDTO.TYPE_ADD);
      } else {// 修改
         // 非京东已经结算,已经失效,状态未改变的订单不处理
         if ((oldCommonOrder.getState() == CommonOrder.STATE_JS
               && oldCommonOrder.getSourceType() != Constant.SOURCE_TYPE_JD)
               || oldCommonOrder.getState() == CommonOrder.STATE_SX
               || oldCommonOrder.getState() == CommonOrder.STATE_WQ
               || (oldCommonOrder.getState().intValue() == commonOrder.getState())) {
            return new CommonOrderAddResultDTO(oldCommonOrder, CommonOrderAddResultDTO.TYPE_NOUPDATE);
         }
         // 交易ID一致才修改
         if (commonOrder.getTradeId() != null
               && commonOrder.getTradeId().equalsIgnoreCase(oldCommonOrder.getTradeId())) {
            CommonOrder updateCommonOrder = new CommonOrder(oldCommonOrder.getId());
            updateCommonOrder.seteIncome(commonOrder.geteIncome());
            updateCommonOrder.setEstimate(commonOrder.getEstimate());
            updateCommonOrder.setPayment(commonOrder.getPayment());
            updateCommonOrder.setSettlement(commonOrder.getSettlement());
            updateCommonOrder.setSettleTime(commonOrder.getSettleTime());
            updateCommonOrder.setState(commonOrder.getState());
            updateCommonOrder.setStateWholeOrder(commonOrder.getStateWholeOrder());
            updateCommonOrder.setUpdateTime(new Date());
            updateCommonOrder.setTradeId(commonOrder.getTradeId());
            commonOrderMapper.updateByPrimaryKeySelective(updateCommonOrder);
            return new CommonOrderAddResultDTO(commonOrderMapper.selectByPrimaryKey(updateCommonOrder.getId()),
                  CommonOrderAddResultDTO.TYPE_UPDATE);
         } else
            return new CommonOrderAddResultDTO(oldCommonOrder, CommonOrderAddResultDTO.TYPE_NOUPDATE);
      }
   }
   @Override
   public long countByUidAndOrderStateWithOrderBalanceTime(Long uid, int state, Date minDate, Date maxDate) {
      return commonOrderMapper.countByUidAndOrderStateWithOrderBalanceTime(uid, state, minDate, maxDate);
   }
   @Override
   public List<CommonOrderVO> listQueryByUid(long start, int count, Long uid, Integer state, Integer type,
         Integer orderState, String orderNo, String startTime, String endTime, Integer dateType)
         throws CommonOrderException {
      List<CommonOrderVO> list = commonOrderMapper.listQueryByUid(start, count, uid, state, type, orderState, orderNo,
            startTime, endTime, dateType);
      if (list == null) {
         list = new ArrayList<CommonOrderVO>();
      }
      if (list.size() == 0) {
         return list;
      }
      SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
      for (CommonOrderVO order : list) {
         // 下单时间
         Date thirdCreateTime = order.getThirdCreateTime();
         if (thirdCreateTime != null) {
            order.setDownTime(format.format(thirdCreateTime));
         }
         // 收货时间
         Date settleTime = order.getSettleTime();
         if (settleTime != null) {
            order.setReceiveTime(format.format(settleTime));
         }
         // 到账时间
         Date accountTime = order.getAccountTime();
         if (accountTime != null) {
            order.setHongBaoDate(format.format(accountTime));
         }
         BigDecimal settlement = order.getSettlement();
         if (settlement != null && settlement.compareTo(new BigDecimal(0)) > 0) {
            order.setPayment(settlement); // 实际付款金额
         }
         /* 订单返利类型 转换 */
         Integer hongBaoType = order.getHongBaoType();
         if (HongBaoV2.TYPE_ZIGOU == hongBaoType || 2 == hongBaoType) {
            // 自购
            order.setHongBaoType(1);
         } else if (HongBaoV2.TYPE_SHARE_GOODS == hongBaoType) {
            // 分享
            order.setHongBaoType(2);
         } else if (HongBaoV2.TYPE_YAOQING == hongBaoType || HongBaoV2.TYPE_YIJI == hongBaoType
               || HongBaoV2.TYPE_ERJI == hongBaoType || HongBaoV2.TYPE_SHARE_YIJI == hongBaoType
               || HongBaoV2.TYPE_SHARE_ERJI == hongBaoType) {
            // 邀请
            order.setHongBaoType(3);
         }
         Integer hongBaoState = order.getHongBaoState();
         if (HongBaoV2.STATE_KELINGQU == hongBaoState || HongBaoV2.STATE_BUKELINGQU == hongBaoState) {
            // 未到账
            order.setHongBaoState(1);
         } else if (HongBaoV2.STATE_YILINGQU == hongBaoState) {
            // 已到账
            order.setHongBaoState(2);
         } else if (HongBaoV2.STATE_SHIXIAO == hongBaoState) {
            // 已失效
            order.setHongBaoState(3);
         }
      }
      return list;
   }
   @Override
   public long countQueryByUid(Long uid, Integer state, Integer type, Integer orderState, String orderNo,
         String startTime, String endTime, Integer dateType) throws CommonOrderException {
      return commonOrderMapper.countQueryByUid(uid, state, type, orderState, orderNo, startTime, endTime, dateType);
   }
   @Override
   public List<CommonOrderVO> listQuery(long start, int count, Integer keyType, String key, Integer state,
         Integer type, Integer orderState, String startTime, String endTime, Integer source, List<Long> listShopId,
         List<Long> listGoodsId, Date minTime, BigDecimal money, BigDecimal payment) throws CommonOrderException {
      List<CommonOrderVO> list = null;
      if (StringUtil.isNullOrEmpty(key) || keyType == 1) {// 搜索框无值或者按订单号搜索时都只搜索主订单
         list = commonOrderMapper.listQueryWithNoChild(start, count, keyType, key, state, type, orderState,
               startTime, endTime, source, payment);
      } else {
         list = commonOrderMapper.listQuery(start, count, keyType, key, state, type, orderState, startTime, endTime,
               source, listShopId, listGoodsId, minTime, money, payment);
      }
      if (list == null) {
         list = new ArrayList<CommonOrderVO>();
      }
      if (list.size() == 0) {
         return list;
      }
      List<String> listTB = new ArrayList<String>();
      List<String> listJD = new ArrayList<String>();
      List<String> listPDD = new ArrayList<String>();
      for (CommonOrderVO commonOrderVO : list) {
         Integer sourceType = commonOrderVO.getSourceType();
         if (sourceType == null) {
            continue;
         } else if (sourceType == Constant.SOURCE_TYPE_TAOBAO) {
            listTB.add(commonOrderVO.getOrderNo());
         } else if (sourceType == Constant.SOURCE_TYPE_JD) {
            listJD.add(commonOrderVO.getOrderNo());
         } else if (sourceType == Constant.SOURCE_TYPE_PDD) {
            listPDD.add(commonOrderVO.getOrderNo());
         }
      }
      List<UserSystemCouponRecord> listRecordTB = null;
      if (listTB.size() > 0) {
         listRecordTB = userSystemCouponRecordService.getRecordByOrderNoList(Constant.SOURCE_TYPE_TAOBAO, listTB);
      }
      List<UserSystemCouponRecord> listRecordJD = null;
      if (listJD.size() > 0) {
         listRecordJD = userSystemCouponRecordService.getRecordByOrderNoList(Constant.SOURCE_TYPE_JD, listJD);
      }
      List<UserSystemCouponRecord> listRecordPDD = null;
      if (listPDD.size() > 0) {
         listRecordPDD = userSystemCouponRecordService.getRecordByOrderNoList(Constant.SOURCE_TYPE_PDD, listPDD);
      }
      SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
      for (CommonOrderVO order : list) {
         // 下单时间
         Date thirdCreateTime = order.getThirdCreateTime();
         if (thirdCreateTime != null) {
            order.setDownTime(format.format(thirdCreateTime));
         }
         // 收货时间
         Date settleTime = order.getSettleTime();
         if (settleTime != null) {
            order.setReceiveTime(format.format(settleTime));
         }
         // 到账时间
         Date accountTime = order.getAccountTime();
         if (accountTime != null) {
            order.setHongBaoDate(format.format(accountTime));
         }
         BigDecimal settlement = order.getSettlement();
         if (settlement != null && settlement.compareTo(new BigDecimal(0)) > 0) {
            order.setPayment(settlement); // 实际付款金额
         }
         /* 订单返利类型 转换 */
         Integer hongBaoType = order.getHongBaoType();
         if (HongBaoV2.TYPE_ZIGOU == hongBaoType || 2 == hongBaoType) {
            // 自购
            order.setHongBaoType(1);
         } else if (HongBaoV2.TYPE_SHARE_GOODS == hongBaoType) {
            // 分享
            order.setHongBaoType(2);
         } else if (HongBaoV2.TYPE_YAOQING == hongBaoType || HongBaoV2.TYPE_YIJI == hongBaoType
               || HongBaoV2.TYPE_ERJI == hongBaoType || HongBaoV2.TYPE_SHARE_YIJI == hongBaoType
               || HongBaoV2.TYPE_SHARE_ERJI == hongBaoType) {
            // 邀请
            order.setHongBaoType(3);
         }
         Integer hongBaoState = order.getHongBaoState();
         if (HongBaoV2.STATE_KELINGQU == hongBaoState || HongBaoV2.STATE_BUKELINGQU == hongBaoState) {
            // 未到账
            order.setHongBaoState(1);
         } else if (HongBaoV2.STATE_YILINGQU == hongBaoState) {
            // 已到账
            order.setHongBaoState(2);
         } else if (HongBaoV2.STATE_SHIXIAO == hongBaoState) {
            // 已失效
            order.setHongBaoState(3);
         }
         List<HongBaoV2> listhb = hongBaoV2Service.listChildrenById(order.getHongbaoId());
         if (listhb != null && listhb.size() > 0) {
            if (listhb.size() == 1) {
               UserInfo userInfo = listhb.get(0).getUserInfo();
               if (userInfo != null) {
                  order.setLevelOneId(userInfo.getId() + "");
                  order.setLevelOneMoney(listhb.get(0).getMoney() + "");
               }
            } else if (listhb.size() == 2) {
               UserInfo userInfo = listhb.get(0).getUserInfo();
               if (userInfo != null) {
                  order.setLevelOneId(userInfo.getId() + "");
                  order.setLevelOneMoney(listhb.get(0).getMoney() + "");
               }
               UserInfo userInfo2 = listhb.get(1).getUserInfo();
               if (userInfo2 != null) {
                  order.setLevelTwoId(userInfo2.getId() + "");
                  order.setLevelTwoMoney(listhb.get(1).getMoney() + "");
               }
            }
         }
         Integer sourceType = order.getSourceType();
         // 奖励订单、免单 使用记录
         if (sourceType == null) {
         } else if (sourceType == Constant.SOURCE_TYPE_TAOBAO && listRecordTB != null && listRecordTB.size() > 0) {
            for (UserSystemCouponRecord couponRecord : listRecordTB) {
               if (order.getOrderNo().equals(couponRecord.getOrderNo())) {
                  String systemCouponType = couponRecord.getCouponType();
                  Integer couponState = couponRecord.getState();
                  if (CouponTypeEnum.freeCoupon.name().equals(systemCouponType)
                        || CouponTypeEnum.welfareFreeCoupon.name().equals(systemCouponType)
                        || CouponTypeEnum.freeCouponBuy.name().equals(systemCouponType)) {
                     if (UserSystemCouponRecord.STATE_SUCCESS == couponState) {
                        // 免单成功
                        order.setOtherState(2);
                     } else if (UserSystemCouponRecord.STATE_FREE_ON == couponState) {
                        order.setOtherState(1);
                     }
                  }
                  break;
               }
            }
         } else if (sourceType == Constant.SOURCE_TYPE_JD && listRecordJD != null && listRecordJD.size() > 0) {
            for (UserSystemCouponRecord couponRecord : listRecordJD) {
               if (order.getOrderNo().equals(couponRecord.getOrderNo())) {
                  String systemCouponType = couponRecord.getCouponType();
                  Integer couponState = couponRecord.getState();
                  if (CouponTypeEnum.freeCoupon.name().equals(systemCouponType)
                        || CouponTypeEnum.welfareFreeCoupon.name().equals(systemCouponType)
                        || CouponTypeEnum.freeCouponBuy.name().equals(systemCouponType)) {
                     if (UserSystemCouponRecord.STATE_SUCCESS == couponState) {
                        // 免单成功
                        order.setOtherState(2);
                     } else if (UserSystemCouponRecord.STATE_FREE_ON == couponState) {
                        order.setOtherState(1);
                     }
                  }
                  break;
               }
            }
         } else if (sourceType == Constant.SOURCE_TYPE_PDD && listRecordPDD != null && listRecordPDD.size() > 0) {
            for (UserSystemCouponRecord couponRecord : listRecordPDD) {
               if (order.getOrderNo().equals(couponRecord.getOrderNo())) {
                  String systemCouponType = couponRecord.getCouponType();
                  Integer couponState = couponRecord.getState();
                  if (CouponTypeEnum.freeCoupon.name().equals(systemCouponType)
                        || CouponTypeEnum.welfareFreeCoupon.name().equals(systemCouponType)
                        || CouponTypeEnum.freeCouponBuy.name().equals(systemCouponType)) {
                     if (UserSystemCouponRecord.STATE_SUCCESS == couponState) {
                        // 免单成功
                        order.setOtherState(2);
                     } else if (UserSystemCouponRecord.STATE_FREE_ON == couponState) {
                        order.setOtherState(1);
                     }
                  }
                  break;
               }
            }
         }
      }
      return list;
   }
   @Override
   public long countQuery(Integer keyType, String key, Integer state, Integer type, Integer orderState,
         String startTime, String endTime, Integer source, List<Long> listShopId, List<Long> listGoodsId,
         Date minTime, BigDecimal money, BigDecimal payment) throws CommonOrderException {
      if (StringUtil.isNullOrEmpty(key) || keyType == 1) {// 搜索框无值或者按订单号搜索时都只搜索主订单
         return commonOrderMapper.countQueryWithNoChild(keyType, key, state, type, orderState, startTime, endTime,
               source, payment);
      } else {
         return commonOrderMapper.countQuery(keyType, key, state, type, orderState, startTime, endTime, source,
               listShopId, listGoodsId, minTime, money, payment);
      }
   }
   @Override
   public CommonOrderVO getCommonOrderByOrderNo(Long uid, String orderNo, Integer orderState, Integer sourceType)
         throws CommonOrderException {
      if (sourceType == null) {
         sourceType = Constant.SOURCE_TYPE_TAOBAO;
      }
      CommonOrderVO commonOrderVO = commonOrderMapper.getCommonOrderByOrderNo(uid, orderNo, orderState, sourceType);
      // 订单信息为空
      if (commonOrderVO == null) {
         return null;
      }
      List<CommonOrderVO> listOrder = new ArrayList<CommonOrderVO>();
      listOrder.add(commonOrderVO);
      // 商品信息
      List<CommonOrderVO> listGoods = commonOrderMapper.listOrderGoodsInfo(listOrder);
      // 订单商品为空
      if (listGoods == null || listGoods.size() == 0) {
         return null;
      }
      /* 组合商品信息 */
      for (CommonOrderVO commonOrder : listGoods) {
         CommonOrderGoods goods = commonOrder.getCommonOrderGoods();
         if (goods == null) {
            continue;
         }
         String orderNo1 = commonOrder.getOrderNo();
         Integer sourceType1 = commonOrder.getSourceType();
         String orderNo2 = commonOrderVO.getOrderNo();
         Integer sourceType2 = commonOrderVO.getSourceType();
         // 来源、订单号相同
         if (sourceType1.equals(sourceType2) && orderNo1.equals(orderNo2)) {
            // 加入商品信息
            List<CommonOrderGoodsVO> listOrderGoods = commonOrderVO.getListOrderGoods();
            CommonOrderGoodsVO commonGoodsVO = new CommonOrderGoodsVO();
            try {
               PropertyUtils.copyProperties(commonGoodsVO, goods);
            } catch (Exception e) {
               e.printStackTrace();
            }
            String picture = commonGoodsVO.getPicture();
            if (!StringUtil.isNullOrEmpty(picture) && !picture.contains("320x320")) {
               commonGoodsVO.setPicture(TbImgUtil.getTBSize320Img(picture));
            }
            Integer hongBaoType = commonOrderVO.getHongBaoType();
            // 邀请订单信息保护
            if (HongBaoV2.TYPE_YAOQING == hongBaoType || HongBaoV2.TYPE_YIJI == hongBaoType
                  || HongBaoV2.TYPE_ERJI == hongBaoType || HongBaoV2.TYPE_SHARE_YIJI == hongBaoType
                  || HongBaoV2.TYPE_SHARE_ERJI == hongBaoType) {
               Map<String, String> titleMap = new HashMap<String, String>();
               titleMap.put("content", "为保障用户隐私,商品信息已隐藏!");
               titleMap.put("fontColor", "#888888");
               titleMap.put("bottomColor", "#E9E9E9");
               commonGoodsVO.setTitle(null);
               commonGoodsVO.setGoodsTitle(titleMap);
            }
            // 购买数量
            commonGoodsVO.setActualCount(commonOrder.getTotalCount() + "件");
            BigDecimal totalSettlement = commonOrder.getTotalSettlement();
            if (totalSettlement == null || totalSettlement.compareTo(new BigDecimal(0)) <= 0) {
               totalSettlement = commonOrder.getTotalPayment();
            }
            // 实付款
            commonGoodsVO.setActualPay("付款金额:¥" + totalSettlement);
            listOrderGoods.add(commonGoodsVO);
            Integer orderType = commonOrder.getOrderType();
            if (orderType == null) {
               String shopType = commonGoodsVO.getShopType();
               if (CommonOrderGoodsVO.TYPE_TAOBAO.equalsIgnoreCase(shopType)) {
                  commonOrder.setOrderType(1);
               } else if (CommonOrderGoodsVO.TYPE_TMALL.equalsIgnoreCase(shopType)) {
                  commonOrder.setOrderType(2);
               }
            }
            break;
         }
      }
      return commonOrderVO;
   }
   @Override
   public JSONObject getRewardJumpInfo(String orderNo, Integer goodsType) {
      JSONObject map = new JSONObject();
      // 订单标识
      List<String> signList = new ArrayList<String>();
      // signList.add(CommonOrder.TYPE_FANLI);
      // signList.add(PIC_REWARD); // 加入奖励成功图片
      map.put("signList", signList);
      ClientTextStyleVO rewardStyleVO = new ClientTextStyleVO();
      // 奖励券进度详情
      rewardStyleVO.setContent("已使用奖励券 >");
      rewardStyleVO.setColor("#E5005C");
      rewardStyleVO.setBottomColor("#FFDCEA");
      Map<String, Object> jumpLink = new HashMap<String, Object>();
      jumpLink.put("orderNo", orderNo);
      jumpLink.put("goodsType", goodsType == null ? goodsType : goodsType + "");
      Map<String, Object> jump = new HashMap<String, Object>();
      jump.put("type", 1);
      jump.put("params", jumpLink);
      jump.put("jumpDetail", jumpDetailV2Service.getByTypeCache("rewardCouponDetail"));
      Map<String, Object> rewardMap = new HashMap<String, Object>();
      rewardMap.put("text", rewardStyleVO);
      rewardMap.put("jump", jump);
      map.put("rewardDetail", rewardMap);
      return map;
   }
   @Override
   public CommonOrder selectBySourceTypeAndTradeId(int sourceType, String tradeId) {
      return commonOrderMapper.selectBySourceTypeAndTradeId(sourceType, tradeId);
   }
   @Transactional
   @Override
   public void deleteErrorCommonOrder(Long coId) {
      // 查询是否返利到账
      HongBaoOrder hongBaoOrder = hongBaoOrderService.selectDetailByCommonOrderId(coId);
      if (hongBaoOrder.getHongBaoV2().getState() == HongBaoV2.STATE_YILINGQU)
         return;
      List<HongBaoV2> hongBaoList = hongBaoV2Service.listChildrenById(hongBaoOrder.getHongBaoV2().getId());
      boolean canDelete = true;
      for (HongBaoV2 child : hongBaoList)
         if (child.getState() == HongBaoV2.STATE_YILINGQU) {
            canDelete = false;
            break;
         }
      // 不能删除
      if (!canDelete)
         return;
      // 删除child
      for (HongBaoV2 child : hongBaoList)
         hongBaoV2Service.deleteByPrimaryKey(child.getId());
      // 删除主红包
      hongBaoV2Service.deleteByPrimaryKey(hongBaoOrder.getHongBaoV2().getId());
      // 删除hongbaoOrder
      hongBaoOrderService.deleteByPrimaryKey(hongBaoOrder.getId());
      // 删除CommonOrder
      commonOrderMapper.deleteByPrimaryKey(hongBaoOrder.getCommonOrder().getId());
   }
   @Override
   public List<CommonOrder> listBySourceTypeAndTradeId(int sourceType, String tradeId) {
      return commonOrderMapper.listBySourceTypeAndTradeId(sourceType, tradeId);
   }
   @Override
   public List<CommonOrder> listBySourceTypeAndStateAndThirdCrateTime(int sourceType, Integer state, Long minTime,
         Long maxTime, int page, int pageSize) {
      return commonOrderMapper.listBySourceTypeAndStateAndThirdCrateTime(sourceType, state, minTime, maxTime,
            (page - 1) * pageSize, pageSize);
   }
   @Override
   public List<CommonOrder> getByOrderNo(Long uid, String orderNO) {
      return commonOrderMapper.getByOrderNo(uid, orderNO);
   }
   @Override
   public CommonOrder selectLatestValidByUid(Long uid) {
      List<Integer> stateList = new ArrayList<>();
      stateList.add(CommonOrder.STATE_FK);
      stateList.add(CommonOrder.STATE_JS);
      List<CommonOrder> commonOrderList = commonOrderMapper.listByUid(uid, stateList, 0, 1);
      if (commonOrderList == null || commonOrderList.size() == 0)
         return null;
      return commonOrderList.get(0);
   }
   @Override
   public CommonOrderVO firstValidOrderByUid(Long uid) {
      return commonOrderMapper.firstValidOrderByUid(uid, null, null);
   }
   @Override
   public CommonOrderVO firstValidOrderByUidAndType(Long uid, Integer type) {
      return commonOrderMapper.firstValidOrderByUid(uid, type, null);
   }
   @Override
   public CommonOrderVO firstValidOrderLastMonthByUidAndType(Long uid, Integer type) {
      return commonOrderMapper.firstValidOrderByUid(uid, type, 4);
   }
   @Override
   public CommonOrder getFirstShareOrderByUid(Long uid) {
      return commonOrderMapper.getFirstShareOrderByUid(uid);
   }
   @Override
   public BigDecimal getTotalRewardMoneyByOrderNoAndSourceType(String orderNo, Integer sourceType) {
      return commonOrderMapper.getTotalRewardMoneyByOrderNoAndSourceType(orderNo, sourceType);
   }
   @Override
   public long count24HValidOrderByUid(Long uid, Date minTime) {
      return commonOrderMapper.count24HValidOrderByUid(uid, minTime);
   }
   @Override
   public long countSearchOrderByUid(Long uid, List<ESOrder> list) {
      return commonOrderMapper.countSearchOrderByUid(uid, list);
   }
   @Override
   public List<CommonOrder> getMinSettleTimeAndUid() {
      return commonOrderMapper.getMinSettleTimeAndUid();
   }
   @Override
   public List<CommonOrderVO> searchOrderByUid(AcceptData acceptData, int page, int size, Long uid, List<ESOrder> list)
         throws Exception {
      List<CommonOrderVO> listVO = commonOrderMapper.searchOrderByUid((page - 1) * size, size, uid, list);
      // 订单信息为空
      if (listVO == null || listVO.size() == 0) {
         listVO = new ArrayList<CommonOrderVO>();
         return listVO;
      }
      // 商品信息
      List<CommonOrderVO> listGoods = commonOrderMapper.listOrderGoodsInfo(listVO);
      // 订单商品为空
      if (listGoods == null || listGoods.size() == 0) {
         return listVO;
      }
      // 数据加工重新组织
      if (VersionUtil.greaterThan_2_1(acceptData.getPlatform(), acceptData.getVersion())) {
         orderVOFactory21(acceptData, listVO, listGoods, uid);
      } else {
         orderVOFactory(acceptData, listVO, listGoods, uid);
      }
      return listVO;
   }
   @Override
   public Date getThirdCreateTime(String orderId, int sourceType) {
      List<CommonOrder> list = listBySourceTypeAndOrderId(sourceType, orderId);
      if (list == null || list.size() == 0)
         return null;
      return list.get(0).getThirdCreateTime();
   }
   @Override
   public List<CommonOrderVO> getOrderList(AcceptData acceptData, Integer page, Long uid, Integer state, Integer type,
         Integer orderState, String orderNo, String startTime, String endTime, Integer dateType,
         List<Integer> listSource) throws CommonOrderException, Exception {
      int pageSize = Constant.PAGE_SIZE;
      List<CommonOrderVO> listOrder = commonOrderMapper.getOrderList((page - 1) * pageSize, pageSize, uid, state,
            type, orderState, orderNo, startTime, endTime, dateType, listSource);
      // 订单信息为空
      if (listOrder == null || listOrder.size() == 0) {
         listOrder = new ArrayList<CommonOrderVO>();
         return listOrder;
      }
      // 商品信息
      List<CommonOrderVO> listGoods = commonOrderMapper.listOrderGoodsInfo(listOrder);
      if (listGoods == null || listGoods.size() == 0) {
         return listOrder;
      }
      // 数据加工重新组织
      orderVOFactory21(acceptData, listOrder, listGoods, uid);
      return listOrder;
   }
   @Override
   public long countOrderList(Long uid, Integer state, Integer type, Integer orderState, String orderNo,
         String startTime, String endTime, Integer dateType, List<Integer> listSource) throws CommonOrderException {
      return commonOrderMapper.countOrderList(uid, state, type, orderState, orderNo, startTime, endTime, dateType,
            listSource);
   }
   /**
    * 订单信息加工
    *
    * @param acceptData
    * @param listOrder
    * @param listGoods
    * @param uid
    */
   private void orderVOFactory21(AcceptData acceptData, List<CommonOrderVO> listOrder, List<CommonOrderVO> listGoods,
         Long uid) throws Exception {
      List<String> listTB = new ArrayList<String>();
      List<String> listJD = new ArrayList<String>();
      List<String> listPDD = new ArrayList<String>();
      for (CommonOrderVO order : listOrder) {
         if (order.getHongBaoType() == HongBaoV2.TYPE_YIJI || order.getHongBaoType() == HongBaoV2.TYPE_ERJI
               || order.getHongBaoType() == HongBaoV2.TYPE_SHARE_ERJI
               || order.getHongBaoType() == HongBaoV2.TYPE_SHARE_ERJI) {
            Integer urank = order.getUrank();
            if (urank != null) {
                UserLevelEnum levelEnum = UserLevelUtil.getByOrderRank(urank);
               if (levelEnum != null) {
                  levelEnum = UserLevelUtil.getShowLevel(levelEnum);
                  order.setOrderDesc("订单来源:" + levelEnum.getName());
               }
            }
         }
         Integer sourceType = order.getSourceType();
         if (sourceType == null) {
            continue;
         } else if (sourceType == Constant.SOURCE_TYPE_TAOBAO) {
            listTB.add(order.getOrderNo());
         } else if (sourceType == Constant.SOURCE_TYPE_JD) {
            listJD.add(order.getOrderNo());
         } else if (sourceType == Constant.SOURCE_TYPE_PDD) {
            listPDD.add(order.getOrderNo());
         }
      }
      List<UserSystemCouponRecord> listRecordTB = null;
      if (listTB.size() > 0) {
         listRecordTB = userSystemCouponRecordService.getRecordByOrderNoList(Constant.SOURCE_TYPE_TAOBAO, listTB);
      }
      List<UserSystemCouponRecord> listRecordJD = null;
      if (listJD.size() > 0) {
         listRecordJD = userSystemCouponRecordService.getRecordByOrderNoList(Constant.SOURCE_TYPE_JD, listJD);
      }
      List<UserSystemCouponRecord> listRecordPDD = null;
      if (listPDD.size() > 0) {
         listRecordPDD = userSystemCouponRecordService.getRecordByOrderNoList(Constant.SOURCE_TYPE_PDD, listPDD);
      }
      SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd HH:mm");
      SimpleDateFormat formatday = new SimpleDateFormat("yyyy.MM.dd");
      // 是否存在奖励券
      for (CommonOrderVO order : listOrder) {
         String orderNo = order.getOrderNo();
         Integer sourceType = order.getSourceType();
         Integer hongBaoType = order.getHongBaoType();
         // 商品信息组合
         for (CommonOrderVO commonOrder : listGoods) {
            CommonOrderGoods goods = commonOrder.getCommonOrderGoods();
            if (goods == null) {
               continue;
            }
            if (sourceType.equals(commonOrder.getSourceType()) && orderNo.equals(commonOrder.getOrderNo())) {
               CommonOrderGoodsVO commonGoodsVO = new CommonOrderGoodsVO();
               PropertyUtils.copyProperties(commonGoodsVO, goods);
               if (commonGoodsVO.getGoodsType() == null) {
                  commonGoodsVO.setGoodsType(sourceType);
               }
               // 淘宝商品图片处理
               String picture = commonGoodsVO.getPicture();
               if (sourceType == Constant.SOURCE_TYPE_TAOBAO && !StringUtil.isNullOrEmpty(picture)
                     && !picture.contains("320x320")) {
                  commonGoodsVO.setPicture(TbImgUtil.getTBSize320Img(picture));
               }
               // 购买数量
               commonGoodsVO.setActualCount(commonOrder.getTotalCount() + "件");
               // 实付款
               BigDecimal totalSettlement = commonOrder.getTotalSettlement();
               if (totalSettlement == null || totalSettlement.compareTo(new BigDecimal(0)) <= 0) {
                  totalSettlement = commonOrder.getTotalPayment();
               }
               commonGoodsVO.setActualPay("付款金额:¥" + totalSettlement);
               // 邀请订单信息保护
               if (HongBaoV2.TYPE_YAOQING == hongBaoType || HongBaoV2.TYPE_YIJI == hongBaoType
                     || HongBaoV2.TYPE_ERJI == hongBaoType || HongBaoV2.TYPE_SHARE_YIJI == hongBaoType
                     || HongBaoV2.TYPE_SHARE_ERJI == hongBaoType) {
                  Map<String, String> titleMap = new HashMap<String, String>();
                  titleMap.put("content", "为保障用户隐私,商品信息已隐藏!");
                  titleMap.put("fontColor", "#888888");
                  titleMap.put("bottomColor", "#E9E9E9");
                  commonGoodsVO.setTitle(null);
                  commonGoodsVO.setGoodsTitle(titleMap);
               }
               // 订单类型为空时 已商品类为准
               String shopType = commonGoodsVO.getShopType();
               if (CommonOrderGoodsVO.TYPE_TAOBAO.equalsIgnoreCase(shopType)) {
                  order.setOrderType(1);
               } else if (CommonOrderGoodsVO.TYPE_TMALL.equalsIgnoreCase(shopType)) {
                  order.setOrderType(2);
               }
               Integer goodsType = commonGoodsVO.getGoodsType();
               if (goodsType != null & goodsType == Constant.SOURCE_TYPE_ELME) {
                  order.setOrderType(Constant.SOURCE_TYPE_ELME); // 饿了么订单
               }
               order.getListOrderGoods().add(commonGoodsVO);
            }
         }
         // 订单类型
         if (sourceType == Constant.SOURCE_TYPE_TAOBAO) {
            Integer orderType = order.getOrderType();
            if (orderType == null) {
               order.setOrderType(1);
            }
         } else if (sourceType == Constant.SOURCE_TYPE_JD) {
            order.setOrderType(3);
         } else if (sourceType == Constant.SOURCE_TYPE_PDD) {
            order.setOrderType(4);
         }
         Date thirdCreateTime = order.getThirdCreateTime();
         if (thirdCreateTime != null) {
            order.setDownTime("下单时间:" + format.format(thirdCreateTime));
            order.setObtainTime(thirdCreateTime.getTime());
         }
         Date settleTime = order.getSettleTime();
         if (settleTime != null) {
            order.setReceiveTime("收货时间:" + format.format(settleTime));
         }
         Map<String, String> orderStateMap = new HashMap<String, String>();
         // 订单状态
         Integer orderState = order.getState();
         Integer stateWholeOrder = order.getStateWholeOrder();
         if (CommonOrder.STATE_WHOLE_ORDER_BUFENYOUXIAO == stateWholeOrder) {
            // 整个订单部分失效:判断真实状态 订单、红包
            CommonOrderVO buFenOrder = commonOrderMapper.getBuFenOrderState(uid, order.getOrderNo());
            if (buFenOrder != null) {
               // 有效的订单状态
               orderState = buFenOrder.getState();
            }
         }
         // 显示返利说明连接> 未失效
         if (CommonOrder.STATE_SX != orderState
               && thirdCreateTime.getTime() > TimeUtil.convertDateToTemp(Constant.ORDER_SHOW_BRACE_TIME)) {
            String rebateLink = configService.get(ConfigKeyEnum.orderRebateDescLink.getKey());
            order.setRebateLink(rebateLink + "?orderNo=" + orderNo + "&sourceType=" + sourceType);
         }
         // 红包信息
         List<HongBaoOrder> hongBaoOrderList = hongBaoOrderService.listDetailByOrderIdAndSourceTypeAndUid(orderNo,
               sourceType, uid);
         HongBaoCountVO hongBaoCountVO = hongBaoOrderService.getHongBaoCountVO(hongBaoOrderList);
         BigDecimal hongBao = hongBaoCountVO.getValidMoney();
         Integer hongBaoState = hongBaoCountVO.getCurrentState();
         /* 订单状态 转换处理 */
         String orderStateContent = "";
         if (CommonOrder.STATE_FK == orderState) {
            orderStateContent = "已付款";
         } else if (CommonOrder.STATE_JS == orderState) {
            orderStateContent = "已收货";
         } else if (CommonOrder.STATE_SX == orderState) {
            orderStateContent = "未付款/已退款";
         } else if (CommonOrder.STATE_WQ == orderState) {
            orderStateContent = "已售后";
            if (sourceType == Constant.SOURCE_TYPE_TAOBAO) {
               /* 订单维权 判断是否全部维权 */
               List<TaoBaoWeiQuanOrder> listWQ = taoBaoWeiQuanOrderMapper
                     .selectListByOrderIdAndState(order.getOrderNo(), "维权成功");
               BigDecimal weiQuanMoney = getWeiQuanMoney(listWQ, sourceType, uid);
               hongBao = MoneyBigDecimalUtil.sub(hongBao, weiQuanMoney);
            }
         }
         orderStateMap.put("content", orderStateContent);
         orderStateMap.put("fontColor", "#666666");
         order.setOrderState(orderStateMap);
         // 订单标识
         List<String> signList = new ArrayList<String>();
         /* 订单返利类型 转换 */
         if (HongBaoV2.TYPE_ZIGOU == hongBaoType || 2 == hongBaoType) {
            // 自购
            order.setOrderOrigin("1");
            order.setHongBaoTypePic(CommonOrder.TYPE_FANLI);
            signList.add(CommonOrder.TYPE_FANLI);
            // 是否已使用奖励券、免单券情况
            if (sourceType == Constant.SOURCE_TYPE_TAOBAO) {
               couponUseFactory(order, listRecordTB);
            } else if (sourceType == Constant.SOURCE_TYPE_JD) {
               couponUseFactory(order, listRecordJD);
            } else if (sourceType == Constant.SOURCE_TYPE_PDD) {
               couponUseFactory(order, listRecordPDD);
            }
         } else if (HongBaoV2.TYPE_SHARE_GOODS == hongBaoType) {
            // 分享
            order.setOrderOrigin("2");
            order.setHongBaoTypePic(CommonOrder.TYPE_SHARE);
            signList.add(CommonOrder.TYPE_SHARE);
         } else if (HongBaoV2.TYPE_SHARE_YIJI == hongBaoType || HongBaoV2.TYPE_SHARE_ERJI == hongBaoType
               || HongBaoV2.TYPE_YAOQING == hongBaoType || HongBaoV2.TYPE_YIJI == hongBaoType
               || HongBaoV2.TYPE_ERJI == hongBaoType) {
            // 邀请订单
            order.setOrderOrigin("3");
            order.setHongBaoTypePic(CommonOrder.TYPE_INVITE);
            signList.add(CommonOrder.TYPE_INVITE);
         }
         order.setSignList(signList);
         String hongBaoDate = null;
         String hongBaoState_Str = "";
         String hongbaoInfoFontColor = "#E5005C";
         /* 红包状态 转换 */
         String stateContent = "";
         String stateFontColor = "#E5005C";
         Integer orderHongBaoState = null;
         if (HongBaoV2.STATE_KELINGQU == hongBaoState || HongBaoV2.STATE_BUKELINGQU == hongBaoState) {
            orderHongBaoState = 1;
            stateContent = "未到账";
            hongBaoState_Str = "预估";
            Date preAccountTime = order.getPreAccountTime();
            if (preAccountTime != null) {
               hongBaoDate = "预计到账时间:" + formatday.format(preAccountTime);
            }
         } else if (HongBaoV2.STATE_YILINGQU == hongBaoState) {
            orderHongBaoState = 3;
            stateContent = "已到账";
            Date accountTime = order.getAccountTime();
            if (accountTime != null) {
               hongBaoDate = "到账时间:" + formatday.format(accountTime);
            }
         } else if (HongBaoV2.STATE_SHIXIAO == hongBaoState) {
            orderHongBaoState = 4;
            stateContent = "已失效";
            hongbaoInfoFontColor = "#888888";
         }
         order.setHongBaoState(orderHongBaoState);
         order.setHongBaoDate(hongBaoDate);
         if (!StringUtil.isNullOrEmpty(order.getStateDesc())) {
            stateContent = stateContent + "-" + order.getStateDesc();
         }
         Map<String, String> stateMap = new HashMap<String, String>();
         stateMap.put("content", stateContent);
         stateMap.put("fontColor", stateFontColor);
         order.setAccountState(stateMap);
         Map<String, String> hongBaoMap = new HashMap<String, String>();
         hongBaoMap.put("content",
               hongBaoState_Str + "收益 ¥" + hongBao.setScale(2, BigDecimal.ROUND_DOWN).toString());
         hongBaoMap.put("fontColor", hongbaoInfoFontColor);
         order.setHongBaoInfo(hongBaoMap);
         // 分享、邀请 隐藏订单号
         if (HongBaoV2.TYPE_YAOQING == hongBaoType || HongBaoV2.TYPE_YIJI == hongBaoType
               || HongBaoV2.TYPE_ERJI == hongBaoType || HongBaoV2.TYPE_SHARE_YIJI == hongBaoType
               || HongBaoV2.TYPE_SHARE_ERJI == hongBaoType) {
            order.setOrderNo(UserUtil.filterOrderId(order.getOrderNo()));
         }
      }
   }
   /**
    * 订单: 免单标识 奖励标识
    *
    * @param order
    * @param list
    */
   private void couponUseFactory(CommonOrderVO order, List<UserSystemCouponRecord> list) throws Exception {
      if (list == null || list.size() == 0) {
         return;
      }
      String text = null;
      for (UserSystemCouponRecord couponRecord : list) {
         int goodSource = couponRecord.getGoodSource();
         if (goodSource == 0)
            goodSource = 1;
         String orderNo = couponRecord.getOrderNo();
         if (order.getOrderNo().equals(orderNo) && goodSource == order.getSourceType()) {
            Integer state = couponRecord.getState();
            String systemCouponType = couponRecord.getCouponType();
            if (CouponTypeEnum.rebatePercentCoupon.name().equals(systemCouponType)
                  && UserSystemCouponRecord.STATE_SUCCESS == state) {
               text = "已奖励";
            } else if (CouponTypeEnum.freeCoupon.name().equals(systemCouponType)
                  || CouponTypeEnum.welfareFreeCoupon.name().equals(systemCouponType)
                  || CouponTypeEnum.freeCouponBuy.name().equals(systemCouponType)) {
               if (UserSystemCouponRecord.STATE_FREE_ON == state) {
                  text = "免单中";
               } else if (UserSystemCouponRecord.STATE_SUCCESS == state) {
                  text = "已免单";
               }
            }
            break;
         }
      }
      if (!StringUtil.isNullOrEmpty(text)) {
         ClientTextStyleVO rewardStyleVO = new ClientTextStyleVO();
         rewardStyleVO.setContent(text);
         rewardStyleVO.setColor("#E5005C");
         rewardStyleVO.setBottomColor("#FFDCEA");
         Map<String, Object> rewardMap = new HashMap<String, Object>();
         rewardMap.put("text", rewardStyleVO);
         order.setRewardDetail(rewardMap);
      }
   }
   @Override
   public long countOrderByUidAndSettled(Long uid, BigDecimal payment) {
      Long count = commonOrderMapper.countOrderByUidAndSettled(uid, payment);
      if (count == null) {
         count = 0L;
      }
      return count;
   }
}