admin
2020-08-26 26f7accb815f55f18f8eedfca4324700a96884ec
资金验证优化
4个文件已添加
49个文件已修改
17815 ■■■■ 已修改文件
fanli/error.log.2020-08-09 66 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/java/com/yeshi/fanli/aspect/RequestFrequencyLimitAspect.java 1 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/java/com/yeshi/fanli/controller/MonitorController.java 2 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/java/com/yeshi/fanli/controller/admin/ExtractAdminController.java 52 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/java/com/yeshi/fanli/controller/client/v1/SMSController.java 421 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/java/com/yeshi/fanli/controller/client/v2/GoodsControllerV2.java 9 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/java/com/yeshi/fanli/controller/client/v2/SearchControllerV2.java 13 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/java/com/yeshi/fanli/controller/client/v2/UserMoneyControllerV2.java 1712 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/java/com/yeshi/fanli/controller/h5/BuWanH5Controller.java 207 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/java/com/yeshi/fanli/controller/wxmp/v1/GoodsController.java 2 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/java/com/yeshi/fanli/dao/mybatis/HongBaoV2Mapper.java 10 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/java/com/yeshi/fanli/dao/mybatis/order/CommonOrderCountMapper.java 398 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/java/com/yeshi/fanli/dao/mybatis/order/CommonOrderMapper.java 860 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/java/com/yeshi/fanli/dto/pdd/PDDGoodsDetail.java 794 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/java/com/yeshi/fanli/entity/SystemEnum.java 14 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/java/com/yeshi/fanli/entity/bus/user/HongBaoV2.java 2 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/java/com/yeshi/fanli/job/goods/HDKGoodsJob.java 1 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/java/com/yeshi/fanli/job/order/OrderTeamIncomeJob.java 7 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/java/com/yeshi/fanli/log/LogHelper.java 410 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/java/com/yeshi/fanli/service/impl/count/CommonOrderCountServiceImpl.java 631 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/java/com/yeshi/fanli/service/impl/money/extract/ExtractServiceImpl.java 2171 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/java/com/yeshi/fanli/service/impl/money/tb/TaoBaoWeiQuanDrawBackServiceImpl.java 2 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/java/com/yeshi/fanli/service/impl/order/CommonOrderServiceImpl.java 3969 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/java/com/yeshi/fanli/service/impl/order/HongBaoV2ServiceImpl.java 19 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/java/com/yeshi/fanli/service/impl/order/OrderMoneySettleServiceImpl.java 1360 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/java/com/yeshi/fanli/service/impl/order/OrderProcessServiceImpl.java 73 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/java/com/yeshi/fanli/service/impl/push/HWPushServiceImpl.java 10 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/java/com/yeshi/fanli/service/impl/taobao/haodanku/HDKGoodsDetailServiceImpl.java 3 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/java/com/yeshi/fanli/service/impl/user/SMSServiceImpl.java 45 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/java/com/yeshi/fanli/service/inter/order/CommonOrderCountService.java 10 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/java/com/yeshi/fanli/service/inter/order/CommonOrderService.java 901 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/java/com/yeshi/fanli/service/inter/order/HongBaoV2Service.java 9 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/java/com/yeshi/fanli/service/inter/order/OrderMoneySettleService.java 4 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/java/com/yeshi/fanli/service/inter/user/SMSService.java 13 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/java/com/yeshi/fanli/service/manger/goods/ConvertLinkManager.java 2 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/java/com/yeshi/fanli/service/manger/money/TeamEincomeManager.java 14 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/java/com/yeshi/fanli/util/Constant.java 2 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/java/com/yeshi/fanli/util/RedisKeyEnum.java 2 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/java/com/yeshi/fanli/util/SpringContext.java 638 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/java/com/yeshi/fanli/util/TencentSMSUtil.java 2 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/java/com/yeshi/fanli/util/cache/TaoBaoGoodsCacheUtil.java 297 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/java/com/yeshi/fanli/util/pinduoduo/PinDuoDuoApiUtil.java 903 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/java/com/yeshi/fanli/util/pinduoduo/PinDuoDuoUtil.java 992 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/java/com/yeshi/fanli/util/taobao/TaoKeApiUtil.java 2 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/resource/docker-compose-copy.yml 25 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/resource/docker-compose.yml 17 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/resource/env-dev/mongo.properties 16 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/resource/env-dev/redis.properties 2 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/resource/mapping/hongbao/HongBaoV2CountMapper.xml 4 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/resource/mapping/hongbao/HongBaoV2Mapper.xml 11 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/resource/mapping/order/CommonOrderCountMapper.xml 660 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/src/main/resource/mapping/order/CommonOrderMapper.xml 24 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
utils/src/main/java/org/yeshi/utils/JsonUtil.java 1 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
fanli/error.log.2020-08-09
New file
@@ -0,0 +1,66 @@
2020-08-09 13:39:03  [ Curator-Framework-0:69946 ] - [ ERROR ]  Connection timed out for connection string (134.175.68.214:2181) and timeout (3000) / elapsed (5046)
org.apache.curator.CuratorConnectionLossException: KeeperErrorCode = ConnectionLoss
    at org.apache.curator.ConnectionState.checkTimeouts(ConnectionState.java:225)
    at org.apache.curator.ConnectionState.getZooKeeper(ConnectionState.java:94)
    at org.apache.curator.CuratorZookeeperClient.getZooKeeper(CuratorZookeeperClient.java:117)
    at org.apache.curator.framework.imps.CuratorFrameworkImpl.performBackgroundOperation(CuratorFrameworkImpl.java:835)
    at org.apache.curator.framework.imps.CuratorFrameworkImpl.backgroundOperationsLoop(CuratorFrameworkImpl.java:809)
    at org.apache.curator.framework.imps.CuratorFrameworkImpl.access$300(CuratorFrameworkImpl.java:64)
    at org.apache.curator.framework.imps.CuratorFrameworkImpl$4.call(CuratorFrameworkImpl.java:267)
    at java.util.concurrent.FutureTask.run$$$capture(FutureTask.java:266)
    at java.util.concurrent.FutureTask.run(FutureTask.java)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
2020-08-09 13:39:24  [ pushExecutor-5:91460 ] - [ ERROR ]  Attempt to send Notification failed and beyond the maximum number of attempts permitted
2020-08-09 13:39:24  [ pushExecutor-5:91461 ] - [ ERROR ]  Delivery error
java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(SocketInputStream.java:210)
    at java.net.SocketInputStream.read(SocketInputStream.java:141)
    at sun.security.ssl.InputRecord.readFully(InputRecord.java:465)
    at sun.security.ssl.InputRecord.read(InputRecord.java:503)
    at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:983)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1385)
    at sun.security.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:757)
    at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:123)
    at java.io.OutputStream.write(OutputStream.java:75)
    at javapns.notification.PushNotificationManager.sendNotification(PushNotificationManager.java:402)
    at javapns.notification.PushNotificationManager.sendNotification(PushNotificationManager.java:350)
    at javapns.notification.PushNotificationManager.sendNotifications(PushNotificationManager.java:286)
    at com.yeshi.fanli.util.push.IOSPushUtil.pushIOS(IOSPushUtil.java:172)
    at com.yeshi.fanli.util.push.IOSPushUtil.allPushIOS(IOSPushUtil.java:124)
    at com.yeshi.fanli.service.impl.push.IOSPushServiceImpl.pushZNX(IOSPushServiceImpl.java:253)
    at com.yeshi.fanli.service.impl.push.IOSPushServiceImpl$$FastClassBySpringCGLIB$$9f77791e.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:720)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:85)
    at com.yeshi.fanli.aspect.VersionLimitAspect.requestSerializable(VersionLimitAspect.java:93)
    at sun.reflect.GeneratedMethodAccessor100.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:629)
    at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:618)
    at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:70)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:85)
    at com.yeshi.fanli.aspect.RequestSerializableServiceAspect.requestSerializable(RequestSerializableServiceAspect.java:113)
    at sun.reflect.GeneratedMethodAccessor99.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:629)
    at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:618)
    at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:70)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.interceptor.AsyncExecutionInterceptor$1.call(AsyncExecutionInterceptor.java:115)
    at java.util.concurrent.FutureTask.run$$$capture(FutureTask.java:266)
    at java.util.concurrent.FutureTask.run(FutureTask.java)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
2020-08-09 13:39:24  [ pushExecutor-5:91462 ] - [ ERROR ]  Delivery error: java.net.SocketException: Connection reset
2020-08-09 13:39:24  [ pushExecutor-5:91462 ] - [ ERROR ]  Delivery error: java.net.SocketException: Socket Closed
fanli/src/main/java/com/yeshi/fanli/aspect/RequestFrequencyLimitAspect.java
@@ -58,6 +58,5 @@
            e.printStackTrace();
        }
        return obj;
    }
}
fanli/src/main/java/com/yeshi/fanli/controller/MonitorController.java
@@ -108,7 +108,7 @@
     * @param out
     */
    @RequestMapping("orderParse")
    public void dubboGoodsService(int sourceType, HttpServletResponse response, PrintWriter out) {
    public void orderParse(int sourceType, HttpServletResponse response, PrintWriter out) {
        if (isParseOrderNormal(sourceType+"")) {
            out.print("200");
        } else {
fanli/src/main/java/com/yeshi/fanli/controller/admin/ExtractAdminController.java
@@ -7,11 +7,7 @@
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
@@ -19,6 +15,8 @@
import com.yeshi.fanli.entity.SystemEnum;
import com.yeshi.fanli.entity.accept.AdminAcceptData;
import com.yeshi.fanli.entity.order.CommonOrder;
import com.yeshi.fanli.service.inter.order.CommonOrderService;
import com.yeshi.fanli.service.inter.user.UserInfoService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@@ -86,6 +84,9 @@
    @Resource
    private CommonOrderCountService commonOrderCountService;
    @Resource
    private CommonOrderService commonOrderService;
    @Resource
    private UserInfoService userInfoService;
@@ -482,12 +483,47 @@
        // 查询同店铺商品,同商品订单超过一定数量的
        List<Integer> typeList = new ArrayList<>();
        typeList.add(HongBaoV2.TYPE_ZIGOU);
        long sameGoodsOrderCount = commonOrderCountService.countSameGoodsOrderByUidAndHongBaoType(typeList, uid,
        List<Long> goodsIds = commonOrderCountService.listSameGoodsIdByUidAndHongBaoType(typeList, uid,
                Integer.parseInt(configService.getValue(ConfigKeyEnum.adminMinSameGoodsOrderCount.getKey(), acceptData.getSystem())));
        int sameGoodsDangerCount = 0;
        if (goodsIds.size() > 0) {
            for (int i = 0; i < goodsIds.size(); i++) {
                long goodsId = goodsIds.get(i);
                Date minDate = new Date(System.currentTimeMillis() - 1000 * 60 * 60L * 24 * 365L);
                List<CommonOrder> commonOrdersList = commonOrderService.listByGoodsIdAndUidAndMinThirdCreateTime(goodsId, uid, minDate);
                Map<String, Date> cmap = new HashMap<>();
                if (commonOrdersList != null)
                    for (CommonOrder co : commonOrdersList) {
                        if (co.getState() == CommonOrder.STATE_FK || co.getState() == CommonOrder.STATE_JS || co.getState() == CommonOrder.STATE_WQ)
                            cmap.put(co.getOrderNo(), co.getThirdCreateTime());
                    }
                List<Date> dateList = new ArrayList<>();
                for (Iterator<String> its = cmap.keySet().iterator(); its.hasNext(); ) {
                    String orderNo = its.next();
                    dateList.add(cmap.get(orderNo));
                }
                Collections.sort(dateList);
                Date lastDate = null;
                for (Date date : dateList) {
                    if (lastDate != null) {
                        if (Math.abs(date.getTime() - lastDate.getTime()) < 1000 * 60 * 60 * 24L * 15) {
                            sameGoodsDangerCount++;
                            break;
                        }
                    } else {
                        lastDate = date;
                    }
                }
            }
        }
        long sameShopOrderCount = commonOrderCountService.countSameShopOrderByUidAndHongBaoType(typeList, uid,
                Integer.parseInt(configService.getValue(ConfigKeyEnum.adminMinSameShopOrderCount.getKey(), acceptData.getSystem())));
        if (sameGoodsOrderCount > 0 || sameShopOrderCount > 0) {
            String text = (String.format("同店铺:%s 同商品:%s", sameShopOrderCount, sameGoodsOrderCount));
        if (sameGoodsDangerCount>0 || sameShopOrderCount > 0) {
            String text = (String.format("同店铺:%s 同商品:%s", sameShopOrderCount, sameGoodsDangerCount));
            JsonUtil.printMode(out, callback, JsonUtil.loadTrueResult(text));
            return;
        }
fanli/src/main/java/com/yeshi/fanli/controller/client/v1/SMSController.java
@@ -4,6 +4,7 @@
import javax.annotation.Resource;
import com.yeshi.fanli.entity.SystemEnum;
import com.yeshi.fanli.util.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@@ -22,238 +23,236 @@
@RequestMapping("api/v1/sms")
public class SMSController {
    @Resource
    private SMSService smsService;
    @Resource
    private SMSService smsService;
    @Resource
    private RedisManager redisManager;
    @Resource
    private RedisManager redisManager;
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private ForbiddenUserIdentifyCodeService forbiddenUserIdentifyCodeService;
    @Resource
    private ForbiddenUserIdentifyCodeService forbiddenUserIdentifyCodeService;
    // 发送短信
    // 发送短信
    @RequestSerializableByKey(key = "#phone+'-'+#uid+'-'+#type")
    @RequestMapping(value = "sendSMS", method = RequestMethod.POST)
    public void sendMSM(AcceptData acceptData, String phone, Long uid, Integer type, PrintWriter out) {
        if (Constant.IS_TEST) {
            out.print(JsonUtil.loadTrueResult("发送成功"));
            return;
        }
        sendMSM(acceptData, phone, uid, type, StringUtil.Md5(phone + "-" + "-" + uid + "-" + type), out);
    }
    @RequestSerializableByKey(key = "#phone+'-'+#uid+'-'+#type")
    @RequestMapping(value = "sendSMS", method = RequestMethod.POST)
    public void sendMSM(AcceptData acceptData, String phone, Long uid, Integer type, PrintWriter out) {
        if (Constant.IS_TEST) {
            out.print(JsonUtil.loadTrueResult("发送成功"));
            return;
        }
        sendMSM(acceptData, phone, uid, type, StringUtil.Md5(phone + "-" + "-" + uid + "-" + type), out);
    }
    public void sendMSM(AcceptData acceptData, String phone, Long uid, Integer type, String key, PrintWriter out) {
        try {
            if (phone.contains("**") && uid != null && uid > 0) {
                UserInfo userInfo = userInfoService.getUserById(uid);
                if (userInfo == null) {
                    out.print(JsonUtil.loadFalseResult(2, "用户不存在"));
                    return;
                } else if (StringUtil.isNullOrEmpty(userInfo.getPhone())) {
                    out.print(JsonUtil.loadFalseResult(3, "尚未绑定电话号码"));
                    return;
                }
                phone = userInfo.getPhone();
            }
    public void sendMSM(AcceptData acceptData, String phone, Long uid, Integer type, String key, PrintWriter out) {
        try {
            if (phone.contains("**") && uid != null && uid > 0) {
                UserInfo userInfo = userInfoService.getUserById(uid);
                if (userInfo == null) {
                    out.print(JsonUtil.loadFalseResult(2, "用户不存在"));
                    return;
                } else if (StringUtil.isNullOrEmpty(userInfo.getPhone())) {
                    out.print(JsonUtil.loadFalseResult(3, "尚未绑定电话号码"));
                    return;
                }
                phone = userInfo.getPhone();
            }
            if (!StringUtil.isMobile(phone)) {
                out.print(JsonUtil.loadFalseResult(4, "电话号码格式不正确"));
                return;
            }
            smsService.sendLoginVCode(phone, 6);
            if (!StringUtil.isMobile(phone)) {
                out.print(JsonUtil.loadFalseResult(4, "电话号码格式不正确"));
                return;
            }
            smsService.sendLoginVCode(acceptData.getSystem(), phone, 6);
            out.print(JsonUtil.loadTrueResult("发送成功"));
        } catch (SMSException e) {
            out.print(JsonUtil.loadFalseResult(e.getCode(), e.getMsg()));
        }
    }
            out.print(JsonUtil.loadTrueResult("发送成功"));
        } catch (SMSException e) {
            out.print(JsonUtil.loadFalseResult(e.getCode(), e.getMsg()));
        }
    }
    /**
     * 1.5.3 登录发送短信
     *
     * @param acceptData
     * @param phone
     * @param out
     */
    @RequestMapping(value = "sendMSMLogin", method = RequestMethod.POST)
    public void sendMSMLogin(AcceptData acceptData, String phone, boolean slideVerify, PrintWriter out) {
        if (phone == null || !StringUtil.isMobile(phone.replaceAll(" ", ""))) {
            out.print(JsonUtil.loadFalseResult(1, "手机号输入有误,请修改"));
            return;
        }
        phone = phone.replaceAll(" ", "");
    /**
     * 1.5.3 登录发送短信
     *
     * @param acceptData
     * @param phone
     * @param uid
     * @param out
     */
    @RequestMapping(value = "sendMSMLogin", method = RequestMethod.POST)
    public void sendMSMLogin(AcceptData acceptData, String phone, boolean slideVerify, PrintWriter out) {
        if (phone == null || !StringUtil.isMobile(phone.replaceAll(" ", ""))) {
            out.print(JsonUtil.loadFalseResult(1, "手机号输入有误,请修改"));
            return;
        }
        phone = phone.replaceAll(" ", "");
        if (Constant.IS_TEST) {
            out.print(JsonUtil.loadTrueResult("发送成功"));
            return;
        }
        if (Constant.IS_TEST) {
            out.print(JsonUtil.loadTrueResult("发送成功"));
            return;
        }
        sendMSNnew(acceptData.getSystem(), phone, slideVerify, 1, StringUtil.Md5(phone + "-" + acceptData.getDevice()), out);
    }
        sendMSNnew(phone, slideVerify, 1, StringUtil.Md5(phone + "-" + acceptData.getDevice()), out);
    }
    /**
     * 1.5.3 绑定发送短信
     *
     * @param acceptData
     * @param phone
     * @param uid
     * @param out
     */
    @RequestSerializableByKey(key = "#acceptData.device+'-'+#phone")
    @RequestMapping(value = "sendMSMBind", method = RequestMethod.POST)
    public void sendMSMBind(AcceptData acceptData, String phone, boolean slideVerify, Long uid, PrintWriter out) {
        if (phone == null || !StringUtil.isMobile(phone.replaceAll(" ", ""))) {
            out.print(JsonUtil.loadFalseResult(1, "手机号输入有误,请修改"));
            return;
        }
        phone = phone.replaceAll(" ", "");
    /**
     * 1.5.3 绑定发送短信
     *
     * @param acceptData
     * @param phone
     * @param uid
     * @param out
     */
    @RequestSerializableByKey(key = "#acceptData.device+'-'+#phone")
    @RequestMapping(value = "sendMSMBind", method = RequestMethod.POST)
    public void sendMSMBind(AcceptData acceptData, String phone, boolean slideVerify, Long uid, PrintWriter out) {
        if (phone == null || !StringUtil.isMobile(phone.replaceAll(" ", ""))) {
            out.print(JsonUtil.loadFalseResult(1, "手机号输入有误,请修改"));
            return;
        }
        phone = phone.replaceAll(" ", "");
        // 判断手机号码是否被封禁
        // ForbiddenUserIdentifyCode identifyCode1 =
        // forbiddenUserIdentifyCodeService
        // .listByTypeAndIdentifyCode(ForbiddenUserIdentifyCodeTypeEnum.phone,
        // phone);
        // if (identifyCode1 != null && identifyCode1.getEffective() != null &&
        // identifyCode1.getEffective()) {
        // out.print(JsonUtil.loadFalseResult(9001,"该电话号码被占用"));
        // return;
        // }
        //
        // 判断手机号码是否被封禁
        UserInfo phoneUser = userInfoService.getEffectiveUserInfoByPhone(phone, SystemInfoUtil.getSystem(acceptData.getPlatform(), acceptData.getPackages()));
        if (phoneUser != null && uid != null) {
            out.print(JsonUtil.loadFalseResult(9001, "该电话号码被占用"));
            return;
        }
        // 判断手机号码是否被封禁
        // ForbiddenUserIdentifyCode identifyCode1 =
        // forbiddenUserIdentifyCodeService
        // .listByTypeAndIdentifyCode(ForbiddenUserIdentifyCodeTypeEnum.phone,
        // phone);
        // if (identifyCode1 != null && identifyCode1.getEffective() != null &&
        // identifyCode1.getEffective()) {
        // out.print(JsonUtil.loadFalseResult(9001,"该电话号码被占用"));
        // return;
        // }
        //
        // 判断手机号码是否被封禁
        UserInfo phoneUser = userInfoService.getEffectiveUserInfoByPhone(phone, SystemInfoUtil.getSystem(acceptData.getPlatform(), acceptData.getPackages()));
        if (phoneUser != null && uid != null) {
            out.print(JsonUtil.loadFalseResult(9001, "该电话号码被占用"));
            return;
        }
        if (Constant.IS_TEST) {
            out.print(JsonUtil.loadTrueResult("发送成功"));
            return;
        }
        if (Constant.IS_TEST) {
            out.print(JsonUtil.loadTrueResult("发送成功"));
            return;
        }
        sendMSNnew(acceptData.getSystem(), phone, slideVerify, 2, StringUtil.Md5(phone + "-" + acceptData.getDevice()), out);
    }
        sendMSNnew(phone, slideVerify, 2, StringUtil.Md5(phone + "-" + acceptData.getDevice()), out);
    }
    public void sendMSNnew(SystemEnum system, String phone, boolean slideVerify, int type, String key, PrintWriter out) {
        try {
            int count = 0;
            String cachekey = null;
            if (type == 1) {
                // 登录验证码
                cachekey = RedisKeyEnum.getRedisKey(RedisKeyEnum.SMSLoginCount, phone + "");
            } else if (type == 2) {
                // 绑定验证码
                cachekey = RedisKeyEnum.getRedisKey(RedisKeyEnum.SMSBindCount, phone + "");
            }
    public void sendMSNnew(String phone, boolean slideVerify, int type, String key, PrintWriter out) {
        try {
            int count = 0;
            String cachekey = null;
            if (type == 1) {
                // 登录验证码
                cachekey = RedisKeyEnum.getRedisKey(RedisKeyEnum.SMSLoginCount, phone + "");
            } else if (type == 2) {
                // 绑定验证码
                cachekey = RedisKeyEnum.getRedisKey(RedisKeyEnum.SMSBindCount, phone + "");
            }
            if (cachekey == null) {
                out.print(JsonUtil.loadFalseResult(1, "发送失败"));
                return;
            }
            if (cachekey == null) {
                out.print(JsonUtil.loadFalseResult(1, "发送失败"));
                return;
            }
            String cacheValue = redisManager.getCommonString(cachekey);
            if (!StringUtil.isNullOrEmpty(cacheValue)) {
                count = Integer.parseInt(cacheValue);
                // 限制3次
                if (count >= 3) {
                    out.print(JsonUtil.loadFalseResult(3, "验证码次数超限,请稍后再试"));
                    return;
                }
            }
            String cacheValue = redisManager.getCommonString(cachekey);
            if (!StringUtil.isNullOrEmpty(cacheValue)) {
                count = Integer.parseInt(cacheValue);
                // 限制3次
                if (count >= 3) {
                    out.print(JsonUtil.loadFalseResult(3, "验证码次数超限,请稍后再试"));
                    return;
                }
            }
            if (count == 2 && !slideVerify) {
                out.print(JsonUtil.loadFalseResult(2, "需要滑动验证"));
                return;
            }
            // 缓存一个小时
            count++;
            redisManager.cacheCommonString(cachekey, count + "", 60 * 60);
            if (count == 2 && !slideVerify) {
                out.print(JsonUtil.loadFalseResult(2, "需要滑动验证"));
                return;
            }
            // 缓存一个小时
            count++;
            redisManager.cacheCommonString(cachekey, count + "", 60 * 60);
            if (type == 1) {
                // 登录验证码
                smsService.sendLoginVCode(system, phone, 4);
            } else if (type == 2) {
                // 绑定验证码
                smsService.sendBindVCode(system, phone, 4);
            }
            if (type == 1) {
                // 登录验证码
                smsService.sendLoginVCode(phone, 4);
            } else if (type == 2) {
                // 绑定验证码
                smsService.sendBindVCode(phone, 4);
            }
            out.print(JsonUtil.loadTrueResult("发送成功"));
            out.print(JsonUtil.loadTrueResult("发送成功"));
        } catch (SMSException e) {
            out.print(JsonUtil.loadFalseResult(e.getCode(), e.getMsg()));
        } catch (Exception e) {
            out.print(JsonUtil.loadFalseResult(1, "发送失败"));
            e.printStackTrace();
        }
    }
        } catch (SMSException e) {
            out.print(JsonUtil.loadFalseResult(e.getCode(), e.getMsg()));
        } catch (Exception e) {
            out.print(JsonUtil.loadFalseResult(1, "发送失败"));
            e.printStackTrace();
        }
    }
    /**
     * 注销账户短信验证
     * @param acceptData
     * @param uid
     * @param phone
     * @param out
     */
    @RequestMapping(value = "sendMSMRemove")
    public void sendMSMRemove(String callback, AcceptData acceptData, Long uid, String phone, PrintWriter out) {
        if (Constant.IS_TEST) {
            JsonUtil.printMode(out, callback, JsonUtil.loadTrueResult("发送成功"));
            return;
        }
        if (uid == null || uid <= 0) {
            JsonUtil.printMode(out, callback, JsonUtil.loadFalseResult(1, "用户未登录"));
            return;
        }
        if (phone == null || !StringUtil.isMobile(phone.replaceAll(" ", ""))) {
            JsonUtil.printMode(out, callback, JsonUtil.loadFalseResult(1, "请输入正确手机号"));
            return;
        }
        phone = phone.replaceAll(" ", "").trim();
        UserInfo userInfo = userInfoService.selectAvailableByPrimaryKey(uid);
        if (userInfo == null) {
            JsonUtil.printMode(out, callback, JsonUtil.loadFalseResult(1, "用户不存在"));
            return;
        }
        if (!phone.equals(userInfo.getPhone())) {
            JsonUtil.printMode(out, callback, JsonUtil.loadFalseResult(1, "请输入正确手机号"));
            return;
        }
        try {
            int count = 0;
            String cachekey = RedisKeyEnum.getRedisKey(RedisKeyEnum.SMSBindRemove, phone + "");
            String cacheValue = redisManager.getCommonString(cachekey);
            if (!StringUtil.isNullOrEmpty(cacheValue)) {
                count = Integer.parseInt(cacheValue);
                // 限制3次
                if (count >= 3) {
                    JsonUtil.printMode(out, callback, JsonUtil.loadFalseResult(1, "验证码次数超限,请稍后再试"));
                    return;
                }
            }
            // 缓存一个小时
            count++;
            redisManager.cacheCommonString(cachekey, count + "", 60 * 60);
            // 发送验证码
            smsService.sendRemoveVCode(phone, 4);
            JsonUtil.printMode(out, callback, JsonUtil.loadTrueResult("发送成功"));
        } catch (SMSException e) {
            JsonUtil.printMode(out, callback, JsonUtil.loadFalseResult(e.getCode(), e.getMsg()));
        } catch (Exception e) {
            JsonUtil.printMode(out, callback, JsonUtil.loadFalseResult(1, "发送失败"));
            e.printStackTrace();
        }
    }
    /**
     * 注销账户短信验证
     *
     * @param acceptData
     * @param uid
     * @param phone
     * @param out
     */
    @RequestMapping(value = "sendMSMRemove")
    public void sendMSMRemove(String callback, AcceptData acceptData, Long uid, String phone, PrintWriter out) {
        if (Constant.IS_TEST) {
            JsonUtil.printMode(out, callback, JsonUtil.loadTrueResult("发送成功"));
            return;
        }
        if (uid == null || uid <= 0) {
            JsonUtil.printMode(out, callback, JsonUtil.loadFalseResult(1, "用户未登录"));
            return;
        }
        if (phone == null || !StringUtil.isMobile(phone.replaceAll(" ", ""))) {
            JsonUtil.printMode(out, callback, JsonUtil.loadFalseResult(1, "请输入正确手机号"));
            return;
        }
        phone = phone.replaceAll(" ", "").trim();
        UserInfo userInfo = userInfoService.selectAvailableByPrimaryKey(uid);
        if (userInfo == null) {
            JsonUtil.printMode(out, callback, JsonUtil.loadFalseResult(1, "用户不存在"));
            return;
        }
        if (!phone.equals(userInfo.getPhone())) {
            JsonUtil.printMode(out, callback, JsonUtil.loadFalseResult(1, "请输入正确手机号"));
            return;
        }
        try {
            int count = 0;
            String cachekey = RedisKeyEnum.getRedisKey(RedisKeyEnum.SMSBindRemove, phone + "");
            String cacheValue = redisManager.getCommonString(cachekey);
            if (!StringUtil.isNullOrEmpty(cacheValue)) {
                count = Integer.parseInt(cacheValue);
                // 限制3次
                if (count >= 3) {
                    JsonUtil.printMode(out, callback, JsonUtil.loadFalseResult(1, "验证码次数超限,请稍后再试"));
                    return;
                }
            }
            // 缓存一个小时
            count++;
            redisManager.cacheCommonString(cachekey, count + "", 60 * 60);
            // 发送验证码
            smsService.sendRemoveVCode(acceptData.getSystem(), phone, 4);
            JsonUtil.printMode(out, callback, JsonUtil.loadTrueResult("发送成功"));
        } catch (SMSException e) {
            JsonUtil.printMode(out, callback, JsonUtil.loadFalseResult(e.getCode(), e.getMsg()));
        } catch (Exception e) {
            JsonUtil.printMode(out, callback, JsonUtil.loadFalseResult(1, "发送失败"));
            e.printStackTrace();
        }
    }
}
fanli/src/main/java/com/yeshi/fanli/controller/client/v2/GoodsControllerV2.java
@@ -970,7 +970,7 @@
        CouponInfoVO couponInfo = goodsDetail.getCouponInfo();
        PDDPromotionUrl convertUrl = null;
        if (couponInfo != null) {
            convertUrl = PinDuoDuoApiUtil.convert(id, PinDuoDuoApiUtil.PID_COUPON + "", null);
            convertUrl = PinDuoDuoApiUtil.convert(id, PinDuoDuoApiUtil.PID_COUPON + "", null, false);
            if (convertUrl != null)
                couponInfo.setLink(convertUrl.getUrl());
        }
@@ -1781,7 +1781,8 @@
            return;
        }
        PDDPromotionUrl convertUrl = PinDuoDuoApiUtil.convert(id, pid + "", uid + "");
        boolean auth = PinDuoDuoApiUtil.isAuth(pid, uid + "");
        PDDPromotionUrl convertUrl = PinDuoDuoApiUtil.convert(id, pid + "", uid + "", !auth);
        JSONObject data = new JSONObject();
        data.put("native", true);
        data.put("jumpLink", convertUrl.getUrl());
@@ -1853,8 +1854,8 @@
        String pid = SuningApiUtil.PID_BUY;
        if (!SystemInfoUtil.hasFunctions(acceptData.getSystem(), SystemFunction.fanli)) {
            pid=SuningApiUtil.PID_COUPON;
            uid=null;
            pid = SuningApiUtil.PID_COUPON;
            uid = null;
        } else {
            if (uid == null || uid <= 0) {
                out.print(JsonUtil.loadFalseResult(1, "用户ID不能为空"));
fanli/src/main/java/com/yeshi/fanli/controller/client/v2/SearchControllerV2.java
@@ -140,6 +140,7 @@
    @Resource
    private UserExtraTaoBaoInfoService userExtraTaoBaoInfoService;
    /**
     * 粘贴板信息推荐
     *
@@ -259,7 +260,7 @@
                                    TaoBaoGoodsBrief goodsBrief = null;
                                    String specialId = userExtraTaoBaoInfoService.getSpecialIdByUid(uid);
                                    try {
                                        goodsBrief = TaoKeApiUtil.searchGoodsDetail(goods.getGoodsId(),specialId,null);
                                        goodsBrief = TaoKeApiUtil.searchGoodsDetail(goods.getGoodsId(), specialId, null);
                                    } catch (TaobaoGoodsDownException e) {
                                        e.printStackTrace();
                                    }
@@ -650,15 +651,19 @@
        }
        // 淘宝api搜索商品
        TaoBaoSearchResult result = TaoBaoUtil.search(sf, specialId, null);
        TaoBaoSearchResult result = taoBaoGoodsCacheUtil.getSearchResult(sf); // TaoBaoUtil.search(sf, specialId, null);
        if (result == null) {
            result = TaoBaoUtil.search(sf, specialId, null);
            taoBaoGoodsCacheUtil.saveSearchResult(sf, result);
        }
        TaoBaoSearchResult finalResult = result;
        // 搜索结果缓存到redis
        if (result != null && result.getTaoBaoGoodsBriefs() != null && result.getTaoBaoGoodsBriefs().size() > 0) {
            ThreadUtil.run(new Runnable() {
                @Override
                public void run() {
                    // 更新到緩存
                    for (TaoBaoGoodsBrief goods : result.getTaoBaoGoodsBriefs())
                    for (TaoBaoGoodsBrief goods : finalResult.getTaoBaoGoodsBriefs())
                        taoBaoGoodsCacheUtil.saveCommonTaoBaoGoodsInfo(goods);
                }
            });
fanli/src/main/java/com/yeshi/fanli/controller/client/v2/UserMoneyControllerV2.java
@@ -64,977 +64,979 @@
/**
 * 账户系统
 *
 * @author Administrator
 *
 * @author Administrator
 */
@Controller
@RequestMapping("api/v2/usermoney")
public class UserMoneyControllerV2 {
    @Resource
    private UserMoneyDetailService userMoneyDetailService;
    @Resource
    private UserMoneyDetailService userMoneyDetailService;
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private HongBaoV2Service hongBaoV2Service;
    @Resource
    private HongBaoV2Service hongBaoV2Service;
    @Resource
    private ExtractService extractService;
    @Resource
    private ExtractService extractService;
    @Resource
    private UserInfoExtraService userInfoExtraService;
    @Resource
    private UserInfoExtraService userInfoExtraService;
    @Resource
    private ConfigService configService;
    @Resource
    private ConfigService configService;
    @Resource
    private HongBaoV2CountService hongBaoV2CountService;
    @Resource
    private HongBaoV2CountService hongBaoV2CountService;
    @Resource
    private OrderMoneyDailyCountService orderMoneyDailyCountService;
    @Resource
    private OrderMoneyDailyCountService orderMoneyDailyCountService;
    @Resource
    private TeamEincomeRecordService teamEincomeRecordService;
    @Resource
    private TeamEincomeRecordService teamEincomeRecordService;
    @Resource
    private PreviewInfoService previewInfoService;
    @Resource
    private PreviewInfoService previewInfoService;
    @Resource
    private TeamDividentsSourceOrderUserMapService teamDividentsSourceOrderUserMapService;
    @Resource
    private TeamDividentsSourceOrderUserMapService teamDividentsSourceOrderUserMapService;
    private Gson getGson() {
        GsonBuilder builder = new GsonBuilder();
        builder.registerTypeAdapter(BigDecimal.class, new JsonSerializer<BigDecimal>() {
            @Override
            public JsonElement serialize(BigDecimal value, Type theType, JsonSerializationContext context) {
                if (value == null) {
                    return new JsonPrimitive("");
                } else {
                    // 保留2位小数
                    value = value.setScale(2, BigDecimal.ROUND_DOWN);
                    return new JsonPrimitive(value.toString());
                }
            }
        });
        return builder.create();
    }
    private Gson getGson() {
        GsonBuilder builder = new GsonBuilder();
        builder.registerTypeAdapter(BigDecimal.class, new JsonSerializer<BigDecimal>() {
            @Override
            public JsonElement serialize(BigDecimal value, Type theType, JsonSerializationContext context) {
                if (value == null) {
                    return new JsonPrimitive("");
                } else {
                    // 保留2位小数
                    value = value.setScale(2, BigDecimal.ROUND_DOWN);
                    return new JsonPrimitive(value.toString());
                }
            }
        });
        return builder.create();
    }
    /**
     * 用户资金统计
     *
     * @param acceptData
     * @param uid
     * @param out
     */
    @RequestMapping(value = "getMoneyStatistic")
    public void getMoneyStatistic(AcceptData acceptData, Long uid, PrintWriter out) {
        if (uid == null || uid == 0) {
            out.print(JsonUtil.loadFalseResult(1, "用户未登录"));
            return;
        }
    /**
     * 用户资金统计
     *
     * @param acceptData
     * @param uid
     * @param out
     */
    @RequestMapping(value = "getMoneyStatistic")
    public void getMoneyStatistic(AcceptData acceptData, Long uid, PrintWriter out) {
        if (uid == null || uid == 0) {
            out.print(JsonUtil.loadFalseResult(1, "用户未登录"));
            return;
        }
        // VIP数据预览
        MoneyStatisticVO vo = null;
        String redisContent = previewInfoService.getRedisContent(uid, PreviewEnum.moneyInfo);
        if (!StringUtil.isNullOrEmpty(redisContent)) {
            vo = new Gson().fromJson(redisContent, MoneyStatisticVO.class);
            if (vo != null) {
                vo.setLink(configService.getValue(ConfigKeyEnum.autoExtractHelpUrl.getKey(),acceptData.getSystem()));
                vo.setExtractDesc("提现金额就是已成功提现到支付宝的资金");
                if (VersionUtil.greaterThan_2_1_2(acceptData.getPlatform(), acceptData.getVersion())) {
                    vo.setMoneyArrivalDesc("尽早确认收货可以促使资金尽早到账");
                } else {
                    vo.setMoneyArrivalDesc("订单已到账后提现时间和金额均不受限制");
                }
                if(vo.getLastMonthSettleMoney() == null) {
                    vo.setLastMonthExtractMoney(BigDecimal.ZERO);
                }
                if(vo.getNotSettleMoney() == null) {
                    vo.setNotSettleMoney(BigDecimal.ZERO);
                }
            }
        }
        // VIP数据预览
        MoneyStatisticVO vo = null;
        String redisContent = previewInfoService.getRedisContent(uid, PreviewEnum.moneyInfo);
        if (!StringUtil.isNullOrEmpty(redisContent)) {
            vo = new Gson().fromJson(redisContent, MoneyStatisticVO.class);
            if (vo != null) {
                vo.setLink(configService.getValue(ConfigKeyEnum.autoExtractHelpUrl.getKey(), acceptData.getSystem()));
                vo.setExtractDesc("提现金额就是已成功提现到支付宝的资金");
                if (VersionUtil.greaterThan_2_1_2(acceptData.getPlatform(), acceptData.getVersion())) {
                    vo.setMoneyArrivalDesc("尽早确认收货可以促使资金尽早到账");
                } else {
                    vo.setMoneyArrivalDesc("订单已到账后提现时间和金额均不受限制");
                }
        if (vo == null) {
            vo = createMoneyStatistic(uid, acceptData);
        }
                if (vo.getLastMonthSettleMoney() == null) {
                    vo.setLastMonthExtractMoney(BigDecimal.ZERO);
                }
        Gson gson = getGson();
        out.print(JsonUtil.loadTrueResult(gson.toJson(vo)));
    }
                if (vo.getNotSettleMoney() == null) {
                    vo.setNotSettleMoney(BigDecimal.ZERO);
                }
            }
        }
    private MoneyStatisticVO createMoneyStatistic(Long uid, AcceptData acceptData) {
        UserInfo user = userInfoService.getUserById(uid);
        if (vo == null) {
            vo = createMoneyStatistic(uid, acceptData);
        }
        MoneyStatisticVO vo = new MoneyStatisticVO();
        vo.setLink(configService.getValue(ConfigKeyEnum.autoExtractHelpUrl.getKey(),acceptData.getSystem()));
        vo.setBalanceMoney(user.getMyHongBao());
        vo.setExtractDesc("提现金额就是已成功提现到支付宝的资金");
        Gson gson = getGson();
        out.print(JsonUtil.loadTrueResult(gson.toJson(vo)));
    }
        // 获取提现中的信息
        BigDecimal extractingMoney = extractService.sumVerifyingMoney(uid);
        if (extractingMoney.compareTo(new BigDecimal(0)) > 0)
            vo.setExtractingMoneyInfo("提现中:¥" + extractingMoney.setScale(2, RoundingMode.HALF_UP));
    private MoneyStatisticVO createMoneyStatistic(Long uid, AcceptData acceptData) {
        UserInfo user = userInfoService.getUserById(uid);
        Date minDate = null;
        Date maxDate = null;
        long timeStamp = System.currentTimeMillis();
        List<UserMoneyDetailTypeEnum> typeList = new ArrayList<>();
        MoneyStatisticVO vo = new MoneyStatisticVO();
        vo.setLink(configService.getValue(ConfigKeyEnum.autoExtractHelpUrl.getKey(), acceptData.getSystem()));
        vo.setBalanceMoney(user.getMyHongBao());
        vo.setExtractDesc("提现金额就是已成功提现到支付宝的资金");
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(timeStamp);
        // 获取提现中的信息
        BigDecimal extractingMoney = extractService.sumVerifyingMoney(uid);
        if (extractingMoney.compareTo(new BigDecimal(0)) > 0)
            vo.setExtractingMoneyInfo("提现中:¥" + extractingMoney.setScale(2, RoundingMode.HALF_UP));
        typeList.clear();
        typeList.add(UserMoneyDetailTypeEnum.extract);
        typeList.add(UserMoneyDetailTypeEnum.extractNew);
        typeList.add(UserMoneyDetailTypeEnum.extractVerify);
        typeList.add(UserMoneyDetailTypeEnum.extractVerifyNew);
        typeList.add(UserMoneyDetailTypeEnum.extractReject);
        typeList.add(UserMoneyDetailTypeEnum.extractAutoWX);
        Date minDate = null;
        Date maxDate = null;
        long timeStamp = System.currentTimeMillis();
        List<UserMoneyDetailTypeEnum> typeList = new ArrayList<>();
        // 本月提现
        maxDate = new Date(timeStamp);
        calendar = Calendar.getInstance();
        minDate = new Date(TimeUtil
                .convertToTimeTemp(calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1), "yyyy-M"));
        calendar.add(Calendar.MONTH, -1);
        vo.setMonthExtractMoney(
                userMoneyDetailService.statisticUserTypeMoneyWithDate(uid, typeList, minDate, maxDate, 1).abs());
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(timeStamp);
        // 上月提现
        maxDate = new Date(TimeUtil
                .convertToTimeTemp(calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1), "yyyy-M"));
        calendar.add(Calendar.MONTH, -1);
        minDate = new Date(TimeUtil
                .convertToTimeTemp(calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1), "yyyy-M"));
        vo.setLastMonthExtractMoney(
                userMoneyDetailService.statisticUserTypeMoneyWithDate(uid, typeList, minDate, maxDate, 1).abs());
        typeList.clear();
        typeList.add(UserMoneyDetailTypeEnum.extract);
        typeList.add(UserMoneyDetailTypeEnum.extractNew);
        typeList.add(UserMoneyDetailTypeEnum.extractVerify);
        typeList.add(UserMoneyDetailTypeEnum.extractVerifyNew);
        typeList.add(UserMoneyDetailTypeEnum.extractReject);
        typeList.add(UserMoneyDetailTypeEnum.extractAutoWX);
        minDate = new Date(0L);
        maxDate = new Date(timeStamp);
        // 累计成功提现
        vo.setTotalExtractMoney(
                userMoneyDetailService.statisticUserTypeMoneyWithDate(uid, typeList, minDate, maxDate, 1).abs());
        // 本月提现
        maxDate = new Date(timeStamp);
        calendar = Calendar.getInstance();
        minDate = new Date(TimeUtil
                .convertToTimeTemp(calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1), "yyyy-M"));
        calendar.add(Calendar.MONTH, -1);
        vo.setMonthExtractMoney(
                userMoneyDetailService.statisticUserTypeMoneyWithDate(uid, typeList, minDate, maxDate, 1).abs());
        // 累计自购返利
        typeList.clear();
        typeList.add(UserMoneyDetailTypeEnum.fanli);
        typeList.add(UserMoneyDetailTypeEnum.fanliNew);
        typeList.add(UserMoneyDetailTypeEnum.fanliWeiQuan);
        typeList.add(UserMoneyDetailTypeEnum.fanliWeiQuanNew);
        typeList.add(UserMoneyDetailTypeEnum.orderReward);
        typeList.add(UserMoneyDetailTypeEnum.orderRewardNew);
        vo.setTotalFanLiMoney(
                userMoneyDetailService.statisticUserTypeMoneyWithDate(uid, typeList, minDate, maxDate).abs());
        // 上月提现
        calendar = Calendar.getInstance();
        maxDate = new Date(TimeUtil
                .convertToTimeTemp(calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1), "yyyy-M"));
        calendar.add(Calendar.MONTH, -1);
        minDate = new Date(TimeUtil
                .convertToTimeTemp(calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1), "yyyy-M"));
        vo.setLastMonthExtractMoney(
                userMoneyDetailService.statisticUserTypeMoneyWithDate(uid, typeList, minDate, maxDate, 1).abs());
        // 累计分享赚
        typeList.clear();
        typeList.add(UserMoneyDetailTypeEnum.share);
        typeList.add(UserMoneyDetailTypeEnum.shareNew);
        typeList.add(UserMoneyDetailTypeEnum.shareWeiQuan);
        vo.setTotalShareMoney(
                userMoneyDetailService.statisticUserTypeMoneyWithDate(uid, typeList, minDate, maxDate).abs());
        minDate = new Date(0L);
        maxDate = new Date(timeStamp);
        // 累计成功提现
        vo.setTotalExtractMoney(
                userMoneyDetailService.statisticUserTypeMoneyWithDate(uid, typeList, minDate, maxDate, 1).abs());
        // 累计邀请赚
        typeList.clear();
        typeList.add(UserMoneyDetailTypeEnum.invite);
        typeList.add(UserMoneyDetailTypeEnum.inviteWeiQuan);
        typeList.add(UserMoneyDetailTypeEnum.inviteAndShare);
        typeList.add(UserMoneyDetailTypeEnum.subsidy);
        typeList.add(UserMoneyDetailTypeEnum.teamReward);
        vo.setTotalInviteMoney(
                userMoneyDetailService.statisticUserTypeMoneyWithDate(uid, typeList, minDate, maxDate).abs());
        // 累计自购返利
        typeList.clear();
        typeList.add(UserMoneyDetailTypeEnum.fanli);
        typeList.add(UserMoneyDetailTypeEnum.fanliNew);
        typeList.add(UserMoneyDetailTypeEnum.fanliWeiQuan);
        typeList.add(UserMoneyDetailTypeEnum.fanliWeiQuanNew);
        typeList.add(UserMoneyDetailTypeEnum.orderReward);
        typeList.add(UserMoneyDetailTypeEnum.orderRewardNew);
        vo.setTotalFanLiMoney(
                userMoneyDetailService.statisticUserTypeMoneyWithDate(uid, typeList, minDate, maxDate).abs());
        //累计所有
        typeList.clear();
        typeList.add(UserMoneyDetailTypeEnum.fanli);
        typeList.add(UserMoneyDetailTypeEnum.fanliNew);
        typeList.add(UserMoneyDetailTypeEnum.fanliWeiQuan);
        typeList.add(UserMoneyDetailTypeEnum.fanliWeiQuanNew);
        typeList.add(UserMoneyDetailTypeEnum.orderReward);
        typeList.add(UserMoneyDetailTypeEnum.orderRewardNew);
        typeList.add(UserMoneyDetailTypeEnum.share);
        typeList.add(UserMoneyDetailTypeEnum.shareNew);
        typeList.add(UserMoneyDetailTypeEnum.shareWeiQuan);
        vo.setTotalMoney(
                userMoneyDetailService.statisticUserTypeMoneyWithDate(uid, typeList, minDate, maxDate).abs());
        // 累计分享赚
        typeList.clear();
        typeList.add(UserMoneyDetailTypeEnum.share);
        typeList.add(UserMoneyDetailTypeEnum.shareNew);
        typeList.add(UserMoneyDetailTypeEnum.shareWeiQuan);
        vo.setTotalShareMoney(
                userMoneyDetailService.statisticUserTypeMoneyWithDate(uid, typeList, minDate, maxDate).abs());
        // 累计邀请赚
        typeList.clear();
        typeList.add(UserMoneyDetailTypeEnum.invite);
        typeList.add(UserMoneyDetailTypeEnum.inviteWeiQuan);
        typeList.add(UserMoneyDetailTypeEnum.inviteAndShare);
        typeList.add(UserMoneyDetailTypeEnum.subsidy);
        typeList.add(UserMoneyDetailTypeEnum.teamReward);
        vo.setTotalInviteMoney(
                userMoneyDetailService.statisticUserTypeMoneyWithDate(uid, typeList, minDate, maxDate).abs());
        if (VersionUtil.greaterThan_2_1_2(acceptData.getPlatform(), acceptData.getVersion())) {
            vo.setMoneyArrivalDesc("尽早确认收货可以促使资金尽早到账");
            minDate = new Date(TimeUtil.convertToTimeTemp(TimeUtil.getGernalTime(timeStamp, "yyyy-MM"), "yyyy-MM"));
            Calendar ca = Calendar.getInstance();
            ca.setTime(new Date(timeStamp));
            ca.add(Calendar.MONTH, 1);
            maxDate = new Date(
                    TimeUtil.convertToTimeTemp(TimeUtil.getGernalTime(ca.getTimeInMillis(), "yyyy-MM"), "yyyy-MM"));
            // 本月未到账
            BigDecimal monthUnRecievedMoney = hongBaoV2Service.getUnRecievedMoneyWithPreGetTime(uid, minDate, maxDate);
            vo.setMonthUnRecievedMoney(monthUnRecievedMoney);
            // 全部未到账
            minDate = new Date(0);
            maxDate = new Date(timeStamp);
            vo.setTotalUnRecievedMoney(hongBaoV2Service.getUnRecievedMoneyWithCreateTime(uid, minDate, maxDate));
        } else {
            vo.setMoneyArrivalDesc("订单已到账后提现时间和金额均不受限制");
            // 本月收货
            maxDate = new Date(timeStamp);
            calendar = Calendar.getInstance();
            minDate = new Date(TimeUtil
                    .convertToTimeTemp(calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1), "yyyy-M"));
            calendar.add(Calendar.MONTH, -1);
            vo.setMonthSettleMoney(hongBaoV2CountService.sumMoneyBySettleTimeAndUid(uid, minDate, maxDate));
        //累计所有
        typeList.clear();
        typeList.add(UserMoneyDetailTypeEnum.fanli);
        typeList.add(UserMoneyDetailTypeEnum.fanliNew);
        typeList.add(UserMoneyDetailTypeEnum.fanliWeiQuan);
        typeList.add(UserMoneyDetailTypeEnum.fanliWeiQuanNew);
        typeList.add(UserMoneyDetailTypeEnum.orderReward);
        typeList.add(UserMoneyDetailTypeEnum.orderRewardNew);
        typeList.add(UserMoneyDetailTypeEnum.share);
        typeList.add(UserMoneyDetailTypeEnum.shareNew);
        typeList.add(UserMoneyDetailTypeEnum.shareWeiQuan);
        vo.setTotalMoney(
                userMoneyDetailService.statisticUserTypeMoneyWithDate(uid, typeList, minDate, maxDate).abs());
            // 上月收货
            maxDate = new Date(TimeUtil
                    .convertToTimeTemp(calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1), "yyyy-M"));
            calendar.add(Calendar.MONTH, -1);
            minDate = new Date(TimeUtil
                    .convertToTimeTemp(calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1), "yyyy-M"));
            vo.setLastMonthSettleMoney(hongBaoV2CountService.sumMoneyBySettleTimeAndUid(uid, minDate, maxDate));
        }
        // 待确认收货(180天内)
        vo.setNotSettleMoney(hongBaoV2CountService.sumMoneyByANotSettleAndUid(uid));
        // 今日预估
        calendar.add(Calendar.DAY_OF_YEAR, -1);
        minDate = new Date(TimeUtil.convertDateToTemp(TimeUtil.getGernalTime(timeStamp)));
        vo.setTodayPredict(cratePredictVO(orderMoneyDailyCountService.query(uid, minDate, null)));
        if (VersionUtil.greaterThan_2_1_2(acceptData.getPlatform(), acceptData.getVersion())) {
            vo.setMoneyArrivalDesc("尽早确认收货可以促使资金尽早到账");
        // 本月预估
        maxDate = new Date(timeStamp);
        calendar = Calendar.getInstance();
        minDate = new Date(TimeUtil
                .convertToTimeTemp(calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1), "yyyy-M"));
        calendar.add(Calendar.MONTH, -1);
        vo.setMonthPredict(cratePredictVO(orderMoneyDailyCountService.query(uid, minDate, maxDate)));
        return vo;
    }
            minDate = new Date(TimeUtil.convertToTimeTemp(TimeUtil.getGernalTime(timeStamp, "yyyy-MM"), "yyyy-MM"));
            Calendar ca = Calendar.getInstance();
            ca.setTime(new Date(timeStamp));
            ca.add(Calendar.MONTH, 1);
            maxDate = new Date(
                    TimeUtil.convertToTimeTemp(TimeUtil.getGernalTime(ca.getTimeInMillis(), "yyyy-MM"), "yyyy-MM"));
            // 本月未到账
            BigDecimal monthUnRecievedMoney = hongBaoV2Service.getUnRecievedMoneyWithPreGetTime(uid, minDate, maxDate);
            vo.setMonthUnRecievedMoney(monthUnRecievedMoney);
    @RequestMapping(value = "getUserMoneyInfo")
    public void getUserMoneyInfo(AcceptData acceptData, Long uid, PrintWriter out) {
        if (uid == null || uid == 0) {
            out.print(JsonUtil.loadFalseResult(1, "用户未登录"));
            return;
        }
        UserInfo user = userInfoService.getUserById(uid);
            // 全部未到账
            minDate = new Date(0);
            maxDate = new Date(timeStamp);
            vo.setTotalUnRecievedMoney(hongBaoV2Service.getUnRecievedMoneyWithCreateTime(uid, minDate, maxDate));
        } else {
            vo.setMoneyArrivalDesc("订单已到账后提现时间和金额均不受限制");
            // 本月收货
            maxDate = new Date(timeStamp);
            calendar = Calendar.getInstance();
            minDate = new Date(TimeUtil
                    .convertToTimeTemp(calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1), "yyyy-M"));
            calendar.add(Calendar.MONTH, -1);
            vo.setMonthSettleMoney(hongBaoV2CountService.sumMoneyBySettleTimeAndUid(uid, minDate, maxDate));
        MoneyStatisticVO vo = new MoneyStatisticVO();
        vo.setLink(configService.getValue(ConfigKeyEnum.autoExtractHelpUrl.getKey(),acceptData.getSystem()));
        vo.setBalanceMoney(user.getMyHongBao());
        // 获取提现中的信息
        BigDecimal extractingMoney = extractService.sumVerifyingMoney(uid);
        if (extractingMoney.compareTo(new BigDecimal(0)) > 0)
            vo.setExtractingMoneyInfo("提现中:¥" + extractingMoney.setScale(2, RoundingMode.HALF_UP));
        Gson gson = getGson();
        out.print(JsonUtil.loadTrueResult(gson.toJson(vo)));
    }
            // 上月收货
            maxDate = new Date(TimeUtil
                    .convertToTimeTemp(calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1), "yyyy-M"));
            calendar.add(Calendar.MONTH, -1);
            minDate = new Date(TimeUtil
                    .convertToTimeTemp(calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1), "yyyy-M"));
            vo.setLastMonthSettleMoney(hongBaoV2CountService.sumMoneyBySettleTimeAndUid(uid, minDate, maxDate));
        }
    private MoneyPredictVO cratePredictVO(List<OrderMoneyDailyCount> list) {
        MoneyPredictVO predictVO = new MoneyPredictVO();
        predictVO.setMineNum(0);
        predictVO.setTeamNum(0);
        predictVO.setTotalNum(0);
        predictVO.setMineMoney(BigDecimal.valueOf(0));
        predictVO.setTeamMoney(BigDecimal.valueOf(0));
        BigDecimal hundred = BigDecimal.valueOf(100);
        if (list != null && list.size() > 0) {
            for (OrderMoneyDailyCount dailyCount : list) {
                if (dailyCount.getOrderNum() != null)
                    predictVO.setMineNum(predictVO.getMineNum() + dailyCount.getOrderNum());
                if (dailyCount.getOrderNumTeam() != null)
                    predictVO.setTeamNum(predictVO.getTeamNum() + dailyCount.getOrderNumTeam());
        // 待确认收货(180天内)
        vo.setNotSettleMoney(hongBaoV2CountService.sumMoneyByANotSettleAndUid(uid));
                if (dailyCount.getTeamDividentsOrderNum() != null)
                    predictVO.setTotalNum(predictVO.getTotalNum() + dailyCount.getTeamDividentsOrderNum());
        // 今日预估
        calendar.add(Calendar.DAY_OF_YEAR, -1);
        minDate = new Date(TimeUtil.convertDateToTemp(TimeUtil.getGernalTime(timeStamp)));
        vo.setTodayPredict(cratePredictVO(orderMoneyDailyCountService.query(uid, minDate, null)));
                if (dailyCount.getIncome() != null)
                    predictVO.setMineMoney(predictVO.getMineMoney()
                            .add(MoneyBigDecimalUtil.div(BigDecimal.valueOf(dailyCount.getIncome()), hundred)));
                if (dailyCount.getIncomeTeam() != null)
                    predictVO.setTeamMoney(predictVO.getTeamMoney()
                            .add(MoneyBigDecimalUtil.div(BigDecimal.valueOf(dailyCount.getIncomeTeam()), hundred)));
            }
        }
        predictVO.setTotalNum(predictVO.getTotalNum());
        predictVO.setTotalMoney(predictVO.getMineMoney().add(predictVO.getTeamMoney()));
        return predictVO;
    }
        // 本月预估
        maxDate = new Date(timeStamp);
        calendar = Calendar.getInstance();
        minDate = new Date(TimeUtil
                .convertToTimeTemp(calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1), "yyyy-M"));
        calendar.add(Calendar.MONTH, -1);
        vo.setMonthPredict(cratePredictVO(orderMoneyDailyCountService.query(uid, minDate, maxDate)));
        return vo;
    }
    /**
     * 提现成功记录
     * @param acceptData
     * @param page
     * @param uid
     * @param out
     */
    @RequestMapping(value = "getExtractRecord")
    public void getExtractRecord(AcceptData acceptData, Integer page, Long uid, PrintWriter out) {
        if (uid == null || uid == 0) {
            out.print(JsonUtil.loadFalseResult(1, "用户未登录"));
            return;
        }
    @RequestMapping(value = "getUserMoneyInfo")
    public void getUserMoneyInfo(AcceptData acceptData, Long uid, PrintWriter out) {
        if (uid == null || uid == 0) {
            out.print(JsonUtil.loadFalseResult(1, "用户未登录"));
            return;
        }
        UserInfo user = userInfoService.getUserById(uid);
        long count = 0;
        MoneyStatisticVO vo = new MoneyStatisticVO();
        vo.setLink(configService.getValue(ConfigKeyEnum.autoExtractHelpUrl.getKey(), acceptData.getSystem()));
        vo.setBalanceMoney(user.getMyHongBao());
        // 获取提现中的信息
        BigDecimal extractingMoney = extractService.sumVerifyingMoney(uid);
        if (extractingMoney.compareTo(new BigDecimal(0)) > 0)
            vo.setExtractingMoneyInfo("提现中:¥" + extractingMoney.setScale(2, RoundingMode.HALF_UP));
        Gson gson = getGson();
        out.print(JsonUtil.loadTrueResult(gson.toJson(vo)));
    }
        List<Extract> list = null;
        String redisContent = previewInfoService.getRedisContent(uid, PreviewEnum.extractRecord);
        if (!StringUtil.isNullOrEmpty(redisContent)) {
            Gson gson = new Gson();
            list = gson.fromJson(redisContent, new TypeToken<ArrayList<Extract>>() {
            }.getType());
        }
    private MoneyPredictVO cratePredictVO(List<OrderMoneyDailyCount> list) {
        MoneyPredictVO predictVO = new MoneyPredictVO();
        predictVO.setMineNum(0);
        predictVO.setTeamNum(0);
        predictVO.setTotalNum(0);
        predictVO.setMineMoney(BigDecimal.valueOf(0));
        predictVO.setTeamMoney(BigDecimal.valueOf(0));
        BigDecimal hundred = BigDecimal.valueOf(100);
        if (list != null && list.size() > 0) {
            for (OrderMoneyDailyCount dailyCount : list) {
                if (dailyCount.getOrderNum() != null)
                    predictVO.setMineNum(predictVO.getMineNum() + dailyCount.getOrderNum());
                if (dailyCount.getOrderNumTeam() != null)
                    predictVO.setTeamNum(predictVO.getTeamNum() + dailyCount.getOrderNumTeam());
        if (list != null && list.size() > 0) {// 有预览数据
            count=list.size();
        } else {// 无预览数据
            list = extractService.getExtractSucceedRecord(page, Constant.PAGE_SIZE, uid);
            count = extractService.countExtractSucceedRecord(uid);
        }
                if (dailyCount.getTeamDividentsOrderNum() != null)
                    predictVO.setTotalNum(predictVO.getTotalNum() + dailyCount.getTeamDividentsOrderNum());
        // 查询真实
        if (list == null)
            list = new ArrayList<>();
                if (dailyCount.getIncome() != null)
                    predictVO.setMineMoney(predictVO.getMineMoney()
                            .add(MoneyBigDecimalUtil.div(BigDecimal.valueOf(dailyCount.getIncome()), hundred)));
                if (dailyCount.getIncomeTeam() != null)
                    predictVO.setTeamMoney(predictVO.getTeamMoney()
                            .add(MoneyBigDecimalUtil.div(BigDecimal.valueOf(dailyCount.getIncomeTeam()), hundred)));
            }
        }
        predictVO.setTotalNum(predictVO.getTotalNum());
        predictVO.setTotalMoney(predictVO.getMineMoney().add(predictVO.getTeamMoney()));
        return predictVO;
    }
        JSONArray JSONArray = new JSONArray();
        for (Extract extract : list) {
            Date receiveTime = extract.getReceiveTime();
            if (receiveTime == null) {
                receiveTime = new Date(extract.getExtractTime());
            }
            String account = "支付宝:" + UserUtil.filterAlipayAccount(extract.getAccount());
            account = account + "-姓名:" + UserUtil.filterAlipayName(extract.getName());
    /**
     * 提现成功记录
     *
     * @param acceptData
     * @param page
     * @param uid
     * @param out
     */
    @RequestMapping(value = "getExtractRecord")
    public void getExtractRecord(AcceptData acceptData, Integer page, Long uid, PrintWriter out) {
        if (uid == null || uid == 0) {
            out.print(JsonUtil.loadFalseResult(1, "用户未登录"));
            return;
        }
            JSONObject object = new JSONObject();
            object.put("title", "你于" + TimeUtil.formatDate(receiveTime) + "提现成功");
            object.put("account", account);
            object.put("money", "¥" + extract.getMoney().setScale(2).toString());
            JSONArray.add(object);
        }
        long count = 0;
        JSONObject json = new JSONObject();
        json.put("count", count);
        json.put("list", JSONArray);
        out.print(JsonUtil.loadTrueResult(json));
    }
        List<Extract> list = null;
        String redisContent = previewInfoService.getRedisContent(uid, PreviewEnum.extractRecord);
        if (!StringUtil.isNullOrEmpty(redisContent)) {
            Gson gson = new Gson();
            list = gson.fromJson(redisContent, new TypeToken<ArrayList<Extract>>() {
            }.getType());
        }
    /**
     * 历史详情
     *
     * @param acceptData
     * @param uid
     * @param datetype   1-天 - 2月
     * @param out
     */
    @RequestMapping(value = "getHistoryDetail")
    public void getHistoryDetail(AcceptData acceptData, Long uid, String date, Integer datetype, PrintWriter out) {
        if (uid == null || uid == 0) {
            out.print(JsonUtil.loadFalseResult(1, "用户未登录"));
            return;
        }
        if (list != null && list.size() > 0) {// 有预览数据
            count = list.size();
        } else {// 无预览数据
            list = extractService.getExtractSucceedRecord(page, Constant.PAGE_SIZE, uid);
            count = extractService.countExtractSucceedRecord(uid);
        }
        if (StringUtil.isNullOrEmpty(date) || datetype == null) {
            out.print(JsonUtil.loadFalseResult(1, "参数不完整"));
            return;
        }
        // 查询真实
        if (list == null)
            list = new ArrayList<>();
        try {
            Date minDay = new Date();
            Date maxDay = new Date();
            BigDecimal zero = new BigDecimal(0);
            List<OrderMoneyDailyCount> listDailyCount = null;
            List<MoneyPredictVO> list = new ArrayList<>();
            SimpleDateFormat formatMonth = new SimpleDateFormat("yyyy年MM月");
            SimpleDateFormat formatDay = new SimpleDateFormat("yyyy年MM月dd日");
            if (datetype == 1) {
                // 后退7个月
                int countNum = 7;
                Date day = TimeUtil.parseYYYYMMDD(date);
                for (int i = 0; i < countNum; i++) {
                    MoneyPredictVO predictVO = new MoneyPredictVO(zero, 0, zero, 0);
                    if (i == 0) {
                        predictVO.setCountDate(formatDay.format(day));
                    } else {
                        predictVO.setCountDate(formatDay.format(DateUtil.reduceDay(i, day)));
                    }
                    list.add(predictVO);
        JSONArray JSONArray = new JSONArray();
        for (Extract extract : list) {
            Date receiveTime = extract.getReceiveTime();
            if (receiveTime == null) {
                receiveTime = new Date(extract.getExtractTime());
            }
            String account = "支付宝:" + UserUtil.filterAlipayAccount(extract.getAccount());
            account = account + "-姓名:" + UserUtil.filterAlipayName(extract.getName());
                    if (i == countNum - 1) {
                        minDay = DateUtil.reduceDay(i, day);
                    }
                }
                maxDay = TimeUtil.parseYYYYMMDD_HHMMSS(date + " 23:59:59");
                listDailyCount = orderMoneyDailyCountService.sumGroupByCountDay(uid, minDay, maxDay);
            } else if (datetype == 2) {
                // 后退3个月
                int countNum = 3;
                Date day = TimeUtil.parseYYYYMMDD(DateUtil.getFirstDayOfMonth(date));
                for (int i = 0; i < countNum; i++) {
                    MoneyPredictVO predictVO = new MoneyPredictVO(zero, 0, zero, 0);
                    if (i == 0) {
                        predictVO.setCountDate(formatMonth.format(day));
                    } else {
                        predictVO.setCountDate(formatMonth.format(DateUtil.reduceMonth(day, i)));
                    }
                    list.add(predictVO);
            JSONObject object = new JSONObject();
            object.put("title", "你于" + TimeUtil.formatDate(receiveTime) + "提现成功");
            object.put("account", account);
            object.put("money", "¥" + extract.getMoney().setScale(2).toString());
            JSONArray.add(object);
        }
                    if (i == countNum - 1) {
                        minDay = DateUtil.reduceMonth(day, i);
                    }
                }
                maxDay = TimeUtil.parseYYYYMMDD_HHMMSS(DateUtil.getLastDayOfMonth(date) + " 23:59:59");
                listDailyCount = orderMoneyDailyCountService.sumGroupByYearMonth(uid, minDay, maxDay);
            }
        JSONObject json = new JSONObject();
        json.put("count", count);
        json.put("list", JSONArray);
        out.print(JsonUtil.loadTrueResult(json));
    }
            BigDecimal hundred = BigDecimal.valueOf(100);
            for (MoneyPredictVO predictVO : list) {
                String countDate = predictVO.getCountDate();
    /**
     * 历史详情
     *
     * @param acceptData
     * @param uid
     * @param datetype   1-天 - 2月
     * @param out
     */
    @RequestMapping(value = "getHistoryDetail")
    public void getHistoryDetail(AcceptData acceptData, Long uid, String date, Integer datetype, PrintWriter out) {
        if (uid == null || uid == 0) {
            out.print(JsonUtil.loadFalseResult(1, "用户未登录"));
            return;
        }
                if (listDailyCount != null && listDailyCount.size() > 0) {
                    for (OrderMoneyDailyCount dailyCount : listDailyCount) {
                        Date countDay = dailyCount.getCountDay();
                        if (datetype == 1 && countDay != null && countDate.equals(formatDay.format(countDay))) {
                            predictVO.setMineNum(dailyCount.getOrderNum());
                            predictVO.setMineMoney(
                                    MoneyBigDecimalUtil.div(BigDecimal.valueOf(dailyCount.getIncome()), hundred));
                            predictVO.setTeamNum(dailyCount.getOrderNumTeam());
                            predictVO.setTeamMoney(
                                    MoneyBigDecimalUtil.div(BigDecimal.valueOf(dailyCount.getIncomeTeam()), hundred));
                            break;
                        }
        if (StringUtil.isNullOrEmpty(date) || datetype == null) {
            out.print(JsonUtil.loadFalseResult(1, "参数不完整"));
            return;
        }
                        String yearMonth = dailyCount.getYearMonth();
                        if (datetype == 2 && !StringUtil.isNullOrEmpty(yearMonth) && countDate.equals(
                                formatMonth.format(TimeUtil.parseYYYYMMDD(DateUtil.getFirstDayOfMonth(yearMonth))))) {
                            predictVO.setMineNum(dailyCount.getOrderNum());
                            predictVO.setMineMoney(
                                    MoneyBigDecimalUtil.div(BigDecimal.valueOf(dailyCount.getIncome()), hundred));
                            predictVO.setTeamNum(dailyCount.getOrderNumTeam());
                            predictVO.setTeamMoney(
                                    MoneyBigDecimalUtil.div(BigDecimal.valueOf(dailyCount.getIncomeTeam()), hundred));
                            break;
                        }
                    }
                }
        try {
            Date minDay = new Date();
            Date maxDay = new Date();
            BigDecimal zero = new BigDecimal(0);
            List<OrderMoneyDailyCount> listDailyCount = null;
            List<MoneyPredictVO> list = new ArrayList<>();
            SimpleDateFormat formatMonth = new SimpleDateFormat("yyyy年MM月");
            SimpleDateFormat formatDay = new SimpleDateFormat("yyyy年MM月dd日");
            if (datetype == 1) {
                // 后退7个月
                int countNum = 7;
                Date day = TimeUtil.parseYYYYMMDD(date);
                for (int i = 0; i < countNum; i++) {
                    MoneyPredictVO predictVO = new MoneyPredictVO(zero, 0, zero, 0);
                    if (i == 0) {
                        predictVO.setCountDate(formatDay.format(day));
                    } else {
                        predictVO.setCountDate(formatDay.format(DateUtil.reduceDay(i, day)));
                    }
                    list.add(predictVO);
                predictVO.setTotalNum(predictVO.getTeamNum() + predictVO.getMineNum());
                predictVO.setTotalMoney(predictVO.getMineMoney().add(predictVO.getTeamMoney()));
            }
                    if (i == countNum - 1) {
                        minDay = DateUtil.reduceDay(i, day);
                    }
                }
                maxDay = TimeUtil.parseYYYYMMDD_HHMMSS(date + " 23:59:59");
                listDailyCount = orderMoneyDailyCountService.sumGroupByCountDay(uid, minDay, maxDay);
            } else if (datetype == 2) {
                // 后退3个月
                int countNum = 3;
                Date day = TimeUtil.parseYYYYMMDD(DateUtil.getFirstDayOfMonth(date));
                for (int i = 0; i < countNum; i++) {
                    MoneyPredictVO predictVO = new MoneyPredictVO(zero, 0, zero, 0);
                    if (i == 0) {
                        predictVO.setCountDate(formatMonth.format(day));
                    } else {
                        predictVO.setCountDate(formatMonth.format(DateUtil.reduceMonth(day, i)));
                    }
                    list.add(predictVO);
            Gson gson = getGson();
                    if (i == countNum - 1) {
                        minDay = DateUtil.reduceMonth(day, i);
                    }
                }
                maxDay = TimeUtil.parseYYYYMMDD_HHMMSS(DateUtil.getLastDayOfMonth(date) + " 23:59:59");
                listDailyCount = orderMoneyDailyCountService.sumGroupByYearMonth(uid, minDay, maxDay);
            }
            JSONObject object = new JSONObject();
            object.put("count", list.size());
            object.put("list", gson.toJson(list));
            out.print(JsonUtil.loadTrueResult(object));
        } catch (ParseException e) {
            out.print(JsonUtil.loadFalseResult(1, "查询失败"));
            e.printStackTrace();
            LogHelper.errorDetailInfo(e);
        }
    }
            BigDecimal hundred = BigDecimal.valueOf(100);
            for (MoneyPredictVO predictVO : list) {
                String countDate = predictVO.getCountDate();
    /**
     * 收益详情
     *
     * @param acceptData
     * @param uid
     * @param datetype
     * @param type
     * @param out
     */
    @RequestMapping(value = "getIncomeDetail")
    public void getIncomeDetail(AcceptData acceptData, Long uid, String date, Integer datetype, Integer type,
            PrintWriter out) {
        if (uid == null || uid == 0) {
            out.print(JsonUtil.loadFalseResult(1, "用户未登录"));
            return;
        }
                if (listDailyCount != null && listDailyCount.size() > 0) {
                    for (OrderMoneyDailyCount dailyCount : listDailyCount) {
                        Date countDay = dailyCount.getCountDay();
                        if (datetype == 1 && countDay != null && countDate.equals(formatDay.format(countDay))) {
                            predictVO.setMineNum(dailyCount.getOrderNum());
                            predictVO.setMineMoney(
                                    MoneyBigDecimalUtil.div(BigDecimal.valueOf(dailyCount.getIncome()), hundred));
                            predictVO.setTeamNum(dailyCount.getOrderNumTeam());
                            predictVO.setTeamMoney(
                                    MoneyBigDecimalUtil.div(BigDecimal.valueOf(dailyCount.getIncomeTeam()), hundred));
                            break;
                        }
                        String yearMonth = dailyCount.getYearMonth();
                        if (datetype == 2 && !StringUtil.isNullOrEmpty(yearMonth) && countDate.equals(
                                formatMonth.format(TimeUtil.parseYYYYMMDD(DateUtil.getFirstDayOfMonth(yearMonth))))) {
                            predictVO.setMineNum(dailyCount.getOrderNum());
                            predictVO.setMineMoney(
                                    MoneyBigDecimalUtil.div(BigDecimal.valueOf(dailyCount.getIncome()), hundred));
                            predictVO.setTeamNum(dailyCount.getOrderNumTeam());
                            predictVO.setTeamMoney(
                                    MoneyBigDecimalUtil.div(BigDecimal.valueOf(dailyCount.getIncomeTeam()), hundred));
                            break;
                        }
                    }
                }
                predictVO.setTotalNum(predictVO.getTeamNum() + predictVO.getMineNum());
                predictVO.setTotalMoney(predictVO.getMineMoney().add(predictVO.getTeamMoney()));
            }
            Gson gson = getGson();
            JSONObject object = new JSONObject();
            object.put("count", list.size());
            object.put("list", gson.toJson(list));
            out.print(JsonUtil.loadTrueResult(object));
        } catch (ParseException e) {
            out.print(JsonUtil.loadFalseResult(1, "查询失败"));
            e.printStackTrace();
            LogHelper.errorDetailInfo(e);
        }
    }
    /**
     * 收益详情
     *
     * @param acceptData
     * @param uid
     * @param datetype
     * @param type
     * @param out
     */
    @RequestMapping(value = "getIncomeDetail")
    public void getIncomeDetail(AcceptData acceptData, Long uid, String date, Integer datetype, Integer type,
                                PrintWriter out) {
        if (uid == null || uid == 0) {
            out.print(JsonUtil.loadFalseResult(1, "用户未登录"));
            return;
        }
        if (StringUtil.isNullOrEmpty(date) || datetype == null || type == null) {
            out.print(JsonUtil.loadFalseResult(1, "参数不完整"));
            return;
        }
        if (StringUtil.isNullOrEmpty(date) || datetype == null || type == null) {
            out.print(JsonUtil.loadFalseResult(1, "参数不完整"));
            return;
        }
        Date minDay = new Date();
        Date maxDay = new Date();
        if (datetype == 1) {
            minDay = TimeUtil.parseYYYYMMDD(date);
            maxDay = TimeUtil.parseYYYYMMDD_HHMMSS(date + " 23:59:59");
        } else if (datetype == 2) {
            String firstDay = DateUtil.getFirstDayOfMonth(date);
            String lastDay = DateUtil.getLastDayOfMonth(date);
            minDay = TimeUtil.parseYYYYMMDD(firstDay);
            maxDay = TimeUtil.parseYYYYMMDD_HHMMSS(lastDay + " 23:59:59");
        }
        Date minDay = new Date();
        Date maxDay = new Date();
        if (datetype == 1) {
            minDay = TimeUtil.parseYYYYMMDD(date);
            maxDay = TimeUtil.parseYYYYMMDD_HHMMSS(date + " 23:59:59");
        } else if (datetype == 2) {
            String firstDay = DateUtil.getFirstDayOfMonth(date);
            String lastDay = DateUtil.getLastDayOfMonth(date);
            minDay = TimeUtil.parseYYYYMMDD(firstDay);
            maxDay = TimeUtil.parseYYYYMMDD_HHMMSS(lastDay + " 23:59:59");
        }
        List<OrderMoneyDailyCount> listDailyCount = null;
        if (type == 1) {
            listDailyCount = orderMoneyDailyCountService.sumGroupBySourceType(uid, minDay, maxDay);
        } else if (type == 2) {
            listDailyCount = orderMoneyDailyCountService.sumTeamGroupBySourceType(uid, minDay, maxDay);
        }
        List<OrderMoneyDailyCount> listDailyCount = null;
        if (type == 1) {
            listDailyCount = orderMoneyDailyCountService.sumGroupBySourceType(uid, minDay, maxDay);
        } else if (type == 2) {
            listDailyCount = orderMoneyDailyCountService.sumTeamGroupBySourceType(uid, minDay, maxDay);
        }
        BigDecimal zero = new BigDecimal(0);
        List<IncomeDetailVO> list = new ArrayList<>();
        BigDecimal zero = new BigDecimal(0);
        List<IncomeDetailVO> list = new ArrayList<>();
        BigDecimal hundred = BigDecimal.valueOf(100);
        SourceTypeEnum[] arrayEnun = SourceTypeEnum.values();
        for (int m = 0; m < arrayEnun.length; m++) {
            SourceTypeEnum typeEnum = arrayEnun[m];
            IncomeDetailVO detail = new IncomeDetailVO(typeEnum.getIcon(), 0, zero);
            if (listDailyCount != null && listDailyCount.size() > 0) {
                for (OrderMoneyDailyCount dailyCount : listDailyCount) {
                    if (dailyCount.getSourceType() == typeEnum) {
                        detail.setNum(detail.getNum() + dailyCount.getOrderNum());
                        detail.setMoney(detail.getMoney()
                                .add(MoneyBigDecimalUtil.div(BigDecimal.valueOf(dailyCount.getIncome()), hundred)));
                    }
                }
            }
            list.add(detail);
        }
        BigDecimal hundred = BigDecimal.valueOf(100);
        SourceTypeEnum[] arrayEnun = SourceTypeEnum.values();
        for (int m = 0; m < arrayEnun.length; m++) {
            SourceTypeEnum typeEnum = arrayEnun[m];
            IncomeDetailVO detail = new IncomeDetailVO(typeEnum.getIcon(), 0, zero);
            if (listDailyCount != null && listDailyCount.size() > 0) {
                for (OrderMoneyDailyCount dailyCount : listDailyCount) {
                    if (dailyCount.getSourceType() == typeEnum) {
                        detail.setNum(detail.getNum() + dailyCount.getOrderNum());
                        detail.setMoney(detail.getMoney()
                                .add(MoneyBigDecimalUtil.div(BigDecimal.valueOf(dailyCount.getIncome()), hundred)));
                    }
                }
            }
            list.add(detail);
        }
        Gson gson = getGson();
        Gson gson = getGson();
        JSONObject object = new JSONObject();
        object.put("count", list.size());
        object.put("list", gson.toJson(list));
        out.print(JsonUtil.loadTrueResult(object));
    }
        JSONObject object = new JSONObject();
        object.put("count", list.size());
        object.put("list", gson.toJson(list));
        out.print(JsonUtil.loadTrueResult(object));
    }
    /**
     * 团队分红
     * @param acceptData
     * @param uid
     * @param out
     */
    @RequestMapping(value = "getTeamDividendStatistic")
    public void getTeamDividendStatistic(String callback, AcceptData acceptData, Long uid, PrintWriter out) {
        if (uid == null || uid == 0) {
            JsonUtil.printMode(out, callback, JsonUtil.loadFalseResult("用户未登录"));
            return;
        }
    /**
     * 团队分红
     *
     * @param acceptData
     * @param uid
     * @param out
     */
    @RequestMapping(value = "getTeamDividendStatistic")
    public void getTeamDividendStatistic(String callback, AcceptData acceptData, Long uid, PrintWriter out) {
        if (uid == null || uid == 0) {
            JsonUtil.printMode(out, callback, JsonUtil.loadFalseResult("用户未登录"));
            return;
        }
        Date minDate = null;
        Date maxDate = null;
        long timeStamp = System.currentTimeMillis();
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(timeStamp);
        // 今日预估
        calendar.add(Calendar.DAY_OF_YEAR, -1);
        minDate = new Date(TimeUtil.convertDateToTemp(TimeUtil.getGernalTime(timeStamp)));
        TeamPredictVO todayVO = crateTeamPredictVO(orderMoneyDailyCountService.query(uid, minDate, null));
        Date minDate = null;
        Date maxDate = null;
        long timeStamp = System.currentTimeMillis();
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(timeStamp);
        // 今日预估
        calendar.add(Calendar.DAY_OF_YEAR, -1);
        minDate = new Date(TimeUtil.convertDateToTemp(TimeUtil.getGernalTime(timeStamp)));
        TeamPredictVO todayVO = crateTeamPredictVO(orderMoneyDailyCountService.query(uid, minDate, null));
        // 本月预估
        maxDate = new Date(timeStamp);
        calendar = Calendar.getInstance();
        minDate = new Date(TimeUtil
                .convertToTimeTemp(calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1), "yyyy-M"));
        calendar.add(Calendar.MONTH, -1);
        TeamPredictVO monthVO = crateTeamPredictVO(orderMoneyDailyCountService.query(uid, minDate, maxDate));
        // 本月预估
        maxDate = new Date(timeStamp);
        calendar = Calendar.getInstance();
        minDate = new Date(TimeUtil
                .convertToTimeTemp(calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1), "yyyy-M"));
        calendar.add(Calendar.MONTH, -1);
        TeamPredictVO monthVO = crateTeamPredictVO(orderMoneyDailyCountService.query(uid, minDate, maxDate));
        // 统计已到账分红、补贴
        BigDecimal subsidy = teamEincomeRecordService.sumRecieveByType(uid, TeamEincomeRecord.TYPE_TEAM_SUBSIDY);
        BigDecimal reward = teamEincomeRecordService.sumRecieveByType(uid, TeamEincomeRecord.TYPE_TEAM_DIVIDENTS);
        // 统计已到账分红、补贴
        BigDecimal subsidy = teamEincomeRecordService.sumRecieveByType(uid, TeamEincomeRecord.TYPE_TEAM_SUBSIDY);
        BigDecimal reward = teamEincomeRecordService.sumRecieveByType(uid, TeamEincomeRecord.TYPE_TEAM_DIVIDENTS);
        Gson gson = getGson();
        JSONObject object = new JSONObject();
        object.put("total", subsidy.add(reward).setScale(2).toString());
        object.put("reward", reward.setScale(2).toString());
        object.put("subsidy", subsidy.setScale(2).toString());
        object.put("today", gson.toJson(todayVO));
        object.put("month", gson.toJson(monthVO));
        JsonUtil.printMode(out, callback, JsonUtil.loadTrueResult(object));
    }
        Gson gson = getGson();
        JSONObject object = new JSONObject();
        object.put("total", subsidy.add(reward).setScale(2).toString());
        object.put("reward", reward.setScale(2).toString());
        object.put("subsidy", subsidy.setScale(2).toString());
        object.put("today", gson.toJson(todayVO));
        object.put("month", gson.toJson(monthVO));
        JsonUtil.printMode(out, callback, JsonUtil.loadTrueResult(object));
    }
    private TeamPredictVO crateTeamPredictVO(List<OrderMoneyDailyCount> list) {
        TeamPredictVO predictVO = new TeamPredictVO(BigDecimal.ZERO, 0, BigDecimal.ZERO, 0, 0);
        if (list != null && list.size() > 0) {
            BigDecimal hundred = BigDecimal.valueOf(100);
            for (OrderMoneyDailyCount dailyCount : list) {
                if (dailyCount.getTeamRewardNum() != null)
                    predictVO.setRewardNum(predictVO.getRewardNum() + dailyCount.getTeamRewardNum());
                if (dailyCount.getTeamSubsidyNum() != null)
                    predictVO.setSubsidyNum(predictVO.getSubsidyNum() + dailyCount.getTeamSubsidyNum());
                if (dailyCount.getTeamReward() != null)
                    predictVO.setReward(predictVO.getReward()
                            .add(MoneyBigDecimalUtil.div(BigDecimal.valueOf(dailyCount.getTeamReward()), hundred)));
                if (dailyCount.getTeamSubsidy() != null)
                    predictVO.setSubsidy(predictVO.getSubsidy()
                            .add(MoneyBigDecimalUtil.div(BigDecimal.valueOf(dailyCount.getTeamSubsidy()), hundred)));
    private TeamPredictVO crateTeamPredictVO(List<OrderMoneyDailyCount> list) {
        TeamPredictVO predictVO = new TeamPredictVO(BigDecimal.ZERO, 0, BigDecimal.ZERO, 0, 0);
        if (list != null && list.size() > 0) {
            BigDecimal hundred = BigDecimal.valueOf(100);
            for (OrderMoneyDailyCount dailyCount : list) {
                if (dailyCount.getTeamRewardNum() != null)
                    predictVO.setRewardNum(predictVO.getRewardNum() + dailyCount.getTeamRewardNum());
                if (dailyCount.getTeamSubsidyNum() != null)
                    predictVO.setSubsidyNum(predictVO.getSubsidyNum() + dailyCount.getTeamSubsidyNum());
                if (dailyCount.getTeamReward() != null)
                    predictVO.setReward(predictVO.getReward()
                            .add(MoneyBigDecimalUtil.div(BigDecimal.valueOf(dailyCount.getTeamReward()), hundred)));
                if (dailyCount.getTeamSubsidy() != null)
                    predictVO.setSubsidy(predictVO.getSubsidy()
                            .add(MoneyBigDecimalUtil.div(BigDecimal.valueOf(dailyCount.getTeamSubsidy()), hundred)));
                if (dailyCount.getTeamDividentsOrderNum() != null)
                    predictVO.setTotalNum(predictVO.getTotalNum() + dailyCount.getTeamDividentsOrderNum());
                if (dailyCount.getTeamDividentsOrderNum() != null)
                    predictVO.setTotalNum(predictVO.getTotalNum() + dailyCount.getTeamDividentsOrderNum());
            }
        }
        predictVO.setTotalNum(predictVO.getTotalNum());
        predictVO.setTotalMoney(predictVO.getReward().add(predictVO.getSubsidy()));
        return predictVO;
    }
            }
        }
        predictVO.setTotalNum(predictVO.getTotalNum());
        predictVO.setTotalMoney(predictVO.getReward().add(predictVO.getSubsidy()));
        return predictVO;
    }
    /**
     * 历史详情
     *
     * @param acceptData
     * @param uid
     * @param datetype   1-天 - 2月
     * @param out
     */
    @RequestMapping(value = "getTeamDividendHistory")
    public void getTeamDividendHistory(String callback, AcceptData acceptData, Long uid, String date, Integer datetype,
            PrintWriter out) {
        if (uid == null || uid == 0) {
            JsonUtil.printMode(out, callback, JsonUtil.loadFalseResult("用户未登录"));
            return;
        }
    /**
     * 历史详情
     *
     * @param acceptData
     * @param uid
     * @param datetype   1-天 - 2月
     * @param out
     */
    @RequestMapping(value = "getTeamDividendHistory")
    public void getTeamDividendHistory(String callback, AcceptData acceptData, Long uid, String date, Integer datetype,
                                       PrintWriter out) {
        if (uid == null || uid == 0) {
            JsonUtil.printMode(out, callback, JsonUtil.loadFalseResult("用户未登录"));
            return;
        }
        if (StringUtil.isNullOrEmpty(date) || datetype == null) {
            JsonUtil.printMode(out, callback, JsonUtil.loadFalseResult("参数不完整"));
            return;
        }
        if (StringUtil.isNullOrEmpty(date) || datetype == null) {
            JsonUtil.printMode(out, callback, JsonUtil.loadFalseResult("参数不完整"));
            return;
        }
        try {
            Date minDay = new Date();
            Date maxDay = new Date();
            BigDecimal zero = new BigDecimal(0);
            List<OrderMoneyDailyCount> listDailyCount = null;
            List<TeamPredictVO> list = new ArrayList<>();
            SimpleDateFormat formatMonth = new SimpleDateFormat("yyyy年MM月");
            SimpleDateFormat formatDay = new SimpleDateFormat("yyyy年MM月dd日");
            if (datetype == 1) {
                // 后退7个月
                int countNum = 7;
                Date day = TimeUtil.parseYYYYMMDD(date);
                for (int i = 0; i < countNum; i++) {
                    TeamPredictVO predictVO = new TeamPredictVO(zero, 0, zero, 0, 0);
                    if (i == 0) {
                        predictVO.setCountDate(formatDay.format(day));
                    } else {
                        predictVO.setCountDate(formatDay.format(DateUtil.reduceDay(i, day)));
                    }
                    list.add(predictVO);
        try {
            Date minDay = new Date();
            Date maxDay = new Date();
            BigDecimal zero = new BigDecimal(0);
            List<OrderMoneyDailyCount> listDailyCount = null;
            List<TeamPredictVO> list = new ArrayList<>();
            SimpleDateFormat formatMonth = new SimpleDateFormat("yyyy年MM月");
            SimpleDateFormat formatDay = new SimpleDateFormat("yyyy年MM月dd日");
            if (datetype == 1) {
                // 后退7个月
                int countNum = 7;
                Date day = TimeUtil.parseYYYYMMDD(date);
                for (int i = 0; i < countNum; i++) {
                    TeamPredictVO predictVO = new TeamPredictVO(zero, 0, zero, 0, 0);
                    if (i == 0) {
                        predictVO.setCountDate(formatDay.format(day));
                    } else {
                        predictVO.setCountDate(formatDay.format(DateUtil.reduceDay(i, day)));
                    }
                    list.add(predictVO);
                    if (i == countNum - 1) {
                        minDay = DateUtil.reduceDay(i, day);
                    }
                }
                maxDay = TimeUtil.parseYYYYMMDD_HHMMSS(date + " 23:59:59");
                listDailyCount = orderMoneyDailyCountService.sumTeamGroupByCountDay(uid, minDay, maxDay);
            } else if (datetype == 2) {
                // 后退3个月
                int countNum = 3;
                Date day = TimeUtil.parseYYYYMMDD(DateUtil.getFirstDayOfMonth(date));
                for (int i = 0; i < countNum; i++) {
                    TeamPredictVO predictVO = new TeamPredictVO(zero, 0, zero, 0, 0);
                    if (i == 0) {
                        predictVO.setCountDate(formatMonth.format(day));
                    } else {
                        predictVO.setCountDate(formatMonth.format(DateUtil.reduceMonth(day, i)));
                    }
                    list.add(predictVO);
                    if (i == countNum - 1) {
                        minDay = DateUtil.reduceDay(i, day);
                    }
                }
                maxDay = TimeUtil.parseYYYYMMDD_HHMMSS(date + " 23:59:59");
                listDailyCount = orderMoneyDailyCountService.sumTeamGroupByCountDay(uid, minDay, maxDay);
            } else if (datetype == 2) {
                // 后退3个月
                int countNum = 3;
                Date day = TimeUtil.parseYYYYMMDD(DateUtil.getFirstDayOfMonth(date));
                for (int i = 0; i < countNum; i++) {
                    TeamPredictVO predictVO = new TeamPredictVO(zero, 0, zero, 0, 0);
                    if (i == 0) {
                        predictVO.setCountDate(formatMonth.format(day));
                    } else {
                        predictVO.setCountDate(formatMonth.format(DateUtil.reduceMonth(day, i)));
                    }
                    list.add(predictVO);
                    if (i == countNum - 1) {
                        minDay = DateUtil.reduceMonth(day, i);
                    }
                }
                maxDay = TimeUtil.parseYYYYMMDD_HHMMSS(DateUtil.getLastDayOfMonth(date) + " 23:59:59");
                listDailyCount = orderMoneyDailyCountService.sumTeamGroupByYearMonth(uid, minDay, maxDay);
            }
                    if (i == countNum - 1) {
                        minDay = DateUtil.reduceMonth(day, i);
                    }
                }
                maxDay = TimeUtil.parseYYYYMMDD_HHMMSS(DateUtil.getLastDayOfMonth(date) + " 23:59:59");
                listDailyCount = orderMoneyDailyCountService.sumTeamGroupByYearMonth(uid, minDay, maxDay);
            }
            BigDecimal hundred = BigDecimal.valueOf(100);
            for (TeamPredictVO predictVO : list) {
                String countDate = predictVO.getCountDate();
            BigDecimal hundred = BigDecimal.valueOf(100);
            for (TeamPredictVO predictVO : list) {
                String countDate = predictVO.getCountDate();
                if (listDailyCount != null && listDailyCount.size() > 0) {
                    for (OrderMoneyDailyCount dailyCount : listDailyCount) {
                        Date countDay = dailyCount.getCountDay();
                        if (datetype == 1 && countDay != null && countDate.equals(formatDay.format(countDay))) {
                            predictVO.setRewardNum(dailyCount.getTeamRewardNum());
                            predictVO.setReward(
                                    MoneyBigDecimalUtil.div(BigDecimal.valueOf(dailyCount.getTeamReward()), hundred));
                            predictVO.setSubsidyNum(dailyCount.getTeamSubsidyNum());
                            predictVO.setSubsidy(
                                    MoneyBigDecimalUtil.div(BigDecimal.valueOf(dailyCount.getTeamSubsidy()), hundred));
                            predictVO.setTotalNum(dailyCount.getTeamDividentsOrderNum());
                            break;
                        }
                if (listDailyCount != null && listDailyCount.size() > 0) {
                    for (OrderMoneyDailyCount dailyCount : listDailyCount) {
                        Date countDay = dailyCount.getCountDay();
                        if (datetype == 1 && countDay != null && countDate.equals(formatDay.format(countDay))) {
                            predictVO.setRewardNum(dailyCount.getTeamRewardNum());
                            predictVO.setReward(
                                    MoneyBigDecimalUtil.div(BigDecimal.valueOf(dailyCount.getTeamReward()), hundred));
                            predictVO.setSubsidyNum(dailyCount.getTeamSubsidyNum());
                            predictVO.setSubsidy(
                                    MoneyBigDecimalUtil.div(BigDecimal.valueOf(dailyCount.getTeamSubsidy()), hundred));
                            predictVO.setTotalNum(dailyCount.getTeamDividentsOrderNum());
                            break;
                        }
                        String yearMonth = dailyCount.getYearMonth();
                        if (datetype == 2 && !StringUtil.isNullOrEmpty(yearMonth) && countDate.equals(
                                formatMonth.format(TimeUtil.parseYYYYMMDD(DateUtil.getFirstDayOfMonth(yearMonth))))) {
                            predictVO.setRewardNum(dailyCount.getTeamRewardNum());
                            predictVO.setReward(
                                    MoneyBigDecimalUtil.div(BigDecimal.valueOf(dailyCount.getTeamReward()), hundred));
                            predictVO.setSubsidyNum(dailyCount.getTeamSubsidyNum());
                            predictVO.setSubsidy(
                                    MoneyBigDecimalUtil.div(BigDecimal.valueOf(dailyCount.getTeamSubsidy()), hundred));
                        String yearMonth = dailyCount.getYearMonth();
                        if (datetype == 2 && !StringUtil.isNullOrEmpty(yearMonth) && countDate.equals(
                                formatMonth.format(TimeUtil.parseYYYYMMDD(DateUtil.getFirstDayOfMonth(yearMonth))))) {
                            predictVO.setRewardNum(dailyCount.getTeamRewardNum());
                            predictVO.setReward(
                                    MoneyBigDecimalUtil.div(BigDecimal.valueOf(dailyCount.getTeamReward()), hundred));
                            predictVO.setSubsidyNum(dailyCount.getTeamSubsidyNum());
                            predictVO.setSubsidy(
                                    MoneyBigDecimalUtil.div(BigDecimal.valueOf(dailyCount.getTeamSubsidy()), hundred));
                            predictVO.setTotalNum(dailyCount.getTeamDividentsOrderNum());
                            break;
                        }
                    }
                }
                            predictVO.setTotalNum(dailyCount.getTeamDividentsOrderNum());
                            break;
                        }
                    }
                }
                predictVO.setTotalNum(predictVO.getTotalNum());
                predictVO.setTotalMoney(predictVO.getReward().add(predictVO.getSubsidy()));
            }
                predictVO.setTotalNum(predictVO.getTotalNum());
                predictVO.setTotalMoney(predictVO.getReward().add(predictVO.getSubsidy()));
            }
            Gson gson = getGson();
            Gson gson = getGson();
            JSONObject object = new JSONObject();
            object.put("count", list.size());
            object.put("list", gson.toJson(list));
            JsonUtil.printMode(out, callback, JsonUtil.loadTrueResult(object));
        } catch (ParseException e) {
            JsonUtil.printMode(out, callback, JsonUtil.loadFalseResult("统计失败"));
            e.printStackTrace();
            LogHelper.errorDetailInfo(e);
        }
    }
            JSONObject object = new JSONObject();
            object.put("count", list.size());
            object.put("list", gson.toJson(list));
            JsonUtil.printMode(out, callback, JsonUtil.loadTrueResult(object));
        } catch (ParseException e) {
            JsonUtil.printMode(out, callback, JsonUtil.loadFalseResult("统计失败"));
            e.printStackTrace();
            LogHelper.errorDetailInfo(e);
        }
    }
    /**
     *  分红详情
     *
     * @param acceptData
     * @param uid
     * @param datetype   1-天 - 2月
     * @param out
     */
    @RequestMapping(value = "getTeamDividendDetail")
    public void getTeamDividendDetail(String callback, AcceptData acceptData, Integer page, Long uid, String date,
            Integer datetype, String key, PrintWriter out) {
        if (uid == null || uid == 0) {
            JsonUtil.printMode(out, callback, JsonUtil.loadFalseResult("用户未登录"));
            return;
        }
    /**
     * 分红详情
     *
     * @param acceptData
     * @param uid
     * @param datetype   1-天 - 2月
     * @param out
     */
    @RequestMapping(value = "getTeamDividendDetail")
    public void getTeamDividendDetail(String callback, AcceptData acceptData, Integer page, Long uid, String date,
                                      Integer datetype, String key, PrintWriter out) {
        if (uid == null || uid == 0) {
            JsonUtil.printMode(out, callback, JsonUtil.loadFalseResult("用户未登录"));
            return;
        }
        if (StringUtil.isNullOrEmpty(date) || datetype == null) {
            JsonUtil.printMode(out, callback, JsonUtil.loadFalseResult("参数不完整"));
            return;
        }
        if (StringUtil.isNullOrEmpty(date) || datetype == null) {
            JsonUtil.printMode(out, callback, JsonUtil.loadFalseResult("参数不完整"));
            return;
        }
        if (page == null)
            page = 1;
        int pageSize = Constant.PAGE_SIZE;
        if (page == null)
            page = 1;
        int pageSize = Constant.PAGE_SIZE;
        try {
            Date minDay = new Date();
            Date maxDay = new Date();
            if (datetype == 1) {
                minDay = TimeUtil.parseYYYYMMDD(date);
                maxDay = TimeUtil.parseYYYYMMDD_HHMMSS(date + " 23:59:59");
            } else if (datetype == 2) {
                minDay = TimeUtil.parseYYYYMMDD(DateUtil.getFirstDayOfMonth(date));
                maxDay = TimeUtil.parseYYYYMMDD_HHMMSS(DateUtil.getLastDayOfMonth(date) + " 23:59:59");
            }
            List<TeamDividentsVO> list = teamDividentsSourceOrderUserMapService
                    .listByDateAndTargetUid((page - 1) * pageSize, pageSize, uid, minDay, maxDay, key);
            if (list == null) {
                list = new ArrayList<>();
            }
            long count = teamDividentsSourceOrderUserMapService.countByDateAndTargetUid(uid, minDay, maxDay, key);
        try {
            Date minDay = new Date();
            Date maxDay = new Date();
            if (datetype == 1) {
                minDay = TimeUtil.parseYYYYMMDD(date);
                maxDay = TimeUtil.parseYYYYMMDD_HHMMSS(date + " 23:59:59");
            } else if (datetype == 2) {
                minDay = TimeUtil.parseYYYYMMDD(DateUtil.getFirstDayOfMonth(date));
                maxDay = TimeUtil.parseYYYYMMDD_HHMMSS(DateUtil.getLastDayOfMonth(date) + " 23:59:59");
            }
            List<TeamDividentsVO> list = teamDividentsSourceOrderUserMapService
                    .listByDateAndTargetUid((page - 1) * pageSize, pageSize, uid, minDay, maxDay, key);
            if (list == null) {
                list = new ArrayList<>();
            }
            long count = teamDividentsSourceOrderUserMapService.countByDateAndTargetUid(uid, minDay, maxDay, key);
            GsonBuilder builder = new GsonBuilder();
            builder.registerTypeAdapter(BigDecimal.class, new JsonSerializer<BigDecimal>() {
                @Override
                public JsonElement serialize(BigDecimal value, Type theType, JsonSerializationContext context) {
                    if (value == null) {
                        return new JsonPrimitive("0.00");
                    } else {
                        // 保留3位小数
                        value = value.setScale(3, RoundingMode.DOWN);
                        return new JsonPrimitive(value.toString());
                    }
                }
            });
            GsonBuilder builder = new GsonBuilder();
            builder.registerTypeAdapter(BigDecimal.class, new JsonSerializer<BigDecimal>() {
                @Override
                public JsonElement serialize(BigDecimal value, Type theType, JsonSerializationContext context) {
                    if (value == null) {
                        return new JsonPrimitive("0.00");
                    } else {
                        // 保留3位小数
                        value = value.setScale(3, RoundingMode.DOWN);
                        return new JsonPrimitive(value.toString());
                    }
                }
            });
            Gson gson = builder.create();
            JSONObject object = new JSONObject();
            Gson gson = builder.create();
            JSONObject object = new JSONObject();
            if (page == 1) {
                TeamDividentsVO teamDividentsVO = teamDividentsSourceOrderUserMapService.sumByDateAndTargetUid(uid,
                        minDay, maxDay, key);
                if (teamDividentsVO == null) {
                    teamDividentsVO = new TeamDividentsVO();
                    teamDividentsVO.setSubsidy(BigDecimal.ZERO);
                    teamDividentsVO.setDividents(BigDecimal.ZERO);
                }
                object.put("subsidy", teamDividentsVO.getSubsidy().setScale(2, RoundingMode.DOWN).toString());
                object.put("dividents", teamDividentsVO.getDividents().setScale(2, RoundingMode.DOWN).toString());
            }
            if (page == 1) {
                TeamDividentsVO teamDividentsVO = teamDividentsSourceOrderUserMapService.sumByDateAndTargetUid(uid,
                        minDay, maxDay, key);
                if (teamDividentsVO == null) {
                    teamDividentsVO = new TeamDividentsVO();
                    teamDividentsVO.setSubsidy(BigDecimal.ZERO);
                    teamDividentsVO.setDividents(BigDecimal.ZERO);
                }
                object.put("subsidy", teamDividentsVO.getSubsidy().setScale(2, RoundingMode.DOWN).toString());
                object.put("dividents", teamDividentsVO.getDividents().setScale(2, RoundingMode.DOWN).toString());
            }
            object.put("count", count);
            object.put("list", gson.toJson(list));
            JsonUtil.printMode(out, callback, JsonUtil.loadTrueResult(object));
        } catch (Exception e) {
            JsonUtil.printMode(out, callback, JsonUtil.loadFalseResult("查询失败"));
            e.printStackTrace();
            LogHelper.errorDetailInfo(e);
        }
    }
            object.put("count", count);
            object.put("list", gson.toJson(list));
            JsonUtil.printMode(out, callback, JsonUtil.loadTrueResult(object));
        } catch (Exception e) {
            JsonUtil.printMode(out, callback, JsonUtil.loadFalseResult("查询失败"));
            e.printStackTrace();
            LogHelper.errorDetailInfo(e);
        }
    }
    /**
     * 订单统计-h5
     *
     * @param acceptData
     * @param out
     */
    @RequestMapping(value = "countTeamOrderNum")
    public void countTeamOrderNum(String callback, AcceptData acceptData, Long uid, PrintWriter out) {
        try {
    /**
     * 订单统计-h5
     *
     * @param acceptData
     * @param out
     */
    @RequestMapping(value = "countTeamOrderNum")
    public void countTeamOrderNum(String callback, AcceptData acceptData, Long uid, PrintWriter out) {
        try {
            Date minDate = null;
            Date maxDate = null;
            long timeStamp = System.currentTimeMillis();
            Date minDate = null;
            Date maxDate = null;
            long timeStamp = System.currentTimeMillis();
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(timeStamp);
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(timeStamp);
            // 今日预估
            calendar.add(Calendar.DAY_OF_YEAR, -1);
            minDate = new Date(TimeUtil.convertDateToTemp(TimeUtil.getGernalTime(timeStamp)));
            OrderMoneyDailyCount todayRecord = createVO(
                    orderMoneyDailyCountService.sumTeamOrderNumGroupByCountDay(uid, minDate, null));
            // 今日预估
            calendar.add(Calendar.DAY_OF_YEAR, -1);
            minDate = new Date(TimeUtil.convertDateToTemp(TimeUtil.getGernalTime(timeStamp)));
            OrderMoneyDailyCount todayRecord = createVO(
                    orderMoneyDailyCountService.sumTeamOrderNumGroupByCountDay(uid, minDate, null));
            // 昨日预估
            calendar.add(Calendar.DAY_OF_YEAR, -1);
            maxDate = new Date(TimeUtil.convertDateToTemp(TimeUtil.getGernalTime(timeStamp)));
            minDate = DateUtil.reduceDay(1, maxDate);
            OrderMoneyDailyCount yesterdayRecord = createVO(
                    orderMoneyDailyCountService.sumTeamOrderNumGroupByCountDay(uid, minDate, maxDate));
            // 昨日预估
            calendar.add(Calendar.DAY_OF_YEAR, -1);
            maxDate = new Date(TimeUtil.convertDateToTemp(TimeUtil.getGernalTime(timeStamp)));
            minDate = DateUtil.reduceDay(1, maxDate);
            OrderMoneyDailyCount yesterdayRecord = createVO(
                    orderMoneyDailyCountService.sumTeamOrderNumGroupByCountDay(uid, minDate, maxDate));
            // 本月预估
            maxDate = new Date(timeStamp);
            calendar = Calendar.getInstance();
            minDate = new Date(TimeUtil.convertToTimeTemp(
                    calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1), "yyyy-M"));
            calendar.add(Calendar.MONTH, -1);
            OrderMoneyDailyCount monthRecord = createVO(
                    orderMoneyDailyCountService.sumTeamOrderNumGroupByYearMonth(uid, minDate, maxDate));
            // 本月预估
            maxDate = new Date(timeStamp);
            calendar = Calendar.getInstance();
            minDate = new Date(TimeUtil.convertToTimeTemp(
                    calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1), "yyyy-M"));
            calendar.add(Calendar.MONTH, -1);
            OrderMoneyDailyCount monthRecord = createVO(
                    orderMoneyDailyCountService.sumTeamOrderNumGroupByYearMonth(uid, minDate, maxDate));
            // 累计
            OrderMoneyDailyCount totalityRecord = createVO(
                    orderMoneyDailyCountService.sumTeamOrderNumGroupByUid(uid, null, null));
            // 累计
            OrderMoneyDailyCount totalityRecord = createVO(
                    orderMoneyDailyCountService.sumTeamOrderNumGroupByUid(uid, null, null));
            JSONObject today = new JSONObject();
            today.put("direct", todayRecord.getDirectOrderNum());
            today.put("indirect", todayRecord.getInDirectOrderNum());
            today.put("beyond", todayRecord.getBeyondOrderNum());
            JSONObject today = new JSONObject();
            today.put("direct", todayRecord.getDirectOrderNum());
            today.put("indirect", todayRecord.getInDirectOrderNum());
            today.put("beyond", todayRecord.getBeyondOrderNum());
            JSONObject yesterday = new JSONObject();
            yesterday.put("direct", yesterdayRecord.getDirectOrderNum());
            yesterday.put("indirect", yesterdayRecord.getInDirectOrderNum());
            yesterday.put("beyond", yesterdayRecord.getBeyondOrderNum());
            JSONObject yesterday = new JSONObject();
            yesterday.put("direct", yesterdayRecord.getDirectOrderNum());
            yesterday.put("indirect", yesterdayRecord.getInDirectOrderNum());
            yesterday.put("beyond", yesterdayRecord.getBeyondOrderNum());
            JSONObject month = new JSONObject();
            month.put("direct", monthRecord.getDirectOrderNum());
            month.put("indirect", monthRecord.getInDirectOrderNum());
            month.put("beyond", monthRecord.getBeyondOrderNum());
            JSONObject month = new JSONObject();
            month.put("direct", monthRecord.getDirectOrderNum());
            month.put("indirect", monthRecord.getInDirectOrderNum());
            month.put("beyond", monthRecord.getBeyondOrderNum());
            JSONObject totality = new JSONObject();
            totality.put("direct", totalityRecord.getDirectOrderNum());
            totality.put("indirect", totalityRecord.getInDirectOrderNum());
            totality.put("beyond", totalityRecord.getBeyondOrderNum());
            JSONObject totality = new JSONObject();
            totality.put("direct", totalityRecord.getDirectOrderNum());
            totality.put("indirect", totalityRecord.getInDirectOrderNum());
            totality.put("beyond", totalityRecord.getBeyondOrderNum());
            JSONObject json = new JSONObject();
            json.put("today", today);
            json.put("yesterday", yesterday);
            json.put("month", month);
            json.put("totality", totality);
            JsonUtil.printMode(out, callback, JsonUtil.loadTrueResult(json));
        } catch (Exception e) {
            JsonUtil.printMode(out, callback, JsonUtil.loadFalseResult("统计失败"));
            e.printStackTrace();
            LogHelper.errorDetailInfo(e);
        }
    }
            JSONObject json = new JSONObject();
            json.put("today", today);
            json.put("yesterday", yesterday);
            json.put("month", month);
            json.put("totality", totality);
            JsonUtil.printMode(out, callback, JsonUtil.loadTrueResult(json));
        } catch (Exception e) {
            JsonUtil.printMode(out, callback, JsonUtil.loadFalseResult("统计失败"));
            e.printStackTrace();
            LogHelper.errorDetailInfo(e);
        }
    }
    private OrderMoneyDailyCount createVO(List<OrderMoneyDailyCount> list) {
        OrderMoneyDailyCount totalityRecord = new OrderMoneyDailyCount(0, 0, 0);
        if (list != null && list.size() > 0) {
            for (OrderMoneyDailyCount record : list) {
                totalityRecord.setDirectOrderNum(totalityRecord.getDirectOrderNum() + record.getDirectOrderNum());
                totalityRecord.setInDirectOrderNum(totalityRecord.getInDirectOrderNum() + record.getInDirectOrderNum());
                totalityRecord.setBeyondOrderNum(totalityRecord.getBeyondOrderNum() + record.getBeyondOrderNum());
            }
        }
        return totalityRecord;
    }
    private OrderMoneyDailyCount createVO(List<OrderMoneyDailyCount> list) {
        OrderMoneyDailyCount totalityRecord = new OrderMoneyDailyCount(0, 0, 0);
        if (list != null && list.size() > 0) {
            for (OrderMoneyDailyCount record : list) {
                totalityRecord.setDirectOrderNum(totalityRecord.getDirectOrderNum() + record.getDirectOrderNum());
                totalityRecord.setInDirectOrderNum(totalityRecord.getInDirectOrderNum() + record.getInDirectOrderNum());
                totalityRecord.setBeyondOrderNum(totalityRecord.getBeyondOrderNum() + record.getBeyondOrderNum());
            }
        }
        return totalityRecord;
    }
    /**
     * 订单排行榜
     * @param callback
     * @param acceptData
     * @param uid
     * @param dateType
     * @param out
     */
    @RequestMapping(value = "getRanking")
    public void getRanking(String callback, AcceptData acceptData, Long uid, Integer dateType, PrintWriter out) {
        if (uid == null || dateType == null) {
            JsonUtil.printMode(out, callback, JsonUtil.loadFalseResult("参数缺失"));
            return;
        }
    /**
     * 订单排行榜
     *
     * @param callback
     * @param acceptData
     * @param uid
     * @param dateType
     * @param out
     */
    @RequestMapping(value = "getRanking")
    public void getRanking(String callback, AcceptData acceptData, Long uid, Integer dateType, PrintWriter out) {
        if (uid == null || dateType == null) {
            JsonUtil.printMode(out, callback, JsonUtil.loadFalseResult("参数缺失"));
            return;
        }
        try {
            Date minDate = null;
            Date maxDate = null;
            long timeStamp = System.currentTimeMillis();
        try {
            Date minDate = null;
            Date maxDate = null;
            long timeStamp = System.currentTimeMillis();
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(timeStamp);
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(timeStamp);
            if (dateType == 1) {
                // 今日
                calendar.add(Calendar.DAY_OF_YEAR, -1);
                minDate = new Date(TimeUtil.convertDateToTemp(TimeUtil.getGernalTime(timeStamp)));
            } else if (dateType == 2) {
                // 昨日
                calendar.add(Calendar.DAY_OF_YEAR, -1);
                maxDate = new Date(TimeUtil.convertDateToTemp(TimeUtil.getGernalTime(timeStamp)));
                minDate = DateUtil.reduceDay(1, maxDate);
            } else {
                // 本月
                maxDate = new Date(timeStamp);
                calendar = Calendar.getInstance();
                minDate = new Date(TimeUtil.convertToTimeTemp(
                        calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1), "yyyy-M"));
                calendar.add(Calendar.MONTH, -1);
            }
            if (dateType == 1) {
                // 今日
                calendar.add(Calendar.DAY_OF_YEAR, -1);
                minDate = new Date(TimeUtil.convertDateToTemp(TimeUtil.getGernalTime(timeStamp)));
            } else if (dateType == 2) {
                // 昨日
                calendar.add(Calendar.DAY_OF_YEAR, -1);
                maxDate = new Date(TimeUtil.convertDateToTemp(TimeUtil.getGernalTime(timeStamp)));
                minDate = DateUtil.reduceDay(1, maxDate);
            } else {
                // 本月
                maxDate = new Date(timeStamp);
                calendar = Calendar.getInstance();
                minDate = new Date(TimeUtil.convertToTimeTemp(
                        calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1), "yyyy-M"));
                calendar.add(Calendar.MONTH, -1);
            }
            List<OrderRankingVO> list = orderMoneyDailyCountService.getRankingByOrderNum(uid, minDate, maxDate);
            if (list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    OrderRankingVO vo = list.get(i);
                    UserInfo user = userInfoService.getUserByIdWithMybatis(vo.getUid());
                    if (user == null) {
                        list.remove(i);
                        i--;
                        continue;
                    }
                    vo.setNickName(user.getNickName());
                    vo.setPortrait(user.getPortrait());
                }
            }
            List<OrderRankingVO> list = orderMoneyDailyCountService.getRankingByOrderNum(uid, minDate, maxDate);
            if (list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    OrderRankingVO vo = list.get(i);
                    UserInfo user = userInfoService.getUserByIdWithMybatis(vo.getUid());
                    if (user == null) {
                        list.remove(i);
                        i--;
                        continue;
                    }
                    vo.setNickName(user.getNickName());
                    vo.setPortrait(user.getPortrait());
                }
            }
            JSONObject json = new JSONObject();
            json.put("list", list);
            JsonUtil.printMode(out, callback, JsonUtil.loadTrueResult(json));
        } catch (Exception e) {
            JsonUtil.printMode(out, callback, JsonUtil.loadFalseResult("统计失败"));
            e.printStackTrace();
            LogHelper.errorDetailInfo(e);
        }
    }
            JSONObject json = new JSONObject();
            json.put("list", list);
            JsonUtil.printMode(out, callback, JsonUtil.loadTrueResult(json));
        } catch (Exception e) {
            JsonUtil.printMode(out, callback, JsonUtil.loadFalseResult("统计失败"));
            e.printStackTrace();
            LogHelper.errorDetailInfo(e);
        }
    }
}
fanli/src/main/java/com/yeshi/fanli/controller/h5/BuWanH5Controller.java
New file
@@ -0,0 +1,207 @@
package com.yeshi.fanli.controller.h5;
import com.yeshi.common.entity.taobao.TaoKeAppInfo;
import com.yeshi.fanli.dto.ConfigParamsDTO;
import com.yeshi.fanli.entity.SystemEnum;
import com.yeshi.fanli.entity.bus.user.vip.UserLevelEnum;
import com.yeshi.fanli.entity.taobao.SearchFilter;
import com.yeshi.fanli.entity.taobao.TaoBaoLink;
import com.yeshi.fanli.entity.taobao.TaoBaoSearchResult;
import com.yeshi.fanli.exception.taobao.TaoBaoConvertLinkException;
import com.yeshi.fanli.exception.taobao.TaobaoGoodsDownException;
import com.yeshi.fanli.service.inter.config.BusinessSystemService;
import com.yeshi.fanli.service.inter.order.OrderHongBaoMoneyComputeService;
import com.yeshi.fanli.service.inter.order.config.HongBaoManageService;
import com.yeshi.fanli.service.manger.goods.TaoBaoLinkManager;
import com.yeshi.fanli.util.StringUtil;
import com.yeshi.fanli.util.TaoBaoConstant;
import com.yeshi.fanli.util.cache.TaoBaoGoodsCacheUtil;
import com.yeshi.fanli.util.factory.goods.GoodsDetailVOFactory;
import com.yeshi.fanli.util.taobao.TaoBaoUtil;
import com.yeshi.fanli.util.taobao.TaoKeApiUtil;
import com.yeshi.fanli.vo.goods.CouponInfoVO;
import com.yeshi.fanli.vo.goods.GoodsDetailExtraVO;
import com.yeshi.fanli.vo.goods.GoodsDetailVO;
import com.yeshi.fanli.vo.goods.MoneyInfoVO;
import com.yeshi.goods.facade.entity.taobao.TaoBaoGoodsBrief;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.yeshi.utils.JsonUtil;
import org.yeshi.utils.taobao.TbImgUtil;
import javax.annotation.Resource;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
/**
 * 布丸相关的H5代码接口
 */
@Controller
@RequestMapping("api/apph5/v1/buwan")
public class BuWanH5Controller {
    @Resource
    private OrderHongBaoMoneyComputeService orderHongBaoMoneyComputeService;
    @Resource
    private TaoBaoGoodsCacheUtil taoBaoGoodsCacheUtil;
    @Resource
    private HongBaoManageService hongBaoManageService;
    @Resource
    private TaoBaoLinkManager taoBaoLinkManager;
    private String pid = "mm_124933865_56750082_19509700484";
    /**
     * 获取商品列表
     *
     * @param sign
     * @param key
     * @param page
     * @param callback
     * @param out
     */
    @RequestMapping(value = "getGoodsList")
    public void getGoodsList(String sign, String key, int page, String callback, PrintWriter out) {
        //搜索内容
        if (StringUtil.isNullOrEmpty(key))
            return;
        SearchFilter sf = new SearchFilter();
        sf.setPage(page);
        sf.setPageSize(20);
        sf.setKey(key);
        sf.setSort(TaoBaoUtil.SORT_TOTAL_SALES_HIGH_TO_LOW);
        ConfigParamsDTO configParamsDTO = orderHongBaoMoneyComputeService.getShowComputeRate("android",
                "60", SystemEnum.flq);
        List<GoodsDetailVO> goodsList = new ArrayList<>();
        TaoBaoSearchResult result = taoBaoGoodsCacheUtil.getSearchResult(sf);
        if (result == null) {
            result = TaoKeApiUtil.searchWuLiao(sf, null, null);
            taoBaoGoodsCacheUtil.saveSearchResult(sf, result);
        }
        if (result != null) {
            for (TaoBaoGoodsBrief goods : result.getTaoBaoGoodsBriefs()) {
                GoodsDetailVO goodsVO = GoodsDetailVOFactory.convertTaoBao(goods, configParamsDTO);
                goodsList.add(goodsVO);
            }
        }
        long count = 0;
        if (result != null)
            count = result.getPageEntity().getTotalCount();
        JSONObject data = new JSONObject();
        data.put("list", goodsList);
        data.put("count", count);
        JsonUtil.printMode(out, callback, JsonUtil.loadTrueResult(data));
    }
    private ConfigParamsDTO getParamsDTO(String platform, String version, Long uid, SystemEnum system) {
        UserLevelEnum level = UserLevelEnum.daRen;
        if (level == null)
            level = UserLevelEnum.daRen;
        return orderHongBaoMoneyComputeService.getShowComputeRate(platform, version, level, system);
    }
    @RequestMapping(value = "getGoodsDetail")
    public void getGoodsDetail(String sign, long id, String callback, PrintWriter out) {
        GoodsDetailExtraVO extraVO = new GoodsDetailExtraVO();
        extraVO.setIsNative(false);
        TaoBaoGoodsBrief goods = null;
        SystemEnum system = SystemEnum.flq;
        TaoKeAppInfo info = new TaoKeAppInfo(TaoBaoConstant.TAOBAO_AUTH_APPKEY, TaoBaoConstant.TAOBAO_AUTH_APPSECRET, pid);
        try {
            goods = TaoKeApiUtil.searchGoodsDetail(id, info);
            if (goods.getTkRate() == null || new BigDecimal(0).compareTo(goods.getTkRate()) == 0) {
                TaoBaoGoodsBrief linkInfo = TaoKeApiUtil.specialConvertCoupon(goods.getAuctionId(), info, null, null);
                if (linkInfo != null) {
                    goods.setAuctionUrl(linkInfo.getAuctionUrl());
                    goods.setCouponLink(linkInfo.getCouponLink());
                    goods.setTkRate(linkInfo.getTkRate());
                }
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        } catch (TaobaoGoodsDownException e) {
        }
        TaoBaoGoodsBrief tb = goods;
        if (tb == null) {
            out.print(JsonUtil.loadFalseResult(2, "商品不存在"));
            return;
        }
        if (tb.getImgList() == null) {
            tb.setImgList(new ArrayList<>());
        }
        List<String> finalImgList = new ArrayList<>();
        for (String img : tb.getImgList()) {
            finalImgList.add(TbImgUtil.getTBSizeImg(img, 600));
        }
        if (finalImgList.size() == 0) {
            finalImgList.add(tb.getPictUrl());
        }
        if (!StringUtil.isNullOrEmpty(tb.getPictUrlWhite()))
            finalImgList.add(0, tb.getPictUrlWhite());
        // 移除相同图片
        if (finalImgList.size() > 0)
            for (int i = 0; i < finalImgList.size(); i++) {
                if (i < finalImgList.size() - 1)
                    if (TbImgUtil.getTBSizeImg(finalImgList.get(i), 600)
                            .equalsIgnoreCase(TbImgUtil.getTBSizeImg(finalImgList.get(i + 1), 600))) {
                        finalImgList.remove(i--);
                    }
            }
        tb.setImgList(finalImgList);
        ConfigParamsDTO paramsDTO = getParamsDTO("android", "60", null, SystemEnum.flq);
        paramsDTO.setBaseFanliRate(hongBaoManageService.getBaseFanliRate(system));
        GoodsDetailVO goodsDetail = GoodsDetailVOFactory.convertTaoBao(goods, paramsDTO);
        extraVO.setDetailUrl("http://apph5.banliapp.com/apppage/goods_img.html?id=" + id);
        int moneyType = 1;
        extraVO.setFanliValid(true);
        MoneyInfoVO goodsMoney = goodsDetail.getMoneyInfo();
        if (goodsMoney != null) {
            goodsMoney.setMoneyType(moneyType);
        }
        if (goodsDetail.isHasCoupon()) {
            // 设置couponList
            List<CouponInfoVO> couponInfoList = new ArrayList<>();
            couponInfoList.add(goodsDetail.getCouponInfo());
            goodsDetail.setCouponInfoList(couponInfoList);
        }
        String url = goods.getAuctionUrl();
        if (!StringUtil.isNullOrEmpty(goods.getCouponLink())) {
            url = goods.getCouponLink();
        }
        String token = TaoKeApiUtil.getTKToken(goods.getPictUrl(), goods.getTitle(), url);
        JSONObject object = new JSONObject();
        object.put("extra", JsonUtil.getApiCommonGson().toJson(extraVO));
        object.put("goods", JsonUtil.getApiCommonGson().toJson(goodsDetail));
        object.put("token", token);
        JsonUtil.printMode(out,callback,JsonUtil.loadTrueResult(object.toString()));
    }
}
fanli/src/main/java/com/yeshi/fanli/controller/wxmp/v1/GoodsController.java
@@ -515,7 +515,7 @@
        CouponInfoVO couponInfo = goodsDetail.getCouponInfo();
        PDDPromotionUrl convertUrl = null;
        if (couponInfo != null) {
            convertUrl = PinDuoDuoApiUtil.convert(id, PinDuoDuoApiUtil.PID_COUPON + "", null);
            convertUrl = PinDuoDuoApiUtil.convert(id, PinDuoDuoApiUtil.PID_COUPON + "", null,false);
            if (convertUrl != null)
                couponInfo.setLink(convertUrl.getUrl());
        }
fanli/src/main/java/com/yeshi/fanli/dao/mybatis/HongBaoV2Mapper.java
@@ -264,4 +264,14 @@
     */
    Integer getDirectBossUrankByPid(@Param("pid")Long pid);
    /**
     * 设置红包已领取
     * @param uid
     * @param typeList
     * @param preGetTime
     * @return
     */
    int setHongBaoRecieved (@Param("uid")Long uid,@Param("typeList")List<Integer> typeList,@Param("preGetTime")Date preGetTime);
}
fanli/src/main/java/com/yeshi/fanli/dao/mybatis/order/CommonOrderCountMapper.java
@@ -12,201 +12,219 @@
public interface CommonOrderCountMapper {
    /**
     * 当前各个状态订单数
     *
     * @param state
     *            状态
     * @return
     */
    Long countByState(@Param("state") Integer state);
    /**
     * 当前各个状态订单数
     *
     * @param state 状态
     * @return
     */
    Long countByState(@Param("state") Integer state);
    /**
     * 统计所有订单
     *
     * @param channel
     * @return
     */
    Long countOrderBySourceTypeAndDay(@Param("preDay") String preDay, @Param("sourceType") int sourceType);
    /**
     * 统计所有订单
     *
     * @param channel
     * @return
     */
    List<ChartTDO> countOrderNumber(@Param("dateType") Integer dateType, @Param("year") String year,
            @Param("startTime") String startTime, @Param("endTime") String endTime,
            @Param("sourceType") int sourceType);
    /**
     * 统计所有订单
     *
     * @param channel
     * @return
     */
    Long countOrderBySourceTypeAndDay(@Param("preDay") String preDay, @Param("sourceType") int sourceType);
    /**
     * 奖金统计
     *
     * @param uid
     * @return
     */
    Map<String, Object> countOrderNumberBySettleTime(@Param("uid") Long uid, @Param("state") Integer state,
            @Param("day") Integer day);
    /**
     * 统计自购、分享有效订单数量
     *
     * @param uid
     * @return
     */
    long countValidOrder(@Param("uid") Long uid);
    /**
     * 统计所有订单
     *
     * @param channel
     * @return
     */
    List<ChartTDO> countOrderNumber(@Param("dateType") Integer dateType, @Param("year") String year,
                                    @Param("startTime") String startTime, @Param("endTime") String endTime,
                                    @Param("sourceType") int sourceType);
    /**
     * 根据订单号 查询金额
     *
     * @param orderNo
     * @return
     */
    BigDecimal getMoneyByOrderNo(@Param("orderNo") String orderNo);
    /**
     * 统计已到账返利订单
     *
     * @param uid
     * @param dateTime
     * @return
     */
    long countValidOrderByDate(@Param("uid") Long uid, @Param("dateTime") String dateTime);
    /**
     * 奖金统计
     *
     * @param uid
     * @return
     */
    Map<String, Object> countOrderNumberBySettleTime(@Param("uid") Long uid, @Param("state") Integer state,
                                                     @Param("day") Integer day);
    /**
     * 查询用户在同一店铺购买超过一定数量商品的店铺数量
     *
     * @param typeList
     *            -红包类型
     * @param uid
     *            -用户ID
     * @param minSameShopGoodsCount
     *            -同一店铺买的最小订单数
     * @return
     */
    long countSameShopOrderByUidAndHongBaoType(@Param("typeList") List<Integer> typeList, @Param("uid") Long uid,
            @Param("minSameShopGoodsCount") int minSameShopGoodsCount);
    /**
     * 查询用户购买相同商品超过一定的订单数量的商品数量
     * @param typeList
     * @param uid
     * @param minSameGoodsOrderCount
     * @return
     */
    long countSameGoodsOrderByUidAndHongBaoType(@Param("typeList") List<Integer> typeList, @Param("uid") Long uid,
            @Param("minSameGoodsOrderCount") int minSameGoodsOrderCount);
    /**
     * 查询用户在同一店铺购买超过一定数量商品的店铺id
     *
     * @param typeList
     *            -红包类型
     * @param uid
     *            -用户ID
     * @param minSameShopGoodsCount
     *            -同一店铺买的最小订单数
     * @return
     */
    List<Long> getSameShopOrderByUidAndHongBaoType(@Param("typeList") List<Integer> typeList, @Param("uid") Long uid,
            @Param("minSameShopGoodsCount") int minSameShopGoodsCount);
    /**
     * 查询用户购买相同商品超过一定的订单数量的商品id
     * @param typeList
     * @param uid
     * @param minSameGoodsOrderCount
     * @return
     */
    List<Long> getSameGoodsOrderByUidAndHongBaoType(@Param("typeList") List<Integer> typeList, @Param("uid") Long uid,
            @Param("minSameGoodsOrderCount") int minSameGoodsOrderCount);
    /**
     * 通过uid 日期筛选   下单数量
     * @param preDay
     * @param uid
     * @return
     */
    Integer countOderByUidAndDate(@Param("preDay") Date preDay,@Param("uid") Long uid);
    /**
     *  日期筛选  每个用户下单数量
     * @param preDay
     * @param uid
     * @return
     */
    List<CountOrderDTO> countValidOrderByDay(@Param("preDay") String preDay);
    /**
     * 查询当日下单用户
     * @param preDay
     * @return
     */
    List<Long> getUidByValidOrderByDay(@Param("preDay") String preDay);
    /**
     * 通过多个uid 日期筛选 下单用户数量
     * @param preDay
     * @param uid
     * @return
     */
    Integer countDownOrderUserByUidAndDate(@Param("preDay") Date preDay,@Param("list") List<Long> list);
    /**
     * 统计订单产生佣金
     * @param preDay
     * @param list
     * @return
     */
    List<CountOrderDTO> countCommissionByDay(@Param("preDay") String preDay);
    /**
     * 通过uid 日期筛选   下单数量
     * @param preDay
     * @return
     */
    Integer countOderByDate(@Param("preDay") String preDay);
    /**
     * 统计订单产生佣金
     * @param preDay
     * @return
     */
    BigDecimal countCommissionByDate(@Param("preDay") String preDay);
    /**
     * 查询最近50小于10的订单数量
     * @param uid
     * @return
     */
    Integer countOderByUidAndLess10(@Param("uid") Long uid);
    List<Long> getDownOrderUserByListUidAndDate(@Param("preDay") Date preDay,@Param("list") List<Long> list);
    /**
     * 统计近 day天有效订单数量
     * @param uid
     * @param source
     * @param day
     * @return
     */
    Long countOrderBySourceAndNearDay(@Param("uid") Long uid, @Param("source") int source, @Param("day") int day);
    /**
     * 统计历史订单数量 -不区分状态、来源  订单号为主
     * @param uid
     * @return
     */
    Long countHistoryOrderNum(@Param("uid") Long uid);
    /**
     * 统计自购、分享有效订单数量
     *
     * @param uid
     * @return
     */
    long countValidOrder(@Param("uid") Long uid);
    /**
     * 根据订单号 查询金额
     *
     * @param orderNo
     * @return
     */
    BigDecimal getMoneyByOrderNo(@Param("orderNo") String orderNo);
    /**
     * 统计已到账返利订单
     *
     * @param uid
     * @param dateTime
     * @return
     */
    long countValidOrderByDate(@Param("uid") Long uid, @Param("dateTime") String dateTime);
    /**
     * 查询用户在同一店铺购买超过一定数量商品的店铺数量
     *
     * @param typeList              -红包类型
     * @param uid                   -用户ID
     * @param minSameShopGoodsCount -同一店铺买的最小订单数
     * @return
     */
    long countSameShopOrderByUidAndHongBaoType(@Param("typeList") List<Integer> typeList, @Param("uid") Long uid,
                                               @Param("minSameShopGoodsCount") int minSameShopGoodsCount, @Param("minDate") Date minDate);
    /**
     * 查询用户购买相同商品超过一定的订单数量的商品数量
     *
     * @param typeList
     * @param uid
     * @param excludeShopIds
     * @param minSameGoodsOrderCount
     * @return
     */
    long countSameGoodsOrderByUidAndHongBaoType(@Param("typeList") List<Integer> typeList, @Param("uid") Long uid, @Param("excludeShopIds") List<Long> excludeShopIds,
                                                @Param("minSameGoodsOrderCount") int minSameGoodsOrderCount, @Param("minDate") Date minDate);
    /**
     * 查询用户购买相同商品超过一定的订单数量的商品ID
     * @param typeList
     * @param uid
     * @param excludeShopIds
     * @param minSameGoodsOrderCount
     * @param minDate
     * @return
     */
    List<Long> listSameGoodsIdByUidAndHongBaoType(@Param("typeList") List<Integer> typeList, @Param("uid") Long uid, @Param("excludeShopIds") List<Long> excludeShopIds,
                                                  @Param("minSameGoodsOrderCount") int minSameGoodsOrderCount, @Param("minDate") Date minDate);
    /**
     * 查询用户在同一店铺购买超过一定数量商品的店铺id
     *
     * @param typeList              -红包类型
     * @param uid                   -用户ID
     * @param minSameShopGoodsCount -同一店铺买的最小订单数
     * @return
     */
    List<Long> getSameShopOrderByUidAndHongBaoType(@Param("typeList") List<Integer> typeList, @Param("uid") Long uid, @Param("excludeShopIds") List<Long> excludeShopIds,
                                                   @Param("minSameShopGoodsCount") int minSameShopGoodsCount);
    /**
     * 查询用户购买相同商品超过一定的订单数量的商品id
     *
     * @param typeList
     * @param uid
     * @param minSameGoodsOrderCount
     * @return
     */
    List<Long> getSameGoodsOrderByUidAndHongBaoType(@Param("typeList") List<Integer> typeList, @Param("uid") Long uid,
                                                    @Param("minSameGoodsOrderCount") int minSameGoodsOrderCount);
    /**
     * 通过uid 日期筛选   下单数量
     *
     * @param preDay
     * @param uid
     * @return
     */
    Integer countOderByUidAndDate(@Param("preDay") Date preDay, @Param("uid") Long uid);
    /**
     * 日期筛选  每个用户下单数量
     *
     * @param preDay
     * @param uid
     * @return
     */
    List<CountOrderDTO> countValidOrderByDay(@Param("preDay") String preDay);
    /**
     * 查询当日下单用户
     *
     * @param preDay
     * @return
     */
    List<Long> getUidByValidOrderByDay(@Param("preDay") String preDay);
    /**
     * 通过多个uid 日期筛选 下单用户数量
     *
     * @param preDay
     * @param uid
     * @return
     */
    Integer countDownOrderUserByUidAndDate(@Param("preDay") Date preDay, @Param("list") List<Long> list);
    /**
     * 统计订单产生佣金
     *
     * @param preDay
     * @param list
     * @return
     */
    List<CountOrderDTO> countCommissionByDay(@Param("preDay") String preDay);
    /**
     * 通过uid 日期筛选   下单数量
     *
     * @param preDay
     * @return
     */
    Integer countOderByDate(@Param("preDay") String preDay);
    /**
     * 统计订单产生佣金
     *
     * @param preDay
     * @return
     */
    BigDecimal countCommissionByDate(@Param("preDay") String preDay);
    /**
     * 查询最近50小于10的订单数量
     *
     * @param uid
     * @return
     */
    Integer countOderByUidAndLess10(@Param("uid") Long uid);
    List<Long> getDownOrderUserByListUidAndDate(@Param("preDay") Date preDay, @Param("list") List<Long> list);
    /**
     * 统计近 day天有效订单数量
     *
     * @param uid
     * @param source
     * @param day
     * @return
     */
    Long countOrderBySourceAndNearDay(@Param("uid") Long uid, @Param("source") int source, @Param("day") int day);
    /**
     * 统计历史订单数量 -不区分状态、来源  订单号为主
     *
     * @param uid
     * @return
     */
    Long countHistoryOrderNum(@Param("uid") Long uid);
}
fanli/src/main/java/com/yeshi/fanli/dao/mybatis/order/CommonOrderMapper.java
@@ -16,440 +16,446 @@
public interface CommonOrderMapper extends BaseMapper<CommonOrder> {
    /**
     * 查询用户订单 并订单号分组
     *
     * @param start
     * @param count
     * @param uid
     * @return
     */
    List<CommonOrderVO> listUserOrder(@Param("start") long start, @Param("count") int count, @Param("uid") Long uid,
            @Param("state") Integer state, @Param("type") Integer type, @Param("orderState") Integer orderState,
            @Param("orderNo") String orderNo, @Param("startTime") String startTime, @Param("endTime") String endTime,
            @Param("day") Integer day, @Param("listSource") List<Integer> listSource);
    /**
     * 查询用户订单 并订单号分组
     *
     * @param start
     * @param count
     * @param uid
     * @return
     */
    /**
     * 统计用户订单 并订单号分组
     *
     * @param start
     * @param count
     * @param uid
     * @return
     */
    long countUserOrder(@Param("uid") Long uid, @Param("state") Integer state, @Param("type") Integer type,
            @Param("orderState") Integer orderState, @Param("orderNo") String orderNo,
            @Param("startTime") String startTime, @Param("endTime") String endTime, @Param("day") Integer day,
            @Param("listSource") List<Integer> listSource);
    List<CommonOrderVO> listUserOrder(@Param("start") long start, @Param("count") int count, @Param("uid") Long uid,
                                      @Param("state") Integer state, @Param("type") Integer type, @Param("orderState") Integer orderState,
                                      @Param("orderNo") String orderNo, @Param("startTime") String startTime, @Param("endTime") String endTime,
                                      @Param("day") Integer day, @Param("listSource") List<Integer> listSource);
    /**
     * 判断部分失效状态
     *
     * @param uid
     * @param orderNo
     * @return
     */
    CommonOrderVO getBuFenOrderState(@Param("uid") Long uid, @Param("orderNo") String orderNo);
    /**
     * 统计用户订单 并订单号分组
     *
     * @param start
     * @param count
     * @param uid
     * @return
     */
    long countUserOrder(@Param("uid") Long uid, @Param("state") Integer state, @Param("type") Integer type,
                        @Param("orderState") Integer orderState, @Param("orderNo") String orderNo,
                        @Param("startTime") String startTime, @Param("endTime") String endTime, @Param("day") Integer day,
                        @Param("listSource") List<Integer> listSource);
    /**
     * 根据用户ID,订单状态和订单结算时间统计订单的数量
     *
     * @param uid
     * @param state
     * @param minDate
     * @param maxDate
     * @return
     */
    long countByUidAndOrderStateWithOrderBalanceTime(@Param("uid") Long uid, @Param("state") int state,
            @Param("minDate") Date minDate, @Param("maxDate") Date maxDate);
    /**
     * 判断部分失效状态
     *
     * @param uid
     * @param orderNo
     * @return
     */
    CommonOrderVO getBuFenOrderState(@Param("uid") Long uid, @Param("orderNo") String orderNo);
    /**
     * 根据订单号、订单类型查询商品
     *
     * @param list
     *            订单对象
     * @return
     */
    List<CommonOrderVO> listOrderGoodsInfo(List<CommonOrderVO> list);
    /**
     * 根据用户ID,订单状态和订单结算时间统计订单的数量
     *
     * @param uid
     * @param state
     * @param minDate
     * @param maxDate
     * @return
     */
    long countByUidAndOrderStateWithOrderBalanceTime(@Param("uid") Long uid, @Param("state") int state,
                                                     @Param("minDate") Date minDate, @Param("maxDate") Date maxDate);
    /**
     * 统计历史订单数量
     *
     * @param uid
     * @return
     */
    Map<String, BigDecimal> countHistoryOrder(@Param("uid") Long uid, @Param("day") Integer day,
            @Param("source") Integer source);
    /**
     * 根据订单号、订单类型查询商品
     *
     * @param list 订单对象
     * @return
     */
    List<CommonOrderVO> listOrderGoodsInfo(List<CommonOrderVO> list);
    /**
     * 统计有效订单数量
     * @param uid
     * @return
     */
    OrderCountVO getOrderCount(@Param("uid") Long uid, @Param("day")Integer day, @Param("listSource") List<Integer> listSource);
    /**
     * 昨日总订单-根据红包类型 自购 邀请 分享
     *
     * @param uid
     * @return
     */
    long countUserOrderToApp(@Param("uid") Long uid, @Param("type") Integer type,
            @Param("startTime") String startTime, @Param("endTime") String endTime, @Param("day") Integer day,
            @Param("source") Integer source,@Param("state") Integer state, @Param("stateOrder") Integer stateOrder);
    /**
     * 奖金订单数量
     *
     * @param uid
     * @return
     */
    long countBonusOrderNumber(@Param("uid") Long uid, @Param("type") Integer type, @Param("day") Integer day,
            @Param("startTime") String startTime, @Param("endTime") String endTime, @Param("source") Integer source);
    /**
     * 奖金统计
     *
     * @param uid
     * @return
     */
    BigDecimal countBonusOrderMoney(@Param("uid") Long uid, @Param("type") Integer type, @Param("day") Integer day,
            @Param("startTime") String startTime, @Param("endTime") String endTime, @Param("source") Integer source);
    /**
     * 奖金统计
     *
     * @param uid
     * @return
     */
    Map<String, Object> countBonusOrderMoneyAndNumber(@Param("uid") Long uid, @Param("type") Integer type,
            @Param("day") Integer day, @Param("startTime") String startTime, @Param("endTime") String endTime,
            @Param("source") Integer source);
    int countByOrderNOAndOrderType(@Param("orderNO") String orderNO, @Param("orderType") int orderType);
    /**
     * 根据订单号与订单排序值获取详情
     *
     * @param orderNo
     *            -订单号
     * @param orderBy
     *            -订单排序值
     * @param orderType
     *            -订单类型
     * @return
     */
    CommonOrder selectByOrderNoAndOrderTypeAndOrderBy(@Param("orderNo") String orderNo,
            @Param("orderType") int orderType, @Param("orderBy") int orderBy);
    /**
     * 订单列表查询
     *
     * @param start
     * @param count
     * @param uid
     * @param state
     * @param type
     * @param orderState
     * @param startTime
     * @param endTime
     * @return
     */
    List<CommonOrderVO> listQueryByUid(@Param("start") long start, @Param("count") int count, @Param("uid") Long uid,
            @Param("state") Integer state, @Param("type") Integer type, @Param("orderState") Integer orderState,
            @Param("orderNo") String orderNo, @Param("startTime") String startTime, @Param("endTime") String endTime,
            @Param("day") Integer day);
    /**
     * 统计
     */
    long countQueryByUid(@Param("uid") Long uid, @Param("state") Integer state, @Param("type") Integer type,
            @Param("orderState") Integer orderState, @Param("orderNo") String orderNo,
            @Param("startTime") String startTime, @Param("endTime") String endTime, @Param("day") Integer day);
    /**
     * 订单列表查询
     *
     * @param start
     * @param count
     * @param uid
     * @param state
     * @param type
     * @param orderState
     * @param startTime
     * @param endTime
     * @return
     */
    List<CommonOrderVO> listQuery(@Param("start") long start, @Param("count") int count,
            @Param("keyType") Integer keyType, @Param("key") String key, @Param("state") Integer state,
            @Param("type") Integer type, @Param("orderState") Integer orderState, @Param("startTime") String startTime,
            @Param("endTime") String endTime, @Param("source") Integer source,
            @Param("listShopId")List<Long> listShopId, @Param("listGoodsId")List<Long> listGoodsId,
            @Param("minTime")Date minTime, @Param("money")BigDecimal money, @Param("payment") BigDecimal payment, @Param("system")  SystemEnum system);
    /**
     * 订单列表查询(不包含子订单)
     *
     * @param start
     * @param count
     * @param keyType
     * @param key
     * @param state
     * @param type
     * @param orderState
     * @param startTime
     * @param endTime
     * @param source
     * @return
     */
    List<CommonOrderVO> listQueryWithNoChild(@Param("start") long start, @Param("count") int count,
            @Param("keyType") Integer keyType, @Param("key") String key, @Param("state") Integer state,
            @Param("type") Integer type, @Param("orderState") Integer orderState, @Param("startTime") String startTime,
            @Param("endTime") String endTime, @Param("source") Integer source, @Param("payment") BigDecimal payment, @Param("system")  SystemEnum system);
    /**
     * 统计
     */
    long countQuery(@Param("keyType") Integer keyType, @Param("key") String key, @Param("state") Integer state,
                    @Param("type") Integer type, @Param("orderState") Integer orderState, @Param("startTime") String startTime,
                    @Param("endTime") String endTime, @Param("source") Integer source,
                    @Param("listShopId")List<Long> listShopId, @Param("listGoodsId")List<Long> listGoodsId,
                    @Param("minTime")Date minTime, @Param("money")BigDecimal money, @Param("payment") BigDecimal payment, @Param("system")  SystemEnum system);
    long countQueryWithNoChild(@Param("keyType") Integer keyType, @Param("key") String key,
            @Param("state") Integer state, @Param("type") Integer type, @Param("orderState") Integer orderState,
            @Param("startTime") String startTime, @Param("endTime") String endTime, @Param("source") Integer source, @Param("payment") BigDecimal payment, @Param("system")  SystemEnum system);
    /**
     * 根据来源类型与订单号查询列表
     *
     * @param sourceType
     * @param orderNo
     * @return
     */
    List<CommonOrder> listBySourceTypeAndOrderNo(@Param("sourceType") int sourceType, @Param("orderNo") String orderNo);
    /**
     * 查询券奖励金额以及订单信息
     *
     * @param uid
     * @param state
     * @param orderNo
     * @return
     */
    List<CommonOrderVO> getCouponHongbaoByOrderNo(@Param("uid") Long uid, @Param("hongBaoState") Integer hongBaoState,
            @Param("orderNo") String orderNo);
    /**
     * 查询券奖励金额以及订单信息
     *
     * @param uid
     * @param state
     * @param orderNo
     * @return
     */
    CommonOrderVO getCommonOrderByOrderNo(@Param("uid") Long uid, @Param("orderNo") String orderNo,
            @Param("orderState") Integer orderState, @Param("sourceType") Integer sourceType);
    /**
     * 根据来源和交易ID获取订单详情
     *
     * @param sourceType
     * @param tradeId
     * @return
     */
    CommonOrder selectBySourceTypeAndTradeId(@Param("sourceType") int sourceType, @Param("tradeId") String tradeId);
    /**
     * 根据来源和交易ID获取订单列表
     *
     * @param sourceType
     * @param tradeId
     * @return
     */
    List<CommonOrder> listBySourceTypeAndTradeId(@Param("sourceType") int sourceType, @Param("tradeId") String tradeId);
    /**
     * 根据来源和交易ID获取订单列表
     *
     * @param sourceType
     * @param tradeIdList
     * @return
     */
    List<CommonOrder> listBySourceTypeAndTradeIdList(@Param("sourceType") int sourceType,
            @Param("tradeIdList") List<String> tradeIdList);
    /**
     *
     * @param sourceType
     * @param state
     * @param minTime
     *            -最大创建时间
     * @param maxTime
     *            -最小创建时间
     * @return
     */
    List<CommonOrder> listBySourceTypeAndStateAndThirdCrateTime(@Param("sourceType") int sourceType,
            @Param("state") Integer state, @Param("minTime") Long minTime, @Param("maxTime") Long maxTime,
            @Param("start") long start, @Param("count") int count);
    /**
     * 根据订单号查询
     *
     * @param orderNO
     * @return
     */
    List<CommonOrder> getByOrderNo(@Param("uid") Long uid, @Param("orderNo") String orderNo);
    /**
     * 根据订单号查询
     *
     * @param orderNO
     * @return
     */
    List<CommonOrder> getByOrderNoAndSourceType(@Param("uid") Long uid, @Param("orderNo") String orderNo,
            @Param("sourceType") int sourceType);
    /**
     * 根据用户ID查询
     * @param uid
     * @param stateList
     * @param start
     * @param count
     * @return
     */
    List<CommonOrder> listByUid(@Param("uid")Long uid,@Param("stateList") List<Integer> stateList,@Param("start") long start,@Param("count") int count);
    /**
     * 查询首笔有效到账订单
     * @param uid
     * @param typeHB 类型: 1自购  2分享 3邀请
     * @param typeDate 日期类型: 3本月 4上月
     * @return
     */
    CommonOrderVO firstValidOrderByUid(@Param("uid") Long uid, @Param("typeHB") Integer typeHB,
            @Param("typeDate") Integer typeDate);
    /**
     * 获取首笔分享订单;
     * @param uid
     * @return
     */
    CommonOrder getFirstShareOrderByUid(@Param("uid") Long uid);
    /**
     * 统计订单号到账金额
     * @param uid
     * @return
     */
    BigDecimal getTotalRewardMoneyByOrderNoAndSourceType(@Param("orderNo") String orderNo, @Param("sourceType") Integer sourceType);
    /**
     * 统计24小时有效自购订单
     * @param uid
     * @return
     */
    long count24HValidOrderByUid(@Param("uid") Long uid, @Param("minTime") Date minTime);
    /**
     * 搜索订单
     * @param start
     * @param count
     * @param uid
     * @param list
     * @return
     */
    List<CommonOrderVO> searchOrderByUid(@Param("start") long start, @Param("count") int count, @Param("uid") Long uid,
            @Param("list")List<ESOrder> list);
    /**
     * 搜索订单
     * @param start
     * @param count
     * @param uid
     * @param list
     * @return
     */
    long countSearchOrderByUid(@Param("uid") Long uid, @Param("list")List<ESOrder> list);
    /**
     * 查询最小结算时间
     * @return
     */
    List<CommonOrder> getMinSettleTimeAndUid();
    /**
     * 查询用户订单 并订单号分组
     *
     * @param start
     * @param count
     * @param uid
     * @return
     */
    List<CommonOrderVO> getOrderList(@Param("start") long start, @Param("count") int count, @Param("uid") Long uid,
            @Param("state") Integer state, @Param("type") Integer type, @Param("orderState") Integer orderState,
            @Param("orderNo") String orderNo, @Param("startTime") String startTime, @Param("endTime") String endTime,
            @Param("day") Integer day, @Param("listSource") List<Integer> listSource);
    /**
     * 统计用户订单 并订单号分组
     *
     * @param start
     * @param count
     * @param uid
     * @return
     */
    long countOrderList(@Param("uid") Long uid, @Param("state") Integer state, @Param("type") Integer type,
            @Param("orderState") Integer orderState, @Param("orderNo") String orderNo,
            @Param("startTime") String startTime, @Param("endTime") String endTime, @Param("day") Integer day,
            @Param("listSource") List<Integer> listSource);
    /**
     * 统计已结算且付款金额大于1的订单(不区分订单状态)
     * @param uid
     * @param payment
     * @return
     */
    Long countOrderByUidAndSettled(@Param("uid") Long uid, @Param("payment") BigDecimal payment);
    /**
     * 获取最新的淘宝订单号
     * @return
     */
    String getNewestOrderNoByTaoBao();
    /**
     * 根据订单号进行sous
     * @param orderNo
     * @return
     */
    List<CommonOrder> listByOrderNo(@Param("orderNo") String orderNo);
    /**
     * 获取首个订单
     * @param orderNo
     * @return
     */
    CommonOrder getFirstOrder(@Param("uid") Long uid);
    /**
     * 统计历史订单数量
     *
     * @param uid
     * @return
     */
    Map<String, BigDecimal> countHistoryOrder(@Param("uid") Long uid, @Param("day") Integer day,
                                              @Param("source") Integer source);
    List<CommonOrder> test();
    /**
     * 统计有效订单数量
     *
     * @param uid
     * @return
     */
    OrderCountVO getOrderCount(@Param("uid") Long uid, @Param("day") Integer day, @Param("listSource") List<Integer> listSource);
    /**
     * 昨日总订单-根据红包类型 自购 邀请 分享
     *
     * @param uid
     * @return
     */
    long countUserOrderToApp(@Param("uid") Long uid, @Param("type") Integer type,
                             @Param("startTime") String startTime, @Param("endTime") String endTime, @Param("day") Integer day,
                             @Param("source") Integer source, @Param("state") Integer state, @Param("stateOrder") Integer stateOrder);
    /**
     * 奖金订单数量
     *
     * @param uid
     * @return
     */
    long countBonusOrderNumber(@Param("uid") Long uid, @Param("type") Integer type, @Param("day") Integer day,
                               @Param("startTime") String startTime, @Param("endTime") String endTime, @Param("source") Integer source);
    /**
     * 奖金统计
     *
     * @param uid
     * @return
     */
    BigDecimal countBonusOrderMoney(@Param("uid") Long uid, @Param("type") Integer type, @Param("day") Integer day,
                                    @Param("startTime") String startTime, @Param("endTime") String endTime, @Param("source") Integer source);
    /**
     * 奖金统计
     *
     * @param uid
     * @return
     */
    Map<String, Object> countBonusOrderMoneyAndNumber(@Param("uid") Long uid, @Param("type") Integer type,
                                                      @Param("day") Integer day, @Param("startTime") String startTime, @Param("endTime") String endTime,
                                                      @Param("source") Integer source);
    int countByOrderNOAndOrderType(@Param("orderNO") String orderNO, @Param("orderType") int orderType);
    /**
     * 根据订单号与订单排序值获取详情
     *
     * @param orderNo   -订单号
     * @param orderBy   -订单排序值
     * @param orderType -订单类型
     * @return
     */
    CommonOrder selectByOrderNoAndOrderTypeAndOrderBy(@Param("orderNo") String orderNo,
                                                      @Param("orderType") int orderType, @Param("orderBy") int orderBy);
    /**
     * 订单列表查询
     *
     * @param start
     * @param count
     * @param uid
     * @param state
     * @param type
     * @param orderState
     * @param startTime
     * @param endTime
     * @return
     */
    List<CommonOrderVO> listQueryByUid(@Param("start") long start, @Param("count") int count, @Param("uid") Long uid,
                                       @Param("state") Integer state, @Param("type") Integer type, @Param("orderState") Integer orderState,
                                       @Param("orderNo") String orderNo, @Param("startTime") String startTime, @Param("endTime") String endTime,
                                       @Param("day") Integer day);
    /**
     * 统计
     */
    long countQueryByUid(@Param("uid") Long uid, @Param("state") Integer state, @Param("type") Integer type,
                         @Param("orderState") Integer orderState, @Param("orderNo") String orderNo,
                         @Param("startTime") String startTime, @Param("endTime") String endTime, @Param("day") Integer day);
    /**
     * 订单列表查询
     *
     * @param start
     * @param count
     * @param uid
     * @param state
     * @param type
     * @param orderState
     * @param startTime
     * @param endTime
     * @return
     */
    List<CommonOrderVO> listQuery(@Param("start") long start, @Param("count") int count,
                                  @Param("keyType") Integer keyType, @Param("key") String key, @Param("state") Integer state,
                                  @Param("type") Integer type, @Param("orderState") Integer orderState, @Param("startTime") String startTime,
                                  @Param("endTime") String endTime, @Param("source") Integer source,
                                  @Param("listShopId") List<Long> listShopId, @Param("listGoodsId") List<Long> listGoodsId,
                                  @Param("minTime") Date minTime, @Param("money") BigDecimal money, @Param("payment") BigDecimal payment, @Param("system") SystemEnum system);
    /**
     * 订单列表查询(不包含子订单)
     *
     * @param start
     * @param count
     * @param keyType
     * @param key
     * @param state
     * @param type
     * @param orderState
     * @param startTime
     * @param endTime
     * @param source
     * @return
     */
    List<CommonOrderVO> listQueryWithNoChild(@Param("start") long start, @Param("count") int count,
                                             @Param("keyType") Integer keyType, @Param("key") String key, @Param("state") Integer state,
                                             @Param("type") Integer type, @Param("orderState") Integer orderState, @Param("startTime") String startTime,
                                             @Param("endTime") String endTime, @Param("source") Integer source, @Param("payment") BigDecimal payment, @Param("system") SystemEnum system);
    /**
     * 统计
     */
    long countQuery(@Param("keyType") Integer keyType, @Param("key") String key, @Param("state") Integer state,
                    @Param("type") Integer type, @Param("orderState") Integer orderState, @Param("startTime") String startTime,
                    @Param("endTime") String endTime, @Param("source") Integer source,
                    @Param("listShopId") List<Long> listShopId, @Param("listGoodsId") List<Long> listGoodsId,
                    @Param("minTime") Date minTime, @Param("money") BigDecimal money, @Param("payment") BigDecimal payment, @Param("system") SystemEnum system);
    long countQueryWithNoChild(@Param("keyType") Integer keyType, @Param("key") String key,
                               @Param("state") Integer state, @Param("type") Integer type, @Param("orderState") Integer orderState,
                               @Param("startTime") String startTime, @Param("endTime") String endTime, @Param("source") Integer source, @Param("payment") BigDecimal payment, @Param("system") SystemEnum system);
    /**
     * 根据来源类型与订单号查询列表
     *
     * @param sourceType
     * @param orderNo
     * @return
     */
    List<CommonOrder> listBySourceTypeAndOrderNo(@Param("sourceType") int sourceType, @Param("orderNo") String orderNo);
    /**
     * 查询券奖励金额以及订单信息
     *
     * @param uid
     * @param state
     * @param orderNo
     * @return
     */
    List<CommonOrderVO> getCouponHongbaoByOrderNo(@Param("uid") Long uid, @Param("hongBaoState") Integer hongBaoState,
                                                  @Param("orderNo") String orderNo);
    /**
     * 查询券奖励金额以及订单信息
     *
     * @param uid
     * @param state
     * @param orderNo
     * @return
     */
    CommonOrderVO getCommonOrderByOrderNo(@Param("uid") Long uid, @Param("orderNo") String orderNo,
                                          @Param("orderState") Integer orderState, @Param("sourceType") Integer sourceType);
    /**
     * 根据来源和交易ID获取订单详情
     *
     * @param sourceType
     * @param tradeId
     * @return
     */
    CommonOrder selectBySourceTypeAndTradeId(@Param("sourceType") int sourceType, @Param("tradeId") String tradeId);
    /**
     * 根据来源和交易ID获取订单列表
     *
     * @param sourceType
     * @param tradeId
     * @return
     */
    List<CommonOrder> listBySourceTypeAndTradeId(@Param("sourceType") int sourceType, @Param("tradeId") String tradeId);
    /**
     * 根据来源和交易ID获取订单列表
     *
     * @param sourceType
     * @param tradeIdList
     * @return
     */
    List<CommonOrder> listBySourceTypeAndTradeIdList(@Param("sourceType") int sourceType,
                                                     @Param("tradeIdList") List<String> tradeIdList);
    /**
     * @param sourceType
     * @param state
     * @param minTime    -最大创建时间
     * @param maxTime    -最小创建时间
     * @return
     */
    List<CommonOrder> listBySourceTypeAndStateAndThirdCrateTime(@Param("sourceType") int sourceType,
                                                                @Param("state") Integer state, @Param("minTime") Long minTime, @Param("maxTime") Long maxTime,
                                                                @Param("start") long start, @Param("count") int count);
    /**
     * 根据订单号查询
     *
     * @param orderNO
     * @return
     */
    List<CommonOrder> getByOrderNo(@Param("uid") Long uid, @Param("orderNo") String orderNo);
    /**
     * 根据订单号查询
     *
     * @param orderNO
     * @return
     */
    List<CommonOrder> getByOrderNoAndSourceType(@Param("uid") Long uid, @Param("orderNo") String orderNo,
                                                @Param("sourceType") int sourceType);
    /**
     * 根据用户ID查询
     *
     * @param uid
     * @param stateList
     * @param start
     * @param count
     * @return
     */
    List<CommonOrder> listByUid(@Param("uid") Long uid, @Param("stateList") List<Integer> stateList, @Param("start") long start, @Param("count") int count);
    /**
     * 查询首笔有效到账订单
     *
     * @param uid
     * @param typeHB   类型: 1自购  2分享 3邀请
     * @param typeDate 日期类型: 3本月 4上月
     * @return
     */
    CommonOrderVO firstValidOrderByUid(@Param("uid") Long uid, @Param("typeHB") Integer typeHB,
                                       @Param("typeDate") Integer typeDate);
    /**
     * 获取首笔分享订单;
     *
     * @param uid
     * @return
     */
    CommonOrder getFirstShareOrderByUid(@Param("uid") Long uid);
    /**
     * 统计订单号到账金额
     *
     * @param uid
     * @return
     */
    BigDecimal getTotalRewardMoneyByOrderNoAndSourceType(@Param("orderNo") String orderNo, @Param("sourceType") Integer sourceType);
    /**
     * 统计24小时有效自购订单
     *
     * @param uid
     * @return
     */
    long count24HValidOrderByUid(@Param("uid") Long uid, @Param("minTime") Date minTime);
    /**
     * 搜索订单
     *
     * @param start
     * @param count
     * @param uid
     * @param list
     * @return
     */
    List<CommonOrderVO> searchOrderByUid(@Param("start") long start, @Param("count") int count, @Param("uid") Long uid,
                                         @Param("list") List<ESOrder> list);
    /**
     * 搜索订单
     *
     * @param start
     * @param count
     * @param uid
     * @param list
     * @return
     */
    long countSearchOrderByUid(@Param("uid") Long uid, @Param("list") List<ESOrder> list);
    /**
     * 查询最小结算时间
     *
     * @return
     */
    List<CommonOrder> getMinSettleTimeAndUid();
    /**
     * 查询用户订单 并订单号分组
     *
     * @param start
     * @param count
     * @param uid
     * @return
     */
    List<CommonOrderVO> getOrderList(@Param("start") long start, @Param("count") int count, @Param("uid") Long uid,
                                     @Param("state") Integer state, @Param("type") Integer type, @Param("orderState") Integer orderState,
                                     @Param("orderNo") String orderNo, @Param("startTime") String startTime, @Param("endTime") String endTime,
                                     @Param("day") Integer day, @Param("listSource") List<Integer> listSource);
    /**
     * 统计用户订单 并订单号分组
     *
     * @param start
     * @param count
     * @param uid
     * @return
     */
    long countOrderList(@Param("uid") Long uid, @Param("state") Integer state, @Param("type") Integer type,
                        @Param("orderState") Integer orderState, @Param("orderNo") String orderNo,
                        @Param("startTime") String startTime, @Param("endTime") String endTime, @Param("day") Integer day,
                        @Param("listSource") List<Integer> listSource);
    /**
     * 统计已结算且付款金额大于1的订单(不区分订单状态)
     *
     * @param uid
     * @param payment
     * @return
     */
    Long countOrderByUidAndSettled(@Param("uid") Long uid, @Param("payment") BigDecimal payment);
    /**
     * 获取最新的淘宝订单号
     *
     * @return
     */
    String getNewestOrderNoByTaoBao();
    /**
     * 根据订单号进行sous
     *
     * @param orderNo
     * @return
     */
    List<CommonOrder> listByOrderNo(@Param("orderNo") String orderNo);
    /**
     * 获取首个订单
     *
     * @param orderNo
     * @return
     */
    CommonOrder getFirstOrder(@Param("uid") Long uid);
    List<CommonOrder> listByGoodsIdAndUidAndMinThirdCreateTime(@Param("goodsId") Long goodsId, @Param("uid") Long uid, @Param("minThirdCreateTime") Date minThirdCreateTime, @Param("start") long start, @Param("count") int count);
    List<CommonOrder> test();
}
fanli/src/main/java/com/yeshi/fanli/dto/pdd/PDDGoodsDetail.java
@@ -6,493 +6,503 @@
import com.google.gson.annotations.SerializedName;
public class PDDGoodsDetail implements Serializable {
    /**
     *
     */
    private static final long serialVersionUID = 1L;
    @SerializedName("goods_id")
    private Long goodsId;// 商品id
    @SerializedName("has_mall_coupon")
    private Boolean hasMallCoupon;// 是否有店铺券
    @SerializedName("mall_coupon_id")
    private Long mallCouponId;// 店铺券id
    @SerializedName("mall_coupon_discount_pct")
    private Integer mallCouponDiscountPct;// 店铺券折扣
    @SerializedName("mall_coupon_min_order_amount")
    private Integer mallCouponMinOrderAmount;// 最小使用金额
    @SerializedName("mall_coupon_max_discount_amount")
    private Integer mallCouponMaxDiscountAmount;// 最大使用金额
    @SerializedName("mall_coupon_total_quantity")
    private Long mallCouponTotalQuantity;// 店铺券总量
    @SerializedName("mall_coupon_remain_quantity")
    private Long mallCouponRemainQuantity;// 店铺券余量
    @SerializedName("mall_coupon_start_time")
    private Long mallCouponStartTime;// 店铺券开始使用时间
    @SerializedName("mall_coupon_end_time")
    private Long mallCouponEndTime;// 店铺券结束使用时间
    @SerializedName("create_at")
    private Long createAt;// 创建时间(unix时间戳)
    @SerializedName("goods_name")
    private String goodsName; // 商品名称
    @SerializedName("goods_desc")
    private String goodsDesc;// 商品描述
    @SerializedName("goods_thumbnail_url")
    private String goodsThumbnailUrl; // 商品缩略图
    @SerializedName("goods_image_url")
    private String goodsImageUrl;// 商品主图
    @SerializedName("goods_gallery_urls")
    private String[] goodsGalleryUrls;// 商品轮播图
    @SerializedName("sold_quantity")
    private Long soldQuantity;// 已售卖件数
    @SerializedName("min_group_price")
    private Long minGroupPrice;// 最小拼团价(单位为分)
    @SerializedName("min_normal_price")
    private Long minNormalPrice;// 最小单买价格(单位为分)
    @SerializedName("mall_name")
    private String mallName; // 店铺名字
    @SerializedName("merchant_type")
    private Integer merchantType; // 铺类型,1-个人,2-企业,3-旗舰店,4-专卖店,5-专营店,6-普通店
    @SerializedName("category_id")
    private Long categoryId; // 商品类目ID,使用pdd.goods.cats.get接口获取
    @SerializedName("category_name")
    private String categoryName;// 商品类目名
    @SerializedName("opt_id")
    private Long optId;// 商品标签ID,使用pdd.goods.opts.get接口获取
    @SerializedName("opt_name")
    private String optName;// 商品标签名
    @SerializedName("opt_ids")
    private Long[] optIds; // 商品标签id
    @SerializedName("cat_ids")
    private Long[] catIds; // 商品类目id
    @SerializedName("mall_cps")
    private Integer mallCps; // 该商品所在店铺是否参与全店推广,0:否,1:是
    @SerializedName("has_coupon")
    private Boolean hasCoupon; // 商品是否有优惠券
                                // true-有,false-没有
    @SerializedName("coupon_min_order_amount")
    private Long couponMinOrderAmount; // 优惠券门槛价格,单位为分
    @SerializedName("coupon_discount")
    private Long couponDiscount;// 优惠券面额,单位为分
    @SerializedName("coupon_total_quantity")
    private Long couponTotalQuantity; // 优惠券总数量
    @SerializedName("coupon_remain_quantity")
    private Long couponRemainQuantity; // 优惠券剩余数量
    @SerializedName("coupon_start_time")
    private Long couponStartTime;// 优惠券生效时间,UNIX时间戳
    @SerializedName("coupon_end_time")
    private Long couponEndTime;// 优惠券失效时间,UNIX时间戳
    @SerializedName("promotion_rate")
    private Long promotionRate;// 佣金比例,千分比
    @SerializedName("goods_eval_score")
    private String goodsEvalScore;// 商品评价分
    @SerializedName("goods_eval_count")
    private Long goodsEvalCount;// 商品评价数量
    @SerializedName("avg_desc")
    private Long avgDesc;// 描述评分
    @SerializedName("avg_lgst")
    private Long avgLgst;// 物流评分
    @SerializedName("avg_serv")
    private Long avgServ;// 服务评分
    @SerializedName("desc_pct")
    private BigDecimal descPct;// 描述分击败同类店铺百分比
    @SerializedName("lgst_pct")
    private BigDecimal lgstPct;// 物流分击败同类店铺百分比
    @SerializedName("serv_pct")
    private BigDecimal servPct;// 服务分击败同类店铺百分比
    @SerializedName("sales_tip")
    private String salesTip;// 模糊销量
    @SerializedName("activity_type")
    private Integer activityType;// 活动类型,0-无活动;1-秒杀;3-限量折扣;12-限时折扣;13-大促活动;14-名品折扣;15-品牌清仓;16-食品超市;17-一元幸运团;18-爱逛街;19-时尚穿搭;20-男人帮;21-9块9;22-竞价活动;23-榜单活动;24-幸运半价购;25-定金预售;26-幸运人气购;27-特色主题活动;28-断码清仓;29-一元话费;30-电器城;31-每日好店;32-品牌卡;101-大促搜索池;102-大促品类分会场;
    @SerializedName("mall_id")
    private Long mallId;//店铺ID
    // mall_id:4217177,cps_sign:null,cat_id:null mall_rate:10
    private Integer state;//状态  1-下线  0-正常
    /**
     *
     */
    private static final long serialVersionUID = 1L;
    public Integer getState() {
        return state;
    }
    public void setState(Integer state) {
        this.state = state;
    }
    @SerializedName("goods_id")
    private Long goodsId;// 商品id
    @SerializedName("has_mall_coupon")
    private Boolean hasMallCoupon;// 是否有店铺券
    @SerializedName("mall_coupon_id")
    private Long mallCouponId;// 店铺券id
    @SerializedName("mall_coupon_discount_pct")
    private Integer mallCouponDiscountPct;// 店铺券折扣
    @SerializedName("mall_coupon_min_order_amount")
    private Integer mallCouponMinOrderAmount;// 最小使用金额
    @SerializedName("mall_coupon_max_discount_amount")
    private Integer mallCouponMaxDiscountAmount;// 最大使用金额
    @SerializedName("mall_coupon_total_quantity")
    private Long mallCouponTotalQuantity;// 店铺券总量
    @SerializedName("mall_coupon_remain_quantity")
    private Long mallCouponRemainQuantity;// 店铺券余量
    @SerializedName("mall_coupon_start_time")
    private Long mallCouponStartTime;// 店铺券开始使用时间
    @SerializedName("mall_coupon_end_time")
    private Long mallCouponEndTime;// 店铺券结束使用时间
    @SerializedName("create_at")
    private Long createAt;// 创建时间(unix时间戳)
    @SerializedName("goods_name")
    private String goodsName; // 商品名称
    @SerializedName("goods_desc")
    private String goodsDesc;// 商品描述
    @SerializedName("goods_thumbnail_url")
    private String goodsThumbnailUrl; // 商品缩略图
    @SerializedName("goods_image_url")
    private String goodsImageUrl;// 商品主图
    @SerializedName("goods_gallery_urls")
    private String[] goodsGalleryUrls;// 商品轮播图
    @SerializedName("sold_quantity")
    private Long soldQuantity;// 已售卖件数
    @SerializedName("min_group_price")
    private Long minGroupPrice;// 最小拼团价(单位为分)
    @SerializedName("min_normal_price")
    private Long minNormalPrice;// 最小单买价格(单位为分)
    @SerializedName("mall_name")
    private String mallName; // 店铺名字
    @SerializedName("merchant_type")
    private Integer merchantType; // 铺类型,1-个人,2-企业,3-旗舰店,4-专卖店,5-专营店,6-普通店
    @SerializedName("category_id")
    private Long categoryId; // 商品类目ID,使用pdd.goods.cats.get接口获取
    @SerializedName("category_name")
    private String categoryName;// 商品类目名
    @SerializedName("opt_id")
    private Long optId;// 商品标签ID,使用pdd.goods.opts.get接口获取
    @SerializedName("opt_name")
    private String optName;// 商品标签名
    @SerializedName("opt_ids")
    private Long[] optIds; // 商品标签id
    @SerializedName("cat_ids")
    private Long[] catIds; // 商品类目id
    @SerializedName("mall_cps")
    private Integer mallCps; // 该商品所在店铺是否参与全店推广,0:否,1:是
    @SerializedName("has_coupon")
    private Boolean hasCoupon; // 商品是否有优惠券
    // true-有,false-没有
    @SerializedName("coupon_min_order_amount")
    private Long couponMinOrderAmount; // 优惠券门槛价格,单位为分
    @SerializedName("coupon_discount")
    private Long couponDiscount;// 优惠券面额,单位为分
    @SerializedName("coupon_total_quantity")
    private Long couponTotalQuantity; // 优惠券总数量
    @SerializedName("coupon_remain_quantity")
    private Long couponRemainQuantity; // 优惠券剩余数量
    @SerializedName("coupon_start_time")
    private Long couponStartTime;// 优惠券生效时间,UNIX时间戳
    @SerializedName("coupon_end_time")
    private Long couponEndTime;// 优惠券失效时间,UNIX时间戳
    @SerializedName("promotion_rate")
    private Long promotionRate;// 佣金比例,千分比
    @SerializedName("goods_eval_score")
    private String goodsEvalScore;// 商品评价分
    @SerializedName("goods_eval_count")
    private Long goodsEvalCount;// 商品评价数量
    @SerializedName("avg_desc")
    private Long avgDesc;// 描述评分
    @SerializedName("avg_lgst")
    private Long avgLgst;// 物流评分
    @SerializedName("avg_serv")
    private Long avgServ;// 服务评分
    @SerializedName("desc_pct")
    private BigDecimal descPct;// 描述分击败同类店铺百分比
    @SerializedName("lgst_pct")
    private BigDecimal lgstPct;// 物流分击败同类店铺百分比
    @SerializedName("serv_pct")
    private BigDecimal servPct;// 服务分击败同类店铺百分比
    @SerializedName("sales_tip")
    private String salesTip;// 模糊销量
    @SerializedName("activity_type")
    private Integer activityType;// 活动类型,0-无活动;1-秒杀;3-限量折扣;12-限时折扣;13-大促活动;14-名品折扣;15-品牌清仓;16-食品超市;17-一元幸运团;18-爱逛街;19-时尚穿搭;20-男人帮;21-9块9;22-竞价活动;23-榜单活动;24-幸运半价购;25-定金预售;26-幸运人气购;27-特色主题活动;28-断码清仓;29-一元话费;30-电器城;31-每日好店;32-品牌卡;101-大促搜索池;102-大促品类分会场;
    @SerializedName("mall_id")
    private Long mallId;//店铺ID
    // mall_id:4217177,cps_sign:null,cat_id:null mall_rate:10
    @SerializedName("predict_promotion_rate")
    private BigDecimal predictPromotionRate;//比价的佣金比
    private Integer state;//状态  1-下线  0-正常
    public Long getMallId() {
        return mallId;
    }
    public void setMallId(Long mallId) {
        this.mallId = mallId;
    }
    public BigDecimal getPredictPromotionRate() {
        return predictPromotionRate;
    }
    public Long getGoodsId() {
        return goodsId;
    }
    public void setPredictPromotionRate(BigDecimal predictPromotionRate) {
        this.predictPromotionRate = predictPromotionRate;
    }
    public void setGoodsId(Long goodsId) {
        this.goodsId = goodsId;
    }
    public Integer getState() {
        return state;
    }
    public Boolean getHasMallCoupon() {
        return hasMallCoupon;
    }
    public void setState(Integer state) {
        this.state = state;
    }
    public void setHasMallCoupon(Boolean hasMallCoupon) {
        this.hasMallCoupon = hasMallCoupon;
    }
    public Long getMallId() {
        return mallId;
    }
    public Long getMallCouponId() {
        return mallCouponId;
    }
    public void setMallId(Long mallId) {
        this.mallId = mallId;
    }
    public void setMallCouponId(Long mallCouponId) {
        this.mallCouponId = mallCouponId;
    }
    public Long getGoodsId() {
        return goodsId;
    }
    public Integer getMallCouponDiscountPct() {
        return mallCouponDiscountPct;
    }
    public void setGoodsId(Long goodsId) {
        this.goodsId = goodsId;
    }
    public void setMallCouponDiscountPct(Integer mallCouponDiscountPct) {
        this.mallCouponDiscountPct = mallCouponDiscountPct;
    }
    public Boolean getHasMallCoupon() {
        return hasMallCoupon;
    }
    public Integer getMallCouponMinOrderAmount() {
        return mallCouponMinOrderAmount;
    }
    public void setHasMallCoupon(Boolean hasMallCoupon) {
        this.hasMallCoupon = hasMallCoupon;
    }
    public void setMallCouponMinOrderAmount(Integer mallCouponMinOrderAmount) {
        this.mallCouponMinOrderAmount = mallCouponMinOrderAmount;
    }
    public Long getMallCouponId() {
        return mallCouponId;
    }
    public Integer getMallCouponMaxDiscountAmount() {
        return mallCouponMaxDiscountAmount;
    }
    public void setMallCouponId(Long mallCouponId) {
        this.mallCouponId = mallCouponId;
    }
    public void setMallCouponMaxDiscountAmount(Integer mallCouponMaxDiscountAmount) {
        this.mallCouponMaxDiscountAmount = mallCouponMaxDiscountAmount;
    }
    public Integer getMallCouponDiscountPct() {
        return mallCouponDiscountPct;
    }
    public Long getMallCouponTotalQuantity() {
        return mallCouponTotalQuantity;
    }
    public void setMallCouponDiscountPct(Integer mallCouponDiscountPct) {
        this.mallCouponDiscountPct = mallCouponDiscountPct;
    }
    public void setMallCouponTotalQuantity(Long mallCouponTotalQuantity) {
        this.mallCouponTotalQuantity = mallCouponTotalQuantity;
    }
    public Integer getMallCouponMinOrderAmount() {
        return mallCouponMinOrderAmount;
    }
    public Long getMallCouponRemainQuantity() {
        return mallCouponRemainQuantity;
    }
    public void setMallCouponMinOrderAmount(Integer mallCouponMinOrderAmount) {
        this.mallCouponMinOrderAmount = mallCouponMinOrderAmount;
    }
    public void setMallCouponRemainQuantity(Long mallCouponRemainQuantity) {
        this.mallCouponRemainQuantity = mallCouponRemainQuantity;
    }
    public Integer getMallCouponMaxDiscountAmount() {
        return mallCouponMaxDiscountAmount;
    }
    public Long getMallCouponStartTime() {
        return mallCouponStartTime;
    }
    public void setMallCouponMaxDiscountAmount(Integer mallCouponMaxDiscountAmount) {
        this.mallCouponMaxDiscountAmount = mallCouponMaxDiscountAmount;
    }
    public void setMallCouponStartTime(Long mallCouponStartTime) {
        this.mallCouponStartTime = mallCouponStartTime;
    }
    public Long getMallCouponTotalQuantity() {
        return mallCouponTotalQuantity;
    }
    public Long getMallCouponEndTime() {
        return mallCouponEndTime;
    }
    public void setMallCouponTotalQuantity(Long mallCouponTotalQuantity) {
        this.mallCouponTotalQuantity = mallCouponTotalQuantity;
    }
    public void setMallCouponEndTime(Long mallCouponEndTime) {
        this.mallCouponEndTime = mallCouponEndTime;
    }
    public Long getMallCouponRemainQuantity() {
        return mallCouponRemainQuantity;
    }
    public Long getCreateAt() {
        return createAt;
    }
    public void setMallCouponRemainQuantity(Long mallCouponRemainQuantity) {
        this.mallCouponRemainQuantity = mallCouponRemainQuantity;
    }
    public void setCreateAt(Long createAt) {
        this.createAt = createAt;
    }
    public Long getMallCouponStartTime() {
        return mallCouponStartTime;
    }
    public String getGoodsName() {
        return goodsName;
    }
    public void setMallCouponStartTime(Long mallCouponStartTime) {
        this.mallCouponStartTime = mallCouponStartTime;
    }
    public void setGoodsName(String goodsName) {
        this.goodsName = goodsName;
    }
    public Long getMallCouponEndTime() {
        return mallCouponEndTime;
    }
    public String getGoodsDesc() {
        return goodsDesc;
    }
    public void setMallCouponEndTime(Long mallCouponEndTime) {
        this.mallCouponEndTime = mallCouponEndTime;
    }
    public void setGoodsDesc(String goodsDesc) {
        this.goodsDesc = goodsDesc;
    }
    public Long getCreateAt() {
        return createAt;
    }
    public void setCreateAt(Long createAt) {
        this.createAt = createAt;
    }
    public String getGoodsName() {
        return goodsName;
    }
    public void setGoodsName(String goodsName) {
        this.goodsName = goodsName;
    }
    public String getGoodsDesc() {
        return goodsDesc;
    }
    public void setGoodsDesc(String goodsDesc) {
        this.goodsDesc = goodsDesc;
    }
    public String getGoodsThumbnailUrl() {
        return goodsThumbnailUrl;
    }
    public String getGoodsThumbnailUrl() {
        return goodsThumbnailUrl;
    }
    public void setGoodsThumbnailUrl(String goodsThumbnailUrl) {
        this.goodsThumbnailUrl = goodsThumbnailUrl;
    }
    public void setGoodsThumbnailUrl(String goodsThumbnailUrl) {
        this.goodsThumbnailUrl = goodsThumbnailUrl;
    }
    public String getGoodsImageUrl() {
        return goodsImageUrl;
    }
    public String getGoodsImageUrl() {
        return goodsImageUrl;
    }
    public void setGoodsImageUrl(String goodsImageUrl) {
        this.goodsImageUrl = goodsImageUrl;
    }
    public void setGoodsImageUrl(String goodsImageUrl) {
        this.goodsImageUrl = goodsImageUrl;
    }
    public String[] getGoodsGalleryUrls() {
        return goodsGalleryUrls;
    }
    public String[] getGoodsGalleryUrls() {
        return goodsGalleryUrls;
    }
    public void setGoodsGalleryUrls(String[] goodsGalleryUrls) {
        this.goodsGalleryUrls = goodsGalleryUrls;
    }
    public void setGoodsGalleryUrls(String[] goodsGalleryUrls) {
        this.goodsGalleryUrls = goodsGalleryUrls;
    }
    public Long getSoldQuantity() {
        return soldQuantity;
    }
    public Long getSoldQuantity() {
        return soldQuantity;
    }
    public void setSoldQuantity(Long soldQuantity) {
        this.soldQuantity = soldQuantity;
    }
    public void setSoldQuantity(Long soldQuantity) {
        this.soldQuantity = soldQuantity;
    }
    public Long getMinGroupPrice() {
        return minGroupPrice;
    }
    public Long getMinGroupPrice() {
        return minGroupPrice;
    }
    public void setMinGroupPrice(Long minGroupPrice) {
        this.minGroupPrice = minGroupPrice;
    }
    public void setMinGroupPrice(Long minGroupPrice) {
        this.minGroupPrice = minGroupPrice;
    }
    public Long getMinNormalPrice() {
        return minNormalPrice;
    }
    public Long getMinNormalPrice() {
        return minNormalPrice;
    }
    public void setMinNormalPrice(Long minNormalPrice) {
        this.minNormalPrice = minNormalPrice;
    }
    public void setMinNormalPrice(Long minNormalPrice) {
        this.minNormalPrice = minNormalPrice;
    }
    public String getMallName() {
        return mallName;
    }
    public String getMallName() {
        return mallName;
    }
    public void setMallName(String mallName) {
        this.mallName = mallName;
    }
    public void setMallName(String mallName) {
        this.mallName = mallName;
    }
    public Integer getMerchantType() {
        return merchantType;
    }
    public Integer getMerchantType() {
        return merchantType;
    }
    public void setMerchantType(Integer merchantType) {
        this.merchantType = merchantType;
    }
    public void setMerchantType(Integer merchantType) {
        this.merchantType = merchantType;
    }
    public Long getCategoryId() {
        return categoryId;
    }
    public Long getCategoryId() {
        return categoryId;
    }
    public void setCategoryId(Long categoryId) {
        this.categoryId = categoryId;
    }
    public void setCategoryId(Long categoryId) {
        this.categoryId = categoryId;
    }
    public String getCategoryName() {
        return categoryName;
    }
    public String getCategoryName() {
        return categoryName;
    }
    public void setCategoryName(String categoryName) {
        this.categoryName = categoryName;
    }
    public void setCategoryName(String categoryName) {
        this.categoryName = categoryName;
    }
    public Long getOptId() {
        return optId;
    }
    public Long getOptId() {
        return optId;
    }
    public void setOptId(Long optId) {
        this.optId = optId;
    }
    public void setOptId(Long optId) {
        this.optId = optId;
    }
    public String getOptName() {
        return optName;
    }
    public String getOptName() {
        return optName;
    }
    public void setOptName(String optName) {
        this.optName = optName;
    }
    public void setOptName(String optName) {
        this.optName = optName;
    }
    public Long[] getOptIds() {
        return optIds;
    }
    public Long[] getOptIds() {
        return optIds;
    }
    public void setOptIds(Long[] optIds) {
        this.optIds = optIds;
    }
    public void setOptIds(Long[] optIds) {
        this.optIds = optIds;
    }
    public Long[] getCatIds() {
        return catIds;
    }
    public Long[] getCatIds() {
        return catIds;
    }
    public void setCatIds(Long[] catIds) {
        this.catIds = catIds;
    }
    public void setCatIds(Long[] catIds) {
        this.catIds = catIds;
    }
    public Integer getMallCps() {
        return mallCps;
    }
    public Integer getMallCps() {
        return mallCps;
    }
    public void setMallCps(Integer mallCps) {
        this.mallCps = mallCps;
    }
    public void setMallCps(Integer mallCps) {
        this.mallCps = mallCps;
    }
    public Boolean getHasCoupon() {
        return hasCoupon;
    }
    public Boolean getHasCoupon() {
        return hasCoupon;
    }
    public void setHasCoupon(Boolean hasCoupon) {
        this.hasCoupon = hasCoupon;
    }
    public void setHasCoupon(Boolean hasCoupon) {
        this.hasCoupon = hasCoupon;
    }
    public Long getCouponMinOrderAmount() {
        return couponMinOrderAmount;
    }
    public Long getCouponMinOrderAmount() {
        return couponMinOrderAmount;
    }
    public void setCouponMinOrderAmount(Long couponMinOrderAmount) {
        this.couponMinOrderAmount = couponMinOrderAmount;
    }
    public void setCouponMinOrderAmount(Long couponMinOrderAmount) {
        this.couponMinOrderAmount = couponMinOrderAmount;
    }
    public Long getCouponDiscount() {
        return couponDiscount;
    }
    public Long getCouponDiscount() {
        return couponDiscount;
    }
    public void setCouponDiscount(Long couponDiscount) {
        this.couponDiscount = couponDiscount;
    }
    public void setCouponDiscount(Long couponDiscount) {
        this.couponDiscount = couponDiscount;
    }
    public Long getCouponTotalQuantity() {
        return couponTotalQuantity;
    }
    public Long getCouponTotalQuantity() {
        return couponTotalQuantity;
    }
    public void setCouponTotalQuantity(Long couponTotalQuantity) {
        this.couponTotalQuantity = couponTotalQuantity;
    }
    public void setCouponTotalQuantity(Long couponTotalQuantity) {
        this.couponTotalQuantity = couponTotalQuantity;
    }
    public Long getCouponRemainQuantity() {
        return couponRemainQuantity;
    }
    public Long getCouponRemainQuantity() {
        return couponRemainQuantity;
    }
    public void setCouponRemainQuantity(Long couponRemainQuantity) {
        this.couponRemainQuantity = couponRemainQuantity;
    }
    public void setCouponRemainQuantity(Long couponRemainQuantity) {
        this.couponRemainQuantity = couponRemainQuantity;
    }
    public Long getCouponStartTime() {
        return couponStartTime;
    }
    public Long getCouponStartTime() {
        return couponStartTime;
    }
    public void setCouponStartTime(Long couponStartTime) {
        this.couponStartTime = couponStartTime;
    }
    public void setCouponStartTime(Long couponStartTime) {
        this.couponStartTime = couponStartTime;
    }
    public Long getCouponEndTime() {
        return couponEndTime;
    }
    public Long getCouponEndTime() {
        return couponEndTime;
    }
    public void setCouponEndTime(Long couponEndTime) {
        this.couponEndTime = couponEndTime;
    }
    public void setCouponEndTime(Long couponEndTime) {
        this.couponEndTime = couponEndTime;
    }
    public Long getPromotionRate() {
        return promotionRate;
    }
    public Long getPromotionRate() {
        return promotionRate;
    }
    public void setPromotionRate(Long promotionRate) {
        this.promotionRate = promotionRate;
    }
    public void setPromotionRate(Long promotionRate) {
        this.promotionRate = promotionRate;
    }
    public String getGoodsEvalScore() {
        return goodsEvalScore;
    }
    public String getGoodsEvalScore() {
        return goodsEvalScore;
    }
    public void setGoodsEvalScore(String goodsEvalScore) {
        this.goodsEvalScore = goodsEvalScore;
    }
    public void setGoodsEvalScore(String goodsEvalScore) {
        this.goodsEvalScore = goodsEvalScore;
    }
    public Long getGoodsEvalCount() {
        return goodsEvalCount;
    }
    public Long getGoodsEvalCount() {
        return goodsEvalCount;
    }
    public void setGoodsEvalCount(Long goodsEvalCount) {
        this.goodsEvalCount = goodsEvalCount;
    }
    public void setGoodsEvalCount(Long goodsEvalCount) {
        this.goodsEvalCount = goodsEvalCount;
    }
    public Long getAvgDesc() {
        return avgDesc;
    }
    public Long getAvgDesc() {
        return avgDesc;
    }
    public void setAvgDesc(Long avgDesc) {
        this.avgDesc = avgDesc;
    }
    public void setAvgDesc(Long avgDesc) {
        this.avgDesc = avgDesc;
    }
    public Long getAvgLgst() {
        return avgLgst;
    }
    public Long getAvgLgst() {
        return avgLgst;
    }
    public void setAvgLgst(Long avgLgst) {
        this.avgLgst = avgLgst;
    }
    public void setAvgLgst(Long avgLgst) {
        this.avgLgst = avgLgst;
    }
    public Long getAvgServ() {
        return avgServ;
    }
    public Long getAvgServ() {
        return avgServ;
    }
    public void setAvgServ(Long avgServ) {
        this.avgServ = avgServ;
    }
    public void setAvgServ(Long avgServ) {
        this.avgServ = avgServ;
    }
    public BigDecimal getDescPct() {
        return descPct;
    }
    public BigDecimal getDescPct() {
        return descPct;
    }
    public void setDescPct(BigDecimal descPct) {
        this.descPct = descPct;
    }
    public void setDescPct(BigDecimal descPct) {
        this.descPct = descPct;
    }
    public BigDecimal getLgstPct() {
        return lgstPct;
    }
    public BigDecimal getLgstPct() {
        return lgstPct;
    }
    public void setLgstPct(BigDecimal lgstPct) {
        this.lgstPct = lgstPct;
    }
    public void setLgstPct(BigDecimal lgstPct) {
        this.lgstPct = lgstPct;
    }
    public BigDecimal getServPct() {
        return servPct;
    }
    public BigDecimal getServPct() {
        return servPct;
    }
    public void setServPct(BigDecimal servPct) {
        this.servPct = servPct;
    }
    public void setServPct(BigDecimal servPct) {
        this.servPct = servPct;
    }
    public String getSalesTip() {
        return salesTip;
    }
    public String getSalesTip() {
        return salesTip;
    }
    public void setSalesTip(String salesTip) {
        this.salesTip = salesTip;
    }
    public void setSalesTip(String salesTip) {
        this.salesTip = salesTip;
    }
    public Integer getActivityType() {
        return activityType;
    }
    public Integer getActivityType() {
        return activityType;
    }
    public void setActivityType(Integer activityType) {
        this.activityType = activityType;
    }
    public void setActivityType(Integer activityType) {
        this.activityType = activityType;
    }
}
fanli/src/main/java/com/yeshi/fanli/entity/SystemEnum.java
@@ -9,17 +9,22 @@
public enum SystemEnum {
    blks("com.yeshi.ec.rebate", "com.xyj.ec.fanli-ios", new String[]{}, new SystemFunction[]{
            SystemFunction.bindPhone, SystemFunction.threeSale, SystemFunction.cloudOrder, SystemFunction.godenCorn, SystemFunction.redPack,SystemFunction.faQuan,SystemFunction.fanli,SystemFunction.vip
    }, 1, "板栗快省"),
    flq("com.fanliunion.android", "com.xyj.ec.flq-ios", new String[]{}, new SystemFunction[]{SystemFunction.faQuan,SystemFunction.fanli}, 11, "返利联盟"),
    yhqjx("com.youhuiquanjx.android","com.youhuiquanjx.ios",new String[]{}, new SystemFunction[]{SystemFunction.faQuan}, 12, "优惠券精选");
    }, 1, "板栗快省","板栗快省"),
    flq("com.fanliunion.android", "com.xyj.ec.flq-ios", new String[]{}, new SystemFunction[]{SystemFunction.faQuan,SystemFunction.fanli}, 11, "返利联盟","淘拼团"),
    yhqjx("com.youhuiquan.android","com.youhuiquanjx.ios",new String[]{}, new SystemFunction[]{SystemFunction.faQuan}, 12, "优惠券精选","淘拼团");
    private String packageName;
    private String bundleId;
    private int systemId;
    private String name;
    private String[] wxxcxAppIds;
    private Set<SystemFunction> functionSet;
    private String smsAlias;
    private SystemEnum(String packageName, String bundleId, String[] wxxcxAppIds, SystemFunction[] functions, int systemId, String name) {
    public String getSmsAlias() {
        return smsAlias;
    }
    private SystemEnum(String packageName, String bundleId, String[] wxxcxAppIds, SystemFunction[] functions, int systemId, String name, String smsAlias) {
        this.bundleId = bundleId;
        this.name = name;
        this.packageName = packageName;
@@ -30,6 +35,7 @@
            for (SystemFunction f : functions)
                set.add(f);
        this.functionSet = set;
        this.smsAlias=smsAlias;
    }
    public Set<SystemFunction> getFunctionSet() {
fanli/src/main/java/com/yeshi/fanli/entity/bus/user/HongBaoV2.java
@@ -25,6 +25,8 @@
    public final static int STATE_KELINGQU = 2;
    public final static int STATE_YILINGQU = 3;
    public final static int STATE_SHIXIAO = 4;
    public final static int STATE_LINGQUING = 5;//领取中,处于2和3之间
    //TODO 中间状态待使用
    // 5-部分失效(返回客户端显示用,不用作逻辑处理)
    public final static int STATE_BUFENSHIXIAO = 5;
fanli/src/main/java/com/yeshi/fanli/job/goods/HDKGoodsJob.java
@@ -54,7 +54,6 @@
                            e.printStackTrace();
                        }
                    }
            } else {
                minId = null;
            }
fanli/src/main/java/com/yeshi/fanli/job/order/OrderTeamIncomeJob.java
@@ -23,13 +23,6 @@
//团队收益
@Component
public class OrderTeamIncomeJob {
    @Resource
    private TeamDividentsManager teamDividentsManager;
    @Resource
    private TeamDividentsSourceUserService teamDividentsSourceUserService;
    @Resource
    private OrderProcessService orderProcessService;
fanli/src/main/java/com/yeshi/fanli/log/LogHelper.java
@@ -15,245 +15,251 @@
import org.yeshi.utils.TimeUtil;
public class LogHelper {
    // log
    private static Logger userLogger = Logger.getLogger("userInfoLog");
    // log
    private static Logger userLogger = Logger.getLogger("userInfoLog");
    private static Logger orderLogger = Logger.getLogger("orderLog");
    private static Logger orderLogger = Logger.getLogger("orderLog");
    private static Logger userOrderLogger = Logger.getLogger("userOrderLog");
    private static Logger userOrderLogger = Logger.getLogger("userOrderLog");
    private static Logger testLogger = Logger.getLogger("testLog");
    private static Logger testLogger = Logger.getLogger("testLog");
    private static Logger errorLogger = Logger.getLogger("errorLog");
    private static Logger errorLogger = Logger.getLogger("errorLog");
    private static Logger httpLogger = Logger.getLogger("httpLog");
    private static Logger httpLogger = Logger.getLogger("httpLog");
    private static Logger taoBaoLinkLog = Logger.getLogger("taoBaoLinkLog");
    private static Logger taoBaoLinkLog = Logger.getLogger("taoBaoLinkLog");
    private static Logger shareGoodsLogger = Logger.getLogger("shareGoodsLog");
    private static Logger shareGoodsLogger = Logger.getLogger("shareGoodsLog");
    private static Logger loginLogger = Logger.getLogger("loginLog");
    private static Logger loginLogger = Logger.getLogger("loginLog");
    private static Logger smsLogger = Logger.getLogger("smsLog");
    private static Logger smsLogger = Logger.getLogger("smsLog");
    private static Logger requestLogger = Logger.getLogger("requestLog");
    private static Logger requestLogger = Logger.getLogger("requestLog");
    private static Logger requestTimeLogger = Logger.getLogger("requestTimeLog");
    private static Logger requestTimeLogger = Logger.getLogger("requestTimeLog");
    private static Logger jobLogger = Logger.getLogger("jobLog");
    private static Logger jobLogger = Logger.getLogger("jobLog");
    private static Logger mqLogger = Logger.getLogger("mqLog");
    private static Logger vipInfoLogger = Logger.getLogger("vipInfoLog");
    private static Logger userProtocolListenLog = Logger.getLogger("userProtocolListenLog");
    private static Logger teamLogger = Logger.getLogger("teamLog");
    private static Logger cloudLogger = Logger.getLogger("cloudLog");
    public static void userProtocolListen(Object obj) {
        userProtocolListenLog.info(obj);
    }
    private static Logger mqLogger = Logger.getLogger("mqLog");
    public static void userInfo(Object obj) {
        userLogger.info(obj);
    }
    private static Logger vipInfoLogger = Logger.getLogger("vipInfoLog");
    public static void userErrorInfo(Object obj) {
        userLogger.error(obj);
    }
    private static Logger userProtocolListenLog = Logger.getLogger("userProtocolListenLog");
    public static void orderInfo(Object obj) {
        orderLogger.info(obj);
    }
    private static Logger teamLogger = Logger.getLogger("teamLog");
    public static void orderErrorInfo(Object obj) {
        orderLogger.error(obj);
    }
    public static void userOrder(Object obj) {
        userOrderLogger.info(obj);
    }
    private static Logger cloudLogger = Logger.getLogger("cloudLog");
    public static void test(Object obj) {
        testLogger.info(obj);
    }
    private static Logger pushHWLog = Logger.getLogger("pushHWLog");
    public static void error(Object obj) {
        errorLogger.info(obj);
    }
    public static void taoBaoLinkError(Object obj) {
        taoBaoLinkLog.info(obj);
    }
    public static void userProtocolListen(Object obj) {
        userProtocolListenLog.info(obj);
    }
    public static void shareGoods(Object obj) {
        shareGoodsLogger.info(obj);
    }
    public static void userInfo(Object obj) {
        userLogger.info(obj);
    }
    public static void job(Object obj) {
        jobLogger.info(obj);
    }
    public static void userErrorInfo(Object obj) {
        userLogger.error(obj);
    }
    public static void mqError(String errorMsg, String topic, String tag, Object data) {
        String error = errorMsg + "\ntopic:" + topic + "\ntag:" + tag + "\nbody:" + data;
        mqLogger.error(error);
    }
    public static void mqInfo(String extraInfo,String msgId, String topic, String tag, Object data) {
        String info = extraInfo+"\nmsgId:"+msgId + "\ntopic:" + topic + "\ntag:" + tag + "\nbody:" + data;
        mqLogger.info(info);
    }
    public static void orderInfo(Object obj) {
        orderLogger.info(obj);
    }
    public static void vipInfo(Object obj) {
        vipInfoLogger.info(obj);
    }
    public static void orderErrorInfo(Object obj) {
        orderLogger.error(obj);
    }
    public static void cloudInfo(Object info) {
        if (info != null)
            cloudLogger.info(info);
    }
    /**
     * 登录信息
     *
     * @param obj
     */
    public static void lgoinInfo(Object obj) {
        loginLogger.info(obj);
    }
    public static void userOrder(Object obj) {
        userOrderLogger.info(obj);
    }
    public static void errorDetailInfo(Throwable e) {
        e.printStackTrace();
        String date = TimeUtil.getGernalTime(System.currentTimeMillis(), "yyyy_MM_dd");
        String os = System.getProperty("os.name");
        String filePath = String.format("/usr/local/tomcat8/logs/error_detail_%s.log", date);
        if (os.toLowerCase().startsWith("win")) {
            filePath = String.format("C:/logs/error_detail_%s.log", date);
        } else
            filePath = String.format("/usr/local/tomcat8/logs/error_detail_%s.log", date);
    public static void test(Object obj) {
        testLogger.info(obj);
    }
        OutputStream out = null;
    public static void error(Object obj) {
        errorLogger.info(obj);
    }
        try {
            out = new FileOutputStream(new File(filePath), true);
            PrintStream ps = new PrintStream(out);
            ps.print(TimeUtil.getGernalTime(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss"));
            ps.print("\n");
            e.printStackTrace(ps);
            ps.flush();
            ps.close();
        } catch (Exception ee) {
    public static void taoBaoLinkError(Object obj) {
        taoBaoLinkLog.info(obj);
    }
        } finally {
            try {
                out.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }
    public static void shareGoods(Object obj) {
        shareGoodsLogger.info(obj);
    }
    public static void errorDetailInfo(Throwable e, String params, String url) {
        e.printStackTrace();
        String date = TimeUtil.getGernalTime(System.currentTimeMillis(), "yyyy_MM_dd");
        String os = System.getProperty("os.name");
        String filePath = String.format("/usr/local/tomcat8/logs/error_detail_%s.log", date);
        if (os.toLowerCase().startsWith("win")) {
            filePath = String.format("C:/logs/error_detail_%s.log", date);
        } else
            filePath = String.format("/usr/local/tomcat8/logs/error_detail_%s.log", date);
        OutputStream out = null;
        try {
            out = new FileOutputStream(new File(filePath), true);
            PrintStream ps = new PrintStream(out);
            ps.print(TimeUtil.getGernalTime(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss"));
            ps.print("\n");
            ps.print("链接:" + url);
            ps.print("\n");
            ps.print("参数:" + params);
            ps.print("\n");
            e.printStackTrace(ps);
            ps.flush();
            ps.close();
        } catch (Exception e1) {
    public static void job(Object obj) {
        jobLogger.info(obj);
    }
        } finally {
            try {
                out.close();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    }
    public static void pushHW(Object obj) {
        pushHWLog.info(obj);
    }
    /**
     * 请求日志
     *
     * @param request
     */
    public static void requestInfo(String url, Map<String, Object> map) {
        try {
            Iterator<String> its = map.keySet().iterator();
            List<String> list = new ArrayList<>();
            while (its.hasNext()) {
                String key = its.next();
                Object value = map.get(key);
                Object[] values = (Object[]) value;
                list.add(key + "=" + values[0].toString());
            }
            String paramsStr = "";
            for (String param : list)
                paramsStr += param + "&";
            if (paramsStr.endsWith("&"))
                paramsStr = paramsStr.substring(0, paramsStr.length() - 1);
            requestLogger.info(String.format("%s#####%s", url, paramsStr));
        } catch (Exception e) {
    public static void mqError(String errorMsg, String topic, String tag, Object data) {
        String error = errorMsg + "\ntopic:" + topic + "\ntag:" + tag + "\nbody:" + data;
        mqLogger.error(error);
    }
        }
    }
    public static void mqInfo(String extraInfo, String msgId, String topic, String tag, Object data) {
        String info = extraInfo + "\nmsgId:" + msgId + "\ntopic:" + topic + "\ntag:" + tag + "\nbody:" + data;
        mqLogger.info(info);
    }
    public static void httpInfo(String url, String params, String response) {
        String msg = url + "\n" + params + "\n" + response;
        httpLogger.info(msg);
    }
    public static void vipInfo(Object obj) {
        vipInfoLogger.info(obj);
    }
    public static void smsInfo(String info) {
        if (info != null)
            smsLogger.info(info);
    }
    public static void cloudInfo(Object info) {
        if (info != null)
            cloudLogger.info(info);
    }
    public static void teamInfo(String info) {
        if (info != null)
            teamLogger.info(info);
    }
    public static void requestTime(String url, Map<String, Object> params, long time) {
        String paramsStr = "";
        try {
            Iterator<String> its = params.keySet().iterator();
            List<String> list = new ArrayList<>();
            while (its.hasNext()) {
                String key = its.next();
                Object value = params.get(key);
                Object[] values = (Object[]) value;
                list.add(key + "=" + values[0].toString());
            }
            for (String param : list)
                paramsStr += param + "&";
            if (paramsStr.endsWith("&"))
                paramsStr = paramsStr.substring(0, paramsStr.length() - 1);
        } catch (Exception e) {
    /**
     * 登录信息
     *
     * @param obj
     */
    public static void lgoinInfo(Object obj) {
        loginLogger.info(obj);
    }
        }
        String content = String.format("链接:%s  参数:%s  响应时间:%s", url, paramsStr, time + "");
        requestTimeLogger.info(content);
    }
    public static void errorDetailInfo(Throwable e) {
        e.printStackTrace();
        String date = TimeUtil.getGernalTime(System.currentTimeMillis(), "yyyy_MM_dd");
        String os = System.getProperty("os.name");
        String filePath = String.format("/usr/local/tomcat8/logs/error_detail_%s.log", date);
        if (os.toLowerCase().startsWith("win")) {
            filePath = String.format("C:/logs/error_detail_%s.log", date);
        } else
            filePath = String.format("/usr/local/tomcat8/logs/error_detail_%s.log", date);
        OutputStream out = null;
        try {
            out = new FileOutputStream(new File(filePath), true);
            PrintStream ps = new PrintStream(out);
            ps.print(TimeUtil.getGernalTime(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss"));
            ps.print("\n");
            e.printStackTrace(ps);
            ps.flush();
            ps.close();
        } catch (Exception ee) {
        } finally {
            try {
                out.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }
    public static void errorDetailInfo(Throwable e, String params, String url) {
        e.printStackTrace();
        String date = TimeUtil.getGernalTime(System.currentTimeMillis(), "yyyy_MM_dd");
        String os = System.getProperty("os.name");
        String filePath = String.format("/usr/local/tomcat8/logs/error_detail_%s.log", date);
        if (os.toLowerCase().startsWith("win")) {
            filePath = String.format("C:/logs/error_detail_%s.log", date);
        } else
            filePath = String.format("/usr/local/tomcat8/logs/error_detail_%s.log", date);
        OutputStream out = null;
        try {
            out = new FileOutputStream(new File(filePath), true);
            PrintStream ps = new PrintStream(out);
            ps.print(TimeUtil.getGernalTime(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss"));
            ps.print("\n");
            ps.print("链接:" + url);
            ps.print("\n");
            ps.print("参数:" + params);
            ps.print("\n");
            e.printStackTrace(ps);
            ps.flush();
            ps.close();
        } catch (Exception e1) {
        } finally {
            try {
                out.close();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    }
    /**
     * 请求日志
     *
     * @param request
     */
    public static void requestInfo(String url, Map<String, Object> map) {
        try {
            Iterator<String> its = map.keySet().iterator();
            List<String> list = new ArrayList<>();
            while (its.hasNext()) {
                String key = its.next();
                Object value = map.get(key);
                Object[] values = (Object[]) value;
                list.add(key + "=" + values[0].toString());
            }
            String paramsStr = "";
            for (String param : list)
                paramsStr += param + "&";
            if (paramsStr.endsWith("&"))
                paramsStr = paramsStr.substring(0, paramsStr.length() - 1);
            requestLogger.info(String.format("%s#####%s", url, paramsStr));
        } catch (Exception e) {
        }
    }
    public static void httpInfo(String url, String params, String response) {
        String msg = url + "\n" + params + "\n" + response;
        httpLogger.info(msg);
    }
    public static void smsInfo(String info) {
        if (info != null)
            smsLogger.info(info);
    }
    public static void teamInfo(String info) {
        if (info != null)
            teamLogger.info(info);
    }
    public static void requestTime(String url, Map<String, Object> params, long time) {
        String paramsStr = "";
        try {
            Iterator<String> its = params.keySet().iterator();
            List<String> list = new ArrayList<>();
            while (its.hasNext()) {
                String key = its.next();
                Object value = params.get(key);
                Object[] values = (Object[]) value;
                list.add(key + "=" + values[0].toString());
            }
            for (String param : list)
                paramsStr += param + "&";
            if (paramsStr.endsWith("&"))
                paramsStr = paramsStr.substring(0, paramsStr.length() - 1);
        } catch (Exception e) {
        }
        String content = String.format("链接:%s  参数:%s  响应时间:%s", url, paramsStr, time + "");
        requestTimeLogger.info(content);
    }
}
fanli/src/main/java/com/yeshi/fanli/service/impl/count/CommonOrderCountServiceImpl.java
@@ -29,336 +29,363 @@
@Service
public class CommonOrderCountServiceImpl implements CommonOrderCountService {
    @Resource
    private TaoBaoWeiQuanOrderMapper taoBaoWeiQuanOrderMapper;
    @Resource
    private TaoBaoWeiQuanOrderMapper taoBaoWeiQuanOrderMapper;
    @Resource
    private TaoBaoOrderMapper taoBaoOrderMapper;
    @Resource
    private TaoBaoOrderMapper taoBaoOrderMapper;
    @Resource
    private JDOrderItemMapper jdOrderItemMapper;
    @Resource
    private JDOrderItemMapper jdOrderItemMapper;
    @Resource
    private PDDOrderMapper pddOrderMapper;
    @Resource
    private PDDOrderMapper pddOrderMapper;
    @Resource
    private CommonOrderCountMapper commonOrderCountMapper;
    @Resource
    private CommonOrderCountMapper commonOrderCountMapper;
    @Resource
    private CountOrderTrackRateDao countOrderTrackRateDao;
    @Override
    public Long countByState(Integer state) {
        return commonOrderCountMapper.countByState(state);
    }
    @Override
    public Integer countOderByUidAndLess10(Long uid) {
        return commonOrderCountMapper.countOderByUidAndLess10(uid);
    }
    @Resource
    private CountOrderTrackRateDao countOrderTrackRateDao;
    public List<ChartTDO> dayFactory(String startTime, String endTime, List<ChartTDO> list) throws Exception {
        List<ChartTDO> listObject = new ArrayList<ChartTDO>();
        if (startTime.equals(endTime)) {
            ChartTDO chartTDO = list.get(0);
            String showValue = chartTDO.getShowValue();
            if (showValue == null) {
                chartTDO.setShowValue("0");
            }
            listObject.add(chartTDO);
            return listObject;
        }
    @Override
    public Long countByState(Integer state) {
        return commonOrderCountMapper.countByState(state);
    }
        String plusDay = "";
        for (int i = 0; i < 1000; i++) {
            if (i == 0) {
                plusDay = startTime;
            } else {
                plusDay = DateUtil.plusDay(i, startTime);
            }
    @Override
    public Integer countOderByUidAndLess10(Long uid) {
        return commonOrderCountMapper.countOderByUidAndLess10(uid);
    }
            String total = null;
            for (int j = 0; j < list.size(); j++) {
                ChartTDO chartTDO = list.get(j);
                String showDate = chartTDO.getShowDate();
                if (plusDay.equalsIgnoreCase(showDate)) {
                    total = chartTDO.getShowValue();
                    break;
                }
            }
            if (total == null) {
                total = "0";
            }
            ChartTDO chartTDO = new ChartTDO();
            chartTDO.setShowDate(plusDay);
            chartTDO.setShowValue(total);
            listObject.add(chartTDO);
    public List<ChartTDO> dayFactory(String startTime, String endTime, List<ChartTDO> list) throws Exception {
        List<ChartTDO> listObject = new ArrayList<ChartTDO>();
        if (startTime.equals(endTime)) {
            ChartTDO chartTDO = list.get(0);
            String showValue = chartTDO.getShowValue();
            if (showValue == null) {
                chartTDO.setShowValue("0");
            }
            listObject.add(chartTDO);
            return listObject;
        }
            if (plusDay.equals(endTime)) {
                break; // 时间结束
            }
        }
        String plusDay = "";
        for (int i = 0; i < 1000; i++) {
            if (i == 0) {
                plusDay = startTime;
            } else {
                plusDay = DateUtil.plusDay(i, startTime);
            }
        return listObject;
    }
            String total = null;
            for (int j = 0; j < list.size(); j++) {
                ChartTDO chartTDO = list.get(j);
                String showDate = chartTDO.getShowDate();
                if (plusDay.equalsIgnoreCase(showDate)) {
                    total = chartTDO.getShowValue();
                    break;
                }
            }
            if (total == null) {
                total = "0";
            }
            ChartTDO chartTDO = new ChartTDO();
            chartTDO.setShowDate(plusDay);
            chartTDO.setShowValue(total);
            listObject.add(chartTDO);
    public List<ChartTDO> monthFactory(List<ChartTDO> list) {
        List<ChartTDO> listObject = new ArrayList<ChartTDO>();
        // 12 个月处理
        for (int i = 1; i <= 12; i++) {
            String total = null;
            for (int j = 0; j < list.size(); j++) {
                ChartTDO chartTDO = list.get(j);
                String month = chartTDO.getShowDate();
                if ((i + "").equalsIgnoreCase(month) || i == Integer.parseInt(month)) {
                    total = chartTDO.getShowValue();
                    break;
                }
            }
            if (plusDay.equals(endTime)) {
                break; // 时间结束
            }
        }
            if (total == null) {
                total = "0";
            }
        return listObject;
    }
            ChartTDO chartTDO = new ChartTDO();
            chartTDO.setShowValue(total);
            if (i < 10) {
                chartTDO.setShowDate("0" + i);
            } else {
                chartTDO.setShowDate(i + "");
            }
            listObject.add(chartTDO);
        }
        return listObject;
    }
    public List<ChartTDO> monthFactory(List<ChartTDO> list) {
        List<ChartTDO> listObject = new ArrayList<ChartTDO>();
        // 12 个月处理
        for (int i = 1; i <= 12; i++) {
            String total = null;
            for (int j = 0; j < list.size(); j++) {
                ChartTDO chartTDO = list.get(j);
                String month = chartTDO.getShowDate();
                if ((i + "").equalsIgnoreCase(month) || i == Integer.parseInt(month)) {
                    total = chartTDO.getShowValue();
                    break;
                }
            }
    public List<ChartTDO> yearFactory(List<ChartTDO> list) {
        List<ChartTDO> listObject = new ArrayList<ChartTDO>();
        for (int i = 0; i < list.size(); i++) {
            ChartTDO chartTDO = list.get(i);
            String showValue = chartTDO.getShowValue();
            if (showValue == null) {
                chartTDO.setShowValue("0");
            }
            listObject.add(chartTDO);
        }
        return listObject;
    }
            if (total == null) {
                total = "0";
            }
            ChartTDO chartTDO = new ChartTDO();
            chartTDO.setShowValue(total);
            if (i < 10) {
                chartTDO.setShowDate("0" + i);
            } else {
                chartTDO.setShowDate(i + "");
            }
            listObject.add(chartTDO);
        }
        return listObject;
    }
    public List<ChartTDO> yearFactory(List<ChartTDO> list) {
        List<ChartTDO> listObject = new ArrayList<ChartTDO>();
        for (int i = 0; i < list.size(); i++) {
            ChartTDO chartTDO = list.get(i);
            String showValue = chartTDO.getShowValue();
            if (showValue == null) {
                chartTDO.setShowValue("0");
            }
            listObject.add(chartTDO);
        }
        return listObject;
    }
    @Override
    public List<ChartTDO> countWeiQaunOrderMoney(Integer dateType, String year, String startTime, String endTime)
            throws Exception {
        return taoBaoWeiQuanOrderMapper.countWeiQaunOrderMoney(dateType, year, startTime, endTime);
    }
    @Override
    public List<ChartTDO> countWeiQaunOrderMoney(Integer dateType, String year, String startTime, String endTime)
            throws Exception {
        return taoBaoWeiQuanOrderMapper.countWeiQaunOrderMoney(dateType, year, startTime, endTime);
    }
    @Override
    public List<ChartTDO> countWeiQaunOrderNumber(Integer dateType, String year, String startTime, String endTime)
            throws Exception {
        return taoBaoWeiQuanOrderMapper.countWeiQaunOrderNumber(dateType, year, startTime, endTime);
    }
    @Override
    public List<ChartTDO> countWeiQaunOrderNumber(Integer dateType, String year, String startTime, String endTime)
            throws Exception {
        return taoBaoWeiQuanOrderMapper.countWeiQaunOrderNumber(dateType, year, startTime, endTime);
    }
    @Override
    public Map<String, Object> countOrderNumberBySettleTime(Long uid, Integer state, Integer day) {
        return commonOrderCountMapper.countOrderNumberBySettleTime(uid, state, day);
    }
    @Override
    public Map<String, Object> countOrderNumberBySettleTime(Long uid, Integer state, Integer day) {
        return commonOrderCountMapper.countOrderNumberBySettleTime(uid, state, day);
    }
    /**
     * 根据结算时间筛选 上个月已结算的订订单数量
     *
     * @param uid
     * @return
     */
    @Override
    public Map<String, Object> lastMonthSettleOrderNumber(Long uid) {
        return countOrderNumberBySettleTime(uid, 2, 4); // 根据
    }
    /**
     * 根据结算时间筛选 上个月已结算的订订单数量
     *
     * @param uid
     * @return
     */
    @Override
    public Map<String, Object> lastMonthSettleOrderNumber(Long uid) {
        return countOrderNumberBySettleTime(uid, 2, 4); // 根据
    }
    @Override
    public BigDecimal getMoneyByOrderNo(String orderNo) {
        return commonOrderCountMapper.getMoneyByOrderNo(orderNo);
    }
    @Override
    public BigDecimal getMoneyByOrderNo(String orderNo) {
        return commonOrderCountMapper.getMoneyByOrderNo(orderNo);
    }
    @Override
    public long countValidOrderByDate(Long uid, String dateTime) {
        return commonOrderCountMapper.countValidOrderByDate(uid, dateTime);
    }
    @Override
    public long countValidOrderByDate(Long uid, String dateTime) {
        return commonOrderCountMapper.countValidOrderByDate(uid, dateTime);
    }
    @Override
    public long countSameShopOrderByUidAndHongBaoType(List<Integer> typeList, Long uid, int minSameShopGoodsCount) {
        return commonOrderCountMapper.countSameShopOrderByUidAndHongBaoType(typeList, uid, minSameShopGoodsCount);
    }
    @Override
    public long countSameShopOrderByUidAndHongBaoType(List<Integer> typeList, Long uid, int minSameShopGoodsCount) {
    @Override
    public long countSameGoodsOrderByUidAndHongBaoType(List<Integer> typeList, Long uid, int minSameGoodsOrderCount) {
        return commonOrderCountMapper.countSameGoodsOrderByUidAndHongBaoType(typeList, uid, minSameGoodsOrderCount);
    }
        Date date = new Date(System.currentTimeMillis() - 1000 * 60 * 60L * 24 * 365);
        return commonOrderCountMapper.countSameShopOrderByUidAndHongBaoType(typeList, uid, minSameShopGoodsCount, date);
    }
    @Override
    public List<Long> getSameShopOrderByUidAndHongBaoType(List<Integer> typeList, Long uid, int minSameShopGoodsCount) {
        return commonOrderCountMapper.getSameShopOrderByUidAndHongBaoType(typeList, uid, minSameShopGoodsCount);
    }
    private List<Long> getExcudeGoodsIds() {
        List<Long> shopIds = new ArrayList<>();
        shopIds.add(2549841410L);//天猫国际官方直营
        shopIds.add(725677994L);//天猫超市
        shopIds.add(4066234693L);//天猫国际海外仓直购
        shopIds.add(123971619L);//天猫国际进口超市
        shopIds.add(231452441L);//天猫会员店
        shopIds.add(464516896L);//天猫精灵官方旗舰店
        shopIds.add(1862759827L);//天猫魔盒官方旗舰店
        shopIds.add(1910146537L);//天猫超市生鲜店
        shopIds.add(2928278102L);//阿里健康
        return shopIds;
    }
    @Override
    public List<Long> getSameGoodsOrderByUidAndHongBaoType(List<Integer> typeList, Long uid, int minSameGoodsOrderCount) {
        return commonOrderCountMapper.getSameGoodsOrderByUidAndHongBaoType(typeList, uid, minSameGoodsOrderCount);
    }
    @Override
    public Integer countOderByUidAndDate(Date preDay, Long uid) {
        return commonOrderCountMapper.countOderByUidAndDate(preDay, uid);
    }
    @Override
    public List<CountOrderDTO> countValidOrderByDay(String preDay) {
        return commonOrderCountMapper.countValidOrderByDay(preDay);
    }
    @Override
    public List<Long> getUidByValidOrderByDay(String preDay) {
        return commonOrderCountMapper.getUidByValidOrderByDay(preDay);
    }
    @Override
    public Integer countDownOrderUserByUidAndDate(Date preDay, List<Long> list) {
        return commonOrderCountMapper.countDownOrderUserByUidAndDate(preDay, list);
    }
    @Override
    public List<Long> getDownOrderUserByListUidAndDate(Date preDay, List<Long> list) {
        return commonOrderCountMapper.getDownOrderUserByListUidAndDate(preDay, list);
    }
    @Override
    public List<CountOrderDTO> countCommissionByDay(String preDay) {
        return commonOrderCountMapper.countCommissionByDay(preDay);
    }
    @Override
    public Integer countOderByDate(String preDay) {
        return commonOrderCountMapper.countOderByDate(preDay);
    }
    @Override
    public BigDecimal countCommissionByDate(String preDay) {
        return commonOrderCountMapper.countCommissionByDate(preDay);
    }
    @Override
    public List<CountOrderTrackRate> getOrderTrackRate(int type, Date startTime, Date endTime) {
        OrderTrackRateEnum trackRateEnum = null;
        if (type == 1) {
            trackRateEnum = OrderTrackRateEnum.taobao;
        } else if (type == 2) {
            trackRateEnum = OrderTrackRateEnum.jd;
        } else if (type == 3) {
            trackRateEnum = OrderTrackRateEnum.pdd;
        } else {
            trackRateEnum = OrderTrackRateEnum.taobao;
        }
    @Override
    public long countSameGoodsOrderByUidAndHongBaoType(List<Integer> typeList, Long uid, int minSameGoodsOrderCount) {
        //排除特殊店铺
        List<Long> shopIds = getExcudeGoodsIds();
        Date date = new Date(System.currentTimeMillis() - 1000 * 60 * 60L * 24 * 365L);
        return commonOrderCountMapper.countSameGoodsOrderByUidAndHongBaoType(typeList, uid, shopIds, minSameGoodsOrderCount, date);
    }
        // 重新查询统计今日以及空缺
        initOrderTrackRate(trackRateEnum);
        return countOrderTrackRateDao.query(trackRateEnum, startTime, endTime);
    }
    @Override
    public List<Long> listSameGoodsIdByUidAndHongBaoType(List<Integer> typeList, Long uid, int minSameGoodsOrderCount) {
        //排除特殊店铺
        List<Long> shopIds = getExcudeGoodsIds();
    // 初始化统计
    private void initOrderTrackRate(OrderTrackRateEnum trackRateEnum) {
        try {
            CountOrderTrackRate lastRecord = countOrderTrackRateDao.getMaxDate(trackRateEnum);
            Date lastDay = null;
            if (lastRecord != null && lastRecord.getDay() != null) {
                lastDay = lastRecord.getDay();
            }
        Date date = new Date(System.currentTimeMillis() - 1000 * 60 * 60L * 24 * 365L);
        return commonOrderCountMapper.listSameGoodsIdByUidAndHongBaoType(typeList, uid, shopIds, minSameGoodsOrderCount, date);
    }
            if (lastDay == null) {
                lastDay = TimeUtil.parse("2018-01-01");
            }
            Date today = new Date();
            int betweenDays = DateUtil.daysBetween2(lastDay, today);
            if (betweenDays > 0) {
                for (int i = 0; i <= betweenDays; i++) {
                    addOrderTrackRateCount(DateUtil.plusDay(i, lastDay), trackRateEnum);
                }
            } else {
                // 重新统计昨日
                addOrderTrackRateCount(DateUtil.reduceDay2(1, lastDay), trackRateEnum);
                // 重新统计今日
                addOrderTrackRateCount(TimeUtil.getGernalTime(today.getTime()), trackRateEnum);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Override
    public List<Long> getSameShopOrderByUidAndHongBaoType(List<Integer> typeList, Long uid, int minSameShopGoodsCount) {
        //排除特殊店铺
        List<Long> shopIds = getExcudeGoodsIds();
        return commonOrderCountMapper.getSameShopOrderByUidAndHongBaoType(typeList, uid, shopIds, minSameShopGoodsCount);
    }
    private void addOrderTrackRateCount(String preDay, OrderTrackRateEnum trackRateEnum) throws Exception {
        int value = trackRateEnum.getValue();
        Long count = commonOrderCountMapper.countOrderBySourceTypeAndDay(preDay,value);
        if (count == null) {
            count = 0L;
        }
        Long total = null;
        switch (value) {
        case Constant.SOURCE_TYPE_TAOBAO:
            total = taoBaoOrderMapper.countOrderByDay(preDay);
            break;
        case Constant.SOURCE_TYPE_JD:
            total = jdOrderItemMapper.countOrderByDay(preDay);
            break;
        case Constant.SOURCE_TYPE_PDD:
            total = pddOrderMapper.countOrderByDay(preDay);
            break;
        }
        if(total == null)
            total = 0L;
        CountOrderTrackRate record = new CountOrderTrackRate();
        record.setNum(count);
        record.setTotalNum(total);
        record.setDay(TimeUtil.parse(preDay));
        record.setType(trackRateEnum.name());
        record.setId(StringUtil.Md5(preDay + trackRateEnum.name()));
        countOrderTrackRateDao.save(record);
    }
    @Override
    public Long countOrderBySourceTypeAndDay(int source, String preDay) {
        return commonOrderCountMapper.countOrderBySourceTypeAndDay(preDay, source);
    }
    @Override
    public long countOrderBySourceAndNearDay(Long uid, int source, int day) {
        Long count = commonOrderCountMapper.countOrderBySourceAndNearDay(uid, source, day);
        if (count  == null) {
            count = 0L;
        }
        return count;
    }
    @Override
    public long countHistoryOrderNum(Long uid) {
        Long count = commonOrderCountMapper.countHistoryOrderNum(uid);
        if (count  == null) {
            count = 0L;
        }
        return count;
    }
    @Override
    public List<Long> getSameGoodsOrderByUidAndHongBaoType(List<Integer> typeList, Long uid, int minSameGoodsOrderCount) {
        return commonOrderCountMapper.getSameGoodsOrderByUidAndHongBaoType(typeList, uid, minSameGoodsOrderCount);
    }
    @Override
    public Integer countOderByUidAndDate(Date preDay, Long uid) {
        return commonOrderCountMapper.countOderByUidAndDate(preDay, uid);
    }
    @Override
    public List<CountOrderDTO> countValidOrderByDay(String preDay) {
        return commonOrderCountMapper.countValidOrderByDay(preDay);
    }
    @Override
    public List<Long> getUidByValidOrderByDay(String preDay) {
        return commonOrderCountMapper.getUidByValidOrderByDay(preDay);
    }
    @Override
    public Integer countDownOrderUserByUidAndDate(Date preDay, List<Long> list) {
        return commonOrderCountMapper.countDownOrderUserByUidAndDate(preDay, list);
    }
    @Override
    public List<Long> getDownOrderUserByListUidAndDate(Date preDay, List<Long> list) {
        return commonOrderCountMapper.getDownOrderUserByListUidAndDate(preDay, list);
    }
    @Override
    public List<CountOrderDTO> countCommissionByDay(String preDay) {
        return commonOrderCountMapper.countCommissionByDay(preDay);
    }
    @Override
    public Integer countOderByDate(String preDay) {
        return commonOrderCountMapper.countOderByDate(preDay);
    }
    @Override
    public BigDecimal countCommissionByDate(String preDay) {
        return commonOrderCountMapper.countCommissionByDate(preDay);
    }
    @Override
    public List<CountOrderTrackRate> getOrderTrackRate(int type, Date startTime, Date endTime) {
        OrderTrackRateEnum trackRateEnum = null;
        if (type == 1) {
            trackRateEnum = OrderTrackRateEnum.taobao;
        } else if (type == 2) {
            trackRateEnum = OrderTrackRateEnum.jd;
        } else if (type == 3) {
            trackRateEnum = OrderTrackRateEnum.pdd;
        } else {
            trackRateEnum = OrderTrackRateEnum.taobao;
        }
        // 重新查询统计今日以及空缺
        initOrderTrackRate(trackRateEnum);
        return countOrderTrackRateDao.query(trackRateEnum, startTime, endTime);
    }
    // 初始化统计
    private void initOrderTrackRate(OrderTrackRateEnum trackRateEnum) {
        try {
            CountOrderTrackRate lastRecord = countOrderTrackRateDao.getMaxDate(trackRateEnum);
            Date lastDay = null;
            if (lastRecord != null && lastRecord.getDay() != null) {
                lastDay = lastRecord.getDay();
            }
            if (lastDay == null) {
                lastDay = TimeUtil.parse("2018-01-01");
            }
            Date today = new Date();
            int betweenDays = DateUtil.daysBetween2(lastDay, today);
            if (betweenDays > 0) {
                for (int i = 0; i <= betweenDays; i++) {
                    addOrderTrackRateCount(DateUtil.plusDay(i, lastDay), trackRateEnum);
                }
            } else {
                // 重新统计昨日
                addOrderTrackRateCount(DateUtil.reduceDay2(1, lastDay), trackRateEnum);
                // 重新统计今日
                addOrderTrackRateCount(TimeUtil.getGernalTime(today.getTime()), trackRateEnum);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void addOrderTrackRateCount(String preDay, OrderTrackRateEnum trackRateEnum) throws Exception {
        int value = trackRateEnum.getValue();
        Long count = commonOrderCountMapper.countOrderBySourceTypeAndDay(preDay, value);
        if (count == null) {
            count = 0L;
        }
        Long total = null;
        switch (value) {
            case Constant.SOURCE_TYPE_TAOBAO:
                total = taoBaoOrderMapper.countOrderByDay(preDay);
                break;
            case Constant.SOURCE_TYPE_JD:
                total = jdOrderItemMapper.countOrderByDay(preDay);
                break;
            case Constant.SOURCE_TYPE_PDD:
                total = pddOrderMapper.countOrderByDay(preDay);
                break;
        }
        if (total == null)
            total = 0L;
        CountOrderTrackRate record = new CountOrderTrackRate();
        record.setNum(count);
        record.setTotalNum(total);
        record.setDay(TimeUtil.parse(preDay));
        record.setType(trackRateEnum.name());
        record.setId(StringUtil.Md5(preDay + trackRateEnum.name()));
        countOrderTrackRateDao.save(record);
    }
    @Override
    public Long countOrderBySourceTypeAndDay(int source, String preDay) {
        return commonOrderCountMapper.countOrderBySourceTypeAndDay(preDay, source);
    }
    @Override
    public long countOrderBySourceAndNearDay(Long uid, int source, int day) {
        Long count = commonOrderCountMapper.countOrderBySourceAndNearDay(uid, source, day);
        if (count == null) {
            count = 0L;
        }
        return count;
    }
    @Override
    public long countHistoryOrderNum(Long uid) {
        Long count = commonOrderCountMapper.countHistoryOrderNum(uid);
        if (count == null) {
            count = 0L;
        }
        return count;
    }
}
fanli/src/main/java/com/yeshi/fanli/service/impl/money/extract/ExtractServiceImpl.java
@@ -84,1265 +84,1284 @@
@Service
public class ExtractServiceImpl implements ExtractService {
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private ConfigService configService;
    @Resource
    private ConfigService configService;
    @Resource
    private ExtractRecordService extractRecordService;
    @Resource
    private ExtractRecordService extractRecordService;
    @Resource
    private SystemConfigService systemConfigService;
    @Resource
    private SystemConfigService systemConfigService;
    @Resource
    private ExtractMapper extractMapper;
    @Resource
    private ExtractMapper extractMapper;
    @Resource
    private ExtractAuditRecordMapper extractAuditRecordMapper;
    @Resource
    private ExtractAuditRecordMapper extractAuditRecordMapper;
    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private PayInfoMapper payInfoMapper;
    @Resource
    private PayInfoMapper payInfoMapper;
    @Resource
    private AccountMessageMapper accountMessageMapper;
    @Resource
    private AccountMessageMapper accountMessageMapper;
    @Resource
    private ExtractRecordMapper extractRecordMapper;
    @Resource
    private ExtractRecordMapper extractRecordMapper;
    @Resource
    private HongBaoV2Mapper hongBaoV2Mapper;
    @Resource
    private HongBaoV2Mapper hongBaoV2Mapper;
    @Resource
    private HongBaoV2Service hongBaoV2Service;
    @Resource
    private HongBaoV2Service hongBaoV2Service;
    @Resource
    private PushService pushService;
    @Resource
    private PushService pushService;
    @Resource
    private UserMoneyDetailMapper userMoneyDetailMapper;
    @Resource
    private UserMoneyDetailMapper userMoneyDetailMapper;
    @Resource
    private UserMoneyMsgNotificationService userMoneyMsgNotificationService;
    @Resource
    private UserMoneyMsgNotificationService userMoneyMsgNotificationService;
    @Resource
    private AlipayAccountValidNormalHistoryMapper alipayAccountValidNormalHistoryMapper;
    @Resource
    private AlipayAccountValidNormalHistoryMapper alipayAccountValidNormalHistoryMapper;
    @Resource
    private UserMoneyDetailService userMoneyDetailService;
    @Resource
    private UserMoneyDetailService userMoneyDetailService;
    @Resource
    private UserAccountBindingHistoryService userAccountBindingHistoryService;
    @Resource
    private UserAccountBindingHistoryService userAccountBindingHistoryService;
    @Resource
    private UserMoneyDebtService userMoneyDebtService;
    @Resource
    private UserMoneyDebtService userMoneyDebtService;
    @Resource
    private UserMoneyService userMoneyService;
    @Resource
    private UserMoneyService userMoneyService;
    @Resource
    private OrderUserStatisticService orderUserStatisticService;
    @Resource
    private OrderUserStatisticService orderUserStatisticService;
    @Resource
    private ExtractWeiXinRecordService extractWeiXinRecordService;
    @Resource
    private ExtractWeiXinRecordService extractWeiXinRecordService;
    @Resource
    private CommonOrderCountService commonOrderCountService;
    @Resource
    private CommonOrderCountService commonOrderCountService;
    @Transactional
    public Integer addExtract(Extract extract) {
        Integer integer = extract(extract);
        return integer;
    }
    @Transactional
    public Integer addExtract(Extract extract) {
        Integer integer = extract(extract);
        return integer;
    }
    @Transactional
    public Integer passExtract(final long id, AdminUser admin) {
        Extract find = extractMapper.selectByPrimaryKeyForUpdate(id);
        if (find == null)
            return Constant.NOT_EXIST_OBJACT;
    @Transactional
    public Integer passExtract(final long id, AdminUser admin) {
        Extract find = extractMapper.selectByPrimaryKeyForUpdate(id);
        if (find == null)
            return Constant.NOT_EXIST_OBJACT;
        if (find.getState() != Extract.STATE_NOT_PROCESS) {
            return Constant.OBJECT_STATE_EXCEPTION;
        }
        if (find.getState() != Extract.STATE_NOT_PROCESS) {
            return Constant.OBJECT_STATE_EXCEPTION;
        }
        // 更改提现状态为处理中
        Extract updateExtract = new Extract();
        updateExtract.setId(id);
        updateExtract.setState(Extract.STATE_PROCESSING);
        extractMapper.updateByPrimaryKeySelective(updateExtract);
        // 改变资金记录状态
        UserMoneyDetail detail = userMoneyDetailService.selectByTypeAndUidAndIdentifyCode(
                UserMoneyDetailTypeEnum.extract, find.getUserInfo().getId(), find.getId());
        if (detail != null) {
            UserMoneyDetail update = new UserMoneyDetail(detail.getId());
            update.setShow(true);
            update.setUpdateTime(new Date());
            userMoneyDetailMapper.updateByPrimaryKeySelective(update);
        }
        // 更改提现状态为处理中
        Extract updateExtract = new Extract();
        updateExtract.setId(id);
        updateExtract.setState(Extract.STATE_PROCESSING);
        extractMapper.updateByPrimaryKeySelective(updateExtract);
        // 改变资金记录状态
        UserMoneyDetail detail = userMoneyDetailService.selectByTypeAndUidAndIdentifyCode(
                UserMoneyDetailTypeEnum.extract, find.getUserInfo().getId(), find.getId());
        if (detail != null) {
            UserMoneyDetail update = new UserMoneyDetail(detail.getId());
            update.setShow(true);
            update.setUpdateTime(new Date());
            userMoneyDetailMapper.updateByPrimaryKeySelective(update);
        }
        transfer(find, admin); // 提现通过,支付宝转账
        transfer(find, admin); // 提现通过,支付宝转账
        return null;
    }
        return null;
    }
    @Transactional(rollbackFor = Exception.class)
    public synchronized void rejectExtract(long id, String reason, AdminUser admin)
            throws ObjectStateException, NotExistObjectException {
        Extract find = extractMapper.selectByPrimaryKey(id);
    @Transactional(rollbackFor = Exception.class)
    public synchronized void rejectExtract(long id, String reason, AdminUser admin)
            throws ObjectStateException, NotExistObjectException {
        Extract find = extractMapper.selectByPrimaryKey(id);
        if (find == null) {
            throw new NotExistObjectException("不存在该对象");
        }
        if (find == null) {
            throw new NotExistObjectException("不存在该对象");
        }
        if (find.getState() != Constant.EXTRACT_DEFUALT) {
            throw new ObjectStateException("该状态不等于不为初始状态");
        }
        if (find.getState() != Constant.EXTRACT_DEFUALT) {
            throw new ObjectStateException("该状态不等于不为初始状态");
        }
        UserInfo user = find.getUserInfo();
        UserInfo user = find.getUserInfo();
        UserMoneyDetail userMoneyDetail = null;
        try {
            userMoneyDetail = UserMoneyDetailFactory.createExtractReject(find);
        } catch (UserMoneyDetailException e1) {
            e1.printStackTrace();
        }
        UserMoneyDetail userMoneyDetail = null;
        try {
            userMoneyDetail = UserMoneyDetailFactory.createExtractReject(find);
        } catch (UserMoneyDetailException e1) {
            e1.printStackTrace();
        }
        // 增加资金
        userMoneyService.addUserMoney(user.getId(), find.getMoney(), userMoneyDetail);
        // 更新原来的状态
        Extract updateExtract = new Extract();
        updateExtract.setId(id);
        updateExtract.setState(Constant.EXTRACT_REJECT);
        updateExtract.setReason(reason);
        extractMapper.updateByPrimaryKeySelective(updateExtract);
        // 增加资金
        userMoneyService.addUserMoney(user.getId(), find.getMoney(), userMoneyDetail);
        // 更新原来的状态
        Extract updateExtract = new Extract();
        updateExtract.setId(id);
        updateExtract.setState(Constant.EXTRACT_REJECT);
        updateExtract.setReason(reason);
        extractMapper.updateByPrimaryKeySelective(updateExtract);
        long auditTime = java.lang.System.currentTimeMillis();
        // 更新审核记录
        ExtractAuditRecord auditRecord = new ExtractAuditRecord();
        List<ExtractAuditRecord> records = extractAuditRecordMapper.getbyExtractId(id);
        if (records != null && records.size() > 0) {
            auditRecord = records.get(0);
        }
        long auditTime = java.lang.System.currentTimeMillis();
        // 更新审核记录
        ExtractAuditRecord auditRecord = new ExtractAuditRecord();
        List<ExtractAuditRecord> records = extractAuditRecordMapper.getbyExtractId(id);
        if (records != null && records.size() > 0) {
            auditRecord = records.get(0);
        }
        // 角色默认:客服
        auditRecord.setAuditRole("客服");
        // 审核人
        auditRecord.setAdminUser(admin);
        // 提现之后金额 不变
        auditRecord.setAfterMoney(auditRecord.getBeforeMoney());
        // 审核时间
        auditRecord.setAuditTime(auditTime);
        // 角色默认:客服
        auditRecord.setAuditRole("客服");
        // 审核人
        auditRecord.setAdminUser(admin);
        // 提现之后金额 不变
        auditRecord.setAfterMoney(auditRecord.getBeforeMoney());
        // 审核时间
        auditRecord.setAuditTime(auditTime);
        // 历史提现金额
        Long uid = user.getId();
        double countSuccessMoneys = extractMapper.countSuccessMoneysByUid(uid);
        auditRecord.setCountMoney(new BigDecimal(countSuccessMoneys));
        // 历史提现金额
        Long uid = user.getId();
        double countSuccessMoneys = extractMapper.countSuccessMoneysByUid(uid);
        auditRecord.setCountMoney(new BigDecimal(countSuccessMoneys));
        // 历史提现次数
        long countSuccess = extractMapper.countSuccessByUid(uid);
        auditRecord.setCountNum(countSuccess);
        // 历史提现次数
        long countSuccess = extractMapper.countSuccessByUid(uid);
        auditRecord.setCountNum(countSuccess);
        // 更新提现记录审核表
        extractAuditRecordMapper.updateByPrimaryKeySelective(auditRecord);
        // 新版资金详情
        // 更新提现记录审核表
        extractAuditRecordMapper.updateByPrimaryKeySelective(auditRecord);
        // 新版资金详情
        // 新版通知
        userMoneyMsgNotificationService.extractFail(find, reason);
    }
        // 新版通知
        userMoneyMsgNotificationService.extractFail(find, reason);
    }
    /**
     * 提现申请
     *
     * @param extract
     * @return
     */
    @Transactional
    private Integer extract(Extract extract) {
        UserAccountBindingHistory history = userAccountBindingHistoryService
                .getLatestHistory(extract.getUserInfo().getId(), UserAccountBindingHistory.TYPE_PHONE);
        // 手机号更换绑定的7天内不能提现
        if (history != null && !history.getFirst()
                && (System.currentTimeMillis() - history.getCreateTime().getTime()) < 1000 * 60 * 60 * 24 * 7L)
            return 111;
    /**
     * 提现申请
     *
     * @param extract
     * @return
     */
    @Transactional
    private Integer extract(Extract extract) {
        UserAccountBindingHistory history = userAccountBindingHistoryService
                .getLatestHistory(extract.getUserInfo().getId(), UserAccountBindingHistory.TYPE_PHONE);
        // 手机号更换绑定的7天内不能提现
        if (history != null && !history.getFirst()
                && (System.currentTimeMillis() - history.getCreateTime().getTime()) < 1000 * 60 * 60 * 24 * 7L)
            return 111;
        UserInfo user = userInfoMapper.selectByPrimaryKeyForUpdate(extract.getUserInfo().getId());
        // 余额不足
        if (user.getMyHongBao().compareTo(extract.getMoney()) < 0) {
            return 3;
        }
        UserInfo user = userInfoMapper.selectByPrimaryKeyForUpdate(extract.getUserInfo().getId());
        // 余额不足
        if (user.getMyHongBao().compareTo(extract.getMoney()) < 0) {
            return 3;
        }
        // 有借贷关系
        boolean isHaveToReplay = userMoneyDebtService.isHaveDebtToRepay(extract.getUserInfo().getId());
        if (isHaveToReplay) {
            return 110;
        }
        // 有借贷关系
        boolean isHaveToReplay = userMoneyDebtService.isHaveDebtToRepay(extract.getUserInfo().getId());
        if (isHaveToReplay) {
            return 110;
        }
        final String autoExtract = configService.getValue(ConfigKeyEnum.extractWay.getKey(),user.getSystem()); // 是否自动转账
        final String maxCount = configService.getValue(ConfigKeyEnum.extractDayCount.getKey(),user.getSystem());
        final String maxMoney = configService.getValue(ConfigKeyEnum.extractMoneyDay.getKey(),user.getSystem());
        final String autoExtract = configService.getValue(ConfigKeyEnum.extractWay.getKey(), user.getSystem()); // 是否自动转账
        final String maxCount = configService.getValue(ConfigKeyEnum.extractDayCount.getKey(), user.getSystem());
        final String maxMoney = configService.getValue(ConfigKeyEnum.extractMoneyDay.getKey(), user.getSystem());
        Integer type = setExtractRecord(extract, maxCount, maxMoney);
        if (type != 0) {
            return type;
        }
        Integer type = setExtractRecord(extract, maxCount, maxMoney);
        if (type != 0) {
            return type;
        }
        extractMapper.insertSelective(extract);
        extractMapper.insertSelective(extract);
        final ExtractAuditRecord auditRecord = new ExtractAuditRecord();
        auditRecord.setBeforeMoney(user.getMyHongBao());
        auditRecord.setExtract(extract);
        final ExtractAuditRecord auditRecord = new ExtractAuditRecord();
        auditRecord.setBeforeMoney(user.getMyHongBao());
        auditRecord.setExtract(extract);
        Date minTime = new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 24 * 180L);
        Date minTime = new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 24 * 180L);
        extractAuditRecordMapper.insertSelective(auditRecord);
        extractAuditRecordMapper.insertSelective(auditRecord);
        ThreadUtil.run(new Runnable() {
        ThreadUtil.run(new Runnable() {
            @Override
            public void run() {
                // 统计数据
                int less10Count = commonOrderCountService.countOderByUidAndLess10(user.getId());
                ExtractAuditRecord update = new ExtractAuditRecord();
                update.setId(auditRecord.getId());
                int orderCount50More = orderUserStatisticService.countOrderCount100MoreByUidAndMinTime(user.getId(),
                        minTime);
                BigDecimal weiQuanOrderFanAmount = orderUserStatisticService.sumWeiQuanOrderFanAmountByUid(user.getId(),
                        minTime);
                int weiQuanOrderCount = orderUserStatisticService.countWeiQuanOrderByUid(user.getId(), minTime);
                update.setExtraInfoStr(new Gson().toJson(new ExtractOrderStatisticDTO(orderCount50More,
                        weiQuanOrderCount, weiQuanOrderFanAmount, 0, less10Count)));
                extractAuditRecordMapper.updateByPrimaryKeySelective(update);
            }
        });
            @Override
            public void run() {
                // 统计数据
                int less10Count = commonOrderCountService.countOderByUidAndLess10(user.getId());
                ExtractAuditRecord update = new ExtractAuditRecord();
                update.setId(auditRecord.getId());
                int orderCount50More = orderUserStatisticService.countOrderCount100MoreByUidAndMinTime(user.getId(),
                        minTime);
                BigDecimal weiQuanOrderFanAmount = orderUserStatisticService.sumWeiQuanOrderFanAmountByUid(user.getId(),
                        minTime);
                int weiQuanOrderCount = orderUserStatisticService.countWeiQuanOrderByUid(user.getId(), minTime);
                update.setExtraInfoStr(new Gson().toJson(new ExtractOrderStatisticDTO(orderCount50More,
                        weiQuanOrderCount, weiQuanOrderFanAmount, 0, less10Count)));
                extractAuditRecordMapper.updateByPrimaryKeySelective(update);
            }
        });
        // 新版资金详情
        UserMoneyDetail userMoneyDetail = null;
        try {
            userMoneyDetail = UserMoneyDetailFactory.createExtract(extract, null);
        } catch (UserMoneyDetailException e2) {
            try {
                LogHelper.errorDetailInfo(e2);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
        // 新版资金详情
        UserMoneyDetail userMoneyDetail = null;
        try {
            userMoneyDetail = UserMoneyDetailFactory.createExtract(extract, null);
        } catch (UserMoneyDetailException e2) {
            try {
                LogHelper.errorDetailInfo(e2);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
        // 减去账户资金
        userMoneyService.subUserMoney(extract.getUserInfo().getId(), extract.getMoney(), userMoneyDetail);
        // 减去账户资金
        userMoneyService.subUserMoney(extract.getUserInfo().getId(), extract.getMoney(), userMoneyDetail);
        // 添加新版通知
        userMoneyMsgNotificationService.extractApplay(extract);
        // 添加新版通知
        userMoneyMsgNotificationService.extractApplay(extract);
        if ("是".equals(autoExtract)) {
            LogHelper.userInfo("uid=" + user.getId() + ",提交转账申请!");
        } else {// 暂时不自动提现
            // transfer(extract, null);
        }
        return null;
    }
        if ("是".equals(autoExtract)) {
            LogHelper.userInfo("uid=" + user.getId() + ",提交转账申请!");
        } else {// 暂时不自动提现
            // transfer(extract, null);
        }
        return null;
    }
    /**
     * 转账
     *
     * @param extract
     * @param session
     */
    @Transactional
    private void transfer(Extract extract, AdminUser adminUser) {
        Integer type = extract.getType();
        if (Constant.ZHIFUBAO == type) {
            extractByZhiFuBao(extract, adminUser);
        } else {
            LogHelper.userInfo("提现类型错误:" + type);
        }
    }
    /**
     * 转账
     *
     * @param extract
     * @param session
     */
    @Transactional
    private void transfer(Extract extract, AdminUser adminUser) {
        Integer type = extract.getType();
        if (Constant.ZHIFUBAO == type) {
            extractByZhiFuBao(extract, adminUser);
        } else {
            LogHelper.userInfo("提现类型错误:" + type);
        }
    }
    /**
     * 增加提现记录
     *
     * @param extract
     * @param maxCount
     *            最多提现次数
     * @param maxMoney
     *            最大提现金额
     * @param session
     * @return 如果为0,则增加成功。为1,则超过每日最多提现次数。为2,则超过每日最多提现金额
     */
    @Transactional
    public Integer setExtractRecord(Extract extract, String maxCount, String maxMoney) {
        long uid = extract.getUserInfo().getId();
        BigDecimal money = extract.getMoney();
    /**
     * 增加提现记录
     *
     * @param extract
     * @param maxCount 最多提现次数
     * @param maxMoney 最大提现金额
     * @param session
     * @return 如果为0,则增加成功。为1,则超过每日最多提现次数。为2,则超过每日最多提现金额
     */
    @Transactional
    public Integer setExtractRecord(Extract extract, String maxCount, String maxMoney) {
        long uid = extract.getUserInfo().getId();
        BigDecimal money = extract.getMoney();
        List<ExtractRecord> extractRecordList = extractRecordMapper.selectByUidAndToday(uid);
        List<ExtractRecord> extractRecordList = extractRecordMapper.selectByUidAndToday(uid);
        if (extractRecordList.size() == 0) {
            ExtractRecord er = new ExtractRecord();
            er.setCount(1);
            er.setMoney(money);
            er.setUserInfo(new UserInfo(uid));
            er.setCreateTime(java.lang.System.currentTimeMillis());
            extractRecordMapper.insertSelective(er);
        } else {
            ExtractRecord er = extractRecordList.get(0);
            int count = er.getCount();
            int maxCountInt = Integer.parseInt(maxCount);
            if (count >= maxCountInt) {
                return 1;
            }
            BigDecimal oldMoney = er.getMoney();
            BigDecimal sumMoney = MoneyBigDecimalUtil.add(money, oldMoney);
            BigDecimal maxMoneyDou = new BigDecimal(maxMoney);
            if (maxMoneyDou.compareTo(sumMoney) == -1) {
                return 2;
            }
        if (extractRecordList.size() == 0) {
            ExtractRecord er = new ExtractRecord();
            er.setCount(1);
            er.setMoney(money);
            er.setUserInfo(new UserInfo(uid));
            er.setCreateTime(java.lang.System.currentTimeMillis());
            extractRecordMapper.insertSelective(er);
        } else {
            ExtractRecord er = extractRecordList.get(0);
            int count = er.getCount();
            int maxCountInt = Integer.parseInt(maxCount);
            if (count >= maxCountInt) {
                return 1;
            }
            BigDecimal oldMoney = er.getMoney();
            BigDecimal sumMoney = MoneyBigDecimalUtil.add(money, oldMoney);
            BigDecimal maxMoneyDou = new BigDecimal(maxMoney);
            if (maxMoneyDou.compareTo(sumMoney) == -1) {
                return 2;
            }
            ExtractRecord updateER = new ExtractRecord();
            updateER.setId(er.getId());
            updateER.setCount(count + 1);
            updateER.setMoney(sumMoney);
            er.setCreateTime(java.lang.System.currentTimeMillis());
            extractRecordMapper.updateByPrimaryKeySelective(updateER);
        }
        return 0;
    }
            ExtractRecord updateER = new ExtractRecord();
            updateER.setId(er.getId());
            updateER.setCount(count + 1);
            updateER.setMoney(sumMoney);
            er.setCreateTime(java.lang.System.currentTimeMillis());
            extractRecordMapper.updateByPrimaryKeySelective(updateER);
        }
        return 0;
    }
    /**
     * 提现到支付宝
     *
     * @param extract
     * @param session
     */
    // TODO 转账逻辑需要改变,固定IP
    @Transactional
    private void extractByZhiFuBao(Extract extract, AdminUser adminUser) {
        LogHelper.userErrorInfo("提现:开始通过提现-" + extract.getId());
        AlipayFundTransUniTransferResponse response = null;
        try {
            response = AlipayUtil.transferNoThrowException("widthdraw_" + extract.getId(), extract.getAccount(),  extract.getName(),  extract.getMoney(), "板栗快省提现到账", "来自板栗快省的提现");
            LogHelper.userErrorInfo("提现:支付宝通过提现成功-" + extract.getId());
        } catch (AlipayApiException e) {
            LogHelper.errorDetailInfo(e, "支付宝转账异常:" + extract.getId(), "");
            LogHelper.userErrorInfo("提现:支付宝提现异常:" + response + ",提现信息" + GsonUtil.toJson(extract));
        }
    /**
     * 提现到支付宝
     *
     * @param extract
     * @param session
     */
    // TODO 转账逻辑需要改变,固定IP
    @Transactional
    private void extractByZhiFuBao(Extract extract, AdminUser adminUser) {
        LogHelper.userErrorInfo("提现:开始通过提现-" + extract.getId());
        AlipayFundTransUniTransferResponse response = null;
        try {
            response = AlipayUtil.transferNoThrowException("widthdraw_" + extract.getId(), extract.getAccount(), extract.getName(), extract.getMoney(), "板栗快省提现到账", "来自板栗快省的提现");
            LogHelper.userErrorInfo("提现:支付宝通过提现成功-" + extract.getId());
        } catch (AlipayApiException e) {
            LogHelper.errorDetailInfo(e, "支付宝转账异常:" + extract.getId(), "");
            LogHelper.userErrorInfo("提现:支付宝提现异常:" + response + ",提现信息" + GsonUtil.toJson(extract));
        }
        try {
            CMQManager.getInstance().addExtractResultMsg(extract, response, adminUser);
            LogHelper.userErrorInfo("提现:添加处理队列成功-" + extract.getId());
        } catch (Exception e) {
            LogHelper
                    .userErrorInfo("提现:支付宝提现CMQ异常:" + new Gson().toJson(response) + ",提现信息" + GsonUtil.toJson(extract));
        }
    }
        try {
            CMQManager.getInstance().addExtractResultMsg(extract, response, adminUser);
            LogHelper.userErrorInfo("提现:添加处理队列成功-" + extract.getId());
        } catch (Exception e) {
            LogHelper
                    .userErrorInfo("提现:支付宝提现CMQ异常:" + new Gson().toJson(response) + ",提现信息" + GsonUtil.toJson(extract));
        }
    }
    /**
     * 提现失败
     *
     * @param extract
     * @param msg
     * @param session
     */
    @Transactional
    private void extractFail(Extract extract, String msg) {
        UserInfo user = extract.getUserInfo();
        // MoneyRecord moneyRecord = new MoneyRecord(user, null, extract
        // .getMoney(), "提现", "提现失败", new Date().getTime(), 3);
        if ("付款方余额不足".equals(msg)) {
            Extract updateExtract = new Extract();
            updateExtract.setId(extract.getId());
            updateExtract.setState(Constant.EXTRACT_DEFUALT);
            updateExtract.setReason(msg);
            extractMapper.updateByPrimaryKeySelective(updateExtract);
        } else {
            // 老版本功能
            // List<MoneyRecord> list = moneyRecordDao.list("from MoneyRecord mr
            // where mr.extract.id =" + extract.getId());
            // if (list.size() > 0) {
            // MoneyRecord moneyRecord = list.get(0);
            // moneyRecordMapper.deleteByPrimaryKey(moneyRecord.getId());
            // }
    /**
     * 提现失败
     *
     * @param extract
     * @param msg
     * @param session
     */
    @Transactional
    private void extractFail(Extract extract, String msg) {
        UserInfo user = extract.getUserInfo();
        // MoneyRecord moneyRecord = new MoneyRecord(user, null, extract
        // .getMoney(), "提现", "提现失败", new Date().getTime(), 3);
        if ("付款方余额不足".equals(msg)) {
            Extract updateExtract = new Extract();
            updateExtract.setId(extract.getId());
            updateExtract.setState(Constant.EXTRACT_DEFUALT);
            updateExtract.setReason(msg);
            extractMapper.updateByPrimaryKeySelective(updateExtract);
        } else {
            // 老版本功能
            // List<MoneyRecord> list = moneyRecordDao.list("from MoneyRecord mr
            // where mr.extract.id =" + extract.getId());
            // if (list.size() > 0) {
            // MoneyRecord moneyRecord = list.get(0);
            // moneyRecordMapper.deleteByPrimaryKey(moneyRecord.getId());
            // }
            Extract updateExtract = new Extract();
            updateExtract.setId(extract.getId());
            updateExtract.setState(Constant.EXTRACT_REJECT);
            updateExtract.setReason(msg);
            extractMapper.updateByPrimaryKeySelective(updateExtract);
            Extract updateExtract = new Extract();
            updateExtract.setId(extract.getId());
            updateExtract.setState(Constant.EXTRACT_REJECT);
            updateExtract.setReason(msg);
            extractMapper.updateByPrimaryKeySelective(updateExtract);
            UserMoneyDetail userMoneyDetail = null;
            // 新版资金详情
            try {
                userMoneyDetail = UserMoneyDetailFactory.createExtractReject(extract);
            } catch (UserMoneyDetailException e2) {
                try {
                    LogHelper.errorDetailInfo(e2);
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
            // 增加资金
            userMoneyService.addUserMoney(user.getId(), extract.getMoney(), userMoneyDetail);
            UserMoneyDetail userMoneyDetail = null;
            // 新版资金详情
            try {
                userMoneyDetail = UserMoneyDetailFactory.createExtractReject(extract);
            } catch (UserMoneyDetailException e2) {
                try {
                    LogHelper.errorDetailInfo(e2);
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
            // 增加资金
            userMoneyService.addUserMoney(user.getId(), extract.getMoney(), userMoneyDetail);
            try {
                LogHelper.userInfo("支付宝转账失败:[提现IP:" + extract.getIp() + ",所转账号:" + extract.getAccount() + ",真实姓名:"
                        + extract.getName() + ",所转金额:" + extract.getMoney() + ",失败原因" + extract.getReason() + "]");
            try {
                LogHelper.userInfo("支付宝转账失败:[提现IP:" + extract.getIp() + ",所转账号:" + extract.getAccount() + ",真实姓名:"
                        + extract.getName() + ",所转金额:" + extract.getMoney() + ",失败原因" + extract.getReason() + "]");
            } catch (Exception e) {
                e.printStackTrace();
            }
            } catch (Exception e) {
                e.printStackTrace();
            }
            // 新版提现
            userMoneyMsgNotificationService.extractFail(extract, null);
        }
    }
            // 新版提现
            userMoneyMsgNotificationService.extractFail(extract, null);
        }
    }
    /**
     * 提现成功
     *
     * @param extract
     * @param session
     */
    @Transactional
    private void extractSuccess(Extract extract,String alipayNo) {
        // 老版本功能
        // List<MoneyRecord> list = moneyRecordDao.list("from MoneyRecord mr
        // where mr.extract.id = " + extract.getId());
        // MoneyRecord moneyRecord = list.get(0);
        // moneyRecord.setType(3);
        // MoneyRecord updateMoneyRecord = new MoneyRecord();
        // updateMoneyRecord.setId(moneyRecord.getId());
        // updateMoneyRecord.setType(3);
        // moneyRecordMapper.updateByPrimaryKeySelective(updateMoneyRecord);
        Extract updateExtract = new Extract();
        updateExtract.setId(extract.getId());
        updateExtract.setState(Constant.EXTRACT_PASS);
        updateExtract.setReceiveTime(new Date());
        updateExtract.setReason("提现成功");
        extractMapper.updateByPrimaryKeySelective(updateExtract);
    /**
     * 提现成功
     *
     * @param extract
     * @param session
     */
    @Transactional
    private void extractSuccess(Extract extract, String alipayNo) {
        // 老版本功能
        // List<MoneyRecord> list = moneyRecordDao.list("from MoneyRecord mr
        // where mr.extract.id = " + extract.getId());
        // MoneyRecord moneyRecord = list.get(0);
        // moneyRecord.setType(3);
        // MoneyRecord updateMoneyRecord = new MoneyRecord();
        // updateMoneyRecord.setId(moneyRecord.getId());
        // updateMoneyRecord.setType(3);
        // moneyRecordMapper.updateByPrimaryKeySelective(updateMoneyRecord);
        Extract updateExtract = new Extract();
        updateExtract.setId(extract.getId());
        updateExtract.setState(Constant.EXTRACT_PASS);
        updateExtract.setReceiveTime(new Date());
        updateExtract.setReason("提现成功");
        extractMapper.updateByPrimaryKeySelective(updateExtract);
        try {
            LogHelper.userInfo("支付宝转账成功:[提现IP:" + extract.getIp() + ",所转账号:" + extract.getAccount() + ",真实姓名:"
                    + extract.getName() + ",所转金额:" + extract.getMoney() + "]");
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            LogHelper.userInfo("支付宝转账成功:[提现IP:" + extract.getIp() + ",所转账号:" + extract.getAccount() + ",真实姓名:"
                    + extract.getName() + ",所转金额:" + extract.getMoney() + "]");
        } catch (Exception e) {
            e.printStackTrace();
        }
        UserMoneyDetail detailNew = null;
        try {
            detailNew = UserMoneyDetailFactory.createExtract(extract, alipayNo);
        } catch (UserMoneyDetailException e) {
            e.printStackTrace();
        }
        UserMoneyDetail detailNew = null;
        try {
            detailNew = UserMoneyDetailFactory.createExtract(extract, alipayNo);
        } catch (UserMoneyDetailException e) {
            e.printStackTrace();
        }
        // 外显账户明细
        UserMoneyDetail userMoneyDetail = userMoneyDetailMapper.selectByTypeAndUidAndIdentifyCode(
                UserMoneyDetailTypeEnum.extractNew, extract.getUserInfo().getId(), extract.getId());
        if (userMoneyDetail != null) {
            UserMoneyDetail detail = new UserMoneyDetail(userMoneyDetail.getId());
            detail.setShow(true);
            detail.setUpdateTime(new Date());
            if (detailNew != null)
                detail.setDescInfo(detailNew.getDescInfo());
            userMoneyDetailMapper.updateByPrimaryKeySelective(detail);
        }
        // 新版通知
        userMoneyMsgNotificationService.extractSuccess(extract, alipayNo);
    }
        // 外显账户明细
        UserMoneyDetail userMoneyDetail = userMoneyDetailMapper.selectByTypeAndUidAndIdentifyCode(
                UserMoneyDetailTypeEnum.extractNew, extract.getUserInfo().getId(), extract.getId());
        if (userMoneyDetail != null) {
            UserMoneyDetail detail = new UserMoneyDetail(userMoneyDetail.getId());
            detail.setShow(true);
            detail.setUpdateTime(new Date());
            if (detailNew != null)
                detail.setDescInfo(detailNew.getDescInfo());
            userMoneyDetailMapper.updateByPrimaryKeySelective(detail);
        }
        // 新版通知
        userMoneyMsgNotificationService.extractSuccess(extract, alipayNo);
    }
    /**
     * 根据提现记录id获取用户uid
     */
    @Override
    public Extract getExtractById(long id) {
        return extractMapper.selectByPrimaryKey(id);
    }
    /**
     * 根据提现记录id获取用户uid
     */
    @Override
    public Extract getExtractById(long id) {
        return extractMapper.selectByPrimaryKey(id);
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void checkExtract(Long uid) throws ExtractException {
        BigDecimal compensateMoney = extractMapper.computeCompensateByUid(uid);
        if (compensateMoney == null)
            compensateMoney = new BigDecimal(0);
        // 不判定到账红包问题
        Long count = hongBaoV2Mapper.countByUidAndState(uid, HongBao.STATE_YILINGQU);
        if ((count == null || count == 0) && compensateMoney.compareTo(new BigDecimal(0)) == 0) {
            throw new ExtractException(1, "没有已到账的红包");
        }
        // 查询是否有欠账
        boolean isDebt = userMoneyDebtService.isHaveDebtToRepay(uid);
        if (isDebt)
            throw new ExtractException(3, "有欠账未还");
        // 获取所有收入所得
        BigDecimal hongBaoMoney = hongBaoV2Service.computeMoneyByUidAndState(uid, HongBaoV2.STATE_YILINGQU);
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void checkExtract(Long uid) throws ExtractException {
        BigDecimal compensateMoney = extractMapper.computeCompensateByUid(uid);
        if (compensateMoney == null)
            compensateMoney = new BigDecimal(0);
        // 不判定到账红包问题
        Long count = hongBaoV2Mapper.countByUidAndState(uid, HongBao.STATE_YILINGQU);
        if ((count == null || count == 0) && compensateMoney.compareTo(new BigDecimal(0)) == 0) {
            throw new ExtractException(1, "没有已到账的红包");
        }
        // 查询是否有欠账
        boolean isDebt = userMoneyDebtService.isHaveDebtToRepay(uid);
        if (isDebt)
            throw new ExtractException(3, "有欠账未还");
        // 获取所有收入所得
        BigDecimal hongBaoMoney = hongBaoV2Service.computeMoneyByUidAndState(uid, HongBaoV2.STATE_YILINGQU);
        Date now = new Date();
        // 获取提现,获取提现验证
        List<UserMoneyDetailTypeEnum> typeList = new ArrayList<>();
        typeList.add(UserMoneyDetailTypeEnum.extract);
        typeList.add(UserMoneyDetailTypeEnum.extractNew);
        typeList.add(UserMoneyDetailTypeEnum.extractReject);
        typeList.add(UserMoneyDetailTypeEnum.extractVerify);
        typeList.add(UserMoneyDetailTypeEnum.extractVerifyNew);
        BigDecimal extractMoney = userMoneyDetailService.statisticUserTypeMoneyWithDate(uid, typeList, new Date(0),
                now);
        extractMoney = extractMoney.abs();
        // 获取维权
        typeList = new ArrayList<>();
        typeList.add(UserMoneyDetailTypeEnum.weiQuan);
        typeList.add(UserMoneyDetailTypeEnum.fanliWeiQuan);
        typeList.add(UserMoneyDetailTypeEnum.inviteWeiQuan);
        typeList.add(UserMoneyDetailTypeEnum.shareWeiQuan);
        typeList.add(UserMoneyDetailTypeEnum.hongbaoDeduct);
        BigDecimal weiqaunMoney = userMoneyDetailService.statisticUserTypeMoneyWithDate(uid, typeList, new Date(0),
                now);
        weiqaunMoney = weiqaunMoney.abs();
        Date now = new Date();
        //获取团队分红
        List<UserMoneyDetailTypeEnum> typeList = new ArrayList<>();
        typeList.add(UserMoneyDetailTypeEnum.teamDividents);
        BigDecimal teamDividents = userMoneyDetailService.statisticUserTypeMoneyWithDate(uid, typeList, new Date(0),
                now);
        BigDecimal balance = userInfoService.selectByPKey(uid).getMyHongBao();
        //红包提现收入
        typeList = new ArrayList<>();
        typeList.add(UserMoneyDetailTypeEnum.redPackExchange);
        BigDecimal redPackExchange = userMoneyDetailService.statisticUserTypeMoneyWithDate(uid, typeList, new Date(0),
                now);
        BigDecimal after = hongBaoMoney.subtract(extractMoney.add(weiqaunMoney).add(balance).add(compensateMoney));
        if (after.compareTo(new BigDecimal("0")) != 0)
            throw new ExtractException(2, "结算资金异常:" + after);
    }
        //----------所有支出开始------------
    @Override
    public Extract selectByPrimaryKey(Long id) {
        return extractMapper.selectByPrimaryKey(id);
    }
        // 获取提现,获取提现验证
        typeList = new ArrayList<>();
        typeList.add(UserMoneyDetailTypeEnum.extract);
        typeList.add(UserMoneyDetailTypeEnum.extractNew);
        typeList.add(UserMoneyDetailTypeEnum.extractReject);
        typeList.add(UserMoneyDetailTypeEnum.extractVerify);
        typeList.add(UserMoneyDetailTypeEnum.extractVerifyNew);
        BigDecimal extractMoney = userMoneyDetailService.statisticUserTypeMoneyWithDate(uid, typeList, new Date(0),
                now);
        extractMoney = extractMoney.abs();
        // 获取维权
        typeList = new ArrayList<>();
        typeList.add(UserMoneyDetailTypeEnum.weiQuan);
        typeList.add(UserMoneyDetailTypeEnum.fanliWeiQuan);
        typeList.add(UserMoneyDetailTypeEnum.inviteWeiQuan);
        typeList.add(UserMoneyDetailTypeEnum.shareWeiQuan);
        typeList.add(UserMoneyDetailTypeEnum.hongbaoDeduct);
        //新版维权(到账时减去了维权资金,但是在资金明细里面加入了维权金额,但并未外显)
        typeList.add(UserMoneyDetailTypeEnum.fanliWeiQuanNew);
    @Override
    public Extract getMyTaskInfo(Long adminId) {
        return extractMapper.getMyTaskInfo(adminId);
    }
        BigDecimal weiqaunMoney = userMoneyDetailService.statisticUserTypeMoneyWithDate(uid, typeList, new Date(0),
                now);
        weiqaunMoney = weiqaunMoney.abs();
    @Override
    public Extract getNewTaskInfo() {
        return extractMapper.getNewTaskInfo();
    }
    @Override
    public List<Map<String, Object>> getFinishRecord(int pageIndex, int pageSize, String key, String startTime,
            String endTime) {
        return extractMapper.getFinishRecord((pageIndex - 1) * pageSize, pageSize, key, startTime, endTime);
    }
        //--------------所有支出结束------------
    @Override
    public int updateByPrimaryKeySelective(Extract record) {
        return extractMapper.updateByPrimaryKeySelective(record);
    }
        BigDecimal balance = userInfoService.selectByPKey(uid).getMyHongBao();
    @Transactional
    @Override
    public void processExtractResult(AlipayTransferResultInfo info) {
        if (info == null)
            return;
        AlipayFundTransUniTransferResponse response = info.getAlipayFundTransUniTransferResponse();
        Extract extract = info.getExtract();
        AdminUser admin = info.getAdminUser();
        if (response == null)
            return;
        if (extract == null)
            return;
        BigDecimal after = hongBaoMoney.add(teamDividents).add(redPackExchange).subtract(extractMoney.add(weiqaunMoney).add(balance).add(compensateMoney));
        extract = extractMapper.selectByPrimaryKey(info.getExtract().getId());
        if (after.compareTo(new BigDecimal("0")) != 0)
            throw new ExtractException(2, "结算资金异常:" + after);
    }
        LogHelper.test("提现结果:code-" + response.getCode() + " 信息:" + response.getMsg());
        long uid = extract.getUserInfo().getId();
        if (response.isSuccess()) {
            String code = response.getCode();
            if ("10000".equals(code)) {
                extractSuccess(extract,response.getOrderId());
            } else {
                extractFail(extract, response.getSubMsg());
            }
        } else {
            extractFail(extract, response.getSubMsg());
        }
        PayInfo payInfo = new PayInfo();
        payInfo.setBizno(response.getOutBizNo());
        payInfo.setCreatetime(new Date());
        payInfo.setExtract(extract);
        if ("10000".equals(response.getCode())) {
            payInfo.setState(1);
        } else {
            payInfo.setState(2);
        }
        payInfo.setOrderId(response.getOrderId());
        payInfo.setOrdertime(response.getTransDate());
        payInfo.setInfo(response.getSubMsg());
        payInfoMapper.insertSelective(payInfo);
    @Override
    public Extract selectByPrimaryKey(Long id) {
        return extractMapper.selectByPrimaryKey(id);
    }
        // 更新审核记录
        ExtractAuditRecord auditRecord = null;
        List<ExtractAuditRecord> records = extractAuditRecordMapper.getbyExtractId(extract.getId());
        if (records != null && records.size() > 0) {
            auditRecord = records.get(0);
        }
    @Override
    public Extract getMyTaskInfo(Long adminId) {
        return extractMapper.getMyTaskInfo(adminId);
    }
        if (auditRecord != null) {
    @Override
    public Extract getNewTaskInfo() {
        return extractMapper.getNewTaskInfo();
    }
            // 提现付款记录
            List<PayInfo> paylist = payInfoMapper.getListbyExtractId(extract.getId());
    @Override
    public List<Map<String, Object>> getFinishRecord(int pageIndex, int pageSize, String key, String startTime,
                                                     String endTime) {
        return extractMapper.getFinishRecord((pageIndex - 1) * pageSize, pageSize, key, startTime, endTime);
    }
            if (paylist != null && paylist.size() > 0) {
                // 提现成功 : 提现之前总金额:提现时金额减去提现金额
                BigDecimal exceedMoney = MoneyBigDecimalUtil.sub(auditRecord.getBeforeMoney(), extract.getMoney());
                // 提现之后金额
                auditRecord.setAfterMoney(exceedMoney);
            } else {
                // 提现失败:付款方余额不足、账户信息错误 提现之后金额 不变
                auditRecord.setAfterMoney(auditRecord.getBeforeMoney());
            }
    @Override
    public int updateByPrimaryKeySelective(Extract record) {
        return extractMapper.updateByPrimaryKeySelective(record);
    }
            // 历史提现金额
            double countSuccessMoneys = extractMapper.countSuccessMoneysByUid(uid);
            auditRecord.setCountMoney(new BigDecimal(countSuccessMoneys));
    @Transactional
    @Override
    public void processExtractResult(AlipayTransferResultInfo info) {
        if (info == null)
            return;
        AlipayFundTransUniTransferResponse response = info.getAlipayFundTransUniTransferResponse();
        Extract extract = info.getExtract();
        AdminUser admin = info.getAdminUser();
        if (response == null)
            return;
        if (extract == null)
            return;
            // 历史提现次数
            long countSuccess = extractMapper.countSuccessByUid(uid);
            auditRecord.setCountNum(countSuccess);
        extract = extractMapper.selectByPrimaryKey(info.getExtract().getId());
            // 角色默认:客服
            auditRecord.setAuditRole("客服");
            // 审核人
            auditRecord.setAdminUser(admin);
            // 审核时间
            auditRecord.setAuditTime(java.lang.System.currentTimeMillis());
        LogHelper.test("提现结果:code-" + response.getCode() + " 信息:" + response.getMsg());
        long uid = extract.getUserInfo().getId();
        if (response.isSuccess()) {
            String code = response.getCode();
            if ("10000".equals(code)) {
                extractSuccess(extract, response.getOrderId());
            } else {
                extractFail(extract, response.getSubMsg());
            }
        } else {
            extractFail(extract, response.getSubMsg());
        }
        PayInfo payInfo = new PayInfo();
        payInfo.setBizno(response.getOutBizNo());
        payInfo.setCreatetime(new Date());
        payInfo.setExtract(extract);
        if ("10000".equals(response.getCode())) {
            payInfo.setState(1);
        } else {
            payInfo.setState(2);
        }
        payInfo.setOrderId(response.getOrderId());
        payInfo.setOrdertime(response.getTransDate());
        payInfo.setInfo(response.getSubMsg());
        payInfoMapper.insertSelective(payInfo);
        // 更新审核记录
        ExtractAuditRecord auditRecord = null;
        List<ExtractAuditRecord> records = extractAuditRecordMapper.getbyExtractId(extract.getId());
        if (records != null && records.size() > 0) {
            auditRecord = records.get(0);
        }
        if (auditRecord != null) {
            // 提现付款记录
            List<PayInfo> paylist = payInfoMapper.getListbyExtractId(extract.getId());
            if (paylist != null && paylist.size() > 0) {
                // 提现成功 : 提现之前总金额:提现时金额减去提现金额
                BigDecimal exceedMoney = MoneyBigDecimalUtil.sub(auditRecord.getBeforeMoney(), extract.getMoney());
                // 提现之后金额
                auditRecord.setAfterMoney(exceedMoney);
            } else {
                // 提现失败:付款方余额不足、账户信息错误 提现之后金额 不变
                auditRecord.setAfterMoney(auditRecord.getBeforeMoney());
            }
            // 历史提现金额
            double countSuccessMoneys = extractMapper.countSuccessMoneysByUid(uid);
            auditRecord.setCountMoney(new BigDecimal(countSuccessMoneys));
            // 历史提现次数
            long countSuccess = extractMapper.countSuccessByUid(uid);
            auditRecord.setCountNum(countSuccess);
            // 角色默认:客服
            auditRecord.setAuditRole("客服");
            // 审核人
            auditRecord.setAdminUser(admin);
            // 审核时间
            auditRecord.setAuditTime(java.lang.System.currentTimeMillis());
            // 更新提现记录审核表
            extractAuditRecordMapper.updateByPrimaryKeySelective(auditRecord);
        }
    }
            // 更新提现记录审核表
            extractAuditRecordMapper.updateByPrimaryKeySelective(auditRecord);
        }
    @Transactional
    @Override
    public void testExtractSuccess(Long id) {
        Extract extract = extractMapper.selectByPrimaryKey(id);
        extractSuccess(extract, null);
        Long uid = extract.getUserInfo().getId();
    }
        // 更新审核记录
        ExtractAuditRecord auditRecord = null;
        List<ExtractAuditRecord> records = extractAuditRecordMapper.getbyExtractId(extract.getId());
        if (records != null && records.size() > 0) {
            auditRecord = records.get(0);
        }
    @Transactional
    @Override
    public void testExtractSuccess(Long id) {
        Extract extract = extractMapper.selectByPrimaryKey(id);
        extractSuccess(extract,null);
        Long uid = extract.getUserInfo().getId();
        if (auditRecord != null) {
            // 提现付款记录
            List<PayInfo> paylist = payInfoMapper.getListbyExtractId(extract.getId());
            if (paylist != null && paylist.size() > 0) {
                // 提现成功 : 提现之前总金额:提现时金额减去提现金额
                BigDecimal exceedMoney = MoneyBigDecimalUtil.sub(auditRecord.getBeforeMoney(), extract.getMoney());
                // 提现之后金额
                auditRecord.setAfterMoney(exceedMoney);
            } else {
                // 提现失败:付款方余额不足、账户信息错误 提现之后金额 不变
                auditRecord.setAfterMoney(auditRecord.getBeforeMoney());
            }
        // 更新审核记录
        ExtractAuditRecord auditRecord = null;
        List<ExtractAuditRecord> records = extractAuditRecordMapper.getbyExtractId(extract.getId());
        if (records != null && records.size() > 0) {
            auditRecord = records.get(0);
        }
            // 历史提现金额
            double countSuccessMoneys = extractMapper.countSuccessMoneysByUid(uid);
            auditRecord.setCountMoney(new BigDecimal(countSuccessMoneys));
        if (auditRecord != null) {
            // 提现付款记录
            List<PayInfo> paylist = payInfoMapper.getListbyExtractId(extract.getId());
            if (paylist != null && paylist.size() > 0) {
                // 提现成功 : 提现之前总金额:提现时金额减去提现金额
                BigDecimal exceedMoney = MoneyBigDecimalUtil.sub(auditRecord.getBeforeMoney(), extract.getMoney());
                // 提现之后金额
                auditRecord.setAfterMoney(exceedMoney);
            } else {
                // 提现失败:付款方余额不足、账户信息错误 提现之后金额 不变
                auditRecord.setAfterMoney(auditRecord.getBeforeMoney());
            }
            // 历史提现次数
            long countSuccess = extractMapper.countSuccessByUid(uid);
            auditRecord.setCountNum(countSuccess);
            // 历史提现金额
            double countSuccessMoneys = extractMapper.countSuccessMoneysByUid(uid);
            auditRecord.setCountMoney(new BigDecimal(countSuccessMoneys));
            // 角色默认:客服
            auditRecord.setAuditRole("客服");
            // 审核人
            auditRecord.setAdminUser(new AdminUser(3L));
            // 审核时间
            auditRecord.setAuditTime(java.lang.System.currentTimeMillis());
            // 历史提现次数
            long countSuccess = extractMapper.countSuccessByUid(uid);
            auditRecord.setCountNum(countSuccess);
            // 更新提现记录审核表
            extractAuditRecordMapper.updateByPrimaryKeySelective(auditRecord);
        }
            // 角色默认:客服
            auditRecord.setAuditRole("客服");
            // 审核人
            auditRecord.setAdminUser(new AdminUser(3L));
            // 审核时间
            auditRecord.setAuditTime(java.lang.System.currentTimeMillis());
    }
            // 更新提现记录审核表
            extractAuditRecordMapper.updateByPrimaryKeySelective(auditRecord);
        }
    @Override
    public BigDecimal sumTodayApplyMoney(Long uid, String day) {
        return extractMapper.sumToadyApplyByUid(uid, day);
    }
    }
    @Override
    public BigDecimal sumVerifyingMoney(Long uid) {
        List<Integer> stateList = new ArrayList<>();
        stateList.add(Extract.STATE_NOT_PROCESS);
        stateList.add(Extract.STATE_PROCESSING);
        BigDecimal money = extractMapper.sumMoneyByUidAndState(uid, stateList);
        if (money == null)
            return new BigDecimal(0);
        else
            return money;
    }
    @Override
    public BigDecimal sumTodayApplyMoney(Long uid, String day) {
        return extractMapper.sumToadyApplyByUid(uid, day);
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void autoExtract(UserInfo user) {
        if (user == null || user.getWxOpenId() == null || user.getWxUnionId() == null
                || user.getState() != UserInfo.STATE_NORMAL)
            return;
    @Override
    public BigDecimal sumVerifyingMoney(Long uid) {
        List<Integer> stateList = new ArrayList<>();
        stateList.add(Extract.STATE_NOT_PROCESS);
        stateList.add(Extract.STATE_PROCESSING);
        BigDecimal money = extractMapper.sumMoneyByUidAndState(uid, stateList);
        if (money == null)
            return new BigDecimal(0);
        else
            return money;
    }
        Date date = new Date();
        BigDecimal money = new BigDecimal(Constant.AUTO_EXTRACT_MONEY);
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void autoExtract(UserInfo user) {
        if (user == null || user.getWxOpenId() == null || user.getWxUnionId() == null
                || user.getState() != UserInfo.STATE_NORMAL)
            return;
        // 1、插入记录
        ExtractWeiXinRecord extractRecord = new ExtractWeiXinRecord();
        extractRecord.setUid(user.getId());
        extractRecord.setOpenId(user.getWxOpenId());
        extractRecord.setUnionId(user.getWxUnionId());
        extractRecord.setMoney(money);
        extractRecord.setCreateTime(date);
        extractRecord.setUpdateTime(date);
        extractWeiXinRecordService.insertSelective(extractRecord);
        Date date = new Date();
        BigDecimal money = new BigDecimal(Constant.AUTO_EXTRACT_MONEY);
        // 交易号
        Long recordId = extractRecord.getId();
        String billno = "BanLiExtract" + recordId;
        // 1、插入记录
        ExtractWeiXinRecord extractRecord = new ExtractWeiXinRecord();
        extractRecord.setUid(user.getId());
        extractRecord.setOpenId(user.getWxOpenId());
        extractRecord.setUnionId(user.getWxUnionId());
        extractRecord.setMoney(money);
        extractRecord.setCreateTime(date);
        extractRecord.setUpdateTime(date);
        extractWeiXinRecordService.insertSelective(extractRecord);
        // 更新记录
        ExtractWeiXinRecord updeteRecord = null;
        // 交易号
        Long recordId = extractRecord.getId();
        String billno = "BanLiExtract" + recordId;
        String mchId = "1520950211";
        String appId = "wx5c0d167c6e3ad726";
        String key = "XYJkJ2018FAfaodCCx899mLl138rfGVd";
        // 更新记录
        ExtractWeiXinRecord updeteRecord = null;
        // 2、发放微信红包
        RedPackParams redPackParams = new RedPackParams();
        redPackParams.setBillno(billno);
        redPackParams.setMchId(mchId);
        redPackParams.setWxappId(appId);
        redPackParams.setSendName("板栗快省");
        redPackParams.setOpenid(user.getWxOpenId());
        redPackParams.setMoney(money);
        redPackParams.setTotalNum(1);
        redPackParams.setWishing("账户中剩余余额请在本App内完成提现");
        redPackParams.setClientIp("106.80.118.163");
        redPackParams.setActName("自动提现");
        redPackParams.setKey(key);
        redPackParams.setRemark("微信自动提现");
        // redPackParams.setSceneId(null);
        // redPackParams.setRiskInfo(null);
        String mchId = "1520950211";
        String appId = "wx5c0d167c6e3ad726";
        String key = "XYJkJ2018FAfaodCCx899mLl138rfGVd";
        // 发生红包状态
        boolean stateRedPack = false;
        // 2、发放微信红包
        RedPackParams redPackParams = new RedPackParams();
        redPackParams.setBillno(billno);
        redPackParams.setMchId(mchId);
        redPackParams.setWxappId(appId);
        redPackParams.setSendName("板栗快省");
        redPackParams.setOpenid(user.getWxOpenId());
        redPackParams.setMoney(money);
        redPackParams.setTotalNum(1);
        redPackParams.setWishing("账户中剩余余额请在本App内完成提现");
        redPackParams.setClientIp("106.80.118.163");
        redPackParams.setActName("自动提现");
        redPackParams.setKey(key);
        redPackParams.setRemark("微信自动提现");
        // redPackParams.setSceneId(null);
        // redPackParams.setRiskInfo(null);
        String pwd = "1520950211";
        InputStream cert = ExtractServiceImpl.class.getClassLoader()
                .getResourceAsStream("certificate/apiclient_cert.p12"); // 读取.p12文件
        // 执行发放红包
        try {
            String result = WXPayUtil.redPackToOpenId(redPackParams, pwd, cert);
            if (!StringUtil.isNullOrEmpty(result)) {
                stateRedPack = parseSendResult(result);
            }
        // 发生红包状态
        boolean stateRedPack = false;
            if (!stateRedPack) {
                String redPackRecord = WXPayUtil.getRedPackRecord(billno, mchId, appId, key, pwd, cert);
                if (!StringUtil.isNullOrEmpty(redPackRecord)) {
                    updeteRecord = parseDTO(redPackRecord);
                }
            }
        } catch (Exception e) {
            String redPackRecord = WXPayUtil.getRedPackRecord(billno, mchId, appId, key, pwd, cert);
            if (!StringUtil.isNullOrEmpty(redPackRecord)) {
                updeteRecord = parseDTO(redPackRecord);
            }
            LogHelper.errorDetailInfo(e);
        }
        try {
            cert.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        String pwd = "1520950211";
        InputStream cert = ExtractServiceImpl.class.getClassLoader()
                .getResourceAsStream("certificate/apiclient_cert.p12"); // 读取.p12文件
        // 执行发放红包
        try {
            String result = WXPayUtil.redPackToOpenId(redPackParams, pwd, cert);
            if (!StringUtil.isNullOrEmpty(result)) {
                stateRedPack = parseSendResult(result);
            }
        // 更新信息
        if (updeteRecord == null) {
            updeteRecord = new ExtractWeiXinRecord();
        } else {
            stateRedPack = true;
        }
            if (!stateRedPack) {
                String redPackRecord = WXPayUtil.getRedPackRecord(billno, mchId, appId, key, pwd, cert);
                if (!StringUtil.isNullOrEmpty(redPackRecord)) {
                    updeteRecord = parseDTO(redPackRecord);
                }
            }
        } catch (Exception e) {
            String redPackRecord = WXPayUtil.getRedPackRecord(billno, mchId, appId, key, pwd, cert);
            if (!StringUtil.isNullOrEmpty(redPackRecord)) {
                updeteRecord = parseDTO(redPackRecord);
            }
            LogHelper.errorDetailInfo(e);
        }
        try {
            cert.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        updeteRecord.setId(recordId);
        updeteRecord.setStatus(ExtractWeiXinRecord.SENDING);
        updeteRecord.setBillno(billno);
        extractWeiXinRecordService.updateByPrimaryKeySelective(updeteRecord);
        // 更新信息
        if (updeteRecord == null) {
            updeteRecord = new ExtractWeiXinRecord();
        } else {
            stateRedPack = true;
        }
        // 红包发放失败
        if (!stateRedPack)
            return;
        updeteRecord.setId(recordId);
        updeteRecord.setStatus(ExtractWeiXinRecord.SENDING);
        updeteRecord.setBillno(billno);
        extractWeiXinRecordService.updateByPrimaryKeySelective(updeteRecord);
        // 3、加入资金明细
        UserMoneyDetail detail = new UserMoneyDetail();
        detail.setCreateTime(new Date());
        detail.setIdentifyCode(StringUtil.Md5(UserMoneyDetailTypeEnum.extractAutoWX.name() + ":" + recordId));
        detail.setMoney(money);
        detail.setTitle(UserMoneyDetailTypeEnum.extractAutoWX.getDesc());
        detail.setType(UserMoneyDetailTypeEnum.extractAutoWX);
        detail.setUpdateTime(new Date());
        detail.setUserInfo(user);
        try {
            userMoneyDetailService.addUserMoneyDetail(detail);
        } catch (UserMoneyDetailException e) {
            LogHelper.errorDetailInfo(e);
        }
        // 红包发放失败
        if (!stateRedPack)
            return;
    }
        // 3、加入资金明细
        UserMoneyDetail detail = new UserMoneyDetail();
        detail.setCreateTime(new Date());
        detail.setIdentifyCode(StringUtil.Md5(UserMoneyDetailTypeEnum.extractAutoWX.name() + ":" + recordId));
        detail.setMoney(money);
        detail.setTitle(UserMoneyDetailTypeEnum.extractAutoWX.getDesc());
        detail.setType(UserMoneyDetailTypeEnum.extractAutoWX);
        detail.setUpdateTime(new Date());
        detail.setUserInfo(user);
        try {
            userMoneyDetailService.addUserMoneyDetail(detail);
        } catch (UserMoneyDetailException e) {
            LogHelper.errorDetailInfo(e);
        }
    private boolean parseSendResult(String result) {
        try {
            Document document = DocumentHelper.parseText(result);
            // 获取根节点元素对象
            Element root = document.getRootElement();
            Element returnCode = root.element("return_code");
    }
            if (!"SUCCESS".equalsIgnoreCase(returnCode.getText())) {
                Element returnMsg = root.element("return_msg");
                System.out.println(returnMsg.getText());
                return false;
            }
    private boolean parseSendResult(String result) {
        try {
            Document document = DocumentHelper.parseText(result);
            // 获取根节点元素对象
            Element root = document.getRootElement();
            Element returnCode = root.element("return_code");
            Element resultCode = root.element("result_code");
            if (!"SUCCESS".equalsIgnoreCase(resultCode.getText())) {
                Element errCode = root.element("err_code");
                Element errCodeDes = root.element("err_code_des");
                System.out.println(errCode.getText() + ":" + errCodeDes.getText());
                return false;
            }
            return true;
        } catch (DocumentException e) {
            e.printStackTrace();
            LogHelper.errorDetailInfo(e);
        }
        return false;
    }
            if (!"SUCCESS".equalsIgnoreCase(returnCode.getText())) {
                Element returnMsg = root.element("return_msg");
                System.out.println(returnMsg.getText());
                return false;
            }
    private ExtractWeiXinRecord parseDTO(String result) {
        try {
            Element resultCode = root.element("result_code");
            if (!"SUCCESS".equalsIgnoreCase(resultCode.getText())) {
                Element errCode = root.element("err_code");
                Element errCodeDes = root.element("err_code_des");
                System.out.println(errCode.getText() + ":" + errCodeDes.getText());
                return false;
            }
            return true;
        } catch (DocumentException e) {
            e.printStackTrace();
            LogHelper.errorDetailInfo(e);
        }
        return false;
    }
            Document document = DocumentHelper.parseText(result);
            // 获取根节点元素对象
            Element root = document.getRootElement();
            Element returnCode = root.element("return_code");
    private ExtractWeiXinRecord parseDTO(String result) {
        try {
            if (!"SUCCESS".equalsIgnoreCase(returnCode.getText())) {
                Element returnMsg = root.element("return_msg");
                System.out.println(returnMsg.getText());
                return null;
            }
            Document document = DocumentHelper.parseText(result);
            // 获取根节点元素对象
            Element root = document.getRootElement();
            Element returnCode = root.element("return_code");
            Element resultCode = root.element("result_code");
            if (!"SUCCESS".equalsIgnoreCase(resultCode.getText())) {
                Element errCode = root.element("err_code");
                Element errCodeDes = root.element("err_code_des");
                System.out.println(errCode.getText() + ":" + errCodeDes.getText());
            }
            if (!"SUCCESS".equalsIgnoreCase(returnCode.getText())) {
                Element returnMsg = root.element("return_msg");
                System.out.println(returnMsg.getText());
                return null;
            }
            ExtractWeiXinRecord resultRecord = new ExtractWeiXinRecord();
            resultRecord.setBillno(root.element("result_code").getText());
            resultRecord.setDetailno(root.element("detail_id").getText());
            resultRecord.setStatus(root.element("status").getText());
            resultRecord.setSendType(root.element("send_type").getText());
            resultRecord.setHbType(root.element("result_code").getText());
            Element resultCode = root.element("result_code");
            if (!"SUCCESS".equalsIgnoreCase(resultCode.getText())) {
                Element errCode = root.element("err_code");
                Element errCodeDes = root.element("err_code_des");
                System.out.println(errCode.getText() + ":" + errCodeDes.getText());
            }
            String totalNum = root.element("total_num").getText();
            resultRecord.setTotalNum(Integer.parseInt(totalNum));
            ExtractWeiXinRecord resultRecord = new ExtractWeiXinRecord();
            resultRecord.setBillno(root.element("result_code").getText());
            resultRecord.setDetailno(root.element("detail_id").getText());
            resultRecord.setStatus(root.element("status").getText());
            resultRecord.setSendType(root.element("send_type").getText());
            resultRecord.setHbType(root.element("result_code").getText());
            String sendTime = root.element("send_time").getText();
            resultRecord.setSendTime(new Date(TimeUtil.convertDateToTemp2(sendTime)));
            String totalNum = root.element("total_num").getText();
            resultRecord.setTotalNum(Integer.parseInt(totalNum));
            Element element = root.element("hblist");
            Iterator<?> iterator = element.elementIterator();
            while (iterator.hasNext()) {
                Element childElement = (Element) iterator.next();
                Element rcvTime = childElement.element("rcv_time");
                resultRecord.setRcvTime(new Date(TimeUtil.convertDateToTemp2(rcvTime.getText())));
                break;
            }
            return resultRecord;
            String sendTime = root.element("send_time").getText();
            resultRecord.setSendTime(new Date(TimeUtil.convertDateToTemp2(sendTime)));
        } catch (DocumentException e) {
            e.printStackTrace();
            LogHelper.errorDetailInfo(e);
        }
        return null;
    }
            Element element = root.element("hblist");
            Iterator<?> iterator = element.elementIterator();
            while (iterator.hasNext()) {
                Element childElement = (Element) iterator.next();
                Element rcvTime = childElement.element("rcv_time");
                resultRecord.setRcvTime(new Date(TimeUtil.convertDateToTemp2(rcvTime.getText())));
                break;
            }
            return resultRecord;
    @Override
    public List<UserInfo> preAutoUser() throws Exception {
        int page = 0;
        int pageSize = 100;
        int maxSize = 300;
        Date nowDate = new Date();
        // 一、自动提现针对的用户群: 前提条件:用户在距今60天到90天内未活跃过的用户
        String beganDate = DateUtil.reduceDayTostring(90, nowDate);
        String endDate = DateUtil.reduceDayTostring(60, nowDate);
        // 条件3:距离上一次成功领取微信红包已经超过了30天时间,可在第31天再次下发;
        String receivedDate = DateUtil.reduceDayTostring(30, nowDate);
        // 条件4:距离上一次未成功领取微信红包已经超过了15天时间,可在第16天再次下发;
        String refundDate = DateUtil.reduceDayTostring(15, nowDate);
        } catch (DocumentException e) {
            e.printStackTrace();
            LogHelper.errorDetailInfo(e);
        }
        return null;
    }
        // 余额最低限制
        BigDecimal minSurplus = BigDecimal.valueOf(Constant.AUTO_EXTRACT_MIN_SURPLUS);
    @Override
    public List<UserInfo> preAutoUser() throws Exception {
        int page = 0;
        int pageSize = 100;
        int maxSize = 300;
        Date nowDate = new Date();
        // 一、自动提现针对的用户群: 前提条件:用户在距今60天到90天内未活跃过的用户
        String beganDate = DateUtil.reduceDayTostring(90, nowDate);
        String endDate = DateUtil.reduceDayTostring(60, nowDate);
        // 条件3:距离上一次成功领取微信红包已经超过了30天时间,可在第31天再次下发;
        String receivedDate = DateUtil.reduceDayTostring(30, nowDate);
        // 条件4:距离上一次未成功领取微信红包已经超过了15天时间,可在第16天再次下发;
        String refundDate = DateUtil.reduceDayTostring(15, nowDate);
        List<UserInfo> list = new ArrayList<UserInfo>();
        // 余额最低限制
        BigDecimal minSurplus = BigDecimal.valueOf(Constant.AUTO_EXTRACT_MIN_SURPLUS);
        while (true) {
            // 查询满足条件 1、2 的uid
            List<UserInfo> listUser = userInfoService.getAutoExtractUser(page * pageSize, pageSize, minSurplus,
                    beganDate, endDate);
            if (listUser == null || listUser.isEmpty())
                break;
        List<UserInfo> list = new ArrayList<UserInfo>();
            List<Long> listId = new ArrayList<Long>();
            for (UserInfo userInfo : listUser) {
                listId.add(userInfo.getId());
            }
        while (true) {
            // 查询满足条件 1、2 的uid
            List<UserInfo> listUser = userInfoService.getAutoExtractUser(page * pageSize, pageSize, minSurplus,
                    beganDate, endDate);
            if (listUser == null || listUser.isEmpty())
                break;
            // 查询记录是否满足
            List<Long> listValid = extractWeiXinRecordService.getValidUsers(listId, receivedDate, refundDate);
            if (listValid == null || listValid.isEmpty()) {
                page++;
                continue;
            }
            List<Long> listId = new ArrayList<Long>();
            for (UserInfo userInfo : listUser) {
                listId.add(userInfo.getId());
            }
            for (Long uid : listValid) {
                if (list.size() >= maxSize)
                    break;
                for (UserInfo userInfo : listUser) {
                    if (list.size() >= maxSize)
                        break;
            // 查询记录是否满足
            List<Long> listValid = extractWeiXinRecordService.getValidUsers(listId, receivedDate, refundDate);
            if (listValid == null || listValid.isEmpty()) {
                page++;
                continue;
            }
                    if (userInfo.getId().longValue() == uid.longValue()) {
                        list.add(userInfo);
                        break;
                    }
                }
            }
            for (Long uid : listValid) {
                if (list.size() >= maxSize)
                    break;
                for (UserInfo userInfo : listUser) {
                    if (list.size() >= maxSize)
                        break;
            if (list.size() >= maxSize)
                break;
                    if (userInfo.getId().longValue() == uid.longValue()) {
                        list.add(userInfo);
                        break;
                    }
                }
            }
            page++;
        }
        return list;
    }
            if (list.size() >= maxSize)
                break;
    @Override
    public List<String> getAutoExtractOpenIds() throws Exception {
        int page = 0;
        int pageSize = 100;
        int maxSize = 301; // appId + 实际openid300个
        Date nowDate = new Date();
        // 一、自动提现针对的用户群: 前提条件:用户在距今60天到90天内未活跃过的用户
        String beganDate = DateUtil.reduceDayTostring(90, nowDate);
        String endDate = DateUtil.reduceDayTostring(60, nowDate);
        // 条件3:距离上一次成功领取微信红包已经超过了30天时间,可在第31天再次下发;
        String receivedDate = DateUtil.reduceDayTostring(30, nowDate);
        // 条件4:距离上一次未成功领取微信红包已经超过了15天时间,可在第16天再次下发;
        String refundDate = DateUtil.reduceDayTostring(15, nowDate);
            page++;
        }
        return list;
    }
        // 提现金额
        BigDecimal money = BigDecimal.valueOf(Constant.AUTO_EXTRACT_MONEY);
        // 余额最低限制
        BigDecimal minSurplus = BigDecimal.valueOf(Constant.AUTO_EXTRACT_MIN_SURPLUS);
    @Override
    public List<String> getAutoExtractOpenIds() throws Exception {
        int page = 0;
        int pageSize = 100;
        int maxSize = 301; // appId + 实际openid300个
        Date nowDate = new Date();
        // 一、自动提现针对的用户群: 前提条件:用户在距今60天到90天内未活跃过的用户
        String beganDate = DateUtil.reduceDayTostring(90, nowDate);
        String endDate = DateUtil.reduceDayTostring(60, nowDate);
        // 条件3:距离上一次成功领取微信红包已经超过了30天时间,可在第31天再次下发;
        String receivedDate = DateUtil.reduceDayTostring(30, nowDate);
        // 条件4:距离上一次未成功领取微信红包已经超过了15天时间,可在第16天再次下发;
        String refundDate = DateUtil.reduceDayTostring(15, nowDate);
        List<String> listOpendIDs = new ArrayList<String>();
        // 首行appID
        listOpendIDs.add(Constant.getWXAccount(null, null).getAppId());
        // 提现金额
        BigDecimal money = BigDecimal.valueOf(Constant.AUTO_EXTRACT_MONEY);
        // 余额最低限制
        BigDecimal minSurplus = BigDecimal.valueOf(Constant.AUTO_EXTRACT_MIN_SURPLUS);
        while (true) {
            // 查询满足条件 1、2 的uid
            List<UserInfo> listUser = userInfoService.getAutoExtractUser(page * pageSize, pageSize, minSurplus,
                    beganDate, endDate);
            if (listUser == null || listUser.isEmpty())
                break;
        List<String> listOpendIDs = new ArrayList<String>();
        // 首行appID
        listOpendIDs.add(Constant.getWXAccount(null, null).getAppId());
            List<Long> listId = new ArrayList<Long>();
            for (UserInfo userInfo : listUser) {
                listId.add(userInfo.getId());
            }
        while (true) {
            // 查询满足条件 1、2 的uid
            List<UserInfo> listUser = userInfoService.getAutoExtractUser(page * pageSize, pageSize, minSurplus,
                    beganDate, endDate);
            if (listUser == null || listUser.isEmpty())
                break;
            // 查询记录是否满足
            List<Long> listValid = extractWeiXinRecordService.getValidUsers(listId, receivedDate, refundDate);
            if (listValid == null || listValid.isEmpty()) {
                page++;
                continue;
            }
            List<Long> listId = new ArrayList<Long>();
            for (UserInfo userInfo : listUser) {
                listId.add(userInfo.getId());
            }
            for (Long uid : listValid) {
                UserInfo userInfo = subHongBaoByUid(uid, money, minSurplus);
                if (userInfo != null) {
                    listOpendIDs.add(userInfo.getWxOpenId());
                    if (listOpendIDs.size() >= maxSize)
                        break;
                }
            }
            // 查询记录是否满足
            List<Long> listValid = extractWeiXinRecordService.getValidUsers(listId, receivedDate, refundDate);
            if (listValid == null || listValid.isEmpty()) {
                page++;
                continue;
            }
            if (listOpendIDs.size() >= maxSize)
                break;
            for (Long uid : listValid) {
                UserInfo userInfo = subHongBaoByUid(uid, money, minSurplus);
                if (userInfo != null) {
                    listOpendIDs.add(userInfo.getWxOpenId());
                    if (listOpendIDs.size() >= maxSize)
                        break;
                }
            }
            page++;
        }
        return listOpendIDs;
    }
            if (listOpendIDs.size() >= maxSize)
                break;
    @Override
    public List<UserInfo> preAutoUserTo1212() throws Exception {
        int page = 0;
        int pageSize = 100;
        int maxSize = 300;
        Date nowDate = new Date();
        // 条件3:距离上一次成功领取微信红包已经超过了30天时间,可在第31天再次下发;
        String receivedDate = DateUtil.reduceDayTostring(30, nowDate);
        // 条件4:距离上一次未成功领取微信红包已经超过了15天时间,可在第16天再次下发;
        String refundDate = DateUtil.reduceDayTostring(15, nowDate);
        // 余额最低限制
        List<UserInfo> list = new ArrayList<UserInfo>();
        while (true) {
            // 查询满足条件 1、2 的uid
            List<UserInfo> listUser = userInfoService.getAutoExtractUserTo1212(page * pageSize, pageSize);
            if (listUser == null || listUser.isEmpty())
                break;
            page++;
        }
        return listOpendIDs;
    }
            List<Long> listId = new ArrayList<Long>();
            for (UserInfo userInfo : listUser) {
                listId.add(userInfo.getId());
            }
    @Override
    public List<UserInfo> preAutoUserTo1212() throws Exception {
        int page = 0;
        int pageSize = 100;
        int maxSize = 300;
        Date nowDate = new Date();
        // 条件3:距离上一次成功领取微信红包已经超过了30天时间,可在第31天再次下发;
        String receivedDate = DateUtil.reduceDayTostring(30, nowDate);
        // 条件4:距离上一次未成功领取微信红包已经超过了15天时间,可在第16天再次下发;
        String refundDate = DateUtil.reduceDayTostring(15, nowDate);
        // 余额最低限制
        List<UserInfo> list = new ArrayList<UserInfo>();
        while (true) {
            // 查询满足条件 1、2 的uid
            List<UserInfo> listUser = userInfoService.getAutoExtractUserTo1212(page * pageSize, pageSize);
            if (listUser == null || listUser.isEmpty())
                break;
            // 查询记录是否满足
            List<Long> listValid = extractWeiXinRecordService.getValidUsers(listId, receivedDate, refundDate);
            if (listValid == null || listValid.isEmpty()) {
                page++;
                continue;
            }
            List<Long> listId = new ArrayList<Long>();
            for (UserInfo userInfo : listUser) {
                listId.add(userInfo.getId());
            }
            for (Long uid : listValid) {
                if (list.size() >= maxSize)
                    break;
                for (UserInfo userInfo : listUser) {
                    if (list.size() >= maxSize)
                        break;
            // 查询记录是否满足
            List<Long> listValid = extractWeiXinRecordService.getValidUsers(listId, receivedDate, refundDate);
            if (listValid == null || listValid.isEmpty()) {
                page++;
                continue;
            }
                    if (userInfo.getId().longValue() == uid.longValue()) {
                        list.add(userInfo);
                        break;
                    }
                }
            }
            for (Long uid : listValid) {
                if (list.size() >= maxSize)
                    break;
                for (UserInfo userInfo : listUser) {
                    if (list.size() >= maxSize)
                        break;
            if (list.size() >= maxSize)
                break;
                    if (userInfo.getId().longValue() == uid.longValue()) {
                        list.add(userInfo);
                        break;
                    }
                }
            }
            page++;
        }
        return list;
    }
            if (list.size() >= maxSize)
                break;
    @Override
    public List<String> getAutoExtractOpenIdsTo1212() throws Exception {
        int page = 0;
        int pageSize = 100;
        int maxSize = 301; // appId + 实际openid300个
        Date nowDate = new Date();
        // 条件3:距离上一次成功领取微信红包已经超过了30天时间,可在第31天再次下发;
        String receivedDate = DateUtil.reduceDayTostring(30, nowDate);
        // 条件4:距离上一次未成功领取微信红包已经超过了15天时间,可在第16天再次下发;
        String refundDate = DateUtil.reduceDayTostring(15, nowDate);
            page++;
        }
        return list;
    }
        // 提现金额
        BigDecimal money = BigDecimal.valueOf(1);
    @Override
    public List<String> getAutoExtractOpenIdsTo1212() throws Exception {
        int page = 0;
        int pageSize = 100;
        int maxSize = 301; // appId + 实际openid300个
        Date nowDate = new Date();
        // 条件3:距离上一次成功领取微信红包已经超过了30天时间,可在第31天再次下发;
        String receivedDate = DateUtil.reduceDayTostring(30, nowDate);
        // 条件4:距离上一次未成功领取微信红包已经超过了15天时间,可在第16天再次下发;
        String refundDate = DateUtil.reduceDayTostring(15, nowDate);
        List<String> listOpendIDs = new ArrayList<String>();
        // 首行appID
        listOpendIDs.add(Constant.getWXAccount(null, null).getAppId());
        // 提现金额
        BigDecimal money = BigDecimal.valueOf(1);
        while (true) {
            // 查询满足条件 1、2 的uid
            List<UserInfo> listUser = userInfoService.getAutoExtractUserTo1212(page * pageSize, pageSize);
            if (listUser == null || listUser.isEmpty())
                break;
        List<String> listOpendIDs = new ArrayList<String>();
        // 首行appID
        listOpendIDs.add(Constant.getWXAccount(null, null).getAppId());
            List<Long> listId = new ArrayList<Long>();
            for (UserInfo userInfo : listUser) {
                listId.add(userInfo.getId());
            }
        while (true) {
            // 查询满足条件 1、2 的uid
            List<UserInfo> listUser = userInfoService.getAutoExtractUserTo1212(page * pageSize, pageSize);
            if (listUser == null || listUser.isEmpty())
                break;
            // 查询记录是否满足
            List<Long> listValid = extractWeiXinRecordService.getValidUsers(listId, receivedDate, refundDate);
            if (listValid == null || listValid.isEmpty()) {
                page++;
                continue;
            }
            List<Long> listId = new ArrayList<Long>();
            for (UserInfo userInfo : listUser) {
                listId.add(userInfo.getId());
            }
            for (Long uid : listValid) {
                UserInfo userInfo = subHongBaoByUid(uid, money, money);
                if (userInfo != null) {
                    listOpendIDs.add(userInfo.getWxOpenId());
                    if (listOpendIDs.size() >= maxSize)
                        break;
                }
            }
            // 查询记录是否满足
            List<Long> listValid = extractWeiXinRecordService.getValidUsers(listId, receivedDate, refundDate);
            if (listValid == null || listValid.isEmpty()) {
                page++;
                continue;
            }
            if (listOpendIDs.size() >= maxSize)
                break;
            for (Long uid : listValid) {
                UserInfo userInfo = subHongBaoByUid(uid, money, money);
                if (userInfo != null) {
                    listOpendIDs.add(userInfo.getWxOpenId());
                    if (listOpendIDs.size() >= maxSize)
                        break;
                }
            }
            page++;
        }
        return listOpendIDs;
    }
            if (listOpendIDs.size() >= maxSize)
                break;
    @Transactional(rollbackFor = Exception.class)
    private UserInfo subHongBaoByUid(Long uid, BigDecimal money, BigDecimal minSurplus) {
        UserInfo userInfo = userInfoMapper.selectByPrimaryKeyForUpdate(uid);
        if (userInfo != null && !StringUtil.isNullOrEmpty(userInfo.getWxOpenId())
                && !StringUtil.isNullOrEmpty(userInfo.getWxUnionId())
                && userInfo.getMyHongBao().compareTo(minSurplus) >= 0) {
            // 微信提现记录
            ExtractWeiXinRecord extractRecord = new ExtractWeiXinRecord();
            extractRecord.setUid(uid);
            extractRecord.setOpenId(userInfo.getWxOpenId());
            extractRecord.setUnionId(userInfo.getWxUnionId());
            extractRecord.setMoney(money);
            extractRecord.setStatus(ExtractWeiXinRecord.SENDING);
            extractRecord.setType(ExtractWeiXinRecord.TYPE_MANUAL);
            extractRecord.setCreateTime(new Date());
            extractRecord.setUpdateTime(new Date());
            extractWeiXinRecordService.insertSelective(extractRecord);
            // 记录id
            Long recordId = extractRecord.getId();
            page++;
        }
        return listOpendIDs;
    }
            // 资金明细
            UserMoneyDetail detail = new UserMoneyDetail();
            detail.setCreateTime(new Date());
            detail.setIdentifyCode(StringUtil.Md5(UserMoneyDetailTypeEnum.extractAutoWX.name() + ":" + recordId));
            detail.setMoney(new BigDecimal("-" + money.toString()));
            detail.setTitle(UserMoneyDetailTypeEnum.extractAutoWX.getDesc());
            detail.setType(UserMoneyDetailTypeEnum.extractAutoWX);
            detail.setUpdateTime(new Date());
            detail.setUserInfo(userInfo);
    @Transactional(rollbackFor = Exception.class)
    private UserInfo subHongBaoByUid(Long uid, BigDecimal money, BigDecimal minSurplus) {
        UserInfo userInfo = userInfoMapper.selectByPrimaryKeyForUpdate(uid);
        if (userInfo != null && !StringUtil.isNullOrEmpty(userInfo.getWxOpenId())
                && !StringUtil.isNullOrEmpty(userInfo.getWxUnionId())
                && userInfo.getMyHongBao().compareTo(minSurplus) >= 0) {
            // 微信提现记录
            ExtractWeiXinRecord extractRecord = new ExtractWeiXinRecord();
            extractRecord.setUid(uid);
            extractRecord.setOpenId(userInfo.getWxOpenId());
            extractRecord.setUnionId(userInfo.getWxUnionId());
            extractRecord.setMoney(money);
            extractRecord.setStatus(ExtractWeiXinRecord.SENDING);
            extractRecord.setType(ExtractWeiXinRecord.TYPE_MANUAL);
            extractRecord.setCreateTime(new Date());
            extractRecord.setUpdateTime(new Date());
            extractWeiXinRecordService.insertSelective(extractRecord);
            // 记录id
            Long recordId = extractRecord.getId();
            // 资金计算
            userMoneyService.subUserMoney(userInfo.getId(), money, detail);
            // 资金明细
            UserMoneyDetail detail = new UserMoneyDetail();
            detail.setCreateTime(new Date());
            detail.setIdentifyCode(StringUtil.Md5(UserMoneyDetailTypeEnum.extractAutoWX.name() + ":" + recordId));
            detail.setMoney(new BigDecimal("-" + money.toString()));
            detail.setTitle(UserMoneyDetailTypeEnum.extractAutoWX.getDesc());
            detail.setType(UserMoneyDetailTypeEnum.extractAutoWX);
            detail.setUpdateTime(new Date());
            detail.setUserInfo(userInfo);
            // 满足条件返回信息
            return userInfo;
        }
        return null;
    }
            // 资金计算
            userMoneyService.subUserMoney(userInfo.getId(), money, detail);
    @Override
    public void updateManualExtractRecord(List<RedPackRecord> list) throws ExtractException {
        if (list == null || list.isEmpty())
            throw new ExtractException(1, "红包记录信息为空");
            // 满足条件返回信息
            return userInfo;
        }
        return null;
    }
        for (RedPackRecord redPackRecord : list) {
            updateWeiXinRecord(redPackRecord);
        }
    }
    @Override
    public void updateManualExtractRecord(List<RedPackRecord> list) throws ExtractException {
        if (list == null || list.isEmpty())
            throw new ExtractException(1, "红包记录信息为空");
    @Transactional(rollbackFor = Exception.class)
    private void updateWeiXinRecord(RedPackRecord redPackRecord) {
        if (StringUtil.isNullOrEmpty(redPackRecord.getOpenId()))
            return;
        for (RedPackRecord redPackRecord : list) {
            updateWeiXinRecord(redPackRecord);
        }
    }
        ExtractWeiXinRecord record = extractWeiXinRecordService.getByOpenIdAndType(redPackRecord.getOpenId(),
                ExtractWeiXinRecord.TYPE_MANUAL);
        if (record == null)
            return;
    @Transactional(rollbackFor = Exception.class)
    private void updateWeiXinRecord(RedPackRecord redPackRecord) {
        if (StringUtil.isNullOrEmpty(redPackRecord.getOpenId()))
            return;
        // 状态过滤
        String statusOld = record.getStatus();
        if (StringUtil.isNullOrEmpty(statusOld) || ExtractWeiXinRecord.REFUND.equals(statusOld)
                || ExtractWeiXinRecord.RECEIVED.equals(statusOld))
            return;
        ExtractWeiXinRecord record = extractWeiXinRecordService.getByOpenIdAndType(redPackRecord.getOpenId(),
                ExtractWeiXinRecord.TYPE_MANUAL);
        if (record == null)
            return;
        ExtractWeiXinRecord updeteRecord = new ExtractWeiXinRecord();
        updeteRecord.setId(record.getId());
        updeteRecord.setUpdateTime(new Date());
        // 状态过滤
        String statusOld = record.getStatus();
        if (StringUtil.isNullOrEmpty(statusOld) || ExtractWeiXinRecord.REFUND.equals(statusOld)
                || ExtractWeiXinRecord.RECEIVED.equals(statusOld))
            return;
        String billno = redPackRecord.getBillno();
        if (!StringUtil.isNullOrEmpty(billno)) {
            updeteRecord.setBillno(billno.replace("`", "").replace("'", ""));
        }
        ExtractWeiXinRecord updeteRecord = new ExtractWeiXinRecord();
        updeteRecord.setId(record.getId());
        updeteRecord.setUpdateTime(new Date());
        String detailno = redPackRecord.getDetailno();
        if (!StringUtil.isNullOrEmpty(detailno)) {
            updeteRecord.setDetailno(detailno.replace("`", "").replace("'", ""));
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String rcvTime = redPackRecord.getRcvTime();
        if (!StringUtil.isNullOrEmpty(rcvTime)) {
            try {
                updeteRecord.setRcvTime(sdf.parse(rcvTime));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        String billno = redPackRecord.getBillno();
        if (!StringUtil.isNullOrEmpty(billno)) {
            updeteRecord.setBillno(billno.replace("`", "").replace("'", ""));
        }
        String sendTime = redPackRecord.getSendTime();
        if (!StringUtil.isNullOrEmpty(sendTime)) {
            try {
                updeteRecord.setSendTime(sdf.parse(sendTime));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        String detailno = redPackRecord.getDetailno();
        if (!StringUtil.isNullOrEmpty(detailno)) {
            updeteRecord.setDetailno(detailno.replace("`", "").replace("'", ""));
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String rcvTime = redPackRecord.getRcvTime();
        if (!StringUtil.isNullOrEmpty(rcvTime)) {
            try {
                updeteRecord.setRcvTime(sdf.parse(rcvTime));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        String status = redPackRecord.getStatus();
        if (!StringUtil.isNullOrEmpty(status)) {
            switch (status) {
                case "已发放待领取":
                    status = ExtractWeiXinRecord.SENT;
                    break;
                case "过期未领退款":
                    status = ExtractWeiXinRecord.REFUND;
                    break;
                case "已领取":
                    status = ExtractWeiXinRecord.RECEIVED;
                    break;
                default:
                    status = null;
                    break;
            }
        }
        updeteRecord.setStatus(status);
        extractWeiXinRecordService.updateByPrimaryKeySelective(updeteRecord);
        String sendTime = redPackRecord.getSendTime();
        if (!StringUtil.isNullOrEmpty(sendTime)) {
            try {
                updeteRecord.setSendTime(sdf.parse(sendTime));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (ExtractWeiXinRecord.RECEIVED.equals(status)) {
        } else if (ExtractWeiXinRecord.REFUND.equals(status)) {
            // 资金明细
            UserMoneyDetail detail = new UserMoneyDetail();
            detail.setCreateTime(new Date());
            detail.setIdentifyCode(
                    StringUtil.Md5(UserMoneyDetailTypeEnum.extractAutoWXRefund.name() + ":" + record.getId()));
            detail.setMoney(record.getMoney());
            detail.setTitle(UserMoneyDetailTypeEnum.extractAutoWXRefund.getDesc());
            detail.setType(UserMoneyDetailTypeEnum.extractAutoWXRefund);
            detail.setUpdateTime(new Date());
            detail.setUserInfo(new UserInfo(record.getUid()));
            // 资金计算
            userMoneyService.addUserMoney(record.getUid(), record.getMoney(), detail);
        }
    }
        String status = redPackRecord.getStatus();
        if (!StringUtil.isNullOrEmpty(status)) {
            switch (status) {
            case "已发放待领取":
                status = ExtractWeiXinRecord.SENT;
                break;
            case "过期未领退款":
                status = ExtractWeiXinRecord.REFUND;
                break;
            case "已领取":
                status = ExtractWeiXinRecord.RECEIVED;
                break;
            default:
                status = null;
                break;
            }
        }
        updeteRecord.setStatus(status);
        extractWeiXinRecordService.updateByPrimaryKeySelective(updeteRecord);
        if (ExtractWeiXinRecord.RECEIVED.equals(status)) {
        } else if (ExtractWeiXinRecord.REFUND.equals(status)) {
            // 资金明细
            UserMoneyDetail detail = new UserMoneyDetail();
            detail.setCreateTime(new Date());
            detail.setIdentifyCode(
                    StringUtil.Md5(UserMoneyDetailTypeEnum.extractAutoWXRefund.name() + ":" + record.getId()));
            detail.setMoney(record.getMoney());
            detail.setTitle(UserMoneyDetailTypeEnum.extractAutoWXRefund.getDesc());
            detail.setType(UserMoneyDetailTypeEnum.extractAutoWXRefund);
            detail.setUpdateTime(new Date());
            detail.setUserInfo(new UserInfo(record.getUid()));
            // 资金计算
            userMoneyService.addUserMoney(record.getUid(), record.getMoney(), detail);
        }
    }
    @Override
    public List<Extract> getExtractSucceedRecord(int page, int pageSize, Long uid) {
        return extractMapper.getExtractSucceedRecord((page - 1) * pageSize, pageSize, uid);
    }
    @Override
    public List<Extract> getExtractSucceedRecord(int page, int pageSize, Long uid) {
        return extractMapper.getExtractSucceedRecord((page-1)*pageSize, pageSize, uid);
    }
    @Override
    public long countExtractSucceedRecord(Long uid) {
       Long count = extractMapper.countExtractSucceedRecord(uid);
       return count== null? 0 : count;
    }
    @Override
    public long countExtractSucceedRecord(Long uid) {
        Long count = extractMapper.countExtractSucceedRecord(uid);
        return count == null ? 0 : count;
    }
}
fanli/src/main/java/com/yeshi/fanli/service/impl/money/tb/TaoBaoWeiQuanDrawBackServiceImpl.java
@@ -217,7 +217,7 @@
            // 退款金额
            BigDecimal drawBackMoney = computeDrawBackMoney(settleMent, wqMoney, userGetMoney);
            userSubMoneyMap.put(uid, drawBackMoney);
            if (subMoneySync) {
            if (subMoneySync) {//同步减去资金
                // 计算资金是否充足
                UserInfo user = userInfoMapper.selectByPrimaryKey(uid);
                if (user != null && user.getMyHongBao().compareTo(drawBackMoney) < 0)// 资金不足
fanli/src/main/java/com/yeshi/fanli/service/impl/order/CommonOrderServiceImpl.java
Diff too large
fanli/src/main/java/com/yeshi/fanli/service/impl/order/HongBaoV2ServiceImpl.java
@@ -739,7 +739,7 @@
                // 插入一级子红包
                BigDecimal firstRate = hongBaoManageService
                        .getFirstInviteRate(boss.getRank() == null ? 0 : boss.getRank(),system);
                        .getFirstInviteRate(boss.getRank() == null ? 0 : boss.getRank(), system);
                if (firstRate.compareTo(new BigDecimal(0)) <= 0)
                    return mianDanMoney != null;
                HongBaoV2 firstHongbao = new HongBaoV2();
@@ -792,7 +792,7 @@
                boss = threeSaleSerivce.getBoss(boss.getId());
                if (boss != null) {// 二级BOSS存在
                    BigDecimal secondRate = hongBaoManageService
                            .getSecondInviteRate(boss.getRank() == null ? 0 : boss.getRank(),system);
                            .getSecondInviteRate(boss.getRank() == null ? 0 : boss.getRank(), system);
                    if (secondRate.compareTo(new BigDecimal(0)) <= 0)
                        return mianDanMoney != null;
                    HongBaoV2 secondHongbao = new HongBaoV2();
@@ -853,10 +853,10 @@
            BigDecimal shareRate = null;
            if (commonOrder.getSourceType() == Constant.SOURCE_TYPE_TAOBAO
                    && commonOrder.getSourcePosition().equalsIgnoreCase(TaoBaoConstant.TAOBAO_TLJ_RELATION_PID_DEFAULT))// 来自于淘礼金的分享
                shareRate = hongBaoManageService.getTLJShareRate(commonOrder.getCreateTime().getTime(),system);
                shareRate = hongBaoManageService.getTLJShareRate(commonOrder.getCreateTime().getTime(), system);
            else
                shareRate = hongBaoManageService.getShareRate(UserLevelEnum.daRen,
                        commonOrder.getCreateTime().getTime(),system);
                        commonOrder.getCreateTime().getTime(), system);
            UserInfo user = userInfoService.getUserById(commonOrder.getUserInfo().getId());
@@ -873,7 +873,7 @@
                    if (taoBaoOrderList != null && taoBaoOrderList.size() > 0
                            && !StringUtil.isNullOrEmpty(taoBaoOrderList.get(0).getRelationId())) {
                        if (shareGoodsActivityOrderService.listByUid(commonOrder.getUserInfo().getId()).size() < 1) {
                            shareRate = new BigDecimal(hongBaoManageService.get("share_activity_proportion",system));
                            shareRate = new BigDecimal(hongBaoManageService.get("share_activity_proportion", system));
                            try {
                                shareGoodsActivityOrderService.addShareGoodsActivityOrder(
                                        commonOrder.getUserInfo().getId(), shareRate, commonOrder.getOrderNo());
@@ -944,7 +944,7 @@
                UserInfo boss = threeSaleSerivce.getBoss(hongBao.getUserInfo().getId());
                if (boss != null) {
                    BigDecimal firstLevelRate = hongBaoManageService.getFirstShareRate(1,
                            commonOrder.getThirdCreateTime().getTime(),system);
                            commonOrder.getThirdCreateTime().getTime(), system);
                    HongBaoV2 child = new HongBaoV2();
                    child.setParent(hongBao);
                    child.setType(HongBaoV2.TYPE_SHARE_YIJI);
@@ -1143,6 +1143,7 @@
        List<Integer> stateList = new ArrayList<>();
        stateList.add(HongBaoV2.STATE_BUKELINGQU);
        stateList.add(HongBaoV2.STATE_KELINGQU);
        stateList.add(HongBaoV2.STATE_LINGQUING);
        stateList.add(HongBaoV2.STATE_YILINGQU);
        List<HongBaoV2> hongBaoV2List = hongBaoV2Mapper.listByStateAndTypeAndUid(stateList, typeList, uid, 0, 1);
        if (hongBaoV2List != null && hongBaoV2List.size() > 0)
@@ -1165,5 +1166,11 @@
        return hongBaoV2Mapper.getDirectBossUrankByPid(pid);
    }
    @Transactional
    @Override
    public void setHongBaoRecieved(Long uid, List<Integer> typeList, Date preGetTime) {
        hongBaoV2Mapper.setHongBaoRecieved(uid, typeList, preGetTime);
    }
}
fanli/src/main/java/com/yeshi/fanli/service/impl/order/OrderMoneySettleServiceImpl.java
@@ -64,864 +64,684 @@
@Service
public class OrderMoneySettleServiceImpl implements OrderMoneySettleService {
    @Resource
    private HongBaoV2Mapper hongBaoV2Mapper;
    @Resource
    private HongBaoV2Mapper hongBaoV2Mapper;
    @Resource
    private HongBaoOrderMapper hongBaoOrderMapper;
    @Resource
    private HongBaoOrderMapper hongBaoOrderMapper;
    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private TaoBaoWeiQuanOrderMapper taoBaoWeiQuanOrderMapper;
    @Resource
    private TaoBaoWeiQuanOrderMapper taoBaoWeiQuanOrderMapper;
    @Resource
    private UserMoneyService userMoneyService;
    @Resource
    private UserMoneyService userMoneyService;
    @Resource
    private UserMoneyMsgNotificationService userMoneyMsgNotificationService;
    @Resource
    private UserMoneyMsgNotificationService userMoneyMsgNotificationService;
    @Resource
    private TaoBaoWeiQuanDrawBackService taoBaoWeiQuanDrawBackService;
    @Resource
    private TaoBaoWeiQuanDrawBackService taoBaoWeiQuanDrawBackService;
    @Resource
    private AccountDetailsHongBaoMapService accountDetailsHongBaoMapService;
    @Resource
    private AccountDetailsHongBaoMapService accountDetailsHongBaoMapService;
    @Resource
    private CommonOrderService commonOrderService;
    @Resource
    private CommonOrderService commonOrderService;
    @Resource
    private UserSystemCouponService userSystemCouponService;
    @Resource
    private UserSystemCouponService userSystemCouponService;
    @Resource(name = "orderTransactionProducer")
    private TransactionProducer orderTransactionProducer;
    @Resource(name = "orderTransactionProducer")
    private TransactionProducer orderTransactionProducer;
    // 邀请补贴
    // 邀请补贴
    @Resource
    private HongBaoV2SettleTempService hongBaoV2SettleTempService;
    @Resource
    private HongBaoV2SettleTempService hongBaoV2SettleTempService;
    @Resource
    private TeamRewardDebtService teamRewardDebtService;
    @Resource
    private TeamRewardDebtService teamRewardDebtService;
    @Resource
    private TeamRewardManager teamRewardManager;
    @Resource
    private RocketMQManager rocketMQManager;
    @Resource
    private TeamRewardManager teamRewardManager;
    // 下级被封禁,红包失效
    private void invalidHongBaoForbidden(Long id) {
        HongBaoV2 updateHongBaoV2 = new HongBaoV2(id);
        updateHongBaoV2.setState(HongBaoV2.STATE_SHIXIAO);
        updateHongBaoV2.setBeizhu("封禁失效");
        updateHongBaoV2.setUpdateTime(new Date());
        hongBaoV2Mapper.updateByPrimaryKeySelective(updateHongBaoV2);
    }
    @Resource
    private RocketMQManager rocketMQManager;
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void inviteSettleTB(Long uid, Date maxPregetTime) throws OrderMoneySettleException {
        // 查询UID的一二级邀请赚
        int sourceType = Constant.SOURCE_TYPE_TAOBAO;
        List<Integer> types = new ArrayList<>();
        types.add(HongBaoV2.TYPE_YIJI);
        types.add(HongBaoV2.TYPE_ERJI);
        types.add(HongBaoV2.TYPE_SHARE_YIJI);
        types.add(HongBaoV2.TYPE_SHARE_ERJI);
        long count = hongBaoV2Mapper.countCanBalanceHongBaoByTypeAndUid(types, uid, sourceType, maxPregetTime);
        List<HongBaoV2> hongBaoList = new ArrayList<>();
        // 1000条数据为1页
        int page = (int) (count % 1000 == 0 ? count / 1000 : count / 1000 + 1);
        for (int i = 0; i < page; i++) {
            List<HongBaoV2> tempHongBaoList = hongBaoV2Mapper.listCanBalanceHongBaoByTypeAndUid(types, uid, sourceType,
                    maxPregetTime, i * 1000, 1000);
            if (tempHongBaoList != null && tempHongBaoList.size() > 0)
                hongBaoList.addAll(tempHongBaoList);
        }
    // 下级被封禁,红包失效
    private void invalidHongBaoForbidden(Long id) {
        HongBaoV2 updateHongBaoV2 = new HongBaoV2(id);
        updateHongBaoV2.setState(HongBaoV2.STATE_SHIXIAO);
        updateHongBaoV2.setBeizhu("封禁失效");
        updateHongBaoV2.setUpdateTime(new Date());
        hongBaoV2Mapper.updateByPrimaryKeySelective(updateHongBaoV2);
    }
        for (int i = 0; i < hongBaoList.size(); i++) {
            HongBaoV2 item = hongBaoList.get(i);
            if (item != null && item.getParent() != null) {
                if (item != null) {
                    HongBaoOrder hongBaoOrder = hongBaoOrderMapper.selectByHongBaoId(item.getParent().getId());
                    if (hongBaoOrder != null && hongBaoOrder.getCommonOrder() != null) {
                        CommonOrder co = hongBaoOrder.getCommonOrder();
                        // 上级用户不是正常用户,订单均不能到账
                        UserInfo userInfo = userInfoMapper.selectAvailableByPrimaryKey(co.getUserInfo().getId());
                        if (userInfo == null || userInfo.getState() != UserInfo.STATE_NORMAL) {
                            invalidHongBaoForbidden(item.getId());
                            hongBaoList.remove(i);
                            i--;
                        }
                    }
                }
            }
        }
        if(hongBaoList.size()==0)
            return;
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void inviteSettleTB(Long uid, Date maxPregetTime) throws OrderMoneySettleException {
        // 查询UID的一二级邀请赚
        int sourceType = Constant.SOURCE_TYPE_TAOBAO;
        inviteSettle(uid,sourceType,maxPregetTime);
    }
        String taskKey = getTaskKey(uid);
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void inviteSettleJD(Long uid, Date maxPregetTime) throws OrderMoneySettleException {
        // 查询UID的一二级邀请赚
        int sourceType = Constant.SOURCE_TYPE_JD;
        inviteSettle(uid,sourceType,maxPregetTime);
    }
        TeamRewardPreRecieveMQMsg mqMsg = new TeamRewardPreRecieveMQMsg(taskKey, uid, sourceType, maxPregetTime,
                new Date());
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void inviteSettlePDD(Long uid, Date maxPregetTime) throws OrderMoneySettleException {
        // 查询UID的一二级邀请赚
        int sourceType = Constant.SOURCE_TYPE_PDD;
        inviteSettle(uid,sourceType,maxPregetTime);
    }
        Message msg = MQMsgBodyFactory.create(MQTopicName.TOPIC_ORDER, OrderTopicTagEnum.teamRewardPreRecieved, mqMsg);
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void inviteSettleVipShop(Long uid, Date maxPregetTime) throws OrderMoneySettleException {
        // 查询UID的一二级邀请赚
        int sourceType = Constant.SOURCE_TYPE_VIP;
        inviteSettle(uid,sourceType,maxPregetTime);
    }
        msg.setKey(taskKey);
        // 添加事务消息
        try {
            orderTransactionProducer.send(msg, new LocalTransactionExecuter() {
                @Override
                public TransactionStatus execute(Message arg0, Object arg1) {
                    try {
                        fanliInvite(hongBaoList, uid, Constant.SOURCE_TYPE_TAOBAO, taskKey, maxPregetTime);
                    } catch (Exception e) {
                        e.printStackTrace();
                        return TransactionStatus.RollbackTransaction;
                    }
                    return TransactionStatus.CommitTransaction;
                }
            }, null);
//            rocketMQManager.sendTransactionalMsg(msg, taskKey, new RocketMQManager.ITransactionalMQEvent() {
//                @Override
//                public TransactionStatus excute(Message arg0, Object arg1) {
//                    try {
//                        fanliInvite(hongBaoList, uid, Constant.SOURCE_TYPE_TAOBAO, taskKey, maxPregetTime);
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                        return TransactionStatus.RollbackTransaction;
//                    }
//                    return TransactionStatus.CommitTransaction;
//                }
//            });
        } catch (Exception e) {
            e.printStackTrace();
            LogHelper.mqError(e.getMessage(), msg.getTopic(), msg.getTag(), new Gson().toJson(mqMsg));
        }
        System.out.println(new Gson().toJson(mqMsg));
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void inviteSettleJD(Long uid, Date maxPregetTime) throws OrderMoneySettleException {
        // 查询UID的一二级邀请赚
        int sourceType = Constant.SOURCE_TYPE_JD;
        List<Integer> types = new ArrayList<>();
        types.add(HongBaoV2.TYPE_YIJI);
        types.add(HongBaoV2.TYPE_ERJI);
        types.add(HongBaoV2.TYPE_SHARE_YIJI);
        types.add(HongBaoV2.TYPE_SHARE_ERJI);
        long count = hongBaoV2Mapper.countCanBalanceHongBaoByTypeAndUid(types, uid, sourceType, maxPregetTime);
        List<HongBaoV2> hongBaoList = new ArrayList<>();
        // 1000条数据为1页
        int page = (int) (count % 1000 == 0 ? count / 1000 : count / 1000 + 1);
        for (int i = 0; i < page; i++) {
            List<HongBaoV2> tempHongBaoList = hongBaoV2Mapper.listCanBalanceHongBaoByTypeAndUid(types, uid, sourceType,
                    maxPregetTime, i * 1000, 1000);
            if (tempHongBaoList != null && tempHongBaoList.size() > 0)
                hongBaoList.addAll(tempHongBaoList);
        }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void inviteSettleSuning(Long uid, Date maxPregetTime) throws OrderMoneySettleException {
        // 查询UID的一二级邀请赚
        int sourceType = Constant.SOURCE_TYPE_SUNING;
        inviteSettle(uid,sourceType,maxPregetTime);
    }
        for (int i = 0; i < hongBaoList.size(); i++) {
            HongBaoV2 item = hongBaoList.get(i);
            if (item != null && item.getParent() != null) {
                if (item != null) {
                    HongBaoOrder hongBaoOrder = hongBaoOrderMapper.selectByHongBaoId(item.getParent().getId());
                    if (hongBaoOrder != null && hongBaoOrder.getCommonOrder() != null) {
                        CommonOrder co = hongBaoOrder.getCommonOrder();
                        // 上级用户不是正常用户,订单均不能到账
                        UserInfo userInfo = userInfoMapper.selectAvailableByPrimaryKey(co.getUserInfo().getId());
                        if (userInfo == null || userInfo.getState() != UserInfo.STATE_NORMAL) {
                            invalidHongBaoForbidden(item.getId());
                            hongBaoList.remove(i);
                            i--;
                        }
                    }
                }
            }
        }
        if(hongBaoList.size()==0)
            return;
        // 邀请赚到账事务消息
    private void inviteSettle(Long uid, int sourceType, Date maxPregetTime) throws OrderMoneySettleException {
        // 查询UID的一二级邀请赚
        List<Integer> types = new ArrayList<>();
        types.add(HongBaoV2.TYPE_YIJI);
        types.add(HongBaoV2.TYPE_ERJI);
        types.add(HongBaoV2.TYPE_SHARE_YIJI);
        types.add(HongBaoV2.TYPE_SHARE_ERJI);
        long count = hongBaoV2Mapper.countCanBalanceHongBaoByTypeAndUid(types, uid, sourceType, maxPregetTime);
        List<HongBaoV2> hongBaoList = new ArrayList<>();
        // 1000条数据为1页
        int page = (int) (count % 1000 == 0 ? count / 1000 : count / 1000 + 1);
        for (int i = 0; i < page; i++) {
            List<HongBaoV2> tempHongBaoList = hongBaoV2Mapper.listCanBalanceHongBaoByTypeAndUid(types, uid, sourceType,
                    maxPregetTime, i * 1000, 1000);
            if (tempHongBaoList != null && tempHongBaoList.size() > 0)
                hongBaoList.addAll(tempHongBaoList);
        }
        String taskKey = getTaskKey(uid);
        TeamRewardPreRecieveMQMsg mqMsg = new TeamRewardPreRecieveMQMsg(taskKey, uid, sourceType, maxPregetTime,
                new Date());
        Message msg = MQMsgBodyFactory.create(MQTopicName.TOPIC_ORDER, OrderTopicTagEnum.teamRewardPreRecieved, mqMsg);
        msg.setKey(taskKey);
        // 添加事务消息
        try {
            orderTransactionProducer.send(msg, new LocalTransactionExecuter() {
                @Override
                public TransactionStatus execute(Message arg0, Object arg1) {
                    try {
                        fanliInvite(hongBaoList, uid, sourceType, taskKey, maxPregetTime);
                    } catch (Exception e) {
                        e.printStackTrace();
                        return TransactionStatus.RollbackTransaction;
                    }
                    return TransactionStatus.CommitTransaction;
                }
            }, null);
        } catch (Exception e) {
            LogHelper.mqError(e.getMessage(), msg.getTopic(), msg.getTag(), new Gson().toJson(mqMsg));
        }
    }
        for (int i = 0; i < hongBaoList.size(); i++) {
            HongBaoV2 item = hongBaoList.get(i);
            if (item != null && item.getParent() != null) {
                if (item != null) {
                    HongBaoOrder hongBaoOrder = hongBaoOrderMapper.selectByHongBaoId(item.getParent().getId());
                    if (hongBaoOrder != null && hongBaoOrder.getCommonOrder() != null) {
                        CommonOrder co = hongBaoOrder.getCommonOrder();
                        // 上级用户不是正常用户,订单均不能到账
                        UserInfo userInfo = userInfoMapper.selectAvailableByPrimaryKey(co.getUserInfo().getId());
                        if (userInfo == null || userInfo.getState() != UserInfo.STATE_NORMAL) {
                            invalidHongBaoForbidden(item.getId());
                            hongBaoList.remove(i);
                            i--;
                        }
                    }
                }
            }
        }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void inviteSettlePDD(Long uid, Date maxPregetTime) throws OrderMoneySettleException {
        // 查询UID的一二级邀请赚
        int sourceType = Constant.SOURCE_TYPE_PDD;
        List<Integer> types = new ArrayList<>();
        types.add(HongBaoV2.TYPE_YIJI);
        types.add(HongBaoV2.TYPE_ERJI);
        types.add(HongBaoV2.TYPE_SHARE_YIJI);
        types.add(HongBaoV2.TYPE_SHARE_ERJI);
        long count = hongBaoV2Mapper.countCanBalanceHongBaoByTypeAndUid(types, uid, sourceType, maxPregetTime);
        List<HongBaoV2> hongBaoList = new ArrayList<>();
        // 1000条数据为1页
        int page = (int) (count % 1000 == 0 ? count / 1000 : count / 1000 + 1);
        for (int i = 0; i < page; i++) {
            List<HongBaoV2> tempHongBaoList = hongBaoV2Mapper.listCanBalanceHongBaoByTypeAndUid(types, uid, sourceType,
                    maxPregetTime, i * 1000, 1000);
            if (tempHongBaoList != null && tempHongBaoList.size() > 0)
                hongBaoList.addAll(tempHongBaoList);
        }
        if (hongBaoList.size() == 0)
            return;
        for (int i = 0; i < hongBaoList.size(); i++) {
            HongBaoV2 item = hongBaoList.get(i);
            if (item != null && item.getParent() != null) {
                if (item != null) {
                    HongBaoOrder hongBaoOrder = hongBaoOrderMapper.selectByHongBaoId(item.getParent().getId());
                    if (hongBaoOrder != null && hongBaoOrder.getCommonOrder() != null) {
                        CommonOrder co = hongBaoOrder.getCommonOrder();
                        // 上级用户不是正常用户,订单均不能到账
                        UserInfo userInfo = userInfoMapper.selectAvailableByPrimaryKey(co.getUserInfo().getId());
                        if (userInfo == null || userInfo.getState() != UserInfo.STATE_NORMAL) {
                            invalidHongBaoForbidden(item.getId());
                            hongBaoList.remove(i);
                            i--;
                        }
                    }
                }
            }
        }
        if(hongBaoList.size()==0)
            return;
        // 邀请赚到账事务消息
        String taskKey = getTaskKey(uid);
        TeamRewardPreRecieveMQMsg mqMsg = new TeamRewardPreRecieveMQMsg(taskKey, uid, sourceType, maxPregetTime,
                new Date());
        Message msg = MQMsgBodyFactory.create(MQTopicName.TOPIC_ORDER, OrderTopicTagEnum.teamRewardPreRecieved, mqMsg);
        msg.setKey(taskKey);
        // 添加事务消息
        try {
            orderTransactionProducer.send(msg, new LocalTransactionExecuter() {
                @Override
                public TransactionStatus execute(Message arg0, Object arg1) {
                    try {
                        fanliInvite(hongBaoList, uid, sourceType, taskKey, maxPregetTime);
                    } catch (Exception e) {
                        return TransactionStatus.RollbackTransaction;
                    }
                    return TransactionStatus.CommitTransaction;
                }
            }, null);
        } catch (Exception e) {
            LogHelper.mqError(e.getMessage(), msg.getTopic(), msg.getTag(), new Gson().toJson(mqMsg));
        }
    }
        // 邀请赚到账事务消息
        String taskKey = getTaskKey(uid);
        TeamRewardPreRecieveMQMsg mqMsg = new TeamRewardPreRecieveMQMsg(taskKey, uid, sourceType, maxPregetTime,
                new Date());
        Message msg = MQMsgBodyFactory.create(MQTopicName.TOPIC_ORDER, OrderTopicTagEnum.teamRewardPreRecieved, mqMsg);
        msg.setKey(taskKey);
        // 添加事务消息
        try {
            orderTransactionProducer.send(msg, new LocalTransactionExecuter() {
                @Override
                public TransactionStatus execute(Message arg0, Object arg1) {
                    try {
                        fanliInvite(hongBaoList, uid, sourceType, taskKey, maxPregetTime);
                    } catch (Exception e) {
                        return TransactionStatus.RollbackTransaction;
                    }
                    return TransactionStatus.CommitTransaction;
                }
            }, null);
        } catch (Exception e) {
            LogHelper.mqError(e.getMessage(), msg.getTopic(), msg.getTag(), new Gson().toJson(mqMsg));
        }
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void shareSettleTB(Long uid, Date maxPregetTime) throws OrderMoneySettleException {
        /**
         * 处理分享赚
         */
        int sourceType = Constant.SOURCE_TYPE_TAOBAO;
        List<Integer> types = new ArrayList<>();
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void inviteSettleVipShop(Long uid, Date maxPregetTime) throws OrderMoneySettleException {
        // 查询UID的一二级邀请赚
        int sourceType = Constant.SOURCE_TYPE_VIP;
        List<Integer> types = new ArrayList<>();
        types.add(HongBaoV2.TYPE_YIJI);
        types.add(HongBaoV2.TYPE_ERJI);
        types.add(HongBaoV2.TYPE_SHARE_YIJI);
        types.add(HongBaoV2.TYPE_SHARE_ERJI);
        long count = hongBaoV2Mapper.countCanBalanceHongBaoByTypeAndUid(types, uid, sourceType, maxPregetTime);
        List<HongBaoV2> hongBaoList = new ArrayList<>();
        // 1000条数据为1页
        int page = (int) (count % 1000 == 0 ? count / 1000 : count / 1000 + 1);
        for (int i = 0; i < page; i++) {
            List<HongBaoV2> tempHongBaoList = hongBaoV2Mapper.listCanBalanceHongBaoByTypeAndUid(types, uid, sourceType,
                    maxPregetTime, i * 1000, 1000);
            if (tempHongBaoList != null && tempHongBaoList.size() > 0)
                hongBaoList.addAll(tempHongBaoList);
        }
        // 查询UID的分享赚订单
        types.add(HongBaoV2.TYPE_SHARE_GOODS);
        long count = hongBaoV2Mapper.countCanBalanceHongBaoByTypeAndUid(types, uid, sourceType, maxPregetTime);
        List<HongBaoV2> hongBaoList = new ArrayList<>();
        // 1000条数据为1页
        int page = (int) (count % 1000 == 0 ? count / 1000 : count / 1000 + 1);
        for (int i = 0; i < page; i++) {
            List<HongBaoV2> tempHongBaoList = hongBaoV2Mapper.listCanBalanceHongBaoByTypeAndUid(types, uid, sourceType,
                    maxPregetTime, i * 1000, 1000);
            if (tempHongBaoList != null && tempHongBaoList.size() > 0)
                hongBaoList.addAll(tempHongBaoList);
        }
        for (int i = 0; i < hongBaoList.size(); i++) {
            HongBaoV2 item = hongBaoList.get(i);
            if (item != null && item.getParent() != null) {
                if (item != null) {
                    HongBaoOrder hongBaoOrder = hongBaoOrderMapper.selectByHongBaoId(item.getParent().getId());
                    if (hongBaoOrder != null && hongBaoOrder.getCommonOrder() != null) {
                        CommonOrder co = hongBaoOrder.getCommonOrder();
                        // 上级用户不是正常用户,订单均不能到账
                        UserInfo userInfo = userInfoMapper.selectAvailableByPrimaryKey(co.getUserInfo().getId());
                        if (userInfo == null || userInfo.getState() != UserInfo.STATE_NORMAL) {
                            invalidHongBaoForbidden(item.getId());
                            hongBaoList.remove(i);
                            i--;
                        }
                    }
                }
            }
        }
        if(hongBaoList.size()==0)
            return;
        OrderMoneyRecievedMQMsg mqMsg = new OrderMoneyRecievedMQMsg(OrderMoneyRecievedMQMsg.TYPE_SHARE, uid, sourceType,
                null, null, new Date(), 0);
        Message msg = MQMsgBodyFactory.create(MQTopicName.TOPIC_ORDER, OrderTopicTagEnum.orderFanLiActual, mqMsg);
        String taskKey = getTaskKey(uid);
        msg.setKey(taskKey);
        // 邀请赚到账事务消息
        String taskKey = getTaskKey(uid);
        TeamRewardPreRecieveMQMsg mqMsg = new TeamRewardPreRecieveMQMsg(taskKey, uid, sourceType, maxPregetTime,
                new Date());
        Message msg = MQMsgBodyFactory.create(MQTopicName.TOPIC_ORDER, OrderTopicTagEnum.teamRewardPreRecieved, mqMsg);
        msg.setKey(taskKey);
        // 添加事务消息
        try {
            orderTransactionProducer.send(msg, new LocalTransactionExecuter() {
                @Override
                public TransactionStatus execute(Message arg0, Object arg1) {
                    try {
                        fanliInvite(hongBaoList, uid, sourceType, taskKey, maxPregetTime);
                    } catch (Exception e) {
                        return TransactionStatus.RollbackTransaction;
                    }
                    return TransactionStatus.CommitTransaction;
                }
            }, null);
        } catch (Exception e) {
            LogHelper.mqError(e.getMessage(), msg.getTopic(), msg.getTag(), new Gson().toJson(mqMsg));
        }
    }
        // 添加事务消息
        try {
            orderTransactionProducer.send(msg, new LocalTransactionExecuter() {
                @Override
                public TransactionStatus execute(Message arg0, Object arg1) {
                    try {
                        fanLiShareTB(hongBaoList, uid, taskKey);
                    } catch (TaoBaoWeiQuanException e) {
                        return TransactionStatus.RollbackTransaction;
                    }
                    return TransactionStatus.CommitTransaction;
                }
            }, null);
        } catch (Exception e) {
            LogHelper.mqError(e.getMessage(), msg.getTopic(), msg.getTag(), new Gson().toJson(mqMsg));
        }
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void shareSettleTB(Long uid, Date maxPregetTime) throws OrderMoneySettleException {
        /**
         * 处理分享赚
         */
        int sourceType = Constant.SOURCE_TYPE_TAOBAO;
        List<Integer> types = new ArrayList<>();
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void shareSettleJD(Long uid, Date maxPregetTime) throws OrderMoneySettleException {
        /**
         * 处理分享赚
         */
        int sourceType = Constant.SOURCE_TYPE_JD;
        List<Integer> types = new ArrayList<>();
        // 查询UID的分享赚订单
        types.add(HongBaoV2.TYPE_SHARE_GOODS);
        long count = hongBaoV2Mapper.countCanBalanceHongBaoByTypeAndUid(types, uid, sourceType, maxPregetTime);
        List<HongBaoV2> hongBaoList = new ArrayList<>();
        // 1000条数据为1页
        int page = (int) (count % 1000 == 0 ? count / 1000 : count / 1000 + 1);
        for (int i = 0; i < page; i++) {
            List<HongBaoV2> tempHongBaoList = hongBaoV2Mapper.listCanBalanceHongBaoByTypeAndUid(types, uid, sourceType,
                    maxPregetTime, i * 1000, 1000);
            if (tempHongBaoList != null && tempHongBaoList.size() > 0)
                hongBaoList.addAll(tempHongBaoList);
        }
        // 查询UID的分享赚订单
        types.add(HongBaoV2.TYPE_SHARE_GOODS);
        long count = hongBaoV2Mapper.countCanBalanceHongBaoByTypeAndUid(types, uid, sourceType, maxPregetTime);
        List<HongBaoV2> hongBaoList = new ArrayList<>();
        // 1000条数据为1页
        int page = (int) (count % 1000 == 0 ? count / 1000 : count / 1000 + 1);
        for (int i = 0; i < page; i++) {
            List<HongBaoV2> tempHongBaoList = hongBaoV2Mapper.listCanBalanceHongBaoByTypeAndUid(types, uid, sourceType,
                    maxPregetTime, i * 1000, 1000);
            if (tempHongBaoList != null && tempHongBaoList.size() > 0)
                hongBaoList.addAll(tempHongBaoList);
        }
        OrderMoneyRecievedMQMsg mqMsg = new OrderMoneyRecievedMQMsg(OrderMoneyRecievedMQMsg.TYPE_SHARE, uid, sourceType,
                null, null, new Date(), 0);
        Message msg = MQMsgBodyFactory.create(MQTopicName.TOPIC_ORDER, OrderTopicTagEnum.orderFanLiActual, mqMsg);
        String taskKey = getTaskKey(uid);
        msg.setKey(taskKey);
        OrderMoneyRecievedMQMsg mqMsg = new OrderMoneyRecievedMQMsg(OrderMoneyRecievedMQMsg.TYPE_SHARE, uid, sourceType,
                null, null, new Date(), 0);
        Message msg = MQMsgBodyFactory.create(MQTopicName.TOPIC_ORDER, OrderTopicTagEnum.orderFanLiActual, mqMsg);
        String taskKey = getTaskKey(uid);
        msg.setKey(taskKey);
        // 添加事务消息
        try {
            orderTransactionProducer.send(msg, new LocalTransactionExecuter() {
                @Override
                public TransactionStatus execute(Message arg0, Object arg1) {
                    fanLiShareOther(hongBaoList, uid, sourceType, taskKey);
                    return TransactionStatus.CommitTransaction;
                }
            }, null);
        } catch (Exception e) {
            LogHelper.mqError(e.getMessage(), msg.getTopic(), msg.getTag(), new Gson().toJson(mqMsg));
        }
    }
        // 添加事务消息
        try {
            orderTransactionProducer.send(msg, new LocalTransactionExecuter() {
                @Override
                public TransactionStatus execute(Message arg0, Object arg1) {
                    try {
                        fanLiShareTB(hongBaoList, uid, taskKey);
                    } catch (TaoBaoWeiQuanException e) {
                        return TransactionStatus.RollbackTransaction;
                    }
                    return TransactionStatus.CommitTransaction;
                }
            }, null);
        } catch (Exception e) {
            LogHelper.mqError(e.getMessage(), msg.getTopic(), msg.getTag(), new Gson().toJson(mqMsg));
        }
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void shareSettlePDD(Long uid, Date maxPregetTime) throws OrderMoneySettleException {
        shareSettle(Constant.SOURCE_TYPE_PDD, uid, maxPregetTime);
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void shareSettleJD(Long uid, Date maxPregetTime) throws OrderMoneySettleException {
        /**
         * 处理分享赚
         */
        int sourceType = Constant.SOURCE_TYPE_JD;
        List<Integer> types = new ArrayList<>();
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void shareSettleVipShop(Long uid, Date maxPregetTime) throws OrderMoneySettleException {
        shareSettle(Constant.SOURCE_TYPE_VIP, uid, maxPregetTime);
    }
        // 查询UID的分享赚订单
        types.add(HongBaoV2.TYPE_SHARE_GOODS);
        long count = hongBaoV2Mapper.countCanBalanceHongBaoByTypeAndUid(types, uid, sourceType, maxPregetTime);
        List<HongBaoV2> hongBaoList = new ArrayList<>();
        // 1000条数据为1页
        int page = (int) (count % 1000 == 0 ? count / 1000 : count / 1000 + 1);
        for (int i = 0; i < page; i++) {
            List<HongBaoV2> tempHongBaoList = hongBaoV2Mapper.listCanBalanceHongBaoByTypeAndUid(types, uid, sourceType,
                    maxPregetTime, i * 1000, 1000);
            if (tempHongBaoList != null && tempHongBaoList.size() > 0)
                hongBaoList.addAll(tempHongBaoList);
        }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void shareSettleSuning(Long uid, Date maxPregetTime) throws OrderMoneySettleException {
        shareSettle(Constant.SOURCE_TYPE_SUNING, uid, maxPregetTime);
    }
        OrderMoneyRecievedMQMsg mqMsg = new OrderMoneyRecievedMQMsg(OrderMoneyRecievedMQMsg.TYPE_SHARE, uid, sourceType,
                null, null, new Date(), 0);
        Message msg = MQMsgBodyFactory.create(MQTopicName.TOPIC_ORDER, OrderTopicTagEnum.orderFanLiActual, mqMsg);
        String taskKey = getTaskKey(uid);
        msg.setKey(taskKey);
        // 添加事务消息
        try {
            orderTransactionProducer.send(msg, new LocalTransactionExecuter() {
                @Override
                public TransactionStatus execute(Message arg0, Object arg1) {
                    fanLiShareOther(hongBaoList, uid, sourceType, taskKey);
                    return TransactionStatus.CommitTransaction;
                }
            }, null);
        } catch (Exception e) {
            LogHelper.mqError(e.getMessage(), msg.getTopic(), msg.getTag(), new Gson().toJson(mqMsg));
        }
    }
    private void shareSettle(int sourceType, Long uid, Date maxPregetTime) throws OrderMoneySettleException {
        /**
         * 处理分享赚
         */
        List<Integer> types = new ArrayList<>();
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void shareSettlePDD(Long uid, Date maxPregetTime) throws OrderMoneySettleException {
        shareSettleVipShop(Constant.SOURCE_TYPE_PDD, uid, maxPregetTime);
    }
        // 查询UID的分享赚订单
        types.add(HongBaoV2.TYPE_SHARE_GOODS);
        long count = hongBaoV2Mapper.countCanBalanceHongBaoByTypeAndUid(types, uid, sourceType, maxPregetTime);
        List<HongBaoV2> hongBaoList = new ArrayList<>();
        // 1000条数据为1页
        int page = (int) (count % 1000 == 0 ? count / 1000 : count / 1000 + 1);
        for (int i = 0; i < page; i++) {
            List<HongBaoV2> tempHongBaoList = hongBaoV2Mapper.listCanBalanceHongBaoByTypeAndUid(types, uid, sourceType,
                    maxPregetTime, i * 1000, 1000);
            if (tempHongBaoList != null && tempHongBaoList.size() > 0)
                hongBaoList.addAll(tempHongBaoList);
        }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void shareSettleVipShop(Long uid, Date maxPregetTime) throws OrderMoneySettleException {
        shareSettleVipShop(Constant.SOURCE_TYPE_VIP, uid, maxPregetTime);
    }
        OrderMoneyRecievedMQMsg mqMsg = new OrderMoneyRecievedMQMsg(OrderMoneyRecievedMQMsg.TYPE_SHARE, uid, sourceType,
                null, null, new Date(), 0);
        Message msg = MQMsgBodyFactory.create(MQTopicName.TOPIC_ORDER, OrderTopicTagEnum.orderFanLiActual, mqMsg);
        String taskKey = getTaskKey(uid);
        msg.setKey(taskKey);
        // 添加事务消息
        try {
            orderTransactionProducer.send(msg, new LocalTransactionExecuter() {
                @Override
                public TransactionStatus execute(Message arg0, Object arg1) {
                    fanLiShareOther(hongBaoList, uid, sourceType, taskKey);
                    return TransactionStatus.CommitTransaction;
                }
            }, null);
        } catch (Exception e) {
            LogHelper.mqError(e.getMessage(), msg.getTopic(), msg.getTag(), new Gson().toJson(mqMsg));
        }
    }
    private void shareSettleVipShop(int sourceType, Long uid, Date maxPregetTime) throws OrderMoneySettleException {
        /**
         * 处理分享赚
         */
        List<Integer> types = new ArrayList<>();
        // 查询UID的分享赚订单
        types.add(HongBaoV2.TYPE_SHARE_GOODS);
        long count = hongBaoV2Mapper.countCanBalanceHongBaoByTypeAndUid(types, uid, sourceType, maxPregetTime);
        List<HongBaoV2> hongBaoList = new ArrayList<>();
        // 1000条数据为1页
        int page = (int) (count % 1000 == 0 ? count / 1000 : count / 1000 + 1);
        for (int i = 0; i < page; i++) {
            List<HongBaoV2> tempHongBaoList = hongBaoV2Mapper.listCanBalanceHongBaoByTypeAndUid(types, uid, sourceType,
                    maxPregetTime, i * 1000, 1000);
            if (tempHongBaoList != null && tempHongBaoList.size() > 0)
                hongBaoList.addAll(tempHongBaoList);
        }
        OrderMoneyRecievedMQMsg mqMsg = new OrderMoneyRecievedMQMsg(OrderMoneyRecievedMQMsg.TYPE_SHARE, uid, sourceType,
                null, null, new Date(), 0);
        Message msg = MQMsgBodyFactory.create(MQTopicName.TOPIC_ORDER, OrderTopicTagEnum.orderFanLiActual, mqMsg);
        String taskKey = getTaskKey(uid);
        msg.setKey(taskKey);
        // 添加事务消息
        try {
            orderTransactionProducer.send(msg, new LocalTransactionExecuter() {
                @Override
                public TransactionStatus execute(Message arg0, Object arg1) {
                    fanLiShareOther(hongBaoList, uid, sourceType, taskKey);
                    return TransactionStatus.CommitTransaction;
                }
            }, null);
        } catch (Exception e) {
            LogHelper.mqError(e.getMessage(), msg.getTopic(), msg.getTag(), new Gson().toJson(mqMsg));
        }
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void ziGouSettle(String orderId, int sourceType, String taskKey) throws OrderMoneySettleException {
        // 查询同一订单号的红包
        List<CommonOrder> orderList = commonOrderService.listBySourceTypeAndOrderId(sourceType, orderId);
        List<HongBaoV2> hongBaoList = new ArrayList<>();
        Map<Long, BigDecimal> userMoney = new HashMap<>();
        Map<Long, List<HongBaoV2>> userHongBao = new HashMap<>();
        Map<Long, Integer> userGoodsCount = new HashMap<>();
        for (CommonOrder co : orderList) {
            HongBaoOrder hongBaoOrder = hongBaoOrderMapper.selectByCommonOrderId(co.getId());
            hongBaoList.add(hongBaoOrder.getHongBaoV2());
            Long uid = co.getUserInfo().getId();
            if (userGoodsCount.get(uid) == null)
                userGoodsCount.put(uid, co.getCount());
            else
                userGoodsCount.put(uid, Integer.valueOf(co.getCount() + userGoodsCount.get(uid)));
        }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void ziGouSettle(String orderId, int sourceType, String taskKey) throws OrderMoneySettleException {
        // 查询同一订单号的红包
        List<CommonOrder> orderList = commonOrderService.listBySourceTypeAndOrderId(sourceType, orderId);
        List<HongBaoV2> hongBaoList = new ArrayList<>();
        Map<Long, BigDecimal> userMoney = new HashMap<>();
        Map<Long, List<HongBaoV2>> userHongBao = new HashMap<>();
        Map<Long, Integer> userGoodsCount = new HashMap<>();
        for (CommonOrder co : orderList) {
            HongBaoOrder hongBaoOrder = hongBaoOrderMapper.selectByCommonOrderId(co.getId());
            hongBaoList.add(hongBaoOrder.getHongBaoV2());
            Long uid = co.getUserInfo().getId();
            if (userGoodsCount.get(uid) == null)
                userGoodsCount.put(uid, co.getCount());
            else
                userGoodsCount.put(uid, Integer.valueOf(co.getCount() + userGoodsCount.get(uid)));
        }
        for (HongBaoV2 hb : hongBaoList) {
            long currentTimeMillis = System.currentTimeMillis();
            if (hb.getState() != HongBao.STATE_SHIXIAO) {
                // 设置为已返利
                // 处理主红包
                if (hb.getState() != HongBaoV2.STATE_SHIXIAO && hb.getState() != HongBaoV2.STATE_YILINGQU
                        && hb.getType() == HongBaoV2.TYPE_ZIGOU) {
                    // 如果红包没被领取
                    Long uid = hb.getUserInfo().getId();
                    HongBaoV2 updateHongBao = new HongBaoV2();
                    updateHongBao.setId(hb.getId());
                    updateHongBao.setState(HongBaoV2.STATE_YILINGQU);
                    updateHongBao.setGetTime(new Date(currentTimeMillis));
                    hongBaoV2Mapper.updateByPrimaryKeySelective(updateHongBao);
                    if (userMoney.get(uid) == null)
                        userMoney.put(uid, hb.getMoney());
                    else
                        userMoney.put(uid, userMoney.get(uid).add(hb.getMoney()));
        for (HongBaoV2 hb : hongBaoList) {
            long currentTimeMillis = System.currentTimeMillis();
            if (hb.getState() != HongBao.STATE_SHIXIAO) {
                // 设置为已返利
                // 处理主红包
                if (hb.getState() != HongBaoV2.STATE_SHIXIAO && hb.getState() != HongBaoV2.STATE_YILINGQU
                        && hb.getType() == HongBaoV2.TYPE_ZIGOU) {
                    // 如果红包没被领取
                    Long uid = hb.getUserInfo().getId();
                    HongBaoV2 updateHongBao = new HongBaoV2();
                    updateHongBao.setId(hb.getId());
                    updateHongBao.setState(HongBaoV2.STATE_YILINGQU);
                    updateHongBao.setGetTime(new Date(currentTimeMillis));
                    hongBaoV2Mapper.updateByPrimaryKeySelective(updateHongBao);
                    if (userMoney.get(uid) == null)
                        userMoney.put(uid, hb.getMoney());
                    else
                        userMoney.put(uid, userMoney.get(uid).add(hb.getMoney()));
                    // 添加红包到用户
                    if (userHongBao.get(uid) == null)
                        userHongBao.put(uid, new ArrayList<>());
                    userHongBao.get(uid).add(hb);
                }
            }
        }
                    // 添加红包到用户
                    if (userHongBao.get(uid) == null)
                        userHongBao.put(uid, new ArrayList<>());
                    userHongBao.get(uid).add(hb);
                }
            }
        }
        // 获取维权资金
        if (sourceType == Constant.SOURCE_TYPE_TAOBAO) {
            try {
                Map<Long, BigDecimal> userSubMoneyMap = taoBaoWeiQuanDrawBackService.doWeiQuanFanli(orderId, false);
                if (userSubMoneyMap != null) {
                    for (Iterator<Long> its = userMoney.keySet().iterator(); its.hasNext();) {
                        Long uid = its.next();
                        if (userSubMoneyMap.get(uid) != null) {
                            // 减去维权资金
                            userMoney.put(uid, userMoney.get(uid).subtract(userSubMoneyMap.get(uid)));
                        }
                    }
                }
            } catch (Exception e) {
                LogHelper.errorDetailInfo(e);
                throw new OrderMoneySettleException(2, "维权订单出错");
            }
        }
        // 获取维权资金
        if (sourceType == Constant.SOURCE_TYPE_TAOBAO) {
            try {
                Map<Long, BigDecimal> userSubMoneyMap = taoBaoWeiQuanDrawBackService.doWeiQuanFanli(orderId, false);
                if (userSubMoneyMap != null) {
                    for (Iterator<Long> its = userMoney.keySet().iterator(); its.hasNext(); ) {
                        Long uid = its.next();
                        if (userSubMoneyMap.get(uid) != null) {
                            // 减去维权资金
                            userMoney.put(uid, userMoney.get(uid).subtract(userSubMoneyMap.get(uid)));
                        }
                    }
                }
            } catch (Exception e) {
                LogHelper.errorDetailInfo(e);
                throw new OrderMoneySettleException(2, "维权订单出错");
            }
        }
        // if (userMoney.isEmpty()) {
        // throw new OrderMoneySettleException(1, "没有需要结算的订单");
        // }
        // if (userMoney.isEmpty()) {
        // throw new OrderMoneySettleException(1, "没有需要结算的订单");
        // }
        Iterator<Long> its = userMoney.keySet().iterator();
        Iterator<Long> its = userMoney.keySet().iterator();
        while (its.hasNext()) {
            // 将自己添加到用户
            Long uid = its.next();
            BigDecimal money = userMoney.get(uid);
            UserMoneyDetail userMoneyDetail = null;
            // 插入新版资金明细
            try {
                // 此处不用订单号做唯一性索引
                userMoneyDetail = UserMoneyDetailFactory.createFanLi(uid, orderId, sourceType, null, money);
            } catch (UserMoneyDetailException e1) {
                try {
                    LogHelper.errorDetailInfo(e1, "订单号:" + orderId, "");
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
        while (its.hasNext()) {
            // 将自己添加到用户
            Long uid = its.next();
            BigDecimal money = userMoney.get(uid);
            UserMoneyDetail userMoneyDetail = null;
            // 插入新版资金明细
            try {
                // 此处不用订单号做唯一性索引
                userMoneyDetail = UserMoneyDetailFactory.createFanLi(uid, orderId, sourceType, null, money);
            } catch (UserMoneyDetailException e1) {
                try {
                    LogHelper.errorDetailInfo(e1, "订单号:" + orderId, "");
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
            userMoneyService.addUserMoney(uid, money, userMoneyDetail);
            userMoneyService.addUserMoney(uid, money, userMoneyDetail);
            List<Long> hbIdList = new ArrayList<>();
            // 添加资金明细与红包的映射关系
            for (HongBaoV2 v2 : userHongBao.get(uid)) {
                hbIdList.add(v2.getId());
                accountDetailsHongBaoMapService.saveAccountDetailsHongBaoMap(v2.getId(), userMoneyDetail.getId());
                try {
                    HongBaoRecieveCMQManager.getInstance().addHongBaoRecieveMsg(v2.getId());
                } catch (Exception e) {
                    LogHelper.errorDetailInfo(e);
                }
            }
            // 添加结算映射
            hongBaoV2SettleTempService.addTemp(hbIdList, taskKey);
            List<Long> hbIdList = new ArrayList<>();
            // 添加资金明细与红包的映射关系
            for (HongBaoV2 v2 : userHongBao.get(uid)) {
                hbIdList.add(v2.getId());
                accountDetailsHongBaoMapService.saveAccountDetailsHongBaoMap(v2.getId(), userMoneyDetail.getId());
                try {
                    HongBaoRecieveCMQManager.getInstance().addHongBaoRecieveMsg(v2.getId());
                } catch (Exception e) {
                    LogHelper.errorDetailInfo(e);
                }
            }
            // 添加结算映射
            hongBaoV2SettleTempService.addTemp(hbIdList, taskKey);
            // 站内信+推送
            UserInfo user = userInfoMapper.selectByPrimaryKey(uid);
            // 站内信+推送
            UserInfo user = userInfoMapper.selectByPrimaryKey(uid);
            // 新版通知
            // 新版通知
            userMoneyMsgNotificationService.fanliOrderReceived(uid, orderId, sourceType, userGoodsCount.get(uid), money,
                    user.getMyHongBao(), orderList.get(0).getThirdCreateTime());
        }
        // 通知免单到账
        try {
            userSystemCouponService.updateStateByArrivalAccount(orderId,sourceType);
        } catch (Exception e) {
            e.printStackTrace();
        }
            userMoneyMsgNotificationService.fanliOrderReceived(uid, orderId, sourceType, userGoodsCount.get(uid), money,
                    user.getMyHongBao(), orderList.get(0).getThirdCreateTime());
        }
        // 通知免单到账
        try {
            userSystemCouponService.updateStateByArrivalAccount(orderId, sourceType);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 添加结算映射
        // 添加结算映射
    }
    }
    private HongBaoV2 filterWeiQuanINGHongBao(HongBaoV2 hongBao) {
    private HongBaoV2 filterWeiQuanINGHongBao(HongBaoV2 hongBao) {
        long hbId = hongBao.getId();
        if (hongBao.getParent() != null) {
            hbId = hongBao.getParent().getId();
        }
        long hbId = hongBao.getId();
        if (hongBao.getParent() != null) {
            hbId = hongBao.getParent().getId();
        }
        HongBaoOrder hongbaoOrder = hongBaoOrderMapper.selectByHongBaoId(hbId);
        HongBaoOrder hongbaoOrder = hongBaoOrderMapper.selectByHongBaoId(hbId);
        if (hongbaoOrder == null)
            return null;
        if (hongbaoOrder == null)
            return null;
        List<TaoBaoWeiQuanOrder> taoBaoWeiQuanList = taoBaoWeiQuanOrderMapper
                .selectListByOrderIdAndState(hongbaoOrder.getCommonOrder().getOrderNo(), "维权创建");
        List<TaoBaoWeiQuanOrder> taoBaoWeiQuanList = taoBaoWeiQuanOrderMapper
                .selectListByOrderIdAndState(hongbaoOrder.getCommonOrder().getOrderNo(), "维权创建");
        List<TaoBaoWeiQuanOrder> taoBaoWeiQuanList1 = taoBaoWeiQuanOrderMapper
                .selectListByOrderIdAndState(hongbaoOrder.getCommonOrder().getOrderNo(), "等待处理");
        if ((taoBaoWeiQuanList != null && taoBaoWeiQuanList.size() > 0)
                || (taoBaoWeiQuanList1 != null && taoBaoWeiQuanList1.size() > 0)) {
            return null;
        }
        return hongBao;
    }
        List<TaoBaoWeiQuanOrder> taoBaoWeiQuanList1 = taoBaoWeiQuanOrderMapper
                .selectListByOrderIdAndState(hongbaoOrder.getCommonOrder().getOrderNo(), "等待处理");
        if ((taoBaoWeiQuanList != null && taoBaoWeiQuanList.size() > 0)
                || (taoBaoWeiQuanList1 != null && taoBaoWeiQuanList1.size() > 0)) {
            return null;
        }
        return hongBao;
    }
    @Transactional
    private void fanliInvite(List<HongBaoV2> hongBaoList, Long uid, int sourceType, String key, Date maxPreGetTime)
            throws TeamEincomeRecordException, ParamsException, TeamRewardDebtException {
        List<Long> hbIdList = new ArrayList<>();
        BigDecimal invitemoney = new BigDecimal(0);
        Set<String> inviteOrders = new HashSet<>();
    private void fanliInvite(List<HongBaoV2> hongBaoList, Long uid, int sourceType, String key, Date maxPreGetTime)
            throws TeamEincomeRecordException, ParamsException, TeamRewardDebtException {
        List<Long> hbIdList = new ArrayList<>();
        BigDecimal invitemoney = new BigDecimal(0);
        Set<String> inviteOrders = new HashSet<>();
        // 需要判断退款的订单号
        for (HongBaoV2 hongBao : hongBaoList) {
            hongBao = filterWeiQuanINGHongBao(hongBao);
            if (hongBao == null)
                continue;
            hongBao = hongBaoV2Mapper.selectByPrimaryKeyForUpdate(hongBao.getId());
            if (hongBao.getState() == HongBaoV2.STATE_BUKELINGQU || hongBao.getState() == HongBaoV2.STATE_KELINGQU) {
                TeamRewardDebt debt = teamRewardDebtService.selectBySourceId(hongBao.getId());
                BigDecimal money = hongBao.getMoney();
                if (debt != null && debt.getLeftMoney().compareTo(new BigDecimal(0)) > 0
                        && money.compareTo(debt.getLeftMoney()) >= 0) {
                    money = money.subtract(debt.getLeftMoney());
                    // 还钱
                    teamRewardDebtService.repayDebt(debt.getId(), debt.getLeftMoney());
                }
        // 需要判断退款的订单号
        for (HongBaoV2 hongBao : hongBaoList) {
            hongBao = filterWeiQuanINGHongBao(hongBao);
            if (hongBao == null)
                continue;
            hongBao = hongBaoV2Mapper.selectByPrimaryKeyForUpdate(hongBao.getId());
            if (hongBao.getState() == HongBaoV2.STATE_BUKELINGQU || hongBao.getState() == HongBaoV2.STATE_KELINGQU) {
                TeamRewardDebt debt = teamRewardDebtService.selectBySourceId(hongBao.getId());
                BigDecimal money = hongBao.getMoney();
                if (debt != null && debt.getLeftMoney().compareTo(new BigDecimal(0)) > 0
                        && money.compareTo(debt.getLeftMoney()) >= 0) {
                    money = money.subtract(debt.getLeftMoney());
                    // 还钱
                    teamRewardDebtService.repayDebt(debt.getId(), debt.getLeftMoney());
                }
                invitemoney = invitemoney.add(money);
                HongBaoV2 updateHongBao = new HongBaoV2();
                updateHongBao.setId(hongBao.getId());
                updateHongBao.setGetTime(new Date());
                updateHongBao.setState(HongBaoV2.STATE_YILINGQU);
                updateHongBao.setUpdateTime(new Date());
                hongBaoV2Mapper.updateByPrimaryKeySelective(updateHongBao);
                // 添加到红包返利记录集合
                hbIdList.add(hongBao.getId());
                invitemoney = invitemoney.add(money);
                HongBaoV2 updateHongBao = new HongBaoV2();
                updateHongBao.setId(hongBao.getId());
                updateHongBao.setGetTime(new Date());
                updateHongBao.setState(HongBaoV2.STATE_LINGQUING);
                updateHongBao.setUpdateTime(new Date());
                hongBaoV2Mapper.updateByPrimaryKeySelective(updateHongBao);
                // 添加到红包返利记录集合
                hbIdList.add(hongBao.getId());
                // 2018-08-05 过后的订单才处理维权
                // 2018-08-05 过后的订单才处理维权
                HongBaoOrder hongBaoOrder = hongBaoOrderMapper.selectByHongBaoId(hongBao.getParent().getId());
                inviteOrders.add(hongBaoOrder.getCommonOrder().getOrderNo());
            }
        }
                HongBaoOrder hongBaoOrder = hongBaoOrderMapper.selectByHongBaoId(hongBao.getParent().getId());
                inviteOrders.add(hongBaoOrder.getCommonOrder().getOrderNo());
            }
        }
        // 邀请赚到账
        if (invitemoney.compareTo(new BigDecimal(0)) > 0) {
            // 获取当前的月份
            teamRewardManager.addToEincome(uid, maxPreGetTime, invitemoney, sourceType);
        }
        // 邀请赚到账
        if (invitemoney.compareTo(new BigDecimal(0)) > 0) {
            // 获取当前的月份
            teamRewardManager.addToEincome(uid, maxPreGetTime, invitemoney, sourceType);
        }
        hongBaoV2SettleTempService.addTemp(hbIdList, key);
        hongBaoV2SettleTempService.addTemp(hbIdList, key);
        // 所有的返利到账红包ID
        for (Long hongBaoId : hbIdList) {
            try {
                if (Constant.ENABLE_MQ)
                    HongBaoRecieveCMQManager.getInstance().addHongBaoRecieveMsg(hongBaoId);
            } catch (Exception e) {
                LogHelper.errorDetailInfo(e);
            }
        }
    }
        // 所有的返利到账红包ID
        for (Long hongBaoId : hbIdList) {
            try {
                if (Constant.ENABLE_MQ)
                    HongBaoRecieveCMQManager.getInstance().addHongBaoRecieveMsg(hongBaoId);
            } catch (Exception e) {
                LogHelper.errorDetailInfo(e);
            }
        }
    }
    /**
     * 淘宝分享赚返利
     *
     * @param hongBaoList
     * @param uid
     * @throws TaoBaoWeiQuanException
     */
    private void fanLiShareTB(List<HongBaoV2> hongBaoList, Long uid, String key) throws TaoBaoWeiQuanException {
        BigDecimal sharemoney = new BigDecimal(0);
        List<Long> hbIdList = new ArrayList<>();
        Set<String> drawBackOrders = new HashSet<String>();
        List<Long> recieveHongBaoIds = new ArrayList<>();
        Set<String> shareOrders = new HashSet<>();
    /**
     * 淘宝分享赚返利
     *
     * @param hongBaoList
     * @param uid
     * @throws TaoBaoWeiQuanException
     */
    private void fanLiShareTB(List<HongBaoV2> hongBaoList, Long uid, String key) throws TaoBaoWeiQuanException {
        BigDecimal sharemoney = new BigDecimal(0);
        List<Long> hbIdList = new ArrayList<>();
        Set<String> drawBackOrders = new HashSet<String>();
        List<Long> recieveHongBaoIds = new ArrayList<>();
        Set<String> shareOrders = new HashSet<>();
        for (HongBaoV2 hongBao : hongBaoList) {
            hongBao = hongBaoV2Mapper.selectByPrimaryKeyForUpdate(hongBao.getId());
            hongBao = filterWeiQuanINGHongBao(hongBao);
            if (hongBao == null)
                continue;
        for (HongBaoV2 hongBao : hongBaoList) {
            hongBao = hongBaoV2Mapper.selectByPrimaryKeyForUpdate(hongBao.getId());
            hongBao = filterWeiQuanINGHongBao(hongBao);
            if (hongBao == null)
                continue;
            if (hongBao.getState() == HongBaoV2.STATE_BUKELINGQU || hongBao.getState() == HongBaoV2.STATE_KELINGQU) {
                sharemoney = sharemoney.add(hongBao.getMoney());
                HongBaoV2 updateHongBao = new HongBaoV2();
                updateHongBao.setId(hongBao.getId());
                updateHongBao.setGetTime(new Date());
                updateHongBao.setState(HongBao.STATE_YILINGQU);
                updateHongBao.setUpdateTime(new Date());
                hongBaoV2Mapper.updateByPrimaryKeySelective(updateHongBao);
                // 添加到红包返利记录集合
                hbIdList.add(hongBao.getId());
                // 2018-08-05 过后的订单才处理维权
                Date balanceTime = null;
                HongBaoOrder hongBaoOrder = hongBaoOrderMapper.selectByHongBaoId(hongBao.getId());
                if (hongBaoOrder != null) {
                    balanceTime = hongBaoOrder.getCommonOrder().getSettleTime();
                }
                shareOrders.add(hongBaoOrder.getCommonOrder().getOrderNo());
                if (balanceTime != null
                        && balanceTime.getTime() >= TimeUtil.convertToTimeTemp("2018-08-05", "yyyy-MM-dd")) {
                    drawBackOrders.add(hongBaoOrder.getCommonOrder().getOrderNo());
                }
            }
        }
            if (hongBao.getState() == HongBaoV2.STATE_BUKELINGQU || hongBao.getState() == HongBaoV2.STATE_KELINGQU) {
                sharemoney = sharemoney.add(hongBao.getMoney());
                HongBaoV2 updateHongBao = new HongBaoV2();
                updateHongBao.setId(hongBao.getId());
                updateHongBao.setGetTime(new Date());
                updateHongBao.setState(HongBao.STATE_YILINGQU);
                updateHongBao.setUpdateTime(new Date());
                hongBaoV2Mapper.updateByPrimaryKeySelective(updateHongBao);
                // 添加到红包返利记录集合
                hbIdList.add(hongBao.getId());
                // 2018-08-05 过后的订单才处理维权
                Date balanceTime = null;
                HongBaoOrder hongBaoOrder = hongBaoOrderMapper.selectByHongBaoId(hongBao.getId());
                if (hongBaoOrder != null) {
                    balanceTime = hongBaoOrder.getCommonOrder().getSettleTime();
                }
                shareOrders.add(hongBaoOrder.getCommonOrder().getOrderNo());
                if (balanceTime != null
                        && balanceTime.getTime() >= TimeUtil.convertToTimeTemp("2018-08-05", "yyyy-MM-dd")) {
                    drawBackOrders.add(hongBaoOrder.getCommonOrder().getOrderNo());
                }
            }
        }
        /**
         * 分享赚到账
         */
        /**
         * 分享赚到账
         */
        if (sharemoney.compareTo(new BigDecimal(0)) > 0) {
            // 添加新版详情记录
            try {
                UserMoneyDetail userMoneyDetail = UserMoneyDetailFactory.createShare(uid, Constant.SOURCE_TYPE_TAOBAO,
                        sharemoney, new Date());
                // 添加资金
                userMoneyService.addUserMoney(uid, sharemoney, userMoneyDetail);
        if (sharemoney.compareTo(new BigDecimal(0)) > 0) {
            // 添加新版详情记录
            try {
                UserMoneyDetail userMoneyDetail = UserMoneyDetailFactory.createShare(uid, Constant.SOURCE_TYPE_TAOBAO,
                        sharemoney, new Date());
                // 添加资金
                userMoneyService.addUserMoney(uid, sharemoney, userMoneyDetail);
                // 添加到红包返利记录集合
                accountDetailsHongBaoMapService.saveAccountDetailsHongBaoMap(hbIdList, userMoneyDetail.getId());
                if (hbIdList.size() > 0)
                    recieveHongBaoIds.addAll(hbIdList);
            } catch (UserMoneyDetailException e) {
                try {
                    LogHelper.errorDetailInfo(e);
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
                // 添加到红包返利记录集合
                accountDetailsHongBaoMapService.saveAccountDetailsHongBaoMap(hbIdList, userMoneyDetail.getId());
                if (hbIdList.size() > 0)
                    recieveHongBaoIds.addAll(hbIdList);
            } catch (UserMoneyDetailException e) {
                try {
                    LogHelper.errorDetailInfo(e);
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
            // 新版通知
            userMoneyMsgNotificationService.shareOrderReceived(uid, Constant.SOURCE_TYPE_TAOBAO, sharemoney,
                    userInfoMapper.selectAvailableByPrimaryKey(uid).getMyHongBao(), new Date());
            // 新版通知
            userMoneyMsgNotificationService.shareOrderReceived(uid, Constant.SOURCE_TYPE_TAOBAO, sharemoney,
                    userInfoMapper.selectAvailableByPrimaryKey(uid).getMyHongBao(), new Date());
            for (String orderId : drawBackOrders)
                taoBaoWeiQuanDrawBackService.doWeiQuanShare(orderId);
        }
            for (String orderId : drawBackOrders)
                taoBaoWeiQuanDrawBackService.doWeiQuanShare(orderId);
        }
        hongBaoV2SettleTempService.addTemp(recieveHongBaoIds, key);
        hongBaoV2SettleTempService.addTemp(recieveHongBaoIds, key);
        // 所有的返利到账红包ID
        for (Long hongBaoId : recieveHongBaoIds) {
            try {
                if (Constant.ENABLE_MQ)
                    HongBaoRecieveCMQManager.getInstance().addHongBaoRecieveMsg(hongBaoId);
            } catch (Exception e) {
                LogHelper.errorDetailInfo(e);
            }
        // 所有的返利到账红包ID
        for (Long hongBaoId : recieveHongBaoIds) {
            try {
                if (Constant.ENABLE_MQ)
                    HongBaoRecieveCMQManager.getInstance().addHongBaoRecieveMsg(hongBaoId);
            } catch (Exception e) {
                LogHelper.errorDetailInfo(e);
            }
        }
    }
        }
    }
    /**
     * 其他平台分享赚返利
     *
     * @param hongBaoList
     * @param uid
     * @param sourceType
     */
    private void fanLiShareOther(List<HongBaoV2> hongBaoList, Long uid, int sourceType, String key) {
        BigDecimal sharemoney = new BigDecimal(0);
        List<Long> hbIdList = new ArrayList<>();
        List<Long> recieveHongBaoIds = new ArrayList<>();
        Set<String> shareOrders = new HashSet<>();
    /**
     * 其他平台分享赚返利
     *
     * @param hongBaoList
     * @param uid
     * @param sourceType
     */
    private void fanLiShareOther(List<HongBaoV2> hongBaoList, Long uid, int sourceType, String key) {
        BigDecimal sharemoney = new BigDecimal(0);
        List<Long> hbIdList = new ArrayList<>();
        List<Long> recieveHongBaoIds = new ArrayList<>();
        Set<String> shareOrders = new HashSet<>();
        for (HongBaoV2 hongBao : hongBaoList) {
            hongBao = hongBaoV2Mapper.selectByPrimaryKeyForUpdate(hongBao.getId());
            hongBao = filterWeiQuanINGHongBao(hongBao);
            if (hongBao == null)
                continue;
        for (HongBaoV2 hongBao : hongBaoList) {
            hongBao = hongBaoV2Mapper.selectByPrimaryKeyForUpdate(hongBao.getId());
            hongBao = filterWeiQuanINGHongBao(hongBao);
            if (hongBao == null)
                continue;
            if (hongBao.getState() == HongBaoV2.STATE_BUKELINGQU || hongBao.getState() == HongBaoV2.STATE_KELINGQU) {
                sharemoney = sharemoney.add(hongBao.getMoney());
                HongBaoV2 updateHongBao = new HongBaoV2();
                updateHongBao.setId(hongBao.getId());
                updateHongBao.setGetTime(new Date());
                updateHongBao.setState(HongBao.STATE_YILINGQU);
                updateHongBao.setUpdateTime(new Date());
                hongBaoV2Mapper.updateByPrimaryKeySelective(updateHongBao);
                // 添加到红包返利记录集合
                hbIdList.add(hongBao.getId());
                // 2018-08-05 过后的订单才处理维权
                HongBaoOrder hongBaoOrder = hongBaoOrderMapper.selectByHongBaoId(hongBao.getId());
                shareOrders.add(hongBaoOrder.getCommonOrder().getOrderNo());
            }
        }
            if (hongBao.getState() == HongBaoV2.STATE_BUKELINGQU || hongBao.getState() == HongBaoV2.STATE_KELINGQU) {
                sharemoney = sharemoney.add(hongBao.getMoney());
                HongBaoV2 updateHongBao = new HongBaoV2();
                updateHongBao.setId(hongBao.getId());
                updateHongBao.setGetTime(new Date());
                updateHongBao.setState(HongBao.STATE_YILINGQU);
                updateHongBao.setUpdateTime(new Date());
                hongBaoV2Mapper.updateByPrimaryKeySelective(updateHongBao);
                // 添加到红包返利记录集合
                hbIdList.add(hongBao.getId());
                // 2018-08-05 过后的订单才处理维权
                HongBaoOrder hongBaoOrder = hongBaoOrderMapper.selectByHongBaoId(hongBao.getId());
                shareOrders.add(hongBaoOrder.getCommonOrder().getOrderNo());
            }
        }
        /**
         * 分享赚到账
         */
        /**
         * 分享赚到账
         */
        if (sharemoney.compareTo(new BigDecimal(0)) > 0) {
            // 添加新版详情记录
            try {
                UserMoneyDetail userMoneyDetail = UserMoneyDetailFactory.createShare(uid, sourceType, sharemoney,
                        new Date());
                // 添加资金
                userMoneyService.addUserMoney(uid, sharemoney, userMoneyDetail);
        if (sharemoney.compareTo(new BigDecimal(0)) > 0) {
            // 添加新版详情记录
            try {
                UserMoneyDetail userMoneyDetail = UserMoneyDetailFactory.createShare(uid, sourceType, sharemoney,
                        new Date());
                // 添加资金
                userMoneyService.addUserMoney(uid, sharemoney, userMoneyDetail);
                // 添加到红包返利记录集合
                accountDetailsHongBaoMapService.saveAccountDetailsHongBaoMap(hbIdList, userMoneyDetail.getId());
                if (hbIdList.size() > 0)
                    recieveHongBaoIds.addAll(hbIdList);
            } catch (UserMoneyDetailException e) {
                try {
                    LogHelper.errorDetailInfo(e);
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
                // 添加到红包返利记录集合
                accountDetailsHongBaoMapService.saveAccountDetailsHongBaoMap(hbIdList, userMoneyDetail.getId());
                if (hbIdList.size() > 0)
                    recieveHongBaoIds.addAll(hbIdList);
            } catch (UserMoneyDetailException e) {
                try {
                    LogHelper.errorDetailInfo(e);
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
            userMoneyMsgNotificationService.shareOrderReceived(uid, sourceType, sharemoney,
                    userInfoMapper.selectAvailableByPrimaryKey(uid).getMyHongBao(), new Date());
        }
            userMoneyMsgNotificationService.shareOrderReceived(uid, sourceType, sharemoney,
                    userInfoMapper.selectAvailableByPrimaryKey(uid).getMyHongBao(), new Date());
        }
        hongBaoV2SettleTempService.addTemp(recieveHongBaoIds, key);
        hongBaoV2SettleTempService.addTemp(recieveHongBaoIds, key);
        // 所有的返利到账红包ID
        for (Long hongBaoId : recieveHongBaoIds) {
            try {
                if (Constant.ENABLE_MQ)
                    HongBaoRecieveCMQManager.getInstance().addHongBaoRecieveMsg(hongBaoId);
            } catch (Exception e) {
                LogHelper.errorDetailInfo(e);
            }
        }
    }
        // 所有的返利到账红包ID
        for (Long hongBaoId : recieveHongBaoIds) {
            try {
                if (Constant.ENABLE_MQ)
                    HongBaoRecieveCMQManager.getInstance().addHongBaoRecieveMsg(hongBaoId);
            } catch (Exception e) {
                LogHelper.errorDetailInfo(e);
            }
        }
    }
    private String getTaskKey(Long uid) {
        return uid + "-" + UUID.randomUUID().toString();
    }
    private String getTaskKey(Long uid) {
        return uid + "-" + UUID.randomUUID().toString();
    }
}
fanli/src/main/java/com/yeshi/fanli/service/impl/order/OrderProcessServiceImpl.java
@@ -25,7 +25,6 @@
import com.google.gson.Gson;
import com.yeshi.fanli.dao.mybatis.HongBaoV2Mapper;
import com.yeshi.fanli.dao.mybatis.UserInfoMapper;
import com.yeshi.fanli.dao.mybatis.money.UserMoneyDetailMapper;
import com.yeshi.fanli.dao.mybatis.order.HongBaoOrderMapper;
import com.yeshi.fanli.dao.mybatis.order.OrderMapper;
import com.yeshi.fanli.dao.mybatis.taobao.TaoBaoWeiQuanOrderMapper;
@@ -68,9 +67,7 @@
import com.yeshi.fanli.service.inter.elme.ElmeHongBaoOrderMapService;
import com.yeshi.fanli.service.inter.elme.ElmeOrderProcessService;
import com.yeshi.fanli.service.inter.elme.ElmeOrderService;
import com.yeshi.fanli.service.inter.hongbao.AccountDetailsHongBaoMapService;
import com.yeshi.fanli.service.inter.money.UserMoneyService;
import com.yeshi.fanli.service.inter.money.msg.UserMoneyMsgNotificationService;
import com.yeshi.fanli.service.inter.money.tb.TaoBaoWeiQuanDrawBackService;
import com.yeshi.fanli.service.inter.order.CommonOrderService;
import com.yeshi.fanli.service.inter.order.HongBaoV2Service;
@@ -83,7 +80,6 @@
import com.yeshi.fanli.service.inter.order.tb.TaoBaoOrderService;
import com.yeshi.fanli.service.inter.taobao.TaoBaoBuyRelationMapService;
import com.yeshi.fanli.service.inter.taobao.TaoBaoUnionConfigService;
import com.yeshi.fanli.service.inter.user.UserSystemCouponService;
import com.yeshi.fanli.service.inter.user.tb.UserExtraTaoBaoInfoService;
import com.yeshi.fanli.service.manger.msg.RocketMQManager;
import com.yeshi.fanli.service.manger.order.HongBaoV2AddManager;
@@ -128,25 +124,13 @@
    private TaoBaoWeiQuanOrderMapper taoBaoWeiQuanOrderMapper;
    @Resource
    private AccountDetailsHongBaoMapService accountDetailsHongBaoMapService;
    @Resource
    private UserMoneyDetailMapper userMoneyDetailMapper;
    @Resource
    private HongBaoV2Mapper hongBaoV2Mapper;
    @Resource
    private UserMoneyMsgNotificationService userMoneyMsgNotificationService;
    @Resource
    private UserOrderMsgNotificationService userOrderMsgNotificationService;
    @Resource
    private UserExtraTaoBaoInfoService userExtraTaoBaoInfoService;
    @Resource
    private UserSystemCouponService userSystemCouponService;
    @Resource
    private UserMoneyService userMoneyService;
@@ -700,6 +684,18 @@
        } catch (OrderMoneySettleException e) {
            e.printStackTrace();
        }
        try {
            orderMoneySettleService.inviteSettleVipShop(uid, maxPreGetTime);
        } catch (OrderMoneySettleException e) {
            e.printStackTrace();
        }
        try {
            orderMoneySettleService.inviteSettleSuning(uid, maxPreGetTime);
        } catch (OrderMoneySettleException e) {
            e.printStackTrace();
        }
    }
    @Override
@@ -720,6 +716,18 @@
        try {
            orderMoneySettleService.shareSettlePDD(uid, maxPreGetTime);
        } catch (OrderMoneySettleException e) {
            e.printStackTrace();
        }
        try {
            orderMoneySettleService.shareSettleVipShop(uid, maxPreGetTime);
        } catch (OrderMoneySettleException e) {
            e.printStackTrace();
        }
        try {
            orderMoneySettleService.shareSettleSuning(uid, maxPreGetTime);
        } catch (OrderMoneySettleException e) {
            e.printStackTrace();
        }
@@ -939,7 +947,6 @@
     * @param jdOrder
     * @param uid
     */
    @Transactional
    private void processFanLiJDOrder(JDOrder jdOrder, Long uid) {
        int invalidCount = 0;
        BigDecimal totalMoney = new BigDecimal(0);
@@ -1015,11 +1022,9 @@
    /**
     * 处理京东分享订单
     *
     * @param order
     * @param jdOrder
     * @param uid
     */
    @Transactional
    private void processShareJDOrder(JDOrder jdOrder, Long uid) {
        try {
            List<CommonOrderAddResultDTO> commonOrderList = commonOrderService.addJDOrder(jdOrder, uid);
@@ -1047,8 +1052,7 @@
    /**
     * 是否是分享赚订单
     *
     * @param order
     * @param pddOrder
     * @return
     */
    private boolean isShareOrder(PDDOrder pddOrder) {
@@ -1086,11 +1090,9 @@
    /**
     * 处理拼多多自购返利订单
     *
     * @param pddOrder
     * @param uid
     */
    @Transactional
    private void processFanLiPDDOrder(PDDOrder pddOrder, Long uid) {
        int orderState = 0;
        if (pddOrder.getOrderStatus() == -1 || pddOrder.getOrderStatus() == 8)
@@ -1157,11 +1159,9 @@
    /**
     * 处理拼多多分享订单
     *
     * @param order
     * @param pddOrder
     * @param uid
     */
    @Transactional
    private void processSharePDDOrder(PDDOrder pddOrder, Long uid) {
        try {
            List<PDDOrder> pddOrderList = new ArrayList<>();
@@ -1220,11 +1220,9 @@
    /**
     * 处理京东返利订单
     *
     * @param jdOrder
     * @param vipShopOrder
     * @param uid
     */
    @Transactional
    private void processFanLiVipShopOrder(VipShopOrder vipShopOrder, Long uid) {
        int invalidCount = 0;
        BigDecimal totalMoney = new BigDecimal(0);
@@ -1295,11 +1293,9 @@
    /**
     * 处理京东分享订单
     *
     * @param order
     * @param jdOrder
     * @param uid
     */
    @Transactional
    private void processShareVipShopOrder(VipShopOrder jdOrder, Long uid) {
        try {
            List<CommonOrderAddResultDTO> commonOrderList = commonOrderService.addVipShopOrder(jdOrder, uid);
@@ -1351,12 +1347,10 @@
    }
    /**
     * 处理拼多多自购返利订单
     *
     * @param pddOrder
     *  处理拼多多自购返利订单
     * @param suningOrder
     * @param uid
     */
    @Transactional
    private void processFanLiSuningOrder(SuningOrderInfo suningOrder, Long uid) {
        int orderState = 0;
@@ -1429,11 +1423,9 @@
    /**
     * 处理拼多多分享订单
     *
     * @param order
     * @param suningOrder
     * @param uid
     */
    @Transactional
    private void processShareSuningOrder(SuningOrderInfo suningOrder, Long uid) {
        try {
            List<SuningOrderInfo> suningOrderList = new ArrayList<>();
@@ -1671,7 +1663,6 @@
     * @param sourceType
     * @param hongBaoType
     */
    @Transactional
    private void addHongBaoWithMQ(List<CommonOrderAddResultDTO> commonOrderList, String orderId, Long uid,
            int sourceType, int hongBaoType) {
        final List<CommonOrder> coList = convertCommonOrder(commonOrderList);
fanli/src/main/java/com/yeshi/fanli/service/impl/push/HWPushServiceImpl.java
@@ -9,6 +9,8 @@
import com.yeshi.fanli.entity.bus.user.UserCustomSettings.UserSettingTypeEnum;
import com.yeshi.fanli.entity.push.DeviceTokenHW;
import com.yeshi.fanli.exception.push.PushException;
import com.yeshi.fanli.log.LogHelper;
import com.yeshi.fanli.log.LogManager;
import com.yeshi.fanli.log.PushLogHelper;
import com.yeshi.fanli.service.inter.config.AppVersionService;
import com.yeshi.fanli.service.inter.push.DeviceTokenHWService;
@@ -139,6 +141,7 @@
     * @throws PushException
     */
    public void push(PushContentDetailDTO dto) throws PushException {
        LogHelper.pushHW("开始推送");
        int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
        List<Integer> newVersionList = getVersionCodeList(dto.getContent().getVersionCodeList(), dto.getContent().getSystem());
        // 1.6.5后开始推送
@@ -148,6 +151,7 @@
        }
        if (dto.getUid() == null || dto.getUid() == 0) {
            LogHelper.pushHW("全推");
            //只推送近30天的活跃
            Date minUpdateTime = new Date(System.currentTimeMillis() - Constant.PUSH_MIN_TIME);
            long deviceCount = deviceTokenHWService.countDeviceToken(newVersionList, minUpdateTime);
@@ -155,7 +159,7 @@
            for (int p = 1; p <= page; p++) {
                List<DeviceTokenHW> hwDeviceList = deviceTokenHWService.getDeviceTokenList(p, 100, newVersionList, minUpdateTime);
                hwDeviceList = filterDeviceToken(hwDeviceList, hour);
                LogHelper.pushHW(String.format("全推:设备数%s",hwDeviceList.size()));
                List<String> tokenList = new ArrayList<>();
                for (DeviceTokenHW token : hwDeviceList)
                    tokenList.add(token.getDeviceToken());
@@ -189,6 +193,7 @@
            }
        } else {
            LogHelper.pushHW("单推");
            // 华为单推
            List<DeviceTokenHW> hwDeviceList = deviceTokenHWService.getDeviceTokenByUid(dto.getUid(), newVersionList);
            List<String> tokenList = new ArrayList<>();
@@ -197,6 +202,9 @@
                for (DeviceTokenHW token : hwDeviceList)
                    tokenList.add(token.getDeviceToken());
            }
            LogHelper.pushHW(String.format("单推:设备数%s 用户:%s",hwDeviceList.size(),dto.getUid()+""));
            if (tokenList.size() == 0)
                return;
fanli/src/main/java/com/yeshi/fanli/service/impl/taobao/haodanku/HDKGoodsDetailServiceImpl.java
@@ -18,8 +18,9 @@
    @Override
    public void addGoods(HDKGoodsDetail goods) {
        if (goods.getCreateTime() != null)
        if (goods.getCreateTime() == null)
            goods.setCreateTime(new Date());
        goods.setUpdateTime(new Date());
        hdkGoodsDetailDao.save(goods);
    }
fanli/src/main/java/com/yeshi/fanli/service/impl/user/SMSServiceImpl.java
@@ -1,24 +1,17 @@
package com.yeshi.fanli.service.impl.user;
import java.math.BigDecimal;
import java.util.Date;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.yeshi.fanli.dao.mybatis.SMSHistoryMapper;
import com.yeshi.fanli.entity.SystemEnum;
import com.yeshi.fanli.entity.bus.user.SMSHistory;
import com.yeshi.fanli.exception.config.SMSException;
import com.yeshi.fanli.service.inter.user.SMSService;
import com.yeshi.fanli.util.AliyunSMSUtil;
import com.yeshi.fanli.util.Constant;
import com.yeshi.fanli.util.RedisKeyEnum;
import com.yeshi.fanli.util.RedisManager;
import com.yeshi.fanli.util.StringUtil;
import com.yeshi.fanli.util.TencentSMSUtil;
import com.yeshi.fanli.util.*;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
@Service
public class SMSServiceImpl implements SMSService {
@@ -30,7 +23,7 @@
    private RedisManager redisManager;
    @Override
    public String sendLoginVCode(String phone, int codeLength) throws SMSException {
    public String sendLoginVCode(SystemEnum system, String phone, int codeLength) throws SMSException {
        boolean limit = redisManager.isSmsFrequencyLimit(phone, SMSHistory.TYPE_LOGIN);
        if (limit)
            throw new SMSException(1001, "请过60秒再试");
@@ -39,7 +32,7 @@
        String msgCode = StringUtil.getVerifyCode(codeLength);
        // 验证码模板
        String msg = Constant.smsConfig.getSmsLogin().replace("[签名]", Constant.smsConfig.getSmsSign()).replace("[验证码]",
        String msg = Constant.smsConfig.getSmsLogin().replace("[签名]", system.getSmsAlias()).replace("[验证码]",
                msgCode);
        // 发送短信
        // 发送间隔2分钟内的采用阿里云短信发送
@@ -69,14 +62,14 @@
    }
    @Override
    public void sendBindVCode(String phone, int codeLength) throws SMSException {
    public void sendBindVCode(SystemEnum system,String phone, int codeLength) throws SMSException {
        boolean limit = redisManager.isSmsFrequencyLimit(phone, SMSHistory.TYPE_BIND);
        if (limit)
            throw new SMSException(1001, "请过60秒再试");
        String msgCode = StringUtil.getVerifyCode(codeLength);
        // 验证码模板
        String msg = Constant.smsConfig.getSmsBind().replace("[签名]", Constant.smsConfig.getSmsSign()).replace("[验证码]",
        String msg = Constant.smsConfig.getSmsBind().replace("[签名]", system.getSmsAlias()).replace("[验证码]",
                msgCode);
        // 发送短信
        TencentSMSUtil.sendSingleMsg(phone, msg);
@@ -94,14 +87,14 @@
    }
    @Override
    public void sendRemoveVCode(String phone, int codeLength) throws SMSException {
    public void sendRemoveVCode(SystemEnum system,String phone, int codeLength) throws SMSException {
        boolean limit = redisManager.isSmsFrequencyLimit(phone, SMSHistory.TYPE_REMVOE);
        if (limit)
            throw new SMSException(1001, "请过60秒再试");
        String msgCode = StringUtil.getVerifyCode(codeLength);
        // 验证码模板
        String msg = Constant.smsConfig.getSmsBind().replace("[签名]", Constant.smsConfig.getSmsSign()).replace("[验证码]",
        String msg = Constant.smsConfig.getSmsBind().replace("[签名]", system.getSmsAlias()).replace("[验证码]",
                msgCode);
        // 发送短信
        TencentSMSUtil.sendSingleMsg(phone, msg);
@@ -119,12 +112,12 @@
    }
    
    @Override
    public void sendExtractVCode(String phone) throws SMSException {
    public void sendExtractVCode(SystemEnum system,String phone) throws SMSException {
        boolean limit = redisManager.isSmsFrequencyLimit(phone, SMSHistory.TYPE_EXTRACT);
        if (limit)
            throw new SMSException(1001, "请过60秒再试");
        String msgCode = StringUtil.getRandomCode(6);
        String msg = Constant.smsConfig.getSmsExtract().replace("[签名]", Constant.smsConfig.getSmsSign())
        String msg = Constant.smsConfig.getSmsExtract().replace("[签名]",system.getSmsAlias())
                .replace("[验证码]", msgCode);
        // 发送短信
        TencentSMSUtil.sendSingleMsg(phone, msg);
@@ -134,16 +127,16 @@
    }
    @Override
    public void sendExtractSuccessMsg(String phone, BigDecimal money) throws SMSException {
        String msg = Constant.smsConfig.getSmsExtractSuccess().replace("[签名]", Constant.smsConfig.getSmsSign())
    public void sendExtractSuccessMsg(SystemEnum system,String phone, BigDecimal money) throws SMSException {
        String msg = Constant.smsConfig.getSmsExtractSuccess().replace("[签名]", system.getSmsAlias())
                .replace("[金额]", money.toString());
        // 发送短信
        TencentSMSUtil.sendSingleMsg(phone, msg);
    }
    @Override
    public void sendExtractFailMsg(String phone, BigDecimal money) throws SMSException {
        String msg = Constant.smsConfig.getSmsExtractFail().replace("[签名]", Constant.smsConfig.getSmsSign())
    public void sendExtractFailMsg(SystemEnum system,String phone, BigDecimal money) throws SMSException {
        String msg = Constant.smsConfig.getSmsExtractFail().replace("[签名]", system.getSmsAlias())
                .replace("[金额]", money.toString());
        // 发送短信
        TencentSMSUtil.sendSingleMsg(phone, msg);
fanli/src/main/java/com/yeshi/fanli/service/inter/order/CommonOrderCountService.java
@@ -106,6 +106,16 @@
     */
    long countSameGoodsOrderByUidAndHongBaoType(List<Integer> typeList, Long uid, int minSameGoodsOrderCount);
    /**
     *查询用户购买相同商品超过一定的订单数量的商品ID
     * @param typeList
     * @param uid
     * @param minSameGoodsOrderCount
     * @return
     */
    List<Long> listSameGoodsIdByUidAndHongBaoType(List<Integer> typeList, Long uid, int minSameGoodsOrderCount);
    
    /**
     * 查询用户在同一店铺购买超过一定数量商品的店铺id
fanli/src/main/java/com/yeshi/fanli/service/inter/order/CommonOrderService.java
@@ -23,478 +23,497 @@
import net.sf.json.JSONObject;
public interface CommonOrderService {
    public int insert(CommonOrder record);
    public int insertSelective(CommonOrder record);
    public int updateByPrimaryKey(CommonOrder record);
    public int updateByPrimaryKeySelective(CommonOrder record);
    public int deleteByPrimaryKey(Long id);
    public CommonOrder selectByPrimaryKey(Long id);
    /**
     * 查询用户订单 并订单号分组
     *
     * @param start
     * @param count
     * @param uid
     * @param state
     * @param type
     * @param orderNo
     *            订单号
     * @param startTime
     *            起始系统录入时间
     * @param endTime
     *            结束系统录入时间
     * @return
     * @throws CommonOrderException
     */
    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;
    /**
     * 统计查询
     *
     * @param uid
     * @param state
     * @param type
     * @param orderNo
     * @param startTime
     * @param endTime
     * @return
     * @throws CommonOrderException
     */
    long countGroupOrderNoByUid(Long uid, Integer state, Integer type, Integer orderState, String orderNo,
            String startTime, String endTime, Integer dateType, List<Integer> listSource) throws CommonOrderException;
    /**
     * 移动段订单列表
     *
     * @param start
     * @param count
     * @param uid
     *            用户id
     * @param type
     *            到账状态
     * @return
     */
    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;
    /**
     * 统计订单-根据红包类型 自购 邀请 分享
     *
     * @param uid
     * @return
     */
    public Map<String, BigDecimal> countHistoryOrder(Long uid, Integer day, Integer source);
    /**
     * 统计订单
     *
     * @param uid
     * @return
     */
    public long countBonusOrderNumber(Long uid, Integer type, Integer isToday, String startTime, String endTime,
            Integer source);
    /**
     * 统计订单
     *
     * @param uid
     * @return
     */
    public BigDecimal countBonusOrderMoney(Long uid, Integer type, Integer isToday, String startTime, String endTime,
            Integer source);
    /**
     * 统计奖金订单数量、金额
     *
     * @param uid
     * @param type
     * @param day
     * @param startTime
     * @param endTime
     * @return
     */
    public Map<String, Object> countBonusOrderMoneyAndNumber(Long uid, Integer type, Integer day, String startTime,
            String endTime, Integer source);
    /**
     * 根据条件统计
     *
     * @param uid
     * @param type
     * @param startTime
     * @param endTime
     * @return
     */
    public Long countUserOrderToApp(Long uid, Integer type, String startTime, String endTime,
            Integer day, Integer source, Integer state, Integer stateOrder);
    /**
     * 根据订单号与订单类型查询订单
     *
     * @param sourceType
     * @param orderId
     * @return
     */
    public List<CommonOrder> listBySourceTypeAndOrderId(int sourceType, String orderId);
    /**
     * 缓存淘宝类普通订单
     *
     * @param taoBaoOrder
     * @param uid
     * @return
     * @throws CommonOrderException
     */
    public List<CommonOrderAddResultDTO> addTaoBaoOrder(List<TaoBaoOrder> taoBaoOrder, Long uid) throws CommonOrderException;
    /**
     * 缓存拼多多类普通订单
     *
     * @param pddOrderList
     * @param uid
     * @return
     * @throws CommonOrderException
     */
    public List<CommonOrderAddResultDTO> addPDDOrder(List<PDDOrder> pddOrderList, Long uid) throws CommonOrderException;
    /**
     * 缓存京东普通订单
     *
     * @param jdOrderList
     * @param uid
     * @return
     * @throws CommonOrderException
     */
    public List<CommonOrderAddResultDTO> addJDOrder(JDOrder jdOrder, Long uid) throws CommonOrderException;
    /**
     * 添加唯品会订单
     * @Title: addVipShopOrder
     * @Description:
     * @param order
     * @param uid
     * @return
     * @throws CommonOrderException
     * List<CommonOrderAddResultDTO> 返回类型
     * @throws
     */
    public List<CommonOrderAddResultDTO> addVipShopOrder(VipShopOrder order, Long uid) throws CommonOrderException;
    /**
     * 添加苏宁订单
     * @Title: addVipShopOrder
     * @Description:
     * @param order
     * @param uid
     * @return
     * @throws CommonOrderException
     * List<CommonOrderAddResultDTO> 返回类型
     * @throws
     */
    public List<CommonOrderAddResultDTO> addSuningOrder(List<SuningOrderInfo> suningOrderList, Long uid) throws CommonOrderException;
    /**
     * 根据用户ID,订单状态,结算时间统计订单数量
     *
     * @param uid
     * @param state
     * @param minDate
     * @param maxDate
     * @return
     */
    public long countByUidAndOrderStateWithOrderBalanceTime(Long uid, int state, Date minDate, Date maxDate);
    public int insert(CommonOrder record);
    /**
     * 后端查询订单列表
     *
     * @param start
     * @param count
     * @param uid
     * @param state
     * @param type
     * @param orderState
     * @param orderNo
     * @param startTime
     * @param endTime
     * @param dateType
     *            1昨天 2今天 3本月 4 上月
     * @return
     * @throws CommonOrderException
     */
    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;
    public int insertSelective(CommonOrder record);
    public long countQueryByUid(Long uid, Integer state, Integer type, Integer orderState, String orderNo,
            String startTime, String endTime, Integer dateType) throws CommonOrderException;
    public int updateByPrimaryKey(CommonOrder record);
    /**
     * 查询所有用户订单
     *
     * @param start
     * @param count
     * @param keyType
     * @param key
     * @param state
     * @param type
     * @param orderState
     * @param startTime
     * @param endTime
     * @return
     * @throws CommonOrderException
     */
    public int updateByPrimaryKeySelective(CommonOrder record);
    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, SystemEnum system)
            throws CommonOrderException;
    public int deleteByPrimaryKey(Long id);
    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, SystemEnum system) throws CommonOrderException;
    public CommonOrder selectByPrimaryKey(Long id);
    /**
     * 查询订单
     *
     * @param uid
     * @param orderNo
     * @return
     * @throws CommonOrderException
     */
    public CommonOrderVO getCommonOrderByOrderNo(Long uid, String orderNo, Integer orderState, Integer sourceType)
            throws CommonOrderException;
    /**
     * 查询用户订单 并订单号分组
     *
     * @param start
     * @param count
     * @param uid
     * @param state
     * @param type
     * @param orderNo   订单号
     * @param startTime 起始系统录入时间
     * @param endTime   结束系统录入时间
     * @return
     * @throws CommonOrderException
     */
    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;
    /**
     * 使用奖励券成功后跳转 修改
     *
     * @param orderNo
     * @return
     */
    public JSONObject getRewardJumpInfo(String orderNo, Integer goodsType);
    /**
     * 统计查询
     *
     * @param uid
     * @param state
     * @param type
     * @param orderNo
     * @param startTime
     * @param endTime
     * @return
     * @throws CommonOrderException
     */
    long countGroupOrderNoByUid(Long uid, Integer state, Integer type, Integer orderState, String orderNo,
                                String startTime, String endTime, Integer dateType, List<Integer> listSource) throws CommonOrderException;
    /**
     * 根据交易号获取订单详情
     *
     * @param sourceType
     * @param tradeId
     * @return
     */
    public CommonOrder selectBySourceTypeAndTradeId(int sourceType, String tradeId);
    /**
     * 移动段订单列表
     *
     * @param start
     * @param count
     * @param uid   用户id
     * @param type  到账状态
     * @return
     */
    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;
    /**
     * 删除错误订单
     *
     * @param coId
     */
    public void deleteErrorCommonOrder(Long coId);
    /**
     * 统计订单-根据红包类型 自购 邀请 分享
     *
     * @param uid
     * @return
     */
    public Map<String, BigDecimal> countHistoryOrder(Long uid, Integer day, Integer source);
    /**
     * 根据订单类型与交易ID查询
     *
     * @param sourceType
     * @param tradeId
     * @return
     */
    public List<CommonOrder> listBySourceTypeAndTradeId(int sourceType, String tradeId);
    /**
     * 统计订单
     *
     * @param uid
     * @return
     */
    public long countBonusOrderNumber(Long uid, Integer type, Integer isToday, String startTime, String endTime,
                                      Integer source);
    /**
     * 根据条件查询订单
     *
     * @param sourceType
     * @param state
     * @param minTime
     * @param maxTime
     * @param page
     * @param pageSize
     * @return
     */
    public List<CommonOrder> listBySourceTypeAndStateAndThirdCrateTime(int sourceType, Integer state, Long minTime,
            Long maxTime, int page, int pageSize);
    /**
     * 统计订单
     *
     * @param uid
     * @return
     */
    public BigDecimal countBonusOrderMoney(Long uid, Integer type, Integer isToday, String startTime, String endTime,
                                           Integer source);
    /**
     * 查询订单 -根据订单号
     *
     * @param uid
     * @param orderNO
     * @return
     */
    public List<CommonOrder> getByOrderNo(Long uid, String orderNO);
    /**
     * 统计奖金订单数量、金额
     *
     * @param uid
     * @param type
     * @param day
     * @param startTime
     * @param endTime
     * @return
     */
    public Map<String, Object> countBonusOrderMoneyAndNumber(Long uid, Integer type, Integer day, String startTime,
                                                             String endTime, Integer source);
    /**
     * 根据用户ID查询最近一条有效的订单
     *
     * @param uid
     * @return
     */
    public CommonOrder selectLatestValidByUid(Long uid);
    /**
     * 查询首笔有效订单
     * @param uid
     * @return
     */
    public CommonOrderVO firstValidOrderByUid(Long uid);
    /**
     * 根据条件统计
     *
     * @param uid
     * @param type
     * @param startTime
     * @param endTime
     * @return
     */
    public Long countUserOrderToApp(Long uid, Integer type, String startTime, String endTime,
                                    Integer day, Integer source, Integer state, Integer stateOrder);
    /**
     * 查询首笔有效订单
     * @param uid
     * @param type 类型: 1自购  2分享 3邀请
     * @return
     */
    public CommonOrderVO firstValidOrderByUidAndType(Long uid, Integer type);
    /**
     * 根据订单号与订单类型查询订单
     *
     * @param sourceType
     * @param orderId
     * @return
     */
    public List<CommonOrder> listBySourceTypeAndOrderId(int sourceType, String orderId);
    /**
     * 查询是否上月到账订单
     * @param uid
     * @param type 类型: 1自购  2分享 3邀请
     * @return
     */
    public CommonOrderVO firstValidOrderLastMonthByUidAndType(Long uid, Integer type);
    /**
     * 缓存淘宝类普通订单
     *
     * @param taoBaoOrder
     * @param uid
     * @return
     * @throws CommonOrderException
     */
    public List<CommonOrderAddResultDTO> addTaoBaoOrder(List<TaoBaoOrder> taoBaoOrder, Long uid) throws CommonOrderException;
    /**
     * 首个分享订单
     * @param uid
     * @return
     */
    public CommonOrder getFirstShareOrderByUid(Long uid);
    /**
     * 缓存拼多多类普通订单
     *
     * @param pddOrderList
     * @param uid
     * @return
     * @throws CommonOrderException
     */
    public List<CommonOrderAddResultDTO> addPDDOrder(List<PDDOrder> pddOrderList, Long uid) throws CommonOrderException;
    /**
     * 订单中获得有效奖金
     * @param orderNo
     * @param sourceType
     * @return
     */
    public BigDecimal getTotalRewardMoneyByOrderNoAndSourceType(String orderNo, Integer sourceType);
    /**
     * 缓存京东普通订单
     *
     * @param jdOrderList
     * @param uid
     * @return
     * @throws CommonOrderException
     */
    public List<CommonOrderAddResultDTO> addJDOrder(JDOrder jdOrder, Long uid) throws CommonOrderException;
    /**
     * 统计24小时有效自购订单
     * @param uid
     * @param minTime
     * @return
     */
    public long count24HValidOrderByUid(Long uid, Date minTime);
    /**
     * 订单统计有效数量
     * @param uid
     * @param day
     * @param source
     * @return
     */
    public OrderCountVO getOrderCount(Long uid, Integer day,  List<Integer> listSource);
    /**
     * 添加唯品会订单
     *
     * @param order
     * @param uid
     * @return
     * @throws CommonOrderException List<CommonOrderAddResultDTO> 返回类型
     * @throws
     * @Title: addVipShopOrder
     * @Description:
     */
    public List<CommonOrderAddResultDTO> addVipShopOrder(VipShopOrder order, Long uid) throws CommonOrderException;
    /**
     * 搜索订单信息
     * @param page
     * @param size
     * @param uid
     * @param list
     * @return
     */
    public List<CommonOrderVO> searchOrderByUid(AcceptData acceptData, int page, int size, Long uid, List<ESOrder> list) throws Exception;
    public long countSearchOrderByUid(Long uid, List<ESOrder> list);
    /**
     * 返回订单的第三方创建时间
     * @Title: getThirdCreateTime
     * @Description:
     * @param orderId
     * @param sourceType
     * @return
     * Date 返回类型
     * @throws
     */
    public Date getThirdCreateTime(String orderId,int sourceType);
    /**
     * 添加苏宁订单
     *
     * @param order
     * @param uid
     * @return
     * @throws CommonOrderException List<CommonOrderAddResultDTO> 返回类型
     * @throws
     * @Title: addVipShopOrder
     * @Description:
     */
    public List<CommonOrderAddResultDTO> addSuningOrder(List<SuningOrderInfo> suningOrderList, Long uid) throws CommonOrderException;
    public List<CommonOrder> getMinSettleTimeAndUid();
    /**
     * 新版红包信息2.1
     * @param acceptData
     * @param page
     * @param uid
     * @param state
     * @param type
     * @param orderState
     * @param orderNo
     * @param startTime
     * @param endTime
     * @param dateType
     * @param listSource
     * @return
     * @throws CommonOrderException
     * @throws Exception
     */
    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;
    /**
     * 根据用户ID,订单状态,结算时间统计订单数量
     *
     * @param uid
     * @param state
     * @param minDate
     * @param maxDate
     * @return
     */
    public long countByUidAndOrderStateWithOrderBalanceTime(Long uid, int state, Date minDate, Date maxDate);
    long countOrderList(Long uid, Integer state, Integer type, Integer orderState, String orderNo, String startTime,
            String endTime, Integer dateType, List<Integer> listSource);
    /**
     * 后端查询订单列表
     *
     * @param start
     * @param count
     * @param uid
     * @param state
     * @param type
     * @param orderState
     * @param orderNo
     * @param startTime
     * @param endTime
     * @param dateType   1昨天 2今天 3本月 4 上月
     * @return
     * @throws CommonOrderException
     */
    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;
    /**
     * 维权金额计算
     * @param listWQ
     * @param sourceType
     * @param uid
     * @return
     */
    public BigDecimal getWeiQuanMoney(List<TaoBaoWeiQuanOrder> listWQ, int sourceType, Long uid);
    public long countQueryByUid(Long uid, Integer state, Integer type, Integer orderState, String orderNo,
                                String startTime, String endTime, Integer dateType) throws CommonOrderException;
    /**
     * 统计订单记录数量-非订单号为主
     * @param uid
     * @param payment
     * @return
     */
    public long countOrderByUidAndSettled(Long uid, BigDecimal payment);
    /**
     * 查询所有用户订单
     *
     * @param start
     * @param count
     * @param keyType
     * @param key
     * @param state
     * @param type
     * @param orderState
     * @param startTime
     * @param endTime
     * @return
     * @throws CommonOrderException
     */
    /**
     * 获取最新的淘宝订单号
     * @return
     */
    public String getNewestOrderNoByTaoBao();
    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, SystemEnum system)
            throws CommonOrderException;
    /**
     * 根据订单号查询
     * @param orderNo
     * @return
     */
    public List<CommonOrder> listByOrderNo(String orderNo);
    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, SystemEnum system) throws CommonOrderException;
    /**
     * 根据订单类型+ 订单号查询
     * @param uid
     * @param orderNO
     * @param sourceType
     * @return
     */
    public List<CommonOrder> getByOrderNoAndSourceType(Long uid, String orderNO, int sourceType);
    /**
     * 查询订单
     *
     * @param uid
     * @param orderNo
     * @return
     * @throws CommonOrderException
     */
    public CommonOrderVO getCommonOrderByOrderNo(Long uid, String orderNo, Integer orderState, Integer sourceType)
            throws CommonOrderException;
    /**
     * 首单
     * @param uid
     * @return
     */
    public CommonOrder getFirstOrder(Long uid);
    /**
     * 使用奖励券成功后跳转 修改
     *
     * @param orderNo
     * @return
     */
    public JSONObject getRewardJumpInfo(String orderNo, Integer goodsType);
    /**
     * 根据交易号获取订单详情
     *
     * @param sourceType
     * @param tradeId
     * @return
     */
    public CommonOrder selectBySourceTypeAndTradeId(int sourceType, String tradeId);
    /**
     * 删除错误订单
     *
     * @param coId
     */
    public void deleteErrorCommonOrder(Long coId);
    /**
     * 根据订单类型与交易ID查询
     *
     * @param sourceType
     * @param tradeId
     * @return
     */
    public List<CommonOrder> listBySourceTypeAndTradeId(int sourceType, String tradeId);
    /**
     * 根据条件查询订单
     *
     * @param sourceType
     * @param state
     * @param minTime
     * @param maxTime
     * @param page
     * @param pageSize
     * @return
     */
    public List<CommonOrder> listBySourceTypeAndStateAndThirdCrateTime(int sourceType, Integer state, Long minTime,
                                                                       Long maxTime, int page, int pageSize);
    /**
     * 查询订单 -根据订单号
     *
     * @param uid
     * @param orderNO
     * @return
     */
    public List<CommonOrder> getByOrderNo(Long uid, String orderNO);
    /**
     * 根据用户ID查询最近一条有效的订单
     *
     * @param uid
     * @return
     */
    public CommonOrder selectLatestValidByUid(Long uid);
    /**
     * 查询首笔有效订单
     *
     * @param uid
     * @return
     */
    public CommonOrderVO firstValidOrderByUid(Long uid);
    /**
     * 查询首笔有效订单
     *
     * @param uid
     * @param type 类型: 1自购  2分享 3邀请
     * @return
     */
    public CommonOrderVO firstValidOrderByUidAndType(Long uid, Integer type);
    /**
     * 查询是否上月到账订单
     *
     * @param uid
     * @param type 类型: 1自购  2分享 3邀请
     * @return
     */
    public CommonOrderVO firstValidOrderLastMonthByUidAndType(Long uid, Integer type);
    /**
     * 首个分享订单
     *
     * @param uid
     * @return
     */
    public CommonOrder getFirstShareOrderByUid(Long uid);
    /**
     * 订单中获得有效奖金
     *
     * @param orderNo
     * @param sourceType
     * @return
     */
    public BigDecimal getTotalRewardMoneyByOrderNoAndSourceType(String orderNo, Integer sourceType);
    /**
     * 统计24小时有效自购订单
     *
     * @param uid
     * @param minTime
     * @return
     */
    public long count24HValidOrderByUid(Long uid, Date minTime);
    /**
     * 订单统计有效数量
     *
     * @param uid
     * @param day
     * @param source
     * @return
     */
    public OrderCountVO getOrderCount(Long uid, Integer day, List<Integer> listSource);
    /**
     * 搜索订单信息
     *
     * @param page
     * @param size
     * @param uid
     * @param list
     * @return
     */
    public List<CommonOrderVO> searchOrderByUid(AcceptData acceptData, int page, int size, Long uid, List<ESOrder> list) throws Exception;
    public long countSearchOrderByUid(Long uid, List<ESOrder> list);
    /**
     * 返回订单的第三方创建时间
     *
     * @param orderId
     * @param sourceType
     * @return Date 返回类型
     * @throws
     * @Title: getThirdCreateTime
     * @Description:
     */
    public Date getThirdCreateTime(String orderId, int sourceType);
    public List<CommonOrder> getMinSettleTimeAndUid();
    /**
     * 新版红包信息2.1
     *
     * @param acceptData
     * @param page
     * @param uid
     * @param state
     * @param type
     * @param orderState
     * @param orderNo
     * @param startTime
     * @param endTime
     * @param dateType
     * @param listSource
     * @return
     * @throws CommonOrderException
     * @throws Exception
     */
    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;
    long countOrderList(Long uid, Integer state, Integer type, Integer orderState, String orderNo, String startTime,
                        String endTime, Integer dateType, List<Integer> listSource);
    /**
     * 维权金额计算
     *
     * @param listWQ
     * @param sourceType
     * @param uid
     * @return
     */
    public BigDecimal getWeiQuanMoney(List<TaoBaoWeiQuanOrder> listWQ, int sourceType, Long uid);
    /**
     * 统计订单记录数量-非订单号为主
     *
     * @param uid
     * @param payment
     * @return
     */
    public long countOrderByUidAndSettled(Long uid, BigDecimal payment);
    /**
     * 获取最新的淘宝订单号
     *
     * @return
     */
    public String getNewestOrderNoByTaoBao();
    /**
     * 根据订单号查询
     *
     * @param orderNo
     * @return
     */
    public List<CommonOrder> listByOrderNo(String orderNo);
    /**
     * 根据订单类型+ 订单号查询
     *
     * @param uid
     * @param orderNO
     * @param sourceType
     * @return
     */
    public List<CommonOrder> getByOrderNoAndSourceType(Long uid, String orderNO, int sourceType);
    /**
     * 首单
     *
     * @param uid
     * @return
     */
    public CommonOrder getFirstOrder(Long uid);
    /**
     * 根据商品ID,用户ID,最小创建时间查询
     *
     * @param goodsId
     * @param uid
     * @param minThirdCreateTime
     * @return
     */
    public List<CommonOrder> listByGoodsIdAndUidAndMinThirdCreateTime(Long goodsId, Long uid, Date minThirdCreateTime);
}
fanli/src/main/java/com/yeshi/fanli/service/inter/order/HongBaoV2Service.java
@@ -10,6 +10,7 @@
import com.yeshi.fanli.entity.order.CommonOrder;
import com.yeshi.fanli.exception.order.HongBaoException;
import com.yeshi.fanli.exception.user.UserAccountException;
import org.omg.CORBA.PUBLIC_MEMBER;
public interface HongBaoV2Service {
@@ -196,4 +197,12 @@
     * @return
     */
    public Integer getDirectBossUrankByPid(Long pid);
    /**
     * 设置红包已领取
     * @param uid
     * @param preGetTime
     */
    public void setHongBaoRecieved(Long uid,List<Integer> typeList, Date preGetTime);
}
fanli/src/main/java/com/yeshi/fanli/service/inter/order/OrderMoneySettleService.java
@@ -22,6 +22,8 @@
    public void inviteSettleJD(Long uid, Date maxPregetTime) throws OrderMoneySettleException;
    public void inviteSettlePDD(Long uid, Date maxPregetTime) throws OrderMoneySettleException;
    public void inviteSettleSuning(Long uid, Date maxPregetTime) throws OrderMoneySettleException;
    
    public void inviteSettleVipShop(Long uid, Date maxPregetTime) throws OrderMoneySettleException;
@@ -38,6 +40,8 @@
    
    public void shareSettleVipShop(Long uid, Date maxPregetTime) throws OrderMoneySettleException;
    public void shareSettleSuning(Long uid, Date maxPregetTime) throws OrderMoneySettleException;
    /**
     * 自购结算
     * 
fanli/src/main/java/com/yeshi/fanli/service/inter/user/SMSService.java
@@ -2,6 +2,7 @@
import java.math.BigDecimal;
import com.yeshi.fanli.entity.SystemEnum;
import com.yeshi.fanli.exception.config.SMSException;
/**
@@ -18,7 +19,7 @@
     * @param phone
     * @throws SMSException
     */
    public String sendLoginVCode(String phone, int codeLength) throws SMSException;
    public String sendLoginVCode(SystemEnum system, String phone, int codeLength) throws SMSException;
    /**
     * 发送绑定验证码
@@ -26,7 +27,7 @@
     * @param phone
     * @throws SMSException
     */
    public void sendBindVCode(String phone, int codeLength) throws SMSException;
    public void sendBindVCode(SystemEnum system,String phone, int codeLength) throws SMSException;
    /**
     * 发送提现验证码
@@ -34,7 +35,7 @@
     * @param phone
     * @throws SMSException
     */
    public void sendExtractVCode(String phone) throws SMSException;
    public void sendExtractVCode(SystemEnum system,String phone) throws SMSException;
    /**
     * 提现成功短信
@@ -42,7 +43,7 @@
     * @param phone
     * @param money
     */
    public void sendExtractSuccessMsg(String phone, BigDecimal money) throws SMSException;
    public void sendExtractSuccessMsg(SystemEnum system,String phone, BigDecimal money) throws SMSException;
    /**
     * 发送提现失败验证码
@@ -50,7 +51,7 @@
     * @param phone
     * @param money
     */
    public void sendExtractFailMsg(String phone, BigDecimal money) throws SMSException;
    public void sendExtractFailMsg(SystemEnum system,String phone, BigDecimal money) throws SMSException;
    /**
     * 账户注销
@@ -58,5 +59,5 @@
     * @param codeLength
     * @throws SMSException
     */
    public void sendRemoveVCode(String phone, int codeLength) throws SMSException;
    public void sendRemoveVCode(SystemEnum system,String phone, int codeLength) throws SMSException;
}
fanli/src/main/java/com/yeshi/fanli/service/manger/goods/ConvertLinkManager.java
@@ -109,7 +109,7 @@
                String goodsId = PinDuoDuoUtil.getPDDGoodsId(shortLink);
                if (!StringUtil.isNullOrEmpty(goodsId)) {
                    PDDPromotionUrl pddUrl = PinDuoDuoApiUtil.convert(Long.parseLong(goodsId),
                            share ? PinDuoDuoApiUtil.PID_SHARE : PinDuoDuoApiUtil.PID_FANLI, uid + "");
                            share ? PinDuoDuoApiUtil.PID_SHARE : PinDuoDuoApiUtil.PID_FANLI, uid + "",false);
                    if (pddUrl != null) {
                        linkMap.put(shortLink, pddUrl.getShortUrl());
                    }
fanli/src/main/java/com/yeshi/fanli/service/manger/money/TeamEincomeManager.java
@@ -7,6 +7,8 @@
import javax.annotation.Resource;
import com.yeshi.fanli.entity.bus.user.HongBaoV2;
import com.yeshi.fanli.service.inter.order.HongBaoV2Service;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
@@ -38,6 +40,9 @@
    @Resource
    private UserMoneyMsgNotificationService userMoneyMsgNotificationService;
    @Resource
    private HongBaoV2Service hongBaoV2Service;
    /**
     * @throws ParamsException 
@@ -122,6 +127,15 @@
        // 发送消息
        BigDecimal balance = userMoneyService.getBalance(uid);
        userMoneyMsgNotificationService.teamRewardReceive(uid, money, balance, now);
        //更改状态
        List<Integer> hongBaoTypeList=new ArrayList<>();
        hongBaoTypeList.add(HongBaoV2.TYPE_YIJI);
        hongBaoTypeList.add(HongBaoV2.TYPE_ERJI);
        hongBaoTypeList.add(HongBaoV2.TYPE_SHARE_YIJI);
        hongBaoTypeList.add(HongBaoV2.TYPE_SHARE_ERJI);
        hongBaoV2Service.setHongBaoRecieved(uid,hongBaoTypeList,preSendTime);
    }
    /**
fanli/src/main/java/com/yeshi/fanli/util/Constant.java
@@ -95,7 +95,7 @@
    public static final String TAOBAO_SPECIAL_PID_DEFAULT = "mm_124933865_56750082_89555600043";
    public static final long PUSH_MIN_TIME=1000*60*60*24*30*2L;
    public static final long PUSH_MIN_TIME=1000*60*60L*24*30*2;
    
    
    //优惠狗云发单群唤起关键词
fanli/src/main/java/com/yeshi/fanli/util/RedisKeyEnum.java
@@ -29,6 +29,8 @@
    taobaoCode("taobao-code-", "淘宝code"),
    taobaoTokenGoodsMap("tb-t-g_m-", "淘宝口令对应商品的映射关系保存"),
    taobaoBaseLink("tb-b-l-", "淘客商品转链结果缓存"),
    taobaoSearchResult("tb-s-r-", "淘宝搜索结果缓存"),
    JDGoods("JD-goods-", "京东商品"),
    JDShortUrl("jd-link-to-goods-", "京东短链"),
    jingDongGoods("jingdong-goods-", "京东商品"),
fanli/src/main/java/com/yeshi/fanli/util/SpringContext.java
@@ -801,169 +801,169 @@
        new JobThreadExecutorServiceImpl().run(new Runnable() {
            @Override
            public void run() {
                    Map<String, Long> map = HongBaoRecieveCMQManager.getInstance()
                            .consumeQueueMsg(HongBaoRecieveCMQManager.QUEUE_INTEGRAL, 16);
                    if (map != null) {
                        Iterator<String> its = map.keySet().iterator();
                        while (its.hasNext()) {
                            String key = its.next();
                            Long hongBaoId = map.get(key);
                            try {
                                HongBaoV2 hongBaoV2 = hongBaoV2Service.selectByPrimaryKey(hongBaoId);
                                if (hongBaoV2 != null && hongBaoV2.getState() == HongBaoV2.STATE_YILINGQU
                                        && hongBaoV2.getMoney().compareTo(new BigDecimal(0)) > 0) {
                                    // 到账送金币
                                    fanliGetIntegral(hongBaoV2);
                                    HongBaoRecieveCMQManager.getInstance()
                                            .deleteQueueMsg(HongBaoRecieveCMQManager.QUEUE_INTEGRAL, key);
                Map<String, Long> map = HongBaoRecieveCMQManager.getInstance()
                        .consumeQueueMsg(HongBaoRecieveCMQManager.QUEUE_INTEGRAL, 16);
                if (map != null) {
                    Iterator<String> its = map.keySet().iterator();
                    while (its.hasNext()) {
                        String key = its.next();
                        Long hongBaoId = map.get(key);
                        try {
                            HongBaoV2 hongBaoV2 = hongBaoV2Service.selectByPrimaryKey(hongBaoId);
                            if (hongBaoV2 != null && hongBaoV2.getState() == HongBaoV2.STATE_YILINGQU
                                    && hongBaoV2.getMoney().compareTo(new BigDecimal(0)) > 0) {
                                // 到账送金币
                                fanliGetIntegral(hongBaoV2);
                                HongBaoRecieveCMQManager.getInstance()
                                        .deleteQueueMsg(HongBaoRecieveCMQManager.QUEUE_INTEGRAL, key);
                                    // 返利不足0.01元送金币
                                    if (hongBaoV2.getType() == HongBaoV2.TYPE_ZIGOU) {// 自购
                                        // 判断是否为该用户的首笔红包
                                        List<Integer> typeList = new ArrayList<>();
                                        typeList.add(HongBaoV2.TYPE_ZIGOU);
                                        HongBaoV2 firstHongBao = hongBaoV2Service.getFirstValidHongBaoByTypeAndUid(
                                                typeList, hongBaoV2.getUserInfo().getId());
                                        if (firstHongBao != null
                                                && firstHongBao.getId().longValue() == hongBaoV2.getId()) {// 自购首单到账
                                            // 查询下级红包
                                            BigDecimal firstLevelMoney = new BigDecimal(0);
                                            BigDecimal secondLevelMoney = new BigDecimal(0);
                                            // 获取改单下面的红包
                                            List<HongBaoV2> hongBaoList = new ArrayList<>();
                                            HongBaoOrder hongBaoOrder = hongBaoOrderService
                                                    .selectDetailByHongBaoId(hongBaoV2.getId());
                                            if (hongBaoOrder != null && hongBaoOrder.getCommonOrder() != null) {// 计算改订单号下面的所有返利金额
                                                CommonOrder commonOrder = hongBaoOrder.getCommonOrder();
                                                List<CommonOrder> list = commonOrderService.listBySourceTypeAndOrderId(
                                                        commonOrder.getSourceType(), commonOrder.getOrderNo());
                                                for (CommonOrder co : list) {
                                                    HongBaoOrder hbo = hongBaoOrderService
                                                            .selectDetailByCommonOrderId(co.getId());
                                                    if (hbo != null && hbo.getHongBaoV2() != null)
                                                        hongBaoList.add(hbo.getHongBaoV2());
                                                }
                                // 返利不足0.01元送金币
                                if (hongBaoV2.getType() == HongBaoV2.TYPE_ZIGOU) {// 自购
                                    // 判断是否为该用户的首笔红包
                                    List<Integer> typeList = new ArrayList<>();
                                    typeList.add(HongBaoV2.TYPE_ZIGOU);
                                    HongBaoV2 firstHongBao = hongBaoV2Service.getFirstValidHongBaoByTypeAndUid(
                                            typeList, hongBaoV2.getUserInfo().getId());
                                    if (firstHongBao != null
                                            && firstHongBao.getId().longValue() == hongBaoV2.getId()) {// 自购首单到账
                                        // 查询下级红包
                                        BigDecimal firstLevelMoney = new BigDecimal(0);
                                        BigDecimal secondLevelMoney = new BigDecimal(0);
                                        // 获取改单下面的红包
                                        List<HongBaoV2> hongBaoList = new ArrayList<>();
                                        HongBaoOrder hongBaoOrder = hongBaoOrderService
                                                .selectDetailByHongBaoId(hongBaoV2.getId());
                                        if (hongBaoOrder != null && hongBaoOrder.getCommonOrder() != null) {// 计算改订单号下面的所有返利金额
                                            CommonOrder commonOrder = hongBaoOrder.getCommonOrder();
                                            List<CommonOrder> list = commonOrderService.listBySourceTypeAndOrderId(
                                                    commonOrder.getSourceType(), commonOrder.getOrderNo());
                                            for (CommonOrder co : list) {
                                                HongBaoOrder hbo = hongBaoOrderService
                                                        .selectDetailByCommonOrderId(co.getId());
                                                if (hbo != null && hbo.getHongBaoV2() != null)
                                                    hongBaoList.add(hbo.getHongBaoV2());
                                            }
                                        }
                                            for (HongBaoV2 hb : hongBaoList) {
                                                List<HongBaoV2> children = hongBaoV2Service
                                                        .listChildrenById(hb.getId());
                                                if (children != null)
                                                    for (HongBaoV2 child : children)
                                                        if (child.getType() == HongBaoV2.TYPE_YIJI) {
                                                            firstLevelMoney = firstLevelMoney.add(child.getMoney());
                                                        } else if (child.getType() == HongBaoV2.TYPE_ERJI) {
                                                            secondLevelMoney = secondLevelMoney.add(child.getMoney());
                                                        }
                                            }
                                            // 查询下级的生效时间
                                            ThreeSale threeSale = threeSaleSerivce.selectLatestByWorkerIdAndState(
                                                    hongBaoV2.getUserInfo().getId(), ThreeSale.STATE_SUCCESS);
                                            if (threeSale != null && threeSale.getSucceedTime() != null && threeSale
                                                    .getSucceedTime() < hongBaoV2.getCreateTime().getTime()) {// 邀请成功的时间是否在下单的时间之前
                                                // 成功时间要大于20190910日才开始送金币
                                                if (threeSale.getSucceedTime() > TimeUtil.convertToTimeTemp("20190901",
                                                        "yyyyMMdd")) {
                                                    if (firstLevelMoney.compareTo(new BigDecimal("0.01")) < 0) {// 一级返利小于0.01
                                                        integralTaskRecordService.firstRebateOrderRewardBoss(
                                                                threeSale.getBoss().getId(),
                                                                hongBaoV2.getUserInfo().getId(), null);
                                                        LogHelper.test("自购-一级用户-" + threeSale.getBoss().getId()
                                                                + "-hongBaoId:" + hongBaoV2.getId());
                                        for (HongBaoV2 hb : hongBaoList) {
                                            List<HongBaoV2> children = hongBaoV2Service
                                                    .listChildrenById(hb.getId());
                                            if (children != null)
                                                for (HongBaoV2 child : children)
                                                    if (child.getType() == HongBaoV2.TYPE_YIJI) {
                                                        firstLevelMoney = firstLevelMoney.add(child.getMoney());
                                                    } else if (child.getType() == HongBaoV2.TYPE_ERJI) {
                                                        secondLevelMoney = secondLevelMoney.add(child.getMoney());
                                                    }
                                                }
                                            }
                                            // 查询下下级生效时间
                                            if (threeSale != null) {
                                                threeSale = threeSaleSerivce.selectLatestByWorkerIdAndState(
                                                        threeSale.getBoss().getId(), ThreeSale.STATE_SUCCESS);
                                                if (threeSale != null && threeSale.getSucceedTime() != null && threeSale
                                                        .getSucceedTime() < hongBaoV2.getCreateTime().getTime()) {// 邀请成功的时间是否在下单的时间之前
                                                    // 成功时间要大于20190910日才开始送金币
                                                    if (threeSale.getSucceedTime() > TimeUtil
                                                            .convertToTimeTemp("20190901", "yyyyMMdd")) {
                                                        if (secondLevelMoney.compareTo(new BigDecimal("0.01")) < 0) {// 二级返利小于0.01
                                                            integralTaskRecordService.firstRebateOrderRewardBossSuper(
                                                                    threeSale.getBoss().getId(),
                                                                    hongBaoV2.getUserInfo().getId(), null);
                                                            LogHelper.test("自购-二级用户-" + threeSale.getBoss().getId()
                                                                    + "-hongBaoId:" + hongBaoV2.getId());
                                                        }
                                                    }
                                        }
                                        // 查询下级的生效时间
                                        ThreeSale threeSale = threeSaleSerivce.selectLatestByWorkerIdAndState(
                                                hongBaoV2.getUserInfo().getId(), ThreeSale.STATE_SUCCESS);
                                        if (threeSale != null && threeSale.getSucceedTime() != null && threeSale
                                                .getSucceedTime() < hongBaoV2.getCreateTime().getTime()) {// 邀请成功的时间是否在下单的时间之前
                                            // 成功时间要大于20190910日才开始送金币
                                            if (threeSale.getSucceedTime() > TimeUtil.convertToTimeTemp("20190901",
                                                    "yyyyMMdd")) {
                                                if (firstLevelMoney.compareTo(new BigDecimal("0.01")) < 0) {// 一级返利小于0.01
                                                    integralTaskRecordService.firstRebateOrderRewardBoss(
                                                            threeSale.getBoss().getId(),
                                                            hongBaoV2.getUserInfo().getId(), null);
                                                    LogHelper.test("自购-一级用户-" + threeSale.getBoss().getId()
                                                            + "-hongBaoId:" + hongBaoV2.getId());
                                                }
                                            }
                                        }
                                    } else if (hongBaoV2.getType() == HongBaoV2.TYPE_SHARE_GOODS) {// 分享赚
                                        // 判断是否为该用户的首笔红包
                                        List<Integer> typeList = new ArrayList<>();
                                        typeList.add(HongBaoV2.TYPE_SHARE_GOODS);
                                        HongBaoV2 firstHongBao = hongBaoV2Service.getFirstValidHongBaoByTypeAndUid(
                                                typeList, hongBaoV2.getUserInfo().getId());
                                        if (firstHongBao != null
                                                && firstHongBao.getId().longValue() == hongBaoV2.getId()) // 分享首笔到账
                                        {
                                            // 查询下级红包
                                            BigDecimal firstLevelMoney = new BigDecimal(0);
                                            // 获取改单下面的红包
                                            List<HongBaoV2> hongBaoList = new ArrayList<>();
                                            HongBaoOrder hongBaoOrder = hongBaoOrderService
                                                    .selectDetailByHongBaoId(hongBaoV2.getId());
                                            if (hongBaoOrder != null && hongBaoOrder.getCommonOrder() != null) {// 计算改订单号下面的所有返利金额
                                                CommonOrder commonOrder = hongBaoOrder.getCommonOrder();
                                                List<CommonOrder> list = commonOrderService.listBySourceTypeAndOrderId(
                                                        commonOrder.getSourceType(), commonOrder.getOrderNo());
                                                for (CommonOrder co : list) {
                                                    HongBaoOrder hbo = hongBaoOrderService
                                                            .selectDetailByCommonOrderId(co.getId());
                                                    if (hbo != null && hbo.getHongBaoV2() != null)
                                                        hongBaoList.add(hbo.getHongBaoV2());
                                                }
                                            }
                                            for (HongBaoV2 hb : hongBaoList) {
                                                List<HongBaoV2> children = hongBaoV2Service
                                                        .listChildrenById(hb.getId());
                                                if (children != null)
                                                    for (HongBaoV2 child : children)
                                                        if (child.getType() == HongBaoV2.TYPE_SHARE_YIJI) {
                                                            firstLevelMoney = firstLevelMoney.add(child.getMoney());
                                                        }
                                            }
                                            ThreeSale threeSale = threeSaleSerivce.selectLatestByWorkerIdAndState(
                                                    hongBaoV2.getUserInfo().getId(), ThreeSale.STATE_SUCCESS);
                                        // 查询下下级生效时间
                                        if (threeSale != null) {
                                            threeSale = threeSaleSerivce.selectLatestByWorkerIdAndState(
                                                    threeSale.getBoss().getId(), ThreeSale.STATE_SUCCESS);
                                            if (threeSale != null && threeSale.getSucceedTime() != null && threeSale
                                                    .getSucceedTime() < hongBaoV2.getCreateTime().getTime()) {// 邀请成功的时间是否在下单的时间之前
                                                // 成功时间要大于20190910日才开始送金币
                                                if (threeSale.getSucceedTime() > TimeUtil.convertToTimeTemp("20190901",
                                                        "yyyyMMdd")) {
                                                    if (firstLevelMoney.compareTo(new BigDecimal("0.01")) < 0) {// 一级返利小于0.01
                                                        integralTaskRecordService.firstSharerOrderRewardBoss(
                                                if (threeSale.getSucceedTime() > TimeUtil
                                                        .convertToTimeTemp("20190901", "yyyyMMdd")) {
                                                    if (secondLevelMoney.compareTo(new BigDecimal("0.01")) < 0) {// 二级返利小于0.01
                                                        integralTaskRecordService.firstRebateOrderRewardBossSuper(
                                                                threeSale.getBoss().getId(),
                                                                hongBaoV2.getUserInfo().getId(), null);
                                                        LogHelper.test("分享-一级用户-" + threeSale.getBoss().getId()
                                                        LogHelper.test("自购-二级用户-" + threeSale.getBoss().getId()
                                                                + "-hongBaoId:" + hongBaoV2.getId());
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                } else if (hongBaoV2.getType() == HongBaoV2.TYPE_SHARE_GOODS) {// 分享赚
                                    // 判断是否为该用户的首笔红包
                                    List<Integer> typeList = new ArrayList<>();
                                    typeList.add(HongBaoV2.TYPE_SHARE_GOODS);
                                    HongBaoV2 firstHongBao = hongBaoV2Service.getFirstValidHongBaoByTypeAndUid(
                                            typeList, hongBaoV2.getUserInfo().getId());
                                    if (firstHongBao != null
                                            && firstHongBao.getId().longValue() == hongBaoV2.getId()) // 分享首笔到账
                                    {
                            } catch (Exception e) {
                                try {
                                    LogHelper.errorDetailInfo(e);
                                } catch (Exception e1) {
                                    e1.printStackTrace();
                                }
                            } finally {
                                        // 查询下级红包
                                        BigDecimal firstLevelMoney = new BigDecimal(0);
                                        // 获取改单下面的红包
                                        List<HongBaoV2> hongBaoList = new ArrayList<>();
                                        HongBaoOrder hongBaoOrder = hongBaoOrderService
                                                .selectDetailByHongBaoId(hongBaoV2.getId());
                                        if (hongBaoOrder != null && hongBaoOrder.getCommonOrder() != null) {// 计算改订单号下面的所有返利金额
                                            CommonOrder commonOrder = hongBaoOrder.getCommonOrder();
                                            List<CommonOrder> list = commonOrderService.listBySourceTypeAndOrderId(
                                                    commonOrder.getSourceType(), commonOrder.getOrderNo());
                                            for (CommonOrder co : list) {
                                                HongBaoOrder hbo = hongBaoOrderService
                                                        .selectDetailByCommonOrderId(co.getId());
                                                if (hbo != null && hbo.getHongBaoV2() != null)
                                                    hongBaoList.add(hbo.getHongBaoV2());
                                            }
                                        }
                                        for (HongBaoV2 hb : hongBaoList) {
                                            List<HongBaoV2> children = hongBaoV2Service
                                                    .listChildrenById(hb.getId());
                                            if (children != null)
                                                for (HongBaoV2 child : children)
                                                    if (child.getType() == HongBaoV2.TYPE_SHARE_YIJI) {
                                                        firstLevelMoney = firstLevelMoney.add(child.getMoney());
                                                    }
                                        }
                                        ThreeSale threeSale = threeSaleSerivce.selectLatestByWorkerIdAndState(
                                                hongBaoV2.getUserInfo().getId(), ThreeSale.STATE_SUCCESS);
                                        if (threeSale != null && threeSale.getSucceedTime() != null && threeSale
                                                .getSucceedTime() < hongBaoV2.getCreateTime().getTime()) {// 邀请成功的时间是否在下单的时间之前
                                            // 成功时间要大于20190910日才开始送金币
                                            if (threeSale.getSucceedTime() > TimeUtil.convertToTimeTemp("20190901",
                                                    "yyyyMMdd")) {
                                                if (firstLevelMoney.compareTo(new BigDecimal("0.01")) < 0) {// 一级返利小于0.01
                                                    integralTaskRecordService.firstSharerOrderRewardBoss(
                                                            threeSale.getBoss().getId(),
                                                            hongBaoV2.getUserInfo().getId(), null);
                                                    LogHelper.test("分享-一级用户-" + threeSale.getBoss().getId()
                                                            + "-hongBaoId:" + hongBaoV2.getId());
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        } catch (Exception e) {
                            try {
                                LogHelper.errorDetailInfo(e);
                            } catch (Exception e1) {
                                e1.printStackTrace();
                            }
                        } finally {
                        }
                    }
                }
            }
        });
    }
@@ -1010,97 +1010,97 @@
        new JobThreadExecutorServiceImpl().run(new Runnable() {
            @Override
            public void run() {
                    Map<String, Order> map = PlaceOrderCMQManager.getInstance()
                            .consumeQueueMsg(PlaceOrderCMQManager.QUEUE_INTEGRAL, 16);
                    if (map != null) {
                Map<String, Order> map = PlaceOrderCMQManager.getInstance()
                        .consumeQueueMsg(PlaceOrderCMQManager.QUEUE_INTEGRAL, 16);
                if (map != null) {
                        for (Iterator<String> its = map.keySet().iterator(); its.hasNext(); ) {
                            try {
                                String key = its.next();
                                Order order = map.get(key);
                                // 是否是首单
                                if (isFirstValidOrder(order.getOrderId(), order.getOrderType(),
                                        order.getUserInfo().getId())) {
                                    // 统计订单下的用户所获得的返利金额
                                    List<CommonOrder> list = commonOrderService
                                            .listBySourceTypeAndOrderId(order.getOrderType(), order.getOrderId());
                                    Map<Long, BigDecimal> hongBaoMoney = new HashMap<>();
                                    if (list != null)
                                        for (CommonOrder commonOrder : list) {
                                            HongBaoOrder hongBaoOrder = hongBaoOrderService
                                                    .selectDetailByCommonOrderId(commonOrder.getId());
                                            if (hongBaoOrder != null && hongBaoOrder.getHongBaoV2() != null) {
                                                Long mainUid = hongBaoOrder.getHongBaoV2().getUserInfo().getId();
                                                if (hongBaoMoney.get(mainUid) == null)
                                                    hongBaoMoney.put(mainUid, new BigDecimal(0));
                                                hongBaoMoney.put(mainUid, hongBaoMoney.get(mainUid)
                                                        .add(hongBaoOrder.getHongBaoV2().getMoney()));
                                                // 查询上级
                                                List<HongBaoV2> children = hongBaoV2Service
                                                        .listChildrenById(hongBaoOrder.getHongBaoV2().getId());
                                                if (children != null) {
                                                    for (HongBaoV2 hongBao : children) {
                                                        Long uid = hongBao.getUserInfo().getId();
                                                        if (hongBaoMoney.get(uid) == null)
                                                            hongBaoMoney.put(uid, new BigDecimal(0));
                                                        hongBaoMoney.put(uid,
                                                                hongBaoMoney.get(uid).add(hongBao.getMoney()));
                                                    }
                                                }
                                            }
                                        }
                                    if (isFirstValidOrder(order.getOrderId(), order.getOrderType(),
                                            order.getUserInfo().getId())) {// 有效的首单
                                        if (hongBaoMoney.get(order.getUserInfo().getId()) == null || hongBaoMoney
                                                .get(order.getUserInfo().getId()).compareTo(new BigDecimal("0")) <= 0) {
                                            // 分享奖金是0
                                            integralTaskRecordService.firstShareOrderReward(order.getUserInfo().getId(),
                                                    null);
                                        }
                                        // 获取上两级数据
                                        UserInfo boss = threeSaleSerivce.getBoss(order.getUserInfo().getId());
                                        if (boss != null) {// 判断上级的红包
                                            if (hongBaoMoney.get(boss.getId()) == null || hongBaoMoney.get(boss.getId())
                                                    .compareTo(new BigDecimal("0")) <= 0) {
                                                // 补偿金币
                                                integralTaskRecordService.firstSharerOrderRewardBoss(boss.getId(),
                                                        order.getUserInfo().getId(), null);
                                            }
                                        }
                                    } else {// 自购订单
                                        UserInfo boss = threeSaleSerivce.getBoss(order.getUserInfo().getId());
                                        if (boss != null) {// 判断上级的红包
                                            if (hongBaoMoney.get(boss.getId()) == null || hongBaoMoney.get(boss.getId())
                                                    .compareTo(new BigDecimal("0")) <= 0) {
                                                // 补偿金币1级
                                                integralTaskRecordService.firstRebateOrderRewardBoss(boss.getId(),
                                                        order.getUserInfo().getId(), null);
                                            }
                                            boss = threeSaleSerivce.getBoss(boss.getId());
                                            if (boss != null) {// 判断上级的红包
                                                if (hongBaoMoney.get(boss.getId()) == null || hongBaoMoney
                                                        .get(boss.getId()).compareTo(new BigDecimal("0")) <= 0) {
                                                    // 补偿金币2级
                                                    integralTaskRecordService.firstRebateOrderRewardBossSuper(
                                                            boss.getId(), order.getUserInfo().getId(), null);
                    for (Iterator<String> its = map.keySet().iterator(); its.hasNext(); ) {
                        try {
                            String key = its.next();
                            Order order = map.get(key);
                            // 是否是首单
                            if (isFirstValidOrder(order.getOrderId(), order.getOrderType(),
                                    order.getUserInfo().getId())) {
                                // 统计订单下的用户所获得的返利金额
                                List<CommonOrder> list = commonOrderService
                                        .listBySourceTypeAndOrderId(order.getOrderType(), order.getOrderId());
                                Map<Long, BigDecimal> hongBaoMoney = new HashMap<>();
                                if (list != null)
                                    for (CommonOrder commonOrder : list) {
                                        HongBaoOrder hongBaoOrder = hongBaoOrderService
                                                .selectDetailByCommonOrderId(commonOrder.getId());
                                        if (hongBaoOrder != null && hongBaoOrder.getHongBaoV2() != null) {
                                            Long mainUid = hongBaoOrder.getHongBaoV2().getUserInfo().getId();
                                            if (hongBaoMoney.get(mainUid) == null)
                                                hongBaoMoney.put(mainUid, new BigDecimal(0));
                                            hongBaoMoney.put(mainUid, hongBaoMoney.get(mainUid)
                                                    .add(hongBaoOrder.getHongBaoV2().getMoney()));
                                            // 查询上级
                                            List<HongBaoV2> children = hongBaoV2Service
                                                    .listChildrenById(hongBaoOrder.getHongBaoV2().getId());
                                            if (children != null) {
                                                for (HongBaoV2 hongBao : children) {
                                                    Long uid = hongBao.getUserInfo().getId();
                                                    if (hongBaoMoney.get(uid) == null)
                                                        hongBaoMoney.put(uid, new BigDecimal(0));
                                                    hongBaoMoney.put(uid,
                                                            hongBaoMoney.get(uid).add(hongBao.getMoney()));
                                                }
                                            }
                                        }
                                    }
                                }
                                PlaceOrderCMQManager.getInstance().deleteQueueMsg(PlaceOrderCMQManager.QUEUE_INTEGRAL,
                                        key);
                            } catch (Exception e) {
                                LogHelper.errorDetailInfo(e);
                            }
                        }
                                if (isFirstValidOrder(order.getOrderId(), order.getOrderType(),
                                        order.getUserInfo().getId())) {// 有效的首单
                                    if (hongBaoMoney.get(order.getUserInfo().getId()) == null || hongBaoMoney
                                            .get(order.getUserInfo().getId()).compareTo(new BigDecimal("0")) <= 0) {
                                        // 分享奖金是0
                                        integralTaskRecordService.firstShareOrderReward(order.getUserInfo().getId(),
                                                null);
                                    }
                                    // 获取上两级数据
                                    UserInfo boss = threeSaleSerivce.getBoss(order.getUserInfo().getId());
                                    if (boss != null) {// 判断上级的红包
                                        if (hongBaoMoney.get(boss.getId()) == null || hongBaoMoney.get(boss.getId())
                                                .compareTo(new BigDecimal("0")) <= 0) {
                                            // 补偿金币
                                            integralTaskRecordService.firstSharerOrderRewardBoss(boss.getId(),
                                                    order.getUserInfo().getId(), null);
                                        }
                                    }
                                } else {// 自购订单
                                    UserInfo boss = threeSaleSerivce.getBoss(order.getUserInfo().getId());
                                    if (boss != null) {// 判断上级的红包
                                        if (hongBaoMoney.get(boss.getId()) == null || hongBaoMoney.get(boss.getId())
                                                .compareTo(new BigDecimal("0")) <= 0) {
                                            // 补偿金币1级
                                            integralTaskRecordService.firstRebateOrderRewardBoss(boss.getId(),
                                                    order.getUserInfo().getId(), null);
                                        }
                                        boss = threeSaleSerivce.getBoss(boss.getId());
                                        if (boss != null) {// 判断上级的红包
                                            if (hongBaoMoney.get(boss.getId()) == null || hongBaoMoney
                                                    .get(boss.getId()).compareTo(new BigDecimal("0")) <= 0) {
                                                // 补偿金币2级
                                                integralTaskRecordService.firstRebateOrderRewardBossSuper(
                                                        boss.getId(), order.getUserInfo().getId(), null);
                                            }
                                        }
                                    }
                                }
                            }
                            PlaceOrderCMQManager.getInstance().deleteQueueMsg(PlaceOrderCMQManager.QUEUE_INTEGRAL,
                                    key);
                        } catch (Exception e) {
                            LogHelper.errorDetailInfo(e);
                        }
                    }
                }
            }
        });
    }
@@ -1135,56 +1135,56 @@
        new JobThreadExecutorServiceImpl().run(new Runnable() {
            @Override
            public void run() {
                    Map<String, DouYinDeviceActiveQueueDTO> map = DouYinDeviceActiveCMQManager.getInstance()
                            .consume(16);
                    if (map != null) {
                        // 是否是首单
                        for (Iterator<String> its = map.keySet().iterator(); its.hasNext(); ) {
                            String key = its.next();
                            DouYinDeviceActiveQueueDTO active = map.get(key);
                            if (active.getType() == DouYinDeviceActiveQueueDTO.TYPE_AD) {// 抖音
                                DouYinClickEvent event = douYinClickEventService.selectByCallback(active.getCallback());
                                if (event != null) {
                                    if (event.getOs() == 0 && !StringUtil.isNullOrEmpty(event.getUuid())) {
                                        DeviceActive deviceActive = deviceActiveService
                                                .getFirstActiveInfoByImei(event.getUuid());
                                        if (deviceActive != null) {
                                            if (event != null) {
                                                if (event.getOs() == 0)
                                                    DouYinAdUtil.activeAndroid(event.getCallback(), event.getImei(),
                                                            deviceActive.getCreateTime().getTime());
                                                else if (event.getOs() == 1)
                                                    DouYinAdUtil.activeIOS(event.getCallback(), event.getIdfa(),
                                                            deviceActive.getCreateTime().getTime());
                                            }
                                        }
                                    } else {// TODO 处理IOS
                                    }
                                }
                            } else if (active.getType() == DouYinDeviceActiveQueueDTO.TYPE_DEVICE) {// 设备
                                if (active.getPlatform() == 1) {
                Map<String, DouYinDeviceActiveQueueDTO> map = DouYinDeviceActiveCMQManager.getInstance()
                        .consume(16);
                if (map != null) {
                    // 是否是首单
                    for (Iterator<String> its = map.keySet().iterator(); its.hasNext(); ) {
                        String key = its.next();
                        DouYinDeviceActiveQueueDTO active = map.get(key);
                        if (active.getType() == DouYinDeviceActiveQueueDTO.TYPE_AD) {// 抖音
                            DouYinClickEvent event = douYinClickEventService.selectByCallback(active.getCallback());
                            if (event != null) {
                                if (event.getOs() == 0 && !StringUtil.isNullOrEmpty(event.getUuid())) {
                                    DeviceActive deviceActive = deviceActiveService
                                            .getFirstActiveInfo(active.getDevice());
                                    if (deviceActive != null && !StringUtil.isNullOrEmpty(deviceActive.getImei())) {
                                        DouYinClickEvent event = douYinClickEventService
                                                .selectByUuid(deviceActive.getImei());
                                        if (event != null) {// 回调
                                            if (deviceActive != null)
                                            .getFirstActiveInfoByImei(event.getUuid());
                                    if (deviceActive != null) {
                                        if (event != null) {
                                            if (event.getOs() == 0)
                                                DouYinAdUtil.activeAndroid(event.getCallback(), event.getImei(),
                                                        deviceActive.getCreateTime().getTime());
                                            else if (event.getOs() == 1)
                                                DouYinAdUtil.activeIOS(event.getCallback(), event.getIdfa(),
                                                        deviceActive.getCreateTime().getTime());
                                        }
                                    }
                                } else {
                                    // TODO 兼容IOS
                                } else {// TODO 处理IOS
                                }
                            }
                            DouYinDeviceActiveCMQManager.getInstance().delete(key);
                        } else if (active.getType() == DouYinDeviceActiveQueueDTO.TYPE_DEVICE) {// 设备
                            if (active.getPlatform() == 1) {
                                DeviceActive deviceActive = deviceActiveService
                                        .getFirstActiveInfo(active.getDevice());
                                if (deviceActive != null && !StringUtil.isNullOrEmpty(deviceActive.getImei())) {
                                    DouYinClickEvent event = douYinClickEventService
                                            .selectByUuid(deviceActive.getImei());
                                    if (event != null) {// 回调
                                        if (deviceActive != null)
                                            DouYinAdUtil.activeAndroid(event.getCallback(), event.getImei(),
                                                    deviceActive.getCreateTime().getTime());
                                    }
                                }
                            } else {
                                // TODO 兼容IOS
                            }
                        }
                        DouYinDeviceActiveCMQManager.getInstance().delete(key);
                    }
                }
            }
        });
    }
@@ -1193,37 +1193,37 @@
        new JobThreadExecutorServiceImpl().run(new Runnable() {
            @Override
            public void run() {
                    Map<String, UidDateDTO> map = TeamOrderCMQManager.getInstance().consumeTeamDividentsPreMsg(16);
                    if (map != null) {
                        Iterator<String> its = map.keySet().iterator();
                        while (its.hasNext()) {
                            String key = its.next();
                            UidDateDTO dto = map.get(key);
                            try {
                                teamDividentsManager.addToTeamEincome(dto.getUid(), dto.getDate());
                Map<String, UidDateDTO> map = TeamOrderCMQManager.getInstance().consumeTeamDividentsPreMsg(16);
                if (map != null) {
                    Iterator<String> its = map.keySet().iterator();
                    while (its.hasNext()) {
                        String key = its.next();
                        UidDateDTO dto = map.get(key);
                        try {
                            teamDividentsManager.addToTeamEincome(dto.getUid(), dto.getDate());
                            TeamOrderCMQManager.getInstance().deleteTeamDividentsPreMsg(key);
                        } catch (TeamDividentsRecordException e1) {
                            if (e1.getCode() == TeamDividentsRecordException.CODE_EXIST) {
                                TeamOrderCMQManager.getInstance().deleteTeamDividentsPreMsg(key);
                            } catch (TeamDividentsRecordException e1) {
                                if (e1.getCode() == TeamDividentsRecordException.CODE_EXIST) {
                                    TeamOrderCMQManager.getInstance().deleteTeamDividentsPreMsg(key);
                                } else {
                                    try {
                                        LogHelper.errorDetailInfo(e1);
                                    } catch (Exception e2) {
                                        e2.printStackTrace();
                                    }
                                }
                            } catch (Exception e) {
                            } else {
                                try {
                                    LogHelper.errorDetailInfo(e);
                                } catch (Exception e1) {
                                    e1.printStackTrace();
                                    LogHelper.errorDetailInfo(e1);
                                } catch (Exception e2) {
                                    e2.printStackTrace();
                                }
                            } finally {
                            }
                        } catch (Exception e) {
                            try {
                                LogHelper.errorDetailInfo(e);
                            } catch (Exception e1) {
                                e1.printStackTrace();
                            }
                        } finally {
                        }
                    }
                }
            }
        });
    }
@@ -1232,26 +1232,26 @@
        new JobThreadExecutorServiceImpl().run(new Runnable() {
            @Override
            public void run() {
                    Map<String, UidDateDTO> map = TeamOrderCMQManager.getInstance().consumeTeamDividentsMsg(16);
                    if (map != null) {
                        Iterator<String> its = map.keySet().iterator();
                        while (its.hasNext()) {
                            String key = its.next();
                            UidDateDTO dto = map.get(key);
                Map<String, UidDateDTO> map = TeamOrderCMQManager.getInstance().consumeTeamDividentsMsg(16);
                if (map != null) {
                    Iterator<String> its = map.keySet().iterator();
                    while (its.hasNext()) {
                        String key = its.next();
                        UidDateDTO dto = map.get(key);
                        try {
                            teamEincomeManager.addTeamDividentsTOUserAccount(dto.getDate(), dto.getUid());
                            TeamOrderCMQManager.getInstance().deleteTeamDividentsMsg(key);
                        } catch (Exception e) {
                            try {
                                teamEincomeManager.addTeamDividentsTOUserAccount(dto.getDate(), dto.getUid());
                                TeamOrderCMQManager.getInstance().deleteTeamDividentsMsg(key);
                            } catch (Exception e) {
                                try {
                                    LogHelper.errorDetailInfo(e);
                                } catch (Exception e1) {
                                    e1.printStackTrace();
                                }
                            } finally {
                                LogHelper.errorDetailInfo(e);
                            } catch (Exception e1) {
                                e1.printStackTrace();
                            }
                        } finally {
                        }
                    }
                }
            }
        });
    }
@@ -1262,27 +1262,29 @@
        new JobThreadExecutorServiceImpl().run(new Runnable() {
            @Override
            public void run() {
                    Map<String, PushContentDetailDTO> map = PushCMQManager.getInstance().consumeHWPush(16);
                    if (map != null) {
                        Iterator<String> its = map.keySet().iterator();
                        while (its.hasNext()) {
                            String key = its.next();
                            PushContentDetailDTO dto = map.get(key);
                            try {
                                hwPushService.push(dto);
                                PushCMQManager.getInstance().deleteHWPush(key);
                            } catch (Exception e) {
                                try {
                                    LogHelper.errorDetailInfo(e);
                                } catch (Exception e1) {
                                    e1.printStackTrace();
                                }
                            } finally {
                Map<String, PushContentDetailDTO> map = PushCMQManager.getInstance().consumeHWPush(16);
                if (map != null) {
                    Iterator<String> its = map.keySet().iterator();
                    while (its.hasNext()) {
                        String key = its.next();
                        PushContentDetailDTO dto = map.get(key);
                        LogHelper.pushHW("接受到消息:" + new Gson().toJson(dto));
                        try {
                            hwPushService.push(dto);
                            PushCMQManager.getInstance().deleteHWPush(key);
                        } catch (Exception e) {
                            try {
                                LogHelper.errorDetailInfo(e);
                            } catch (Exception e1) {
                                e1.printStackTrace();
                            }
                        } finally {
                        }
                    }
                }
            }
        });
    }
fanli/src/main/java/com/yeshi/fanli/util/TencentSMSUtil.java
@@ -18,7 +18,7 @@
     * @param phone
     * @param msg
     */
    public static void sendSingleMsg(String phone, String msg) throws SMSException {
    public static void sendSingleMsg( String phone, String msg) throws SMSException {
        SmsSingleSender ssender = new SmsSingleSender(Integer.parseInt(Constant.smsConfig.getSmsAppId()),
                Constant.smsConfig.getSmsAppKey());
        SmsSingleSenderResult result = null;
fanli/src/main/java/com/yeshi/fanli/util/cache/TaoBaoGoodsCacheUtil.java
@@ -4,6 +4,8 @@
import javax.annotation.Resource;
import com.yeshi.fanli.entity.taobao.SearchFilter;
import com.yeshi.fanli.entity.taobao.TaoBaoSearchResult;
import org.springframework.stereotype.Component;
import com.google.gson.Gson;
@@ -15,152 +17,183 @@
@Component
public class TaoBaoGoodsCacheUtil {
    @Resource
    private RedisManager redisManager;
    @Resource
    private RedisManager redisManager;
    /**
     * 保存常规的淘宝商品详情(搜索,详情)
     *
     * @param goods
     */
    public void saveCommonTaoBaoGoodsInfo(TaoBaoGoodsBrief goods) {
        if (goods == null || goods.getAuctionId() == null)
            return;
        String key = RedisKeyEnum.getRedisKey(RedisKeyEnum.taobaoGoodsCommon, goods.getAuctionId() + "");
        // 保存20分钟
        redisManager.cacheCommonString(key, new Gson().toJson(goods), 60 * 20);
    }
    /**
     * 保存常规的淘宝商品详情(搜索,详情)
     *
     * @param goods
     */
    public void saveCommonTaoBaoGoodsInfo(TaoBaoGoodsBrief goods) {
        if (goods == null || goods.getAuctionId() == null)
            return;
        String key = RedisKeyEnum.getRedisKey(RedisKeyEnum.taobaoGoodsCommon, goods.getAuctionId() + "");
        // 保存20分钟
        redisManager.cacheCommonString(key, new Gson().toJson(goods), 60 * 20);
    }
    /**
     * 获取缓存
     *
     * @param auctionId
     * @return
     */
    public TaoBaoGoodsBrief getCommonTaoBaoGoodsInfo(long auctionId) {
        String key = RedisKeyEnum.getRedisKey(RedisKeyEnum.taobaoGoodsCommon, auctionId + "");
        String value = redisManager.getCommonString(key);
        if (!StringUtil.isNullOrEmpty(value)) {
            return new Gson().fromJson(value, TaoBaoGoodsBrief.class);
        } else
            return null;
    }
    /**
     * 获取缓存
     *
     * @param auctionId
     * @return
     */
    public TaoBaoGoodsBrief getCommonTaoBaoGoodsInfo(long auctionId) {
        String key = RedisKeyEnum.getRedisKey(RedisKeyEnum.taobaoGoodsCommon, auctionId + "");
        String value = redisManager.getCommonString(key);
        if (!StringUtil.isNullOrEmpty(value)) {
            return new Gson().fromJson(value, TaoBaoGoodsBrief.class);
        } else
            return null;
    }
    /**
     * 是否可以添加到更新队列中
     *
     * @param auctionId
     * @return
     */
    public boolean canAddToUpdateQueue(Long auctionId) {
        String key = RedisKeyEnum.getRedisKey(RedisKeyEnum.taobaoQueue, auctionId + "");
        String value = redisManager.getCommonString(key);
        if (StringUtil.isNullOrEmpty(value))
            return true;
        else
            return false;
    }
    /**
     * 是否可以添加到更新队列中
     *
     * @param auctionId
     * @return
     */
    public boolean canAddToUpdateQueue(Long auctionId) {
        String key = RedisKeyEnum.getRedisKey(RedisKeyEnum.taobaoQueue, auctionId + "");
        String value = redisManager.getCommonString(key);
        if (StringUtil.isNullOrEmpty(value))
            return true;
        else
            return false;
    }
    /**
     * 增加添加到队列中的记录
     *
     * @param auctionId
     */
    public void addAddToQueueHistory(Long auctionId) {
        String key = RedisKeyEnum.getRedisKey(RedisKeyEnum.taobaoQueue, auctionId + "");
        redisManager.cacheCommonString(key, "1", 60 * 60 * 2);// 有效期2个小时
    }
    /**
     * 增加添加到队列中的记录
     *
     * @param auctionId
     */
    public void addAddToQueueHistory(Long auctionId) {
        String key = RedisKeyEnum.getRedisKey(RedisKeyEnum.taobaoQueue, auctionId + "");
        redisManager.cacheCommonString(key, "1", 60 * 60 * 2);// 有效期2个小时
    }
    /**
     * 查询商品是否需要更新
     *
     * @param actionId
     * @return
     */
    public boolean needUpdate(Long actionId) {
        String key = RedisKeyEnum.getRedisKey(RedisKeyEnum.taobaoUpdate, actionId + "");
        String value = redisManager.getCommonString(key);
        if (StringUtil.isNullOrEmpty(value))
            return true;
        else
            return false;
    }
    /**
     * 查询商品是否需要更新
     *
     * @param actionId
     * @return
     */
    public boolean needUpdate(Long actionId) {
        String key = RedisKeyEnum.getRedisKey(RedisKeyEnum.taobaoUpdate, actionId + "");
        String value = redisManager.getCommonString(key);
        if (StringUtil.isNullOrEmpty(value))
            return true;
        else
            return false;
    }
    /**
     * 添加更新记录数据
     *
     * @param actionId
     * @return
     */
    public void addUpdateHistory(Long actionId) {
        String key = RedisKeyEnum.getRedisKey(RedisKeyEnum.taobaoUpdate, actionId + "");
        redisManager.cacheCommonString(key, "1", 60 * 60 * 1);// 有效期1个小时
    }
    /**
     * 添加更新记录数据
     *
     * @param actionId
     * @return
     */
    public void addUpdateHistory(Long actionId) {
        String key = RedisKeyEnum.getRedisKey(RedisKeyEnum.taobaoUpdate, actionId + "");
        redisManager.cacheCommonString(key, "1", 60 * 60 * 1);// 有效期1个小时
    }
    /**
     * 删除更新记录
     */
    public void removeUpdateHistory() {
        // TODO 凌晨删除缓存记录
    }
    /**
     * 删除更新记录
     */
    public void removeUpdateHistory() {
        // TODO 凌晨删除缓存记录
    }
    /**
     * 保存口令对应的商品ID
     *
     * @param token
     * @param auctionId
     */
    public void saveTokenGoodsIdMap(String token, Long auctionId) {
        String key = RedisKeyEnum.getRedisKey(RedisKeyEnum.taobaoTokenGoodsMap, StringUtil.Md5(token));
        redisManager.cacheCommonString(key, auctionId + "", 60 * 30);// 有效期30分钟
    }
    /**
     * 保存口令对应的商品ID
     *
     * @param token
     * @param auctionId
     */
    public void saveTokenGoodsIdMap(String token, Long auctionId) {
        String key = RedisKeyEnum.getRedisKey(RedisKeyEnum.taobaoTokenGoodsMap, StringUtil.Md5(token));
        redisManager.cacheCommonString(key, auctionId + "", 60 * 30);// 有效期30分钟
    }
    /**
     * 通过口令获取商品ID
     *
     * @param token
     * @return
     */
    public Long getGoodsIdByToken(String token) {
        String key = RedisKeyEnum.getRedisKey(RedisKeyEnum.taobaoTokenGoodsMap, StringUtil.Md5(token));
        String goodsId = redisManager.getCommonString(key);
        if (StringUtil.isNullOrEmpty(goodsId))
            return null;
        return Long.parseLong(goodsId);
    }
    /**
     * 通过口令获取商品ID
     *
     * @param token
     * @return
     */
    public Long getGoodsIdByToken(String token) {
        String key = RedisKeyEnum.getRedisKey(RedisKeyEnum.taobaoTokenGoodsMap, StringUtil.Md5(token));
        String goodsId = redisManager.getCommonString(key);
        if (StringUtil.isNullOrEmpty(goodsId))
            return null;
        return Long.parseLong(goodsId);
    }
    /**
     * 缓存转链结果
     * @Title: cacheBaseConvertLink
     * @Description:
     * @param auctionId
     * @param pid
     * @param link
     * void 返回类型
     * @throws
     */
    public void cacheBaseConvertLink(Long auctionId, String pid, String link) {
        String key = RedisKeyEnum.getRedisKey(RedisKeyEnum.taobaoBaseLink, StringUtil.Md5(auctionId + "#" + pid));
        //
        Calendar calendar = Calendar.getInstance();
        long now = calendar.getTimeInMillis();
        calendar.add(Calendar.HOUR, 1);
    /**
     * 缓存转链结果
     *
     * @param auctionId
     * @param pid
     * @param link      void 返回类型
     * @throws
     * @Title: cacheBaseConvertLink
     * @Description:
     */
    public void cacheBaseConvertLink(Long auctionId, String pid, String link) {
        String key = RedisKeyEnum.getRedisKey(RedisKeyEnum.taobaoBaseLink, StringUtil.Md5(auctionId + "#" + pid));
        //
        Calendar calendar = Calendar.getInstance();
        long now = calendar.getTimeInMillis();
        calendar.add(Calendar.HOUR, 1);
        Long time = TimeUtil.convertToTimeTemp(TimeUtil.getGernalTime(calendar.getTimeInMillis(), "yyyy-MM-dd HH"),
                "yyyy-MM-dd HH");
        Long time = TimeUtil.convertToTimeTemp(TimeUtil.getGernalTime(calendar.getTimeInMillis(), "yyyy-MM-dd HH"),
                "yyyy-MM-dd HH");
        int second = (int) ((time - now) / 1000);
        if (second <= 0)
            second = 1;
        int second = (int) ((time - now) / 1000);
        if (second <= 0)
            second = 1;
        redisManager.cacheCommonString(key, link, second);// 有效期30分钟
    }
        redisManager.cacheCommonString(key, link, second);// 有效期30分钟
    }
    public String getBaseConvertLink(Long auctionId, String pid) {
        String key = RedisKeyEnum.getRedisKey(RedisKeyEnum.taobaoBaseLink, StringUtil.Md5(auctionId + "#" + pid));
        String url = redisManager.getCommonString(key);
    public String getBaseConvertLink(Long auctionId, String pid) {
        String key = RedisKeyEnum.getRedisKey(RedisKeyEnum.taobaoBaseLink, StringUtil.Md5(auctionId + "#" + pid));
        String url = redisManager.getCommonString(key);
        return StringUtil.isNullOrEmpty(url) ? null : url;
    }
        return StringUtil.isNullOrEmpty(url) ? null : url;
    }
    /**
     * 保存搜索接口
     *
     * @param sf
     * @param result
     */
    public void saveSearchResult(SearchFilter sf, TaoBaoSearchResult result) {
        if (result == null||result.getTaoBaoGoodsBriefs()==null)
            return;
        String key = RedisKeyEnum.taobaoSearchResult.getKey() + StringUtil.Md5(new Gson().toJson(sf));
        //缓存20分钟
        redisManager.cacheCommonString(key, new Gson().toJson(result), 60 * 20);
    }
    /**
     * 获取搜索结果
     *
     * @param sf
     * @return
     */
    public TaoBaoSearchResult getSearchResult(SearchFilter sf) {
        String key = RedisKeyEnum.taobaoSearchResult.getKey() + StringUtil.Md5(new Gson().toJson(sf));
        String result = redisManager.getCommonString(key);
        if (StringUtil.isNullOrEmpty(result))
            return null;
        else
            return new Gson().fromJson(result, TaoBaoSearchResult.class);
    }
}
fanli/src/main/java/com/yeshi/fanli/util/pinduoduo/PinDuoDuoApiUtil.java
@@ -32,492 +32,519 @@
import net.sf.json.JSONObject;
public class PinDuoDuoApiUtil {
    public final static String PID_FANLI = "8590899_72067894";
    public final static String PID_SHARE = "8590899_72067895";
    public final static String PID_COUPON = "8590899_102657575";
    public final static String PID_FANLI = "8590899_72067894";
    public final static String PID_SHARE = "8590899_72067895";
    public final static String PID_COUPON = "8590899_102657575";
    private final static String CLIENT_ID = "9f6ee5ebd3b94c2080c4d51c2427e9fa";
    private final static String CLIENT_SECRET = "95e1f1904385664bf4b87d4b34de12f9f31c505d";
    private final static String CLIENT_ID = "9f6ee5ebd3b94c2080c4d51c2427e9fa";
    private final static String CLIENT_SECRET = "95e1f1904385664bf4b87d4b34de12f9f31c505d";
    private static String getSign(Map<String, String> map) {
        List<String> keyList = new ArrayList<>();
        Iterator<String> keys = map.keySet().iterator();
        while (keys.hasNext()) {
            String key = keys.next();
            keyList.add(key);
        }
        Collections.sort(keyList);
        String org = "";
        for (String key : keyList) {
            org += key + map.get(key);
        }
        return StringUtil.Md5(CLIENT_SECRET + org + CLIENT_SECRET).toUpperCase();
    }
    private static String getSign(Map<String, String> map) {
        List<String> keyList = new ArrayList<>();
        Iterator<String> keys = map.keySet().iterator();
        while (keys.hasNext()) {
            String key = keys.next();
            keyList.add(key);
        }
        Collections.sort(keyList);
        String org = "";
        for (String key : keyList) {
            org += key + map.get(key);
        }
        return StringUtil.Md5(CLIENT_SECRET + org + CLIENT_SECRET).toUpperCase();
    }
    private static String baseRequest(Map<String, String> map) {
        map.put("client_id", CLIENT_ID);
        map.put("timestamp", System.currentTimeMillis() / 1000 + "");
        map.put("sign", getSign(map));
        Iterator<String> keys = map.keySet().iterator();
        String url = "https://gw-api.pinduoduo.com/api/router?";
        while (keys.hasNext()) {
            String key = keys.next();
            try {
                url += key + "=" + URLEncoder.encode(map.get(key), "UTF-8") + "&";
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        if (url.endsWith("&"))
            url = url.substring(0, url.length() - 1);
        return HttpUtil.postSimple(url);
    }
    private static String baseRequest(Map<String, String> map) {
        map.put("client_id", CLIENT_ID);
        map.put("timestamp", System.currentTimeMillis() / 1000 + "");
        map.put("sign", getSign(map));
        Iterator<String> keys = map.keySet().iterator();
        String url = "https://gw-api.pinduoduo.com/api/router?";
        while (keys.hasNext()) {
            String key = keys.next();
            try {
                url += key + "=" + URLEncoder.encode(map.get(key), "UTF-8") + "&";
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        if (url.endsWith("&"))
            url = url.substring(0, url.length() - 1);
        return HttpUtil.postSimple(url);
    }
    /**
     * 多多进宝商品查询
     *
     * @param sf
     * @return
     */
    public static PDDGoodsResult searchGoods(PDDSearchFilter sf) {
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        Map<String, String> map = new HashMap<>();
        map.put("type", "pdd.ddk.goods.search");
        if (sf.getOptId() != null)
            map.put("opt_id", sf.getOptId() + "");
        if (sf.getPage() != null)
            map.put("page", sf.getPage() + "");
        if (sf.getPageSize() != null)
            map.put("page_size", sf.getPageSize() + "");
        if (sf.getSortType() != null)
            map.put("sort_type", sf.getSortType() + "");
        if (sf.getHasCoupon() != null)
            map.put("with_coupon", sf.getHasCoupon() + "");
        if (sf.getIsBrand() != null)
            map.put("is_brand_goods", sf.getIsBrand() + "");
        if (sf.getCatId() != null)
            map.put("cat_id", sf.getCatId() + "");
        if (sf.getKw() != null)
            map.put("keyword", sf.getKw());
        if (sf.getGoodsIdList() != null)
            map.put("goods_id_list", "[" + StringUtil.concat(sf.getGoodsIdList(), ",") + "]");
        if (sf.getMerchantType() != null)
            map.put("merchant_type", sf.getMerchantType() + "");
        if (sf.getRangeList() != null && sf.getRangeList().size() > 0) {
            map.put("range_list",gson.toJson(sf.getRangeList()).toString());
        }
        map.put("pid", PID_FANLI);
        String result = baseRequest(map);
        JSONObject json = JSONObject.fromObject(result);
        JSONObject root = json.optJSONObject("goods_search_response");
        if (root == null) {
            return null;
        }
    /**
     * 多多进宝商品查询
     *
     * @param sf
     * @return
     */
    public static PDDGoodsResult searchGoods(PDDSearchFilter sf) {
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        Map<String, String> map = new HashMap<>();
        map.put("type", "pdd.ddk.goods.search");
        if (sf.getOptId() != null)
            map.put("opt_id", sf.getOptId() + "");
        if (sf.getPage() != null)
            map.put("page", sf.getPage() + "");
        if (sf.getPageSize() != null)
            map.put("page_size", sf.getPageSize() + "");
        if (sf.getSortType() != null)
            map.put("sort_type", sf.getSortType() + "");
        if (sf.getHasCoupon() != null)
            map.put("with_coupon", sf.getHasCoupon() + "");
        if (sf.getIsBrand() != null)
            map.put("is_brand_goods", sf.getIsBrand() + "");
        if (sf.getCatId() != null)
            map.put("cat_id", sf.getCatId() + "");
        if (sf.getKw() != null)
            map.put("keyword", sf.getKw());
        if (sf.getGoodsIdList() != null)
            map.put("goods_id_list", "[" + StringUtil.concat(sf.getGoodsIdList(), ",") + "]");
        if (sf.getMerchantType() != null)
            map.put("merchant_type", sf.getMerchantType() + "");
        JSONArray array = root.optJSONArray("goods_list");
        if (array == null) {
            return null;
        }
        if (sf.getRangeList() != null && sf.getRangeList().size() > 0) {
            map.put("range_list", gson.toJson(sf.getRangeList()).toString());
        }
        Type type = new TypeToken<List<PDDGoodsDetail>>() {
        }.getType();
        map.put("pid", PID_FANLI);
        String result = baseRequest(map);
        JSONObject json = JSONObject.fromObject(result);
        JSONObject root = json.optJSONObject("goods_search_response");
        if (root == null) {
            return null;
        }
        List<PDDGoodsDetail> goodsList = gson.fromJson(array.toString(), type);
        int totalCount = root.optInt("total_count");
        return new PDDGoodsResult(totalCount, goodsList);
    }
        JSONArray array = root.optJSONArray("goods_list");
        if (array == null) {
            return null;
        }
    public static List<PDDGoodsDetail> listGoodsDetail(List<Long> goodsIds) {
        PDDSearchFilter filter = new PDDSearchFilter();
        Long[] ids = new Long[goodsIds.size()];
        goodsIds.toArray(ids);
        filter.setGoodsIdList(ids);
        PDDGoodsResult result = searchGoods(filter);
        if (result != null)
            return result.getGoodsList();
        return null;
    }
        Type type = new TypeToken<List<PDDGoodsDetail>>() {
        }.getType();
    /**
     * 运营频道商品查询API
     *
     * @param page
     * @param pageSize
     * @param channelType
     *            频道类型;0, "1.9包邮", 1, "今日爆款", 2, "品牌清仓", 非必填 ,默认是1
     * @return
     */
    public static PDDGoodsResult searchByChannelType(Integer page, Integer pageSize, String channelType) {
        Map<String, String> map = new HashMap<>();
        map.put("type", "pdd.ddk.goods.recommend.get");
        map.put("offset", (page == null ? 0 : page) + "");
        map.put("offset", (pageSize == null ? Constant.PAGE_SIZE : pageSize) + "");
        List<PDDGoodsDetail> goodsList = gson.fromJson(array.toString(), type);
        int totalCount = root.optInt("total_count");
        return new PDDGoodsResult(totalCount, goodsList);
    }
        if (channelType != null)
            map.put("channel_type", channelType);
    public static List<PDDGoodsDetail> listGoodsDetail(List<Long> goodsIds) {
        PDDSearchFilter filter = new PDDSearchFilter();
        Long[] ids = new Long[goodsIds.size()];
        goodsIds.toArray(ids);
        filter.setGoodsIdList(ids);
        PDDGoodsResult result = searchGoods(filter);
        if (result != null)
            return result.getGoodsList();
        return null;
    }
        map.put("pid", PID_FANLI);
        String result = baseRequest(map);
    /**
     * 运营频道商品查询API
     *
     * @param page
     * @param pageSize
     * @param channelType 频道类型;0, "1.9包邮", 1, "今日爆款", 2, "品牌清仓", 非必填 ,默认是1
     * @return
     */
    public static PDDGoodsResult searchByChannelType(Integer page, Integer pageSize, String channelType) {
        Map<String, String> map = new HashMap<>();
        map.put("type", "pdd.ddk.goods.recommend.get");
        map.put("offset", (page == null ? 0 : page) + "");
        map.put("offset", (pageSize == null ? Constant.PAGE_SIZE : pageSize) + "");
        JSONObject json = JSONObject.fromObject(result);
        JSONObject root = json.optJSONObject("goods_basic_detail_response");
        if (root == null) {
            return null;
        }
        JSONArray array = root.optJSONArray("list");
        if (array == null) {
            return null;
        }
        if (channelType != null)
            map.put("channel_type", channelType);
        Type type = new TypeToken<List<PDDGoodsDetail>>() {
        }.getType();
        map.put("pid", PID_FANLI);
        String result = baseRequest(map);
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        List<PDDGoodsDetail> goodsList = gson.fromJson(array.toString(), type);
        int totalCount = root.optInt("total");
        return new PDDGoodsResult(totalCount, goodsList);
    }
        JSONObject json = JSONObject.fromObject(result);
        JSONObject root = json.optJSONObject("goods_basic_detail_response");
        if (root == null) {
            return null;
        }
        JSONArray array = root.optJSONArray("list");
        if (array == null) {
            return null;
        }
    public static void getGoodsClass() {
        Map<String, String> map = new HashMap<>();
        map.put("type", "pdd.goods.cats.get");
        map.put("parent_cat_id", "0");
        String result = baseRequest(map);
        Type type = new TypeToken<List<PDDGoodsDetail>>() {
        }.getType();
        JSONObject json = JSONObject.fromObject(result);
        JSONObject root = json.optJSONObject("goods_cats_get_response");
        JSONArray array = root.optJSONArray("goods_cats_list");
    }
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        List<PDDGoodsDetail> goodsList = gson.fromJson(array.toString(), type);
        int totalCount = root.optInt("total");
        return new PDDGoodsResult(totalCount, goodsList);
    }
    public static void getThemes(Integer page, Integer pageSize) {
        Map<String, String> map = new HashMap<>();
        map.put("type", "pdd.ddk.theme.list.get");
        map.put("page", page + "");
        map.put("page_size", pageSize + "");
        String result = baseRequest(map);
    public static void getGoodsClass() {
        Map<String, String> map = new HashMap<>();
        map.put("type", "pdd.goods.cats.get");
        map.put("parent_cat_id", "0");
        String result = baseRequest(map);
        JSONObject json = JSONObject.fromObject(result);
        JSONObject root = json.optJSONObject("theme_list_get_response");
        JSONArray array = root.optJSONArray("theme_list");
        for (int i = 0; i < array.size(); i++) {
            System.out.println(array.optJSONObject(i).optString("id"));
            System.out.println(array.optJSONObject(i).optString("name"));
            System.out.println(array.optJSONObject(i).optString("image_url"));
            System.out.println(array.optJSONObject(i).optString("goods_num"));
            System.out.println("-------------------------------------------");
        }
        JSONObject json = JSONObject.fromObject(result);
        JSONObject root = json.optJSONObject("goods_cats_get_response");
        JSONArray array = root.optJSONArray("goods_cats_list");
    }
        System.out.println(root.optLong("total"));
    }
    public static void getThemes(Integer page, Integer pageSize) {
        Map<String, String> map = new HashMap<>();
        map.put("type", "pdd.ddk.theme.list.get");
        map.put("page", page + "");
        map.put("page_size", pageSize + "");
        String result = baseRequest(map);
    public static void getGoodsOpt() {
        Map<String, String> map = new HashMap<>();
        map.put("type", "pdd.goods.opt.get");
        map.put("parent_opt_id", "0");
        String result = baseRequest(map);
        JSONObject json = JSONObject.fromObject(result);
        JSONObject root = json.optJSONObject("theme_list_get_response");
        JSONArray array = root.optJSONArray("theme_list");
        for (int i = 0; i < array.size(); i++) {
            System.out.println(array.optJSONObject(i).optString("id"));
            System.out.println(array.optJSONObject(i).optString("name"));
            System.out.println(array.optJSONObject(i).optString("image_url"));
            System.out.println(array.optJSONObject(i).optString("goods_num"));
            System.out.println("-------------------------------------------");
        }
        JSONObject json = JSONObject.fromObject(result);
        JSONObject root = json.optJSONObject("goods_opt_get_response");
        JSONArray array = root.optJSONArray("goods_opt_list");
    }
        System.out.println(root.optLong("total"));
    }
    /**
     * 多多客获取爆款排行商品接口
     *
     * @param pid
     *            推广位id (非必填)
     * @param page
     *            从多少位置开始请求;默认值 : 0 (非必填)
     * @param pageSize
     *            请求数量;默认值 :20 (非必填)
     * @param sortType
     *            1-实时热销榜;2-实时收益榜 (非必填)
     * @return
     */
    public static PDDGoodsResult getTopList(String pid, Integer page, Integer pageSize, Integer sortType) {
        Map<String, String> map = new HashMap<>();
        map.put("type", "pdd.ddk.top.goods.list.query");
        map.put("offset", (page == null ? 0 : (page - 1) * Constant.PAGE_SIZE) + "");
        map.put("limit", (pageSize == null ? Constant.PAGE_SIZE : pageSize) + "");
    public static void getGoodsOpt() {
        Map<String, String> map = new HashMap<>();
        map.put("type", "pdd.goods.opt.get");
        map.put("parent_opt_id", "0");
        String result = baseRequest(map);
        if (!StringUtil.isNullOrEmpty(pid))
            map.put("p_id", pid + "");
        JSONObject json = JSONObject.fromObject(result);
        JSONObject root = json.optJSONObject("goods_opt_get_response");
        JSONArray array = root.optJSONArray("goods_opt_list");
    }
        if (sortType != null)
            map.put("sort_type", sortType + "");
    /**
     * 多多客获取爆款排行商品接口
     *
     * @param pid      推广位id (非必填)
     * @param page     从多少位置开始请求;默认值 : 0 (非必填)
     * @param pageSize 请求数量;默认值 :20 (非必填)
     * @param sortType 1-实时热销榜;2-实时收益榜 (非必填)
     * @return
     */
    public static PDDGoodsResult getTopList(String pid, Integer page, Integer pageSize, Integer sortType) {
        Map<String, String> map = new HashMap<>();
        map.put("type", "pdd.ddk.top.goods.list.query");
        map.put("offset", (page == null ? 0 : (page - 1) * Constant.PAGE_SIZE) + "");
        map.put("limit", (pageSize == null ? Constant.PAGE_SIZE : pageSize) + "");
        String result = baseRequest(map);
        JSONObject json = JSONObject.fromObject(result);
        JSONObject root = json.optJSONObject("top_goods_list_get_response");
        if (root == null) {
            return null;
        }
        JSONArray array = root.optJSONArray("list");
        if (array == null) {
            return null;
        }
        if (!StringUtil.isNullOrEmpty(pid))
            map.put("p_id", pid + "");
        Type type = new TypeToken<List<PDDGoodsDetail>>() {
        }.getType();
        if (sortType != null)
            map.put("sort_type", sortType + "");
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        List<PDDGoodsDetail> goodsList = gson.fromJson(array.toString(), type);
        // int totalCount = root.optInt("total");
        int totalCount = 400; // 默认设置成400
        return new PDDGoodsResult(totalCount, goodsList);
    }
        String result = baseRequest(map);
        JSONObject json = JSONObject.fromObject(result);
        JSONObject root = json.optJSONObject("top_goods_list_get_response");
        if (root == null) {
            return null;
        }
        JSONArray array = root.optJSONArray("list");
        if (array == null) {
            return null;
        }
    /**
     * 商品转链
     *
     * @param goodsId
     * @param pid
     * @param customParams
     * @return
     */
    public static PDDPromotionUrl convert(Long goodsId, String pid, String customParams) {
        Map<String, String> map = new HashMap<>();
        map.put("type", "pdd.ddk.goods.promotion.url.generate");
        map.put("p_id", pid);
        map.put("multi_group", "true");
        map.put("generate_weapp_webview", "true");
        Type type = new TypeToken<List<PDDGoodsDetail>>() {
        }.getType();
        // map.put("generate_weiboapp_webview", "true");
        JSONArray array = new JSONArray();
        array.add(goodsId);
        map.put("goods_id_list", array.toString());
        if (!StringUtil.isNullOrEmpty(customParams)) {
            map.put("custom_parameters", customParams);
        }
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        List<PDDGoodsDetail> goodsList = gson.fromJson(array.toString(), type);
        // int totalCount = root.optInt("total");
        int totalCount = 400; // 默认设置成400
        return new PDDGoodsResult(totalCount, goodsList);
    }
        String result = baseRequest(map);
        JSONObject root = JSONObject.fromObject(result);
        JSONObject json = root.optJSONObject("goods_promotion_url_generate_response");
        if (json == null) {
            return null;
        }
        JSONArray resultArray = json.optJSONArray("goods_promotion_url_list");
        if (resultArray != null && resultArray.size() > 0) {
            Type type = new TypeToken<PDDPromotionUrl>() {
            }.getType();
            Gson gson = new GsonBuilder().disableHtmlEscaping().create();
            return gson.fromJson(resultArray.optJSONObject(0).toString(), type);
        }
        return null;
    }
    /**
     * 商品转链
     *
     * @param goodsId
     * @param pid
     * @param customParams
     * @return
     */
    public static PDDPromotionUrl convert(Long goodsId, String pid, String customParams, boolean withAuthLink) {
        Map<String, String> map = new HashMap<>();
        map.put("type", "pdd.ddk.goods.promotion.url.generate");
        map.put("p_id", pid);
        map.put("multi_group", "true");
        map.put("generate_weapp_webview", "true");
    /**
     * 微信小程序转链 @Title: convertWXMP @Description: @param goodsId @param
     * pid @param customParams @return PDDPromotionUrl 返回类型 @throws
     */
    public static String convertWXMP(Long goodsId, String pid, String customParams) {
        Map<String, String> map = new HashMap<>();
        map.put("type", "pdd.ddk.goods.promotion.url.generate");
        map.put("p_id", pid);
        map.put("multi_group", "true");
        map.put("generate_we_app", "true");
        // map.put("generate_weiboapp_webview", "true");
        JSONArray array = new JSONArray();
        array.add(goodsId);
        map.put("goods_id_list", array.toString());
        if (!StringUtil.isNullOrEmpty(customParams)) {
            map.put("custom_parameters", customParams);
        }
        JSONArray array = new JSONArray();
        array.add(goodsId);
        map.put("goods_id_list", array.toString());
        if (!StringUtil.isNullOrEmpty(customParams)) {
            map.put("custom_parameters", customParams);
        }
        //是否生成带授权的单品链接
        if (withAuthLink)
            map.put("generate_authority_url", true + "");
        String result = baseRequest(map);
        JSONObject root = JSONObject.fromObject(result);
        JSONObject json = root.optJSONObject("goods_promotion_url_generate_response");
        if (json == null) {
            return null;
        }
        JSONArray resultArray = json.optJSONArray("goods_promotion_url_list");
        if (resultArray != null && resultArray.size() > 0) {
            JSONObject weApp = resultArray.optJSONObject(0).optJSONObject("we_app_info");
            if (weApp != null)
                return weApp.optString("page_path");
        }
        return null;
    }
        String result = baseRequest(map);
        JSONObject root = JSONObject.fromObject(result);
        JSONObject json = root.optJSONObject("goods_promotion_url_generate_response");
        if (json == null) {
            return null;
        }
        JSONArray resultArray = json.optJSONArray("goods_promotion_url_list");
        if (resultArray != null && resultArray.size() > 0) {
            Type type = new TypeToken<PDDPromotionUrl>() {
            }.getType();
            Gson gson = new GsonBuilder().disableHtmlEscaping().create();
            return gson.fromJson(resultArray.optJSONObject(0).toString(), type);
        }
        return null;
    }
    /**
     * 商品转链
     *
     * @param goodsId
     * @param pid
     * @param customParams
     * @return
     */
    public static String getPromotionUrl(Long goodsId, String pid, String customParams) {
        PDDPromotionUrl promotion = convert(goodsId, pid, customParams);
        if (promotion != null) {
            return promotion.getShortUrl();
        }
        return null;
    }
    /**
     * 微信小程序转链 @Title: convertWXMP @Description: @param goodsId @param
     * pid @param customParams @return PDDPromotionUrl 返回类型 @throws
     */
    public static String convertWXMP(Long goodsId, String pid, String customParams) {
        Map<String, String> map = new HashMap<>();
        map.put("type", "pdd.ddk.goods.promotion.url.generate");
        map.put("p_id", pid);
        map.put("multi_group", "true");
        map.put("generate_we_app", "true");
    public static void createPid() {
        Map<String, String> map = new HashMap<>();
        map.put("type", "pdd.ddk.goods.pid.generate");
        map.put("number", "2");
        JSONArray array = new JSONArray();
        array.add("返利PID");
        array.add("分享PID");
        map.put("p_id_name_list", array.toString());
        JSONArray array = new JSONArray();
        array.add(goodsId);
        map.put("goods_id_list", array.toString());
        if (!StringUtil.isNullOrEmpty(customParams)) {
            map.put("custom_parameters", customParams);
        }
        String result = baseRequest(map);
        System.out.println(result);
    }
        String result = baseRequest(map);
        JSONObject root = JSONObject.fromObject(result);
        JSONObject json = root.optJSONObject("goods_promotion_url_generate_response");
        if (json == null) {
            return null;
        }
        JSONArray resultArray = json.optJSONArray("goods_promotion_url_list");
        if (resultArray != null && resultArray.size() > 0) {
            JSONObject weApp = resultArray.optJSONObject(0).optJSONObject("we_app_info");
            if (weApp != null)
                return weApp.optString("page_path");
        }
        return null;
    }
    /**
     * 获取订单
     *
     * @param page
     *            -页码
     * @param pageSize-每页数量
     * @param startTime-开始时间
     * @param endTime-结束时间
     *            与开始时间不得大于24小时
     * @return
     */
    public static PDDOrderResult getOrdersList(int page, int pageSize, long startTime, long endTime) {
        Map<String, String> map = new HashMap<>();
        map.put("type", "pdd.ddk.order.list.increment.get");
        map.put("start_update_time", startTime / 1000 + "");
        map.put("end_update_time", endTime / 1000 + "");
        map.put("page", page + "");
        map.put("page_size", pageSize + "");
        String result = baseRequest(map);
        System.out.println(result);
        JSONObject json = JSONObject.fromObject(result);
        JSONObject root = json.optJSONObject("order_list_get_response");
        if (root != null) {
            int totalCount = root.optInt("total_count");
            JSONArray array = root.optJSONArray("order_list");
            Type type = new TypeToken<List<PDDOrder>>() {
            }.getType();
            List<PDDOrder> orderList = new Gson().fromJson(array.toString(), type);
            return new PDDOrderResult(totalCount, orderList);
        }
        return null;
    }
    /**
     * 商品转链
     *
     * @param goodsId
     * @param pid
     * @param customParams
     * @return
     */
    public static String getPromotionUrl(Long goodsId, String pid, String customParams) {
        PDDPromotionUrl promotion = convert(goodsId, pid, customParams,false);
        if (promotion != null) {
            return promotion.getShortUrl();
        }
        return null;
    }
    public static PDDOrder getOrderDetail(String orderSn) {
        Map<String, String> map = new HashMap<>();
        map.put("type", "pdd.ddk.order.detail.get");
        map.put("order_sn", orderSn);
        String result = baseRequest(map);
        System.out.println(result);
        JSONObject json = JSONObject.fromObject(result);
        JSONObject root = json.optJSONObject("order_detail_response");
        if (root != null) {
            return new Gson().fromJson(root.toString(), PDDOrder.class);
        }
        return null;
    }
    public static void createPid() {
        Map<String, String> map = new HashMap<>();
        map.put("type", "pdd.ddk.goods.pid.generate");
        map.put("number", "2");
        JSONArray array = new JSONArray();
        array.add("返利PID");
        array.add("分享PID");
        map.put("p_id_name_list", array.toString());
    /**
     * 获取商品详情
     *
     * @param goodsId
     */
    public static PDDGoodsDetail getGoodsDetail(Long goodsId) {
        JSONArray array = new JSONArray();
        array.add(goodsId);
        Map<String, String> map = new HashMap<>();
        map.put("type", "pdd.ddk.goods.detail");
        map.put("goods_id_list", array.toString());
        String result = baseRequest(map);
        JSONObject resultJson = JSONObject.fromObject(result);
        JSONObject root = resultJson.optJSONObject("goods_detail_response");
        if (root == null) {
            return null;
        }
        String result = baseRequest(map);
        System.out.println(result);
    }
        JSONArray resultArray = root.optJSONArray("goods_details");
        if (resultArray == null) {
            return null;
        }
    /**
     * 获取订单
     *
     * @param page           -页码
     * @param pageSize-每页数量
     * @param startTime-开始时间
     * @param endTime-结束时间   与开始时间不得大于24小时
     * @return
     */
    public static PDDOrderResult getOrdersList(int page, int pageSize, long startTime, long endTime) {
        Map<String, String> map = new HashMap<>();
        map.put("type", "pdd.ddk.order.list.increment.get");
        map.put("start_update_time", startTime / 1000 + "");
        map.put("end_update_time", endTime / 1000 + "");
        map.put("page", page + "");
        map.put("page_size", pageSize + "");
        String result = baseRequest(map);
        JSONObject json = JSONObject.fromObject(result);
        JSONObject root = json.optJSONObject("order_list_get_response");
        if (root != null) {
            int totalCount = root.optInt("total_count");
            JSONArray array = root.optJSONArray("order_list");
            Type type = new TypeToken<List<PDDOrder>>() {
            }.getType();
            List<PDDOrder> orderList = new Gson().fromJson(array.toString(), type);
            return new PDDOrderResult(totalCount, orderList);
        }
        return null;
    }
        Type type = new TypeToken<List<PDDGoodsDetail>>() {
        }.getType();
        List<PDDGoodsDetail> goodsList = new Gson().fromJson(resultArray.toString(), type);
        if (goodsList != null && goodsList.size() > 0)
            return goodsList.get(0);
        return null;
    }
    public static PDDOrder getOrderDetail(String orderSn) {
        Map<String, String> map = new HashMap<>();
        map.put("type", "pdd.ddk.order.detail.get");
        map.put("order_sn", orderSn);
        String result = baseRequest(map);
        JSONObject json = JSONObject.fromObject(result);
        JSONObject root = json.optJSONObject("order_detail_response");
        if (root != null) {
            return new Gson().fromJson(root.toString(), PDDOrder.class);
        }
        return null;
    }
    /**
     * 获取商品详情
     *
     * @param goodsId
     */
    public static String createGenerate(Long goodsId) {
        JSONArray array = new JSONArray();
        array.add(goodsId);
        Map<String, String> map = new HashMap<>();
        map.put("type", "pdd.ddk.phrase.generate");
        map.put("goods_id_list", array.toString());
        map.put("p_id", PID_FANLI);
        String result = baseRequest(map);
        JSONObject resultJson = JSONObject.fromObject(result);
        System.out.println(result);
        JSONObject root = resultJson.optJSONObject("ddk_phrase_generate_response");
        if (root != null) {
            array = root.optJSONArray("promotion_phrase_list");
            JSONObject phraseObject = JSONObject.fromObject(array.get(0));
            return phraseObject.optString("phrase");
        }
    /**
     * 获取商品详情
     *
     * @param goodsId
     */
    public static PDDGoodsDetail getGoodsDetail(Long goodsId) {
        return getGoodsDetail(goodsId, null, null);
    }
        return null;
    }
    public static PDDGoodsDetail getGoodsDetail(Long goodsId, String pid, String customParameters) {
        JSONArray array = new JSONArray();
        array.add(goodsId);
        Map<String, String> map = new HashMap<>();
        map.put("type", "pdd.ddk.goods.detail");
        map.put("goods_id_list", array.toString());
        if (!StringUtil.isNullOrEmpty(pid)) {
            map.put("pid", pid);
        }
    public static Date getSystemTime() {
        try {
            Map<String, String> map = new HashMap<>();
            map.put("type", "pdd.time.get");
            String result = baseRequest(map);
            String time = JSONObject.fromObject(result).optJSONObject("time_get_response").optString("time");
            return new Date(TimeUtil.convertToTimeTemp(time, "yyyy-MM-dd HH:mm:ss"));
        } catch (Exception e) {
        }
        return null;
    }
        if (!StringUtil.isNullOrEmpty(customParameters)) {
            map.put("custom_parameters", customParameters);
        }
    /**
     * 获取商品详情
     *
     * @param goodsId
     */
    public static PDDShopResult getShopList(Integer page, Long catId) {
        JSONArray arrayType = new JSONArray();
        arrayType.add(3);
        String result = baseRequest(map);
        System.out.println(result);
        JSONObject resultJson = JSONObject.fromObject(result);
        JSONObject root = resultJson.optJSONObject("goods_detail_response");
        if (root == null) {
            return null;
        }
        Map<String, String> map = new HashMap<>();
        map.put("type", "pdd.ddk.merchant.list.get");
        if (catId != null)
            map.put("cat_id", catId + "");
        if (page != null)
            map.put("page_number", page + "");
        JSONArray resultArray = root.optJSONArray("goods_details");
        if (resultArray == null) {
            return null;
        }
        if (page != null)
            map.put("page_number", page + "");
        Type type = new TypeToken<List<PDDGoodsDetail>>() {
        }.getType();
        List<PDDGoodsDetail> goodsList = new Gson().fromJson(resultArray.toString(), type);
        if (goodsList != null && goodsList.size() > 0)
            return goodsList.get(0);
        return null;
    }
        map.put("merchant_type_list", arrayType.toString());
    /**
     * 获取商品详情
     *
     * @param goodsId
     */
    public static String createGenerate(Long goodsId) {
        JSONArray array = new JSONArray();
        array.add(goodsId);
        Map<String, String> map = new HashMap<>();
        map.put("type", "pdd.ddk.phrase.generate");
        map.put("goods_id_list", array.toString());
        map.put("p_id", PID_FANLI);
        String result = baseRequest(map);
        JSONObject resultJson = JSONObject.fromObject(result);
        JSONObject root = resultJson.optJSONObject("ddk_phrase_generate_response");
        if (root != null) {
            array = root.optJSONArray("promotion_phrase_list");
            JSONObject phraseObject = JSONObject.fromObject(array.get(0));
            return phraseObject.optString("phrase");
        }
        String result = baseRequest(map);
        JSONObject resultJson = JSONObject.fromObject(result);
        JSONObject root = resultJson.optJSONObject("merchant_list_response");
        if (root != null) {
            int totalCount = root.optInt("total");
        return null;
    }
            JSONArray array = root.optJSONArray("mall_search_info_vo_list");
            Type type = new TypeToken<List<PDDShopDetail>>() {
            }.getType();
            List<PDDShopDetail> listShop = new Gson().fromJson(array.toString(), type);
            return new PDDShopResult(totalCount, listShop);
        }
        return null;
    }
    public static Date getSystemTime() {
        try {
            Map<String, String> map = new HashMap<>();
            map.put("type", "pdd.time.get");
            String result = baseRequest(map);
            String time = JSONObject.fromObject(result).optJSONObject("time_get_response").optString("time");
            return new Date(TimeUtil.convertToTimeTemp(time, "yyyy-MM-dd HH:mm:ss"));
        } catch (Exception e) {
        }
        return null;
    }
    /**
     * @param page
     * @param catId
     * @return
     */
    public static PDDShopResult getShopList(Integer page, Long catId) {
        JSONArray arrayType = new JSONArray();
        arrayType.add(3);
        Map<String, String> map = new HashMap<>();
        map.put("type", "pdd.ddk.merchant.list.get");
        if (catId != null)
            map.put("cat_id", catId + "");
        if (page != null)
            map.put("page_number", page + "");
        if (page != null)
            map.put("page_number", page + "");
        map.put("merchant_type_list", arrayType.toString());
        String result = baseRequest(map);
        JSONObject resultJson = JSONObject.fromObject(result);
        JSONObject root = resultJson.optJSONObject("merchant_list_response");
        if (root != null) {
            int totalCount = root.optInt("total");
            JSONArray array = root.optJSONArray("mall_search_info_vo_list");
            Type type = new TypeToken<List<PDDShopDetail>>() {
            }.getType();
            List<PDDShopDetail> listShop = new Gson().fromJson(array.toString(), type);
            return new PDDShopResult(totalCount, listShop);
        }
        return null;
    }
    /**
     * 是否授权
     *
     * @param pid
     * @param customParameters
     * @return
     */
    public static boolean isAuth(String pid, String customParameters) {
        Map<String, String> map = new HashMap<>();
        map.put("type", "pdd.ddk.member.authority.query");
        map.put("pid", pid);
        map.put("custom_parameters", customParameters);
        String result = baseRequest(map);
        JSONObject resultJson = JSONObject.fromObject(result);
        if (resultJson.optJSONObject("authority_query_response").optInt("bind") == 0) {
            return false;
        } else
            return true;
    }
}
fanli/src/main/java/com/yeshi/fanli/util/pinduoduo/PinDuoDuoUtil.java
@@ -40,577 +40,581 @@
public class PinDuoDuoUtil {
    /**
     * 商品佣金计算
     *
     * @param goods
     * @param rate
     * @return
     */
    public static BigDecimal getGoodsFanLiMoney(PDDGoodsDetail goods, BigDecimal rate) {
        BigDecimal money = null;
        BigDecimal hundred = new BigDecimal(100);
        rate = MoneyBigDecimalUtil.div(rate, hundred);
        BigDecimal price = MoneyBigDecimalUtil.div(new BigDecimal(goods.getMinGroupPrice()), hundred).setScale(2);
        BigDecimal promotionRate = MoneyBigDecimalUtil.div3(new BigDecimal(goods.getPromotionRate()),
                new BigDecimal(1000));
    /**
     * 商品佣金计算
     *
     * @param goods
     * @param rate
     * @return
     */
    public static BigDecimal getGoodsFanLiMoney(PDDGoodsDetail goods, BigDecimal rate) {
        BigDecimal money = null;
        BigDecimal hundred = new BigDecimal(100);
        rate = MoneyBigDecimalUtil.div(rate, hundred);
        BigDecimal price = MoneyBigDecimalUtil.div(new BigDecimal(goods.getMinGroupPrice()), hundred).setScale(2);
        BigDecimal promotionRate = MoneyBigDecimalUtil.div3(new BigDecimal(goods.getPromotionRate()),
                new BigDecimal(1000));
        if (goods.getPredictPromotionRate() != null)
            promotionRate = MoneyBigDecimalUtil.div3(goods.getPredictPromotionRate(),
                    new BigDecimal(1000));
        Boolean hasCoupon = goods.getHasCoupon();
        if (hasCoupon == null || !hasCoupon) {
            money = MoneyBigDecimalUtil.mul(MoneyBigDecimalUtil.mul(price, promotionRate), rate);
        } else {
            BigDecimal amount = MoneyBigDecimalUtil.div(new BigDecimal(goods.getCouponDiscount()), hundred);
            BigDecimal startFree = MoneyBigDecimalUtil.div(new BigDecimal(goods.getCouponMinOrderAmount()), hundred);
            if (startFree.compareTo(price) <= 0 && price.compareTo(amount) > 0) {
                BigDecimal finalPrice = price.subtract(amount);
                money = MoneyBigDecimalUtil.mul(MoneyBigDecimalUtil.mul(finalPrice, promotionRate), rate);
            } else {// 不能用券
                money = MoneyBigDecimalUtil.mul(MoneyBigDecimalUtil.mul(price, promotionRate), rate);
            }
        }
        return BigDecimalUtil.getWithNoZera(money).setScale(2);
    }
        Boolean hasCoupon = goods.getHasCoupon();
        if (hasCoupon == null || !hasCoupon) {
            money = MoneyBigDecimalUtil.mul(MoneyBigDecimalUtil.mul(price, promotionRate), rate);
        } else {
            BigDecimal amount = MoneyBigDecimalUtil.div(new BigDecimal(goods.getCouponDiscount()), hundred);
            BigDecimal startFree = MoneyBigDecimalUtil.div(new BigDecimal(goods.getCouponMinOrderAmount()), hundred);
            if (startFree.compareTo(price) <= 0 && price.compareTo(amount) > 0) {
                BigDecimal finalPrice = price.subtract(amount);
                money = MoneyBigDecimalUtil.mul(MoneyBigDecimalUtil.mul(finalPrice, promotionRate), rate);
            } else {// 不能用券
                money = MoneyBigDecimalUtil.mul(MoneyBigDecimalUtil.mul(price, promotionRate), rate);
            }
        }
        return BigDecimalUtil.getWithNoZera(money).setScale(2);
    }
    /**
     * 计算商品券后价,没有券则返回原价
     *
     * @param goodsBrief
     * @return
     */
    public static BigDecimal getQuanPrice(PDDGoodsDetail goods) {
        BigDecimal hundred = new BigDecimal(100);
        BigDecimal price = MoneyBigDecimalUtil.div(new BigDecimal(goods.getMinGroupPrice()), hundred);
        Boolean hasCoupon = goods.getHasCoupon();
        if (hasCoupon == null || !hasCoupon) {
            return price.setScale(2);
        }
    /**
     * 计算商品券后价,没有券则返回原价
     *
     * @param goodsBrief
     * @return
     */
    public static BigDecimal getQuanPrice(PDDGoodsDetail goods) {
        BigDecimal hundred = new BigDecimal(100);
        BigDecimal price = MoneyBigDecimalUtil.div(new BigDecimal(goods.getMinGroupPrice()), hundred);
        Boolean hasCoupon = goods.getHasCoupon();
        if (hasCoupon == null || !hasCoupon) {
            return price.setScale(2);
        }
        BigDecimal amount = MoneyBigDecimalUtil.div(new BigDecimal(goods.getCouponDiscount()), hundred);
        BigDecimal startFree = MoneyBigDecimalUtil.div(new BigDecimal(goods.getCouponMinOrderAmount()), hundred);
        if (startFree.compareTo(price) <= 0) {
            BigDecimal quanPrice = MoneyBigDecimalUtil.sub(price, amount);
            return quanPrice.setScale(2);
        } else {
            return price.setScale(2);
        }
    }
        BigDecimal amount = MoneyBigDecimalUtil.div(new BigDecimal(goods.getCouponDiscount()), hundred);
        BigDecimal startFree = MoneyBigDecimalUtil.div(new BigDecimal(goods.getCouponMinOrderAmount()), hundred);
        if (startFree.compareTo(price) <= 0) {
            BigDecimal quanPrice = MoneyBigDecimalUtil.sub(price, amount);
            return quanPrice.setScale(2);
        } else {
            return price.setScale(2);
        }
    }
    public static List<String> getDetailImages(Long id) {
        List<String> imgList = new ArrayList<>();
        try {
            Document doc = Jsoup.connect("http://yangkeduo.com/goods.html?goods_id=" + id)
                    .userAgent(
                            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36")
                    .get();
            Elements els = doc.getElementsByTag("script");
            for (int i = 0; i < els.size(); i++) {
                if (els.get(i).html().contains("window.rawData")) {
                    String dataJS = els.get(i).html().replace("window.", "var ");
                    dataJS += "function getData(){return JSON.stringify(rawData);}";
    public static List<String> getDetailImages(Long id) {
        List<String> imgList = new ArrayList<>();
        try {
            Document doc = Jsoup.connect("http://yangkeduo.com/goods.html?goods_id=" + id)
                    .userAgent(
                            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36")
                    .get();
            Elements els = doc.getElementsByTag("script");
            for (int i = 0; i < els.size(); i++) {
                if (els.get(i).html().contains("window.rawData")) {
                    String dataJS = els.get(i).html().replace("window.", "var ");
                    dataJS += "function getData(){return JSON.stringify(rawData);}";
                    ScriptEngineManager manager = new ScriptEngineManager();
                    ScriptEngine engine = manager.getEngineByName("javascript");
                    try {
                        engine.eval(dataJS);
                        if (engine instanceof Invocable) {
                            Invocable in = (Invocable) engine;
                            String jsonStr = in.invokeFunction("getData").toString();
                            JSONObject json = JSONObject.fromObject(jsonStr);
                            JSONArray array = json.optJSONObject("store").optJSONObject("initDataObj")
                                    .optJSONObject("goods").optJSONArray("detailGallery");
                            for (int j = 0; j < array.size(); j++) {
                                imgList.add("http:" + array.optJSONObject(j).optString("url"));
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                }
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }
                    ScriptEngineManager manager = new ScriptEngineManager();
                    ScriptEngine engine = manager.getEngineByName("javascript");
                    try {
                        engine.eval(dataJS);
                        if (engine instanceof Invocable) {
                            Invocable in = (Invocable) engine;
                            String jsonStr = in.invokeFunction("getData").toString();
                            JSONObject json = JSONObject.fromObject(jsonStr);
                            JSONArray array = json.optJSONObject("store").optJSONObject("initDataObj")
                                    .optJSONObject("goods").optJSONArray("detailGallery");
                            for (int j = 0; j < array.size(); j++) {
                                imgList.add("http:" + array.optJSONObject(j).optString("url"));
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                }
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return imgList;
        return imgList;
    }
    }
    public static List<Long> getRecommendGoodsId(Long id) {
        List<Long> list = new ArrayList<Long>();
        JSONObject params = new JSONObject();
        params.put("pageNo", 1);
        params.put("show_tags", 1);
        params.put("goods_id", id);
        params.put("app_name", "goods_detail");
        params.put("list_id", "goods_detail_HgfiMc");
        params.put("pdduid", StringUtil.Md5(System.currentTimeMillis() + ""));
    public static List<Long> getRecommendGoodsId(Long id) {
        List<Long> list = new ArrayList<Long>();
        JSONObject params = new JSONObject();
        params.put("pageNo", 1);
        params.put("show_tags", 1);
        params.put("goods_id", id);
        params.put("app_name", "goods_detail");
        params.put("list_id", "goods_detail_HgfiMc");
        params.put("pdduid", StringUtil.Md5(System.currentTimeMillis() + ""));
        HttpClient client = new HttpClient();
        PostMethod pm = new PostMethod("https://mobile.yangkeduo.com/proxy/api/api/tesla/query");
        pm.setRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko");
        pm.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
        pm.setRequestHeader("Referer", "https://jinbao.pinduoduo.com/promotion/brand-promotion");
        pm.setRequestBody(params.toString());
        try {
            client.executeMethod(pm);
            String result = pm.getResponseBodyAsString();
            LogHelper.test("拼多多猜你喜欢:" + result);
            JSONObject json = JSONObject.fromObject(result);
            JSONArray array = json.optJSONArray("data");
            if (array != null) {
                for (int i = 0; i < array.size(); i++) {
                    list.add(array.optJSONObject(i).optLong("goods_id"));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        HttpClient client = new HttpClient();
        PostMethod pm = new PostMethod("https://mobile.yangkeduo.com/proxy/api/api/tesla/query");
        pm.setRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko");
        pm.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
        pm.setRequestHeader("Referer", "https://jinbao.pinduoduo.com/promotion/brand-promotion");
        pm.setRequestBody(params.toString());
        try {
            client.executeMethod(pm);
            String result = pm.getResponseBodyAsString();
            LogHelper.test("拼多多猜你喜欢:" + result);
            JSONObject json = JSONObject.fromObject(result);
            JSONArray array = json.optJSONArray("data");
            if (array != null) {
                for (int i = 0; i < array.size(); i++) {
                    list.add(array.optJSONObject(i).optLong("goods_id"));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }
        return list;
    }
    /**
     * 搜索候选词
     *
     * @param key
     * @return
     */
    public static List<String> suggestSearch(String key) {
        List<String> list = new ArrayList<>();
        if (StringUtil.isNullOrEmpty(key))
            return list;
        String url = null;
        try {
            url = String.format("http://apiv3.yangkeduo.com/search_suggest?query=%s&pdduid=0",
                    URLEncoder.encode(key, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    /**
     * 搜索候选词
     *
     * @param key
     * @return
     */
    public static List<String> suggestSearch(String key) {
        List<String> list = new ArrayList<>();
        if (StringUtil.isNullOrEmpty(key))
            return list;
        String url = null;
        try {
            url = String.format("http://apiv3.yangkeduo.com/search_suggest?query=%s&pdduid=0",
                    URLEncoder.encode(key, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (url == null)
            return list;
        try {
            String result = HttpUtil.get(url);
            JSONObject dataJSON = JSONObject.fromObject(result);
            JSONArray array = dataJSON.optJSONArray("suggest_list");
            for (int i = 0; i < array.size(); i++) {
                String sk = array.optJSONObject(i).optJSONObject("item_data").optString("suggestion");
                if (!StringUtil.isNullOrEmpty(sk))
                    list.add(sk);
            }
        } catch (Exception e) {
        }
        return list;
    }
        if (url == null)
            return list;
        try {
            String result = HttpUtil.get(url);
            JSONObject dataJSON = JSONObject.fromObject(result);
            JSONArray array = dataJSON.optJSONArray("suggest_list");
            for (int i = 0; i < array.size(); i++) {
                String sk = array.optJSONObject(i).optJSONObject("item_data").optString("suggestion");
                if (!StringUtil.isNullOrEmpty(sk))
                    list.add(sk);
            }
        } catch (Exception e) {
        }
        return list;
    }
    /**
     * 多多进宝爬取数据-品牌好货
     *
     * @param sf
     * @return
     */
    public static PDDGoodsResult getBrandGoods(PDDSearchFilter sf) {
        JSONObject params = new JSONObject();
        params.put("pageNumber", sf.getPage());
        params.put("pageSize", sf.getPageSize());
    /**
     * 多多进宝爬取数据-品牌好货
     *
     * @param sf
     * @return
     */
    public static PDDGoodsResult getBrandGoods(PDDSearchFilter sf) {
        JSONObject params = new JSONObject();
        params.put("pageNumber", sf.getPage());
        params.put("pageSize", sf.getPageSize());
        if (sf.getSortType() != null) {
            params.put("sortType", sf.getSortType());
        }
        if (sf.getSortType() != null) {
            params.put("sortType", sf.getSortType());
        }
        if (sf.getHasCoupon() != null) {
            params.put("withCoupon", sf.getHasCoupon() ? 1 : 0);
        }
        if (sf.getHasCoupon() != null) {
            params.put("withCoupon", sf.getHasCoupon() ? 1 : 0);
        }
        if (sf.getKw() != null) {
            params.put("keyword", sf.getKw());
        } else {
            params.put("keyword", "");
        }
        if (sf.getKw() != null) {
            params.put("keyword", sf.getKw());
        } else {
            params.put("keyword", "");
        }
        if (sf.getOptId() != null) {
            params.put("optId", sf.getOptId());
        }
        if (sf.getOptId() != null) {
            params.put("optId", sf.getOptId());
        }
        if (sf.getCatId() != null) {
            params.put("categoryId", sf.getCatId());
        }
        if (sf.getCatId() != null) {
            params.put("categoryId", sf.getCatId());
        }
        System.out.println(params.toString());
        System.out.println(params.toString());
        HttpClient client = new HttpClient();
        PostMethod pm = new PostMethod("https://jinbao.pinduoduo.com/network/api/common/brand/goodsList");
        pm.setRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko");
        pm.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
        pm.setRequestHeader("Referer", "https://jinbao.pinduoduo.com/promotion/brand-promotion");
        pm.setRequestBody(params.toString());
        HttpClient client = new HttpClient();
        PostMethod pm = new PostMethod("https://jinbao.pinduoduo.com/network/api/common/brand/goodsList");
        pm.setRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko");
        pm.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
        pm.setRequestHeader("Referer", "https://jinbao.pinduoduo.com/promotion/brand-promotion");
        pm.setRequestBody(params.toString());
        PDDGoodsResult goodsResult = null;
        PDDGoodsResult goodsResult = null;
        try {
            client.executeMethod(pm);
            String result = pm.getResponseBodyAsString();
            System.out.println(result);
        try {
            client.executeMethod(pm);
            String result = pm.getResponseBodyAsString();
            System.out.println(result);
            JSONObject json = JSONObject.fromObject(result);
            Boolean code = json.optBoolean("success");
            if (code != null && code) {
                JSONObject root = json.optJSONObject("result");
                if (root == null) {
                    return null;
                }
                JSONArray array = root.optJSONArray("goodsList");
                if (array == null) {
                    return null;
                }
            JSONObject json = JSONObject.fromObject(result);
            Boolean code = json.optBoolean("success");
            if (code != null && code) {
                JSONObject root = json.optJSONObject("result");
                if (root == null) {
                    return null;
                }
                JSONArray array = root.optJSONArray("goodsList");
                if (array == null) {
                    return null;
                }
                List<PDDGoodsDetail> goodsList = new ArrayList<PDDGoodsDetail>();
                for (int i = 0; i < array.size(); i++) {
                    PDDGoodsDetail parseGoods = parseGoods(array.getJSONObject(i));
                    if (parseGoods != null) {
                        goodsList.add(parseGoods);
                    }
                }
                int totalCount = root.optInt("total");
                List<PDDGoodsDetail> goodsList = new ArrayList<PDDGoodsDetail>();
                for (int i = 0; i < array.size(); i++) {
                    PDDGoodsDetail parseGoods = parseGoods(array.getJSONObject(i));
                    if (parseGoods != null) {
                        goodsList.add(parseGoods);
                    }
                }
                int totalCount = root.optInt("total");
                goodsResult = new PDDGoodsResult();
                goodsResult.setGoodsList(goodsList);
                goodsResult.setTotalCount(totalCount);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
                goodsResult = new PDDGoodsResult();
                goodsResult.setGoodsList(goodsList);
                goodsResult.setTotalCount(totalCount);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return goodsResult;
    }
        return goodsResult;
    }
    private static PDDGoodsDetail parseGoods(JSONObject json) {
        PDDGoodsDetail goods = new PDDGoodsDetail();
        goods.setMallName(json.optString("mallName"));
        goods.setMerchantType(json.optInt("merchantType"));
        goods.setGoodsId(json.optLong("goodsId"));
        goods.setGoodsName(json.optString("goodsName"));
        goods.setGoodsDesc(json.optString("goodsDesc"));
        goods.setSalesTip(json.optString("salesTip"));
    private static PDDGoodsDetail parseGoods(JSONObject json) {
        PDDGoodsDetail goods = new PDDGoodsDetail();
        goods.setMallName(json.optString("mallName"));
        goods.setMerchantType(json.optInt("merchantType"));
        goods.setGoodsId(json.optLong("goodsId"));
        goods.setGoodsName(json.optString("goodsName"));
        goods.setGoodsDesc(json.optString("goodsDesc"));
        goods.setSalesTip(json.optString("salesTip"));
        if (json.optString("goodsImageUrl") != null) {
            goods.setGoodsImageUrl("http:" + json.optString("goodsImageUrl"));
        }
        if (json.optString("goodsImageUrl") != null) {
            goods.setGoodsImageUrl("http:" + json.optString("goodsImageUrl"));
        }
        if (json.optString("goodsThumbnailUrl") != null) {
            goods.setGoodsThumbnailUrl("http:" + json.optString("goodsThumbnailUrl"));
        }
        if (json.optString("goodsThumbnailUrl") != null) {
            goods.setGoodsThumbnailUrl("http:" + json.optString("goodsThumbnailUrl"));
        }
        if (json.optString("minGroupPrice") != null) {
            goods.setMinGroupPrice(json.getLong("minGroupPrice") / 10);
        }
        if (json.optString("minGroupPrice") != null) {
            goods.setMinGroupPrice(json.getLong("minGroupPrice") / 10);
        }
        if (json.optString("categoryId") != null) {
            goods.setCategoryId(json.getLong("categoryId"));
        }
        if (json.optString("categoryId") != null) {
            goods.setCategoryId(json.getLong("categoryId"));
        }
        goods.setCategoryName(json.optString("categoryName"));
        goods.setHasCoupon(json.optBoolean("hasCoupon"));
        goods.setCategoryName(json.optString("categoryName"));
        goods.setHasCoupon(json.optBoolean("hasCoupon"));
        if (json.optString("couponMinOrderAmount") != null) {
            goods.setCouponMinOrderAmount(json.getLong("couponMinOrderAmount") / 10);
        }
        if (json.optString("couponMinOrderAmount") != null) {
            goods.setCouponMinOrderAmount(json.getLong("couponMinOrderAmount") / 10);
        }
        if (json.optString("couponDiscount") != null) {
            goods.setCouponDiscount(json.getLong("couponDiscount") / 10);
        }
        if (json.optString("couponDiscount") != null) {
            goods.setCouponDiscount(json.getLong("couponDiscount") / 10);
        }
        if (json.optString("couponTotalQuantity") != null) {
            goods.setCouponTotalQuantity(json.getLong("couponTotalQuantity"));
        }
        if (json.optString("couponTotalQuantity") != null) {
            goods.setCouponTotalQuantity(json.getLong("couponTotalQuantity"));
        }
        if (json.optString("couponRemainQuantity") != null) {
            goods.setCouponRemainQuantity(json.getLong("couponRemainQuantity"));
        }
        if (json.optString("couponRemainQuantity") != null) {
            goods.setCouponRemainQuantity(json.getLong("couponRemainQuantity"));
        }
        if (json.optString("couponStartTime") != null) {
            goods.setCouponStartTime(json.getLong("couponStartTime"));
        }
        if (json.optString("couponStartTime") != null) {
            goods.setCouponStartTime(json.getLong("couponStartTime"));
        }
        if (json.optString("couponEndTime") != null) {
            goods.setCouponEndTime(json.getLong("couponEndTime"));
        }
        if (json.optString("couponEndTime") != null) {
            goods.setCouponEndTime(json.getLong("couponEndTime"));
        }
        if (json.optString("promotionRate") != null) {
            goods.setPromotionRate(json.getLong("promotionRate"));
        }
        if (json.optString("promotionRate") != null) {
            goods.setPromotionRate(json.getLong("promotionRate"));
        }
        if (json.optString("optId") != null) {
            goods.setOptId(json.getLong("optId"));
        }
        if (json.optString("optId") != null) {
            goods.setOptId(json.getLong("optId"));
        }
        return goods;
    }
        return goods;
    }
    // 获取Android打开原生APP的uri
    public static String getAndroidNativeURI(String url) {
        if (url.contains("duo_coupon_landing.html?")) {
            int index = url.indexOf("duo_coupon_landing.html?");
            if (index >= 0) {
                return "pinduoduo://com.xunmeng.pinduoduo/" + url.substring(index, url.length());
            }
        }
        return null;
    }
    // 获取Android打开原生APP的uri
    public static String getAndroidNativeURI(String url) {
        if (url.contains("duo_coupon_landing.html?")) {
            int index = url.indexOf("duo_coupon_landing.html?");
            if (index >= 0) {
                return "pinduoduo://com.xunmeng.pinduoduo/" + url.substring(index, url.length());
            }
        }
        return null;
    }
    /**
     * 多多进宝爬取数据-品牌好货
     *
     * @param sf
     * @return
     */
    public static PDDGoodsResult getTodaySaleGoods() {
        JSONObject params = new JSONObject();
        params.put("type", 1);
        params.put("sortType", 3);
    /**
     * 多多进宝爬取数据-品牌好货
     *
     * @param sf
     * @return
     */
    public static PDDGoodsResult getTodaySaleGoods() {
        JSONObject params = new JSONObject();
        params.put("type", 1);
        params.put("sortType", 3);
        HttpClient client = new HttpClient();
        PostMethod pm = new PostMethod("https://jinbao.pinduoduo.com/network/api/common/queryTopGoodsList");
        pm.setRequestHeader("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3730.400 QQBrowser/10.5.3805.400");
        pm.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
        pm.setRequestHeader("Referer", "https://jinbao.pinduoduo.com/promotion/hot-promotion");
        pm.setRequestBody(params.toString());
        HttpClient client = new HttpClient();
        PostMethod pm = new PostMethod("https://jinbao.pinduoduo.com/network/api/common/queryTopGoodsList");
        pm.setRequestHeader("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3730.400 QQBrowser/10.5.3805.400");
        pm.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
        pm.setRequestHeader("Referer", "https://jinbao.pinduoduo.com/promotion/hot-promotion");
        pm.setRequestBody(params.toString());
        PDDGoodsResult goodsResult = null;
        PDDGoodsResult goodsResult = null;
        try {
            client.executeMethod(pm);
            String result = pm.getResponseBodyAsString();
            JSONObject json = JSONObject.fromObject(result);
            Boolean code = json.optBoolean("success");
            if (code != null && code) {
                JSONObject root = json.optJSONObject("result");
                if (root == null) {
                    return null;
                }
                JSONArray array = root.optJSONArray("list");
                if (array == null) {
                    return null;
                }
        try {
            client.executeMethod(pm);
            String result = pm.getResponseBodyAsString();
            JSONObject json = JSONObject.fromObject(result);
            Boolean code = json.optBoolean("success");
            if (code != null && code) {
                JSONObject root = json.optJSONObject("result");
                if (root == null) {
                    return null;
                }
                JSONArray array = root.optJSONArray("list");
                if (array == null) {
                    return null;
                }
                List<PDDGoodsDetail> goodsList = new ArrayList<PDDGoodsDetail>();
                for (int i = 0; i < array.size(); i++) {
                    PDDGoodsDetail parseGoods = parseTodaySaleGoods(array.getJSONObject(i));
                    if (parseGoods != null) {
                        goodsList.add(parseGoods);
                    }
                }
                int totalCount = root.optInt("total");
                List<PDDGoodsDetail> goodsList = new ArrayList<PDDGoodsDetail>();
                for (int i = 0; i < array.size(); i++) {
                    PDDGoodsDetail parseGoods = parseTodaySaleGoods(array.getJSONObject(i));
                    if (parseGoods != null) {
                        goodsList.add(parseGoods);
                    }
                }
                int totalCount = root.optInt("total");
                goodsResult = new PDDGoodsResult();
                goodsResult.setGoodsList(goodsList);
                goodsResult.setTotalCount(totalCount);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
                goodsResult = new PDDGoodsResult();
                goodsResult.setGoodsList(goodsList);
                goodsResult.setTotalCount(totalCount);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return goodsResult;
    }
        return goodsResult;
    }
    private static PDDGoodsDetail parseTodaySaleGoods(JSONObject json) {
        PDDGoodsDetail goods = new PDDGoodsDetail();
        goods.setMallName(json.optString("mallName"));
        goods.setMerchantType(json.optInt("merchantType"));
        goods.setGoodsId(json.optLong("goodsId"));
        goods.setGoodsName(json.optString("goodsName"));
        goods.setGoodsDesc(json.optString("goodsDesc"));
        goods.setSalesTip(json.optString("salesTip"));
    private static PDDGoodsDetail parseTodaySaleGoods(JSONObject json) {
        PDDGoodsDetail goods = new PDDGoodsDetail();
        goods.setMallName(json.optString("mallName"));
        goods.setMerchantType(json.optInt("merchantType"));
        goods.setGoodsId(json.optLong("goodsId"));
        goods.setGoodsName(json.optString("goodsName"));
        goods.setGoodsDesc(json.optString("goodsDesc"));
        goods.setSalesTip(json.optString("salesTip"));
        if (json.optString("mallId") != null) {
            goods.setMallId(json.getLong("mallId"));
        }
        if (json.optString("mallId") != null) {
            goods.setMallId(json.getLong("mallId"));
        }
        if (json.optString("goodsImageUrl") != null) {
            goods.setGoodsImageUrl(json.optString("goodsImageUrl"));
        }
        if (json.optString("goodsImageUrl") != null) {
            goods.setGoodsImageUrl(json.optString("goodsImageUrl"));
        }
        if (json.optString("goodsThumbnailUrl") != null) {
            goods.setGoodsThumbnailUrl(json.optString("goodsThumbnailUrl"));
        }
        if (json.optString("goodsThumbnailUrl") != null) {
            goods.setGoodsThumbnailUrl(json.optString("goodsThumbnailUrl"));
        }
        if (json.optString("minGroupPrice") != null) {
            goods.setMinGroupPrice(json.getLong("minGroupPrice"));
        }
        if (json.optString("minGroupPrice") != null) {
            goods.setMinGroupPrice(json.getLong("minGroupPrice"));
        }
        if (json.optString("minNormalPrice") != null) {
            goods.setMinNormalPrice(json.getLong("minNormalPrice"));
        }
        if (json.optString("minNormalPrice") != null) {
            goods.setMinNormalPrice(json.getLong("minNormalPrice"));
        }
        if (json.optString("categoryId") != null) {
            goods.setCategoryId(json.getLong("categoryId"));
        }
        if (json.optString("categoryId") != null) {
            goods.setCategoryId(json.getLong("categoryId"));
        }
        goods.setCategoryName(json.optString("categoryName"));
        goods.setHasCoupon(json.optBoolean("hasCoupon"));
        goods.setCategoryName(json.optString("categoryName"));
        goods.setHasCoupon(json.optBoolean("hasCoupon"));
        if (json.optString("couponMinOrderAmount") != null) {
            goods.setCouponMinOrderAmount(json.getLong("couponMinOrderAmount"));
        }
        if (json.optString("couponMinOrderAmount") != null) {
            goods.setCouponMinOrderAmount(json.getLong("couponMinOrderAmount"));
        }
        if (json.optString("couponDiscount") != null) {
            goods.setCouponDiscount(json.getLong("couponDiscount"));
        }
        if (json.optString("couponDiscount") != null) {
            goods.setCouponDiscount(json.getLong("couponDiscount"));
        }
        if (json.optString("couponTotalQuantity") != null) {
            goods.setCouponTotalQuantity(json.getLong("couponTotalQuantity"));
        }
        if (json.optString("couponTotalQuantity") != null) {
            goods.setCouponTotalQuantity(json.getLong("couponTotalQuantity"));
        }
        if (json.optString("couponRemainQuantity") != null) {
            goods.setCouponRemainQuantity(json.getLong("couponRemainQuantity"));
        }
        if (json.optString("couponRemainQuantity") != null) {
            goods.setCouponRemainQuantity(json.getLong("couponRemainQuantity"));
        }
        if (json.optString("couponStartTime") != null) {
            goods.setCouponStartTime(json.getLong("couponStartTime"));
        }
        if (json.optString("couponStartTime") != null) {
            goods.setCouponStartTime(json.getLong("couponStartTime"));
        }
        if (json.optString("couponEndTime") != null) {
            goods.setCouponEndTime(json.getLong("couponEndTime"));
        }
        if (json.optString("couponEndTime") != null) {
            goods.setCouponEndTime(json.getLong("couponEndTime"));
        }
        if (json.optString("promotionRate") != null) {
            goods.setPromotionRate(json.getLong("promotionRate"));
        }
        if (json.optString("promotionRate") != null) {
            goods.setPromotionRate(json.getLong("promotionRate"));
        }
        if (json.optString("optId") != null) {
            goods.setOptId(json.getLong("optId"));
        }
        if (json.optString("optId") != null) {
            goods.setOptId(json.getLong("optId"));
        }
        return goods;
    }
        return goods;
    }
    public static String getJDGoodsJS() {
        InputStream input = JDUtil.class.getClassLoader().getResourceAsStream("pddGoods.js");
        StringBuilder sb = new StringBuilder();
        String line;
        BufferedReader br = new BufferedReader(new InputStreamReader(input));
        try {
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
    public static String getJDGoodsJS() {
        InputStream input = JDUtil.class.getClassLoader().getResourceAsStream("pddGoods.js");
        StringBuilder sb = new StringBuilder();
        String line;
        BufferedReader br = new BufferedReader(new InputStreamReader(input));
        try {
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
    static String jdGoodsJs = null;
    static ScriptEngine engine = null;
    static String jdGoodsJs = null;
    static ScriptEngine engine = null;
    static {
        if (jdGoodsJs == null)
            jdGoodsJs = getJDGoodsJS();
        ScriptEngineManager manager = new ScriptEngineManager();
        engine = manager.getEngineByName("javascript");
        try {
            engine.eval(jdGoodsJs);
        } catch (ScriptException e) {
            e.printStackTrace();
        }
    static {
        if (jdGoodsJs == null)
            jdGoodsJs = getJDGoodsJS();
        ScriptEngineManager manager = new ScriptEngineManager();
        engine = manager.getEngineByName("javascript");
        try {
            engine.eval(jdGoodsJs);
        } catch (ScriptException e) {
            e.printStackTrace();
        }
    }
    }
    public static String getPDDGoodsId(String url) {
        if (url == null)
            return null;
        String link = url;
        if (link.contains("://p.pinduoduo.com/")) {// 拼多多的短链
            HttpClient client = new HttpClient();
            client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
            PostMethod pm = new PostMethod(link);
            try {
                client.executeMethod(pm);
                Header location = pm.getResponseHeader("Location");
                if (location != null)
                    link = location.getValue();
            } catch (HttpException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    public static String getPDDGoodsId(String url) {
        if (url == null)
            return null;
        String link = url;
        if (link.contains("://p.pinduoduo.com/")) {// 拼多多的短链
            HttpClient client = new HttpClient();
            client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
            PostMethod pm = new PostMethod(link);
            try {
                client.executeMethod(pm);
                Header location = pm.getResponseHeader("Location");
                if (location != null)
                    link = location.getValue();
            } catch (HttpException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            if (engine instanceof Invocable) {
                Invocable in = (Invocable) engine;
                Object goodsId = in.invokeFunction("getGoodsId", link);
                if (goodsId != null)
                    return goodsId.toString().trim();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
        try {
            if (engine instanceof Invocable) {
                Invocable in = (Invocable) engine;
                Object goodsId = in.invokeFunction("getGoodsId", link);
                if (goodsId != null)
                    return goodsId.toString().trim();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public static PDDGoodsDetail getPDDGoodsInfo(String id) {
        try {
            Document doc = Jsoup.connect("http://yangkeduo.com/goods.html?goods_id=" + id)
                    .userAgent(
                            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36")
                    .get();
            Elements els = doc.getElementsByTag("script");
            for (int i = 0; i < els.size(); i++) {
                if (els.get(i).html().contains("window.rawData")) {
                    String dataJS = els.get(i).html().replace("window.", "var ");
                    dataJS += "function getData(){return JSON.stringify(rawData);}";
    public static PDDGoodsDetail getPDDGoodsInfo(String id) {
        try {
            Document doc = Jsoup.connect("http://yangkeduo.com/goods.html?goods_id=" + id)
                    .userAgent(
                            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36")
                    .get();
            Elements els = doc.getElementsByTag("script");
            for (int i = 0; i < els.size(); i++) {
                if (els.get(i).html().contains("window.rawData")) {
                    String dataJS = els.get(i).html().replace("window.", "var ");
                    dataJS += "function getData(){return JSON.stringify(rawData);}";
                    ScriptEngineManager manager = new ScriptEngineManager();
                    ScriptEngine engine = manager.getEngineByName("javascript");
                    try {
                        engine.eval(dataJS);
                        if (engine instanceof Invocable) {
                            Invocable in = (Invocable) engine;
                            String jsonStr = in.invokeFunction("getData").toString();
                            JSONObject json = JSONObject.fromObject(jsonStr);
                    ScriptEngineManager manager = new ScriptEngineManager();
                    ScriptEngine engine = manager.getEngineByName("javascript");
                    try {
                        engine.eval(dataJS);
                        if (engine instanceof Invocable) {
                            Invocable in = (Invocable) engine;
                            String jsonStr = in.invokeFunction("getData").toString();
                            JSONObject json = JSONObject.fromObject(jsonStr);
                            JSONObject goods = json.optJSONObject("store").optJSONObject("initDataObj")
                                    .optJSONObject("goods");
                            JSONObject goods = json.optJSONObject("store").optJSONObject("initDataObj")
                                    .optJSONObject("goods");
                            String imageData = goods.optString("viewImageData");
                            imageData = imageData.replace("[", "").replace("]", "");
                            String[] images = imageData.split(",");
                            String imageData = goods.optString("viewImageData");
                            imageData = imageData.replace("[", "").replace("]", "");
                            String[] images = imageData.split(",");
                            String image = images[0].trim();
                            if (image.startsWith("\""))
                                image = image.substring(1, image.length() - 1);
                            if (image.endsWith("\""))
                                image = image.substring(0, image.length() - 2);
                            String image = images[0].trim();
                            if (image.startsWith("\""))
                                image = image.substring(1, image.length() - 1);
                            if (image.endsWith("\""))
                                image = image.substring(0, image.length() - 2);
                            PDDGoodsDetail goodsDetail = new PDDGoodsDetail();
                            goodsDetail.setGoodsImageUrl("http:" + image);
                            goodsDetail.setGoodsThumbnailUrl("http:" + image);
                            goodsDetail.setGoodsName(goods.optString("goodsName"));
                            goodsDetail.setGoodsId(goods.optLong("goodsID"));
                            return goodsDetail;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                }
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return null;
    }
                            PDDGoodsDetail goodsDetail = new PDDGoodsDetail();
                            goodsDetail.setGoodsImageUrl("http:" + image);
                            goodsDetail.setGoodsThumbnailUrl("http:" + image);
                            goodsDetail.setGoodsName(goods.optString("goodsName"));
                            goodsDetail.setGoodsId(goods.optLong("goodsID"));
                            return goodsDetail;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                }
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return null;
    }
    public static List<String> getPDDShortLinksFromText(String text) {
        String regex = "(https://p\\.pinduoduo\\.com/)[0-9A-Za-z]{1,20}";
        Pattern pattern = Pattern.compile(regex);
        Matcher m = pattern.matcher(text);
        List<String> urlList = new ArrayList<>();
        while (m.find()) {
            urlList.add(m.group());
        }
        return urlList;
    }
    public static List<String> getPDDShortLinksFromText(String text) {
        String regex = "(https://p\\.pinduoduo\\.com/)[0-9A-Za-z]{1,20}";
        Pattern pattern = Pattern.compile(regex);
        Matcher m = pattern.matcher(text);
        List<String> urlList = new ArrayList<>();
        while (m.find()) {
            urlList.add(m.group());
        }
        return urlList;
    }
}
fanli/src/main/java/com/yeshi/fanli/util/taobao/TaoKeApiUtil.java
@@ -459,6 +459,8 @@
        if (newGoods != null) {
            goods.setTkRate(newGoods.getTkRate());
            goods.setAuctionUrl(newGoods.getAuctionUrl());
            goods.setCouponLink(newGoods.getCouponLink());
            if (!StringUtil.isNullOrEmpty(newGoods.getCouponInfo())) {
                List<BigDecimal> couponInfo = TaoBaoCouponUtil.getCouponInfo(newGoods.getCouponInfo());
                if (couponInfo != null && couponInfo.size() > 1) {
fanli/src/main/resource/docker-compose-copy.yml
New file
@@ -0,0 +1,25 @@
version: '3'
services:
  jobs:
    restart: always
    image: tomcat:8
    container_name: fanli-job1
    ports:
      - "9081:8080"
      - "9991:9999"
    volumes:
      - "/usr/local/docker/fanli-job1/webapps:/usr/local/tomcat/webapps"
      - "/root/logs/fanli-job1:/usr/local/tomcat/logs"
    command:
      - /bin/bash
      - -c
      - |
        cd /usr/local/tomcat/bin
        if [ $(grep -o "Duser.timezone" catalina.sh |wc -l) -le 0 ] ;then
            #sed -i '127i\JAVA_OPTS=\"-Duser.timezone=GMT+08\"'  catalina.sh
        fi
    logging:
      driver: "json-file"
      options:
        max-size: "1g"
fanli/src/main/resource/docker-compose.yml
New file
@@ -0,0 +1,17 @@
version: '3'
services:
  jobs:
    restart: always
    image: timecat-bj:8
    container_name: fanli-job
    ports:
      - "8081:8080"
      - "9999:9999"
    volumes:
      - "/usr/local/docker/fanli-job/webapps:/usr/local/tomcat/webapps"
      - "/root/logs/fanli-job:/usr/local/tomcat/logs"
    logging:
      driver: "json-file"
      options:
        max-size: "1g"
fanli/src/main/resource/env-dev/mongo.properties
@@ -1,13 +1,13 @@
mongo.dbname=flq
mongo.port=27016
mongo.port=27017
#开发环境
#mongo.host=192.168.1.253
#mongo.username=admin
#mongo.password=123456
#
mongo.host=193.112.35.168
mongo.username=yeshi
mongo.password=Yeshi2016@
mongo.host=192.168.1.253
mongo.username=admin
mongo.password=123456
#mongo.host=193.112.35.168
#mongo.username=yeshi
#mongo.password=Yeshi2016@
mongo.connectionsPerHost=8
mongo.threadsAllowedToBlockForConnectionMultiplier=4
fanli/src/main/resource/env-dev/redis.properties
@@ -1,4 +1,4 @@
redis.addr=192.168.3.253
redis.addr=192.168.1.253
redis.port=6379
redis.auth=123456
#redis.addr=193.112.34.40
fanli/src/main/resource/mapping/hongbao/HongBaoV2CountMapper.xml
@@ -74,7 +74,7 @@
    </sql>
    <sql id="Count_Select_State">
        <if test="state != null and state == 1">  <!-- 未到账 -->
            AND (t.hb_state = 1 or t.hb_state = 2)
            AND (t.hb_state = 1 or t.hb_state = 2  or t.hb_state = 5)
        </if>
        <if test="state != null and state == 2"> <!-- 已到账 -->
            AND t.hb_state = 3
@@ -382,7 +382,7 @@
            </if>
            
            <if test="moneyState != null and moneyState == 1"> <!-- 未到账 -->
                AND (v.hb_state = 1 or v.hb_state = 2)
                AND (v.hb_state = 1 or v.hb_state = 2 or v.hb_state = 5)
            </if>
            <if test="moneyState != null and moneyState == 2"> <!-- 已到账 -->
                AND v.hb_state = 3
fanli/src/main/resource/mapping/hongbao/HongBaoV2Mapper.xml
@@ -177,7 +177,7 @@
        SELECT IF(a.money IS NULL,0,a.money ) FROM (SELECT
        SUM(h.`hb_money`) AS money FROM `yeshi_ec_hongbao_v2` h WHERE
        h.`hb_uid`=#{0}
        AND (h.`hb_state`=1 OR h.hb_state=2 )AND
        AND (h.`hb_state`=1 OR h.hb_state=2 OR h.hb_state=5 )AND
        (h.`hb_type`=20 OR h.`hb_type`=21 OR
        h.`hb_type`=22 OR h.`hb_type`=6 OR
        h.`hb_type`=7)) a
@@ -473,6 +473,15 @@
        LIMIT 1
    </select>
    <update id="setHongBaoRecieved" >
        update yeshi_ec_hongbao_v2 v set v.hb_state=3 ,v.hb_update_time=NOW() where v.hb_uid=#{uid} and v.hb_state=5 and v.hb_pre_get_time=#{preGetTime}
        <if test="typeList!=null">
            <foreach collection="typeList" item="type" open=" and (" separator=" or " close=")">
                v.hb_type=#{type}
            </foreach>
        </if>
    </update>
    <delete id="deleteByPrimaryKey" parameterType="java.lang.Long">delete from
        yeshi_ec_hongbao_v2 where hb_id = #{id,jdbcType=BIGINT}
    </delete>
fanli/src/main/resource/mapping/order/CommonOrderCountMapper.xml
@@ -3,188 +3,191 @@
<mapper namespace="com.yeshi.fanli.dao.mybatis.order.CommonOrderCountMapper">
    <resultMap id="ChartMap" type="com.yeshi.fanli.dto.ChartTDO">
        <result column="showDate" property="showDate" jdbcType="VARCHAR" />
        <result column="showValue" property="showValue" jdbcType="VARCHAR" />
    </resultMap>
        <result column="showDate" property="showDate" jdbcType="VARCHAR"/>
        <result column="showValue" property="showValue" jdbcType="VARCHAR"/>
    </resultMap>
     <resultMap id="CountOrderMap" type="com.yeshi.fanli.dto.order.CountOrderDTO">
        <result column="uid" property="uid" jdbcType="BIGINT" />
        <result column="totalOrder" property="totalOrder" jdbcType="INTEGER" />
        <result column="commission" property="commission" jdbcType="DECIMAL" />
    </resultMap>
    <sql id="Column_DateType">
        <if test="dateType == 1">
            DATE_FORMAT(t.`co_third_create_time`,'%Y-%m-%d') AS 'showDate'
        </if>
        <if test="dateType == 2">
            DATE_FORMAT(t.`co_third_create_time`,'%m') AS 'showDate'
        </if>
        <if test="dateType == 3">
            DATE_FORMAT(t.`co_third_create_time`,'%Y') AS 'showDate'
        </if>
    </sql>
    <resultMap id="CountOrderMap" type="com.yeshi.fanli.dto.order.CountOrderDTO">
        <result column="uid" property="uid" jdbcType="BIGINT"/>
        <result column="totalOrder" property="totalOrder" jdbcType="INTEGER"/>
        <result column="commission" property="commission" jdbcType="DECIMAL"/>
    </resultMap>
    <sql id="Count_Select_DateType">
        <if test="startTime != null and startTime != '' ">
            AND DATE_FORMAT(t.`co_third_create_time`,'%Y-%m-%d')<![CDATA[ >= ]]>'${startTime}'
        </if>
        <if test="endTime != null and endTime != '' ">
            AND DATE_FORMAT(t.`co_third_create_time`,'%Y-%m-%d') <![CDATA[ <= ]]>'${endTime}'
        </if>
        <if test="year != null and year != '' ">
            AND DATE_FORMAT(t.`co_third_create_time`,'%Y') = '${year}'
        </if>
    </sql>
    <sql id="Column_DateType">
        <if test="dateType == 1">
            DATE_FORMAT(t.`co_third_create_time`,'%Y-%m-%d') AS 'showDate'
        </if>
        <if test="dateType == 2">
            DATE_FORMAT(t.`co_third_create_time`,'%m') AS 'showDate'
        </if>
        <if test="dateType == 3">
            DATE_FORMAT(t.`co_third_create_time`,'%Y') AS 'showDate'
        </if>
    </sql>
    <sql id="Count_Group_DateType">
        <if test="dateType == 1">
            GROUP BY DATE_FORMAT(t.`co_third_create_time`,'%Y-%m-%d')
        </if>
        <if test="dateType == 2">
            GROUP BY DATE_FORMAT(t.`co_third_create_time`,'%Y-%m')
        </if>
        <if test="dateType == 3">
            GROUP BY DATE_FORMAT(t.`co_third_create_time`,'%Y')
        </if>
    </sql>
    <sql id="Count_Select_DateType">
        <if test="startTime != null and startTime != '' ">
            AND DATE_FORMAT(t.`co_third_create_time`,'%Y-%m-%d')<![CDATA[ >= ]]>'${startTime}'
        </if>
        <if test="endTime != null and endTime != '' ">
            AND DATE_FORMAT(t.`co_third_create_time`,'%Y-%m-%d') <![CDATA[ <= ]]>'${endTime}'
        </if>
        <if test="year != null and year != '' ">
            AND DATE_FORMAT(t.`co_third_create_time`,'%Y') = '${year}'
        </if>
    </sql>
    <select id="countByState" resultType="java.lang.Long">
        SELECT IFNULL(COUNT(t.`co_id`),0) FROM  `yeshi_ec_common_order` t
        WHERE 1=1
            <if test="type != null">
                AND t.`co_state` = #{state}
            </if>
    </select>
    <select id="countOrderBySourceTypeAndDay" resultType="java.lang.Long">
    <sql id="Count_Group_DateType">
        <if test="dateType == 1">
            GROUP BY DATE_FORMAT(t.`co_third_create_time`,'%Y-%m-%d')
        </if>
        <if test="dateType == 2">
            GROUP BY DATE_FORMAT(t.`co_third_create_time`,'%Y-%m')
        </if>
        <if test="dateType == 3">
            GROUP BY DATE_FORMAT(t.`co_third_create_time`,'%Y')
        </if>
    </sql>
    <select id="countByState" resultType="java.lang.Long">
        SELECT IFNULL(COUNT(t.`co_id`),0) FROM `yeshi_ec_common_order` t
        WHERE 1=1
        <if test="type != null">
            AND t.`co_state` = #{state}
        </if>
    </select>
    <select id="countOrderBySourceTypeAndDay" resultType="java.lang.Long">
        SELECT COUNT(t.`co_id`) FROM `yeshi_ec_common_order` t 
        WHERE t.co_source_type=#{sourceType} AND DATE_FORMAT(t.`co_third_create_time`,'%Y-%m-%d') = #{preDay}
    </select>
    <select id="countOrderNumber" resultMap="ChartMap">
        SELECT IFNULL(COUNT(t.`co_id`),0) AS showValue,<include refid="Column_DateType"/>
        FROM `yeshi_ec_common_order` t
        WHERE t.co_source_type=#{sourceType} and t.`co_third_create_time` IS NOT NULL <include refid="Count_Select_DateType"/>
        <include refid="Count_Group_DateType"/>
        ORDER BY t.`co_third_create_time`
    </select>
    <select id="countOrderNumberBySettleTime" resultType="java.util.HashMap">
        <!-- 统计历史订单数量  根据结算时间 -->
        SELECT SUM(A.self)AS totalSelf,SUM(A.shared)AS totalShared,SUM(A.invite)AS totalInvite
        FROM (
            <!-- 返利订单 -->
            SELECT IFNULL(COUNT(ho_id),0) AS self,0 AS shared,0 AS invite
            FROM  (SELECT ho.`ho_id` FROM yeshi_ec_hongbao_order ho
                LEFT JOIN (
                    SELECT * FROM yeshi_ec_hongbao_v2 v2
                    WHERE v2.`hb_uid`= ${uid} and v2.hb_state!=4 AND (v2.`hb_type` = 1 OR v2.`hb_type` = 2)
                    ) hb  ON hb.hb_id=ho.`ho_hongbao_id` <!-- 自购订单 -->
            LEFT JOIN yeshi_ec_common_order co ON co.`co_id`=ho.`ho_order_id`
            WHERE hb.hb_id IS NOT NULL
                 <if test="state != null">
                    AND co.`co_state` = ${state}
                </if>
                <if test="day != null and day == 1"> <!-- 今天 -->
                    AND TO_DAYS(co.`co_settle_time`) = TO_DAYS(NOW())
                </if>
                <if test="day != null and day == 2">  <!-- 昨天 -->
                    AND TO_DAYS(NOW()) - TO_DAYS(co.co_settle_time) = 1
                </if>
                <if test="day != null and day == 3">  <!-- 本月 -->
                    AND DATE_FORMAT(co.`co_settle_time`,'%Y%m') =
                    DATE_FORMAT(CURDATE(),'%Y%m')
                </if>
                <if test="day != null and day == 4">  <!-- 上月 -->
                    AND PERIOD_DIFF(DATE_FORMAT(NOW(), '%Y%m'),
                    DATE_FORMAT(co.`co_settle_time`, '%Y%m')) = 1
                </if>
            GROUP BY co.`co_order_no`, co.`co_source_type`)YX
            UNION ALL
            <!-- 分享订单 -->
            SELECT 0 AS self,IFNULL(COUNT(ho_id),0) AS shared,0 AS invite
            FROM  (SELECT ho.`ho_id` FROM yeshi_ec_hongbao_order ho
                    LEFT JOIN (
                        SELECT * FROM yeshi_ec_hongbao_v2 v2
                        WHERE v2.`hb_uid`= ${uid} AND v2.`hb_type` = 20 and v2.hb_state!=4
                    ) hb  ON hb.hb_id=ho.`ho_hongbao_id`  <!-- 分享订单 -->
                LEFT JOIN yeshi_ec_common_order co ON co.`co_id`=ho.`ho_order_id`
                WHERE hb.hb_id IS NOT NULL and hb.hb_state!=4
                    <if test="state != null">
                        AND co.`co_state` = ${state}
                    </if>
                    <if test="day != null and day == 1"> <!-- 今天 -->
                        AND TO_DAYS(co.`co_settle_time`) = TO_DAYS(NOW())
                    </if>
                    <if test="day != null and day == 2">  <!-- 昨天 -->
                        AND TO_DAYS(NOW()) - TO_DAYS(co.`co_settle_time`) = 1
                    </if>
                    <if test="day != null and day == 3">  <!-- 本月 -->
                        AND DATE_FORMAT(co.`co_settle_time`,'%Y%m') =
                        DATE_FORMAT(CURDATE(),'%Y%m')
                    </if>
                    <if test="day != null and day == 4">  <!-- 上月 -->
                        AND PERIOD_DIFF(DATE_FORMAT(NOW(), '%Y%m'),
                        DATE_FORMAT(co.`co_settle_time`, '%Y%m')) = 1
                    </if>
                GROUP BY co.`co_order_no`, co.`co_source_type`)WQ
            UNION ALL
            <!-- 邀请订单 -->
            SELECT 0 AS self,0 AS shared,IFNULL(COUNT(ho_id),0) AS invite
            FROM  (SELECT ho.`ho_id` FROM yeshi_ec_hongbao_order ho
                LEFT JOIN (
                    SELECT * FROM yeshi_ec_hongbao_v2 v2
                    WHERE v2.`hb_uid`= ${uid}
                         AND (v2.`hb_type` = 5 OR v2.`hb_type` = 6 OR v2.`hb_type` = 7
                               OR v2.`hb_type` = 21 OR v2.`hb_type` = 22 ) and v2.hb_state!=4
                    ) hbp  ON hbp.hb_pid=ho.`ho_hongbao_id`
                LEFT JOIN yeshi_ec_common_order co ON co.`co_id`=ho.`ho_order_id`
                WHERE  hbp.hb_id IS NOT NULL and hbp.hb_state!=4
                    <if test="state != null">
                        AND co.`co_state` = ${state}
                    </if>
                    <if test="day != null and day == 1"> <!-- 今天 -->
                        AND TO_DAYS(co.`co_settle_time`) = TO_DAYS(NOW())
                    </if>
                    <if test="day != null and day == 2">  <!-- 昨天 -->
                        AND TO_DAYS(NOW()) - TO_DAYS(co.`co_settle_time`) = 1
                    </if>
                    <if test="day != null and day == 3">  <!-- 本月 -->
                        AND DATE_FORMAT(co.`co_settle_time`,'%Y%m') =
                        DATE_FORMAT(CURDATE(),'%Y%m')
                    </if>
                    <if test="day != null and day == 4">  <!-- 上月 -->
                        AND PERIOD_DIFF(DATE_FORMAT(NOW(), '%Y%m'),
                        DATE_FORMAT(co.`co_settle_time`, '%Y%m')) = 1
                    </if>
                GROUP BY co.`co_order_no`, co.`co_source_type`)SX
        )A
    </select>
    <select id="countValidOrder" resultType="java.lang.Long">
    <select id="countOrderNumber" resultMap="ChartMap">
        SELECT IFNULL(COUNT(t.`co_id`),0) AS showValue,
        <include refid="Column_DateType"/>
        FROM `yeshi_ec_common_order` t
        WHERE t.co_source_type=#{sourceType} and t.`co_third_create_time` IS NOT NULL
        <include refid="Count_Select_DateType"/>
        <include refid="Count_Group_DateType"/>
        ORDER BY t.`co_third_create_time`
    </select>
    <select id="countOrderNumberBySettleTime" resultType="java.util.HashMap">
        <!-- 统计历史订单数量  根据结算时间 -->
        SELECT SUM(A.self)AS totalSelf,SUM(A.shared)AS totalShared,SUM(A.invite)AS totalInvite
        FROM (
        <!-- 返利订单 -->
        SELECT IFNULL(COUNT(ho_id),0) AS self,0 AS shared,0 AS invite
        FROM (SELECT ho.`ho_id` FROM yeshi_ec_hongbao_order ho
        LEFT JOIN (
        SELECT * FROM yeshi_ec_hongbao_v2 v2
        WHERE v2.`hb_uid`= ${uid} and v2.hb_state!=4 AND (v2.`hb_type` = 1 OR v2.`hb_type` = 2)
        ) hb ON hb.hb_id=ho.`ho_hongbao_id` <!-- 自购订单 -->
        LEFT JOIN yeshi_ec_common_order co ON co.`co_id`=ho.`ho_order_id`
        WHERE hb.hb_id IS NOT NULL
        <if test="state != null">
            AND co.`co_state` = ${state}
        </if>
        <if test="day != null and day == 1"> <!-- 今天 -->
            AND TO_DAYS(co.`co_settle_time`) = TO_DAYS(NOW())
        </if>
        <if test="day != null and day == 2">  <!-- 昨天 -->
            AND TO_DAYS(NOW()) - TO_DAYS(co.co_settle_time) = 1
        </if>
        <if test="day != null and day == 3">  <!-- 本月 -->
            AND DATE_FORMAT(co.`co_settle_time`,'%Y%m') =
            DATE_FORMAT(CURDATE(),'%Y%m')
        </if>
        <if test="day != null and day == 4">  <!-- 上月 -->
            AND PERIOD_DIFF(DATE_FORMAT(NOW(), '%Y%m'),
            DATE_FORMAT(co.`co_settle_time`, '%Y%m')) = 1
        </if>
        GROUP BY co.`co_order_no`, co.`co_source_type`)YX
        UNION ALL
        <!-- 分享订单 -->
        SELECT 0 AS self,IFNULL(COUNT(ho_id),0) AS shared,0 AS invite
        FROM (SELECT ho.`ho_id` FROM yeshi_ec_hongbao_order ho
        LEFT JOIN (
        SELECT * FROM yeshi_ec_hongbao_v2 v2
        WHERE v2.`hb_uid`= ${uid} AND v2.`hb_type` = 20 and v2.hb_state!=4
        ) hb ON hb.hb_id=ho.`ho_hongbao_id`  <!-- 分享订单 -->
        LEFT JOIN yeshi_ec_common_order co ON co.`co_id`=ho.`ho_order_id`
        WHERE hb.hb_id IS NOT NULL and hb.hb_state!=4
        <if test="state != null">
            AND co.`co_state` = ${state}
        </if>
        <if test="day != null and day == 1"> <!-- 今天 -->
            AND TO_DAYS(co.`co_settle_time`) = TO_DAYS(NOW())
        </if>
        <if test="day != null and day == 2">  <!-- 昨天 -->
            AND TO_DAYS(NOW()) - TO_DAYS(co.`co_settle_time`) = 1
        </if>
        <if test="day != null and day == 3">  <!-- 本月 -->
            AND DATE_FORMAT(co.`co_settle_time`,'%Y%m') =
            DATE_FORMAT(CURDATE(),'%Y%m')
        </if>
        <if test="day != null and day == 4">  <!-- 上月 -->
            AND PERIOD_DIFF(DATE_FORMAT(NOW(), '%Y%m'),
            DATE_FORMAT(co.`co_settle_time`, '%Y%m')) = 1
        </if>
        GROUP BY co.`co_order_no`, co.`co_source_type`)WQ
        UNION ALL
        <!-- 邀请订单 -->
        SELECT 0 AS self,0 AS shared,IFNULL(COUNT(ho_id),0) AS invite
        FROM (SELECT ho.`ho_id` FROM yeshi_ec_hongbao_order ho
        LEFT JOIN (
        SELECT * FROM yeshi_ec_hongbao_v2 v2
        WHERE v2.`hb_uid`= ${uid}
        AND (v2.`hb_type` = 5 OR v2.`hb_type` = 6 OR v2.`hb_type` = 7
        OR v2.`hb_type` = 21 OR v2.`hb_type` = 22 ) and v2.hb_state!=4
        ) hbp ON hbp.hb_pid=ho.`ho_hongbao_id`
        LEFT JOIN yeshi_ec_common_order co ON co.`co_id`=ho.`ho_order_id`
        WHERE hbp.hb_id IS NOT NULL and hbp.hb_state!=4
        <if test="state != null">
            AND co.`co_state` = ${state}
        </if>
        <if test="day != null and day == 1"> <!-- 今天 -->
            AND TO_DAYS(co.`co_settle_time`) = TO_DAYS(NOW())
        </if>
        <if test="day != null and day == 2">  <!-- 昨天 -->
            AND TO_DAYS(NOW()) - TO_DAYS(co.`co_settle_time`) = 1
        </if>
        <if test="day != null and day == 3">  <!-- 本月 -->
            AND DATE_FORMAT(co.`co_settle_time`,'%Y%m') =
            DATE_FORMAT(CURDATE(),'%Y%m')
        </if>
        <if test="day != null and day == 4">  <!-- 上月 -->
            AND PERIOD_DIFF(DATE_FORMAT(NOW(), '%Y%m'),
            DATE_FORMAT(co.`co_settle_time`, '%Y%m')) = 1
        </if>
        GROUP BY co.`co_order_no`, co.`co_source_type`)SX
        )A
    </select>
    <select id="countValidOrder" resultType="java.lang.Long">
        SELECT IFNULL(COUNT(co.`co_id`),0) FROM yeshi_ec_hongbao_order ho 
        LEFT JOIN (SELECT * FROM yeshi_ec_hongbao_v2 v2 
            WHERE v2.`hb_uid`= #{uid}  AND v2.`hb_type` IN(1,20))hb 
            ON IF(hb.hb_pid IS NULL,hb.hb_id,hb.hb_pid)=ho.`ho_hongbao_id`
        LEFT JOIN yeshi_ec_common_order co ON co.`co_id`=ho.`ho_order_id`
        WHERE hb.hb_id IS NOT NULL AND <![CDATA[co.`co_state` <> 4]]>
    </select>
    <select id="getMoneyByOrderNo" resultType="java.math.BigDecimal">
        WHERE hb.hb_id IS NOT NULL AND <![CDATA[co.`co_state` <> 4
        ]]>
    </select>
    <select id="getMoneyByOrderNo" resultType="java.math.BigDecimal">
        SELECT SUM(v2.`hb_money`) FROM yeshi_ec_common_order co 
        LEFT JOIN  yeshi_ec_hongbao_order ho ON co.`co_id`=ho.`ho_order_id`
        LEFT JOIN yeshi_ec_hongbao_v2 v2 ON  v2.hb_id=ho.`ho_hongbao_id` 
        WHERE co.`co_order_no` = #{orderNo}
    </select>
    <select id="countValidOrderByDate" resultType="Long">
    <select id="countValidOrderByDate" resultType="Long">
        SELECT IFNULL(COUNT(co_order_no),0) FROM
            (SELECT DISTINCT co.co_order_no FROM yeshi_ec_common_order co 
             LEFT JOIN  yeshi_ec_hongbao_order ho ON co.`co_id`=ho.`ho_order_id`
@@ -192,107 +195,168 @@
             WHERE co.`co_uid` = #{uid} AND v2.`hb_type` = 1 
                   AND v2.`hb_state` = 3 AND  AND co.`co_third_create_time` <![CDATA[>]]> #{dateTime})A
    </select>
    <select id="countSameShopOrderByUidAndHongBaoType" resultType="Long">
        SELECT COUNT(*) FROM
        (
            SELECT a.*,COUNT(*) AS num FROM
            (
                SELECT co.*,COUNT(*) AS c,g.`cog_shop_id` AS shopId FROM yeshi_ec_common_order co
                LEFT JOIN yeshi_ec_hongbao_order ho ON co.`co_id`=ho.`ho_order_id`
                LEFT JOIN yeshi_ec_hongbao_v2 v ON v.`hb_id`=ho.`ho_hongbao_id`
                LEFT JOIN yeshi_ec_common_order_goods g  ON co.`co_order_goods_id`=g.`cog_id`
                WHERE  co.`co_uid`=#{uid}  AND g.`cog_shop_id` <![CDATA[<>]]> 725677994  <!-- 天猫超市 -->
                <if test="typeList!=null">
                    <foreach collection="typeList" item="type" open=" and (" separator=" or " close=")">
                        v.`hb_type`=#{type}
                    </foreach>
                </if>
                AND v.`hb_id` IS NOT NULL
                AND (co.`co_state`=1 OR  co.`co_state`=2 OR co.`co_state`=3)
                AND g.`cog_shop_id`>0 GROUP BY co.`co_order_no`,co.`co_source_type`
            ) a GROUP BY a.shopId
        ) b WHERE b.num>=#{minSameShopGoodsCount};
    </select>
    <select id="countSameGoodsOrderByUidAndHongBaoType" resultType="Long">
        SELECT COUNT(*) FROM
        (
            SELECT a.goodsId,COUNT(*) AS c FROM
            (
                SELECT co.`co_order_goods_id` AS goodsId,co.`co_order_no` FROM yeshi_ec_common_order co
                LEFT JOIN yeshi_ec_hongbao_order ho ON co.`co_id`=ho.`ho_order_id`
                LEFT JOIN yeshi_ec_hongbao_v2 v ON v.`hb_id`=ho.`ho_hongbao_id`
                LEFT JOIN yeshi_ec_common_order_goods g  ON co.`co_order_goods_id`=g.`cog_id`
                WHERE co.`co_uid`=#{uid} AND g.`cog_shop_id` <![CDATA[<>]]> 725677994  <!-- 天猫超市 -->
                <if test="typeList!=null">
                    <foreach collection="typeList" item="type" open=" and (" separator=" or " close=")">
                        v.`hb_type`=#{type}
                    </foreach>
                </if>
                AND v.`hb_id` IS NOT NULL
                AND (co.`co_state`=1 OR  co.`co_state`=2 OR co.`co_state`=3)
                GROUP BY co.`co_order_no`,co.`co_order_goods_id`
            ) a GROUP BY goodsId
        ) b WHERE b.c>=#{minSameGoodsOrderCount}
    </select>
    <select id="getSameShopOrderByUidAndHongBaoType" resultType="Long">
        SELECT b.shopId FROM
        (
            SELECT a.*,COUNT(*) AS num FROM
            (
                SELECT co.*,COUNT(*) AS c,g.`cog_shop_id` AS shopId FROM yeshi_ec_common_order co
                LEFT JOIN yeshi_ec_hongbao_order ho ON co.`co_id`=ho.`ho_order_id`
                LEFT JOIN yeshi_ec_hongbao_v2 v ON v.`hb_id`=ho.`ho_hongbao_id`
                LEFT JOIN yeshi_ec_common_order_goods g  ON co.`co_order_goods_id`=g.`cog_id`
                WHERE  co.`co_uid`=#{uid} AND g.`cog_shop_id` <![CDATA[<>]]> 725677994  <!-- 天猫超市 -->
                <if test="typeList!=null">
                    <foreach collection="typeList" item="type" open=" and (" separator=" or " close=")">
                        v.`hb_type`=#{type}
                    </foreach>
                </if>
                AND v.`hb_id` IS NOT NULL
                AND (co.`co_state`=1 OR  co.`co_state`=2 OR co.`co_state`=3)
                AND g.`cog_shop_id`>0 GROUP BY co.`co_order_no`,co.`co_source_type`
            ) a GROUP BY a.shopId
        ) b WHERE b.num>=#{minSameShopGoodsCount};
    </select>
    <select id="getSameGoodsOrderByUidAndHongBaoType" resultType="Long">
        SELECT b.goodsId FROM
        (
            SELECT a.goodsId,COUNT(*) AS c FROM
            (
                SELECT co.`co_order_goods_id` AS goodsId,co.`co_order_no` FROM yeshi_ec_common_order co
                LEFT JOIN yeshi_ec_hongbao_order ho ON co.`co_id`=ho.`ho_order_id`
                LEFT JOIN yeshi_ec_hongbao_v2 v ON v.`hb_id`=ho.`ho_hongbao_id`
                LEFT JOIN yeshi_ec_common_order_goods g  ON co.`co_order_goods_id`=g.`cog_id`
                WHERE co.`co_uid`=#{uid} AND g.`cog_shop_id` <![CDATA[<>]]> 725677994  <!-- 天猫超市 -->
                <if test="typeList!=null">
                    <foreach collection="typeList" item="type" open=" and (" separator=" or " close=")">
                        v.`hb_type`=#{type}
                    </foreach>
                </if>
                AND v.`hb_id` IS NOT NULL
                AND (co.`co_state`=1 OR  co.`co_state`=2 OR co.`co_state`=3)
                GROUP BY co.`co_order_no`,co.`co_order_goods_id`
            ) a GROUP BY goodsId
        ) b WHERE b.c>=#{minSameGoodsOrderCount}
    </select>
    <select id="countOderByUidAndDate" resultType="Integer">
    <select id="countSameShopOrderByUidAndHongBaoType" resultType="Long">
        SELECT COUNT(*) FROM
        (
        SELECT a.*,COUNT(*) AS num FROM
        (
        SELECT co.*,COUNT(*) AS c,g.`cog_shop_id` AS shopId FROM yeshi_ec_common_order co
        LEFT JOIN yeshi_ec_hongbao_order ho ON co.`co_id`=ho.`ho_order_id`
        LEFT JOIN yeshi_ec_hongbao_v2 v ON v.`hb_id`=ho.`ho_hongbao_id`
        LEFT JOIN yeshi_ec_common_order_goods g ON co.`co_order_goods_id`=g.`cog_id`
        WHERE co.`co_uid`=#{uid} AND g.`cog_shop_id` <![CDATA[<>]]> 725677994  <!-- 天猫超市 -->
        <if test="typeList!=null">
            <foreach collection="typeList" item="type" open=" and (" separator=" or " close=")">
                v.`hb_type`=#{type}
            </foreach>
        </if>
        AND v.`hb_id` IS NOT NULL
        AND (co.`co_state`=1 OR co.`co_state`=2 OR co.`co_state`=3)
        AND g.`cog_shop_id`>0
        <if test="minDate!=null">
           and co.co_third_create_time>=#{minDate}
        </if>
        GROUP BY co.`co_order_no`,co.`co_source_type`
        ) a GROUP BY a.shopId
        ) b WHERE b.num>=#{minSameShopGoodsCount};
    </select>
    <select id="countSameGoodsOrderByUidAndHongBaoType" resultType="Long">
        SELECT COUNT(*) FROM
        (
        SELECT a.goodsId,COUNT(*) AS c FROM
        (
        SELECT co.`co_order_goods_id` AS goodsId,co.`co_order_no` FROM yeshi_ec_common_order co
        LEFT JOIN yeshi_ec_hongbao_order ho ON co.`co_id`=ho.`ho_order_id`
        LEFT JOIN yeshi_ec_hongbao_v2 v ON v.`hb_id`=ho.`ho_hongbao_id`
        LEFT JOIN yeshi_ec_common_order_goods g ON co.`co_order_goods_id`=g.`cog_id`
        WHERE co.`co_uid`=#{uid}
        <if test="excludeShopIds!=null">
            <foreach collection="excludeShopIds" item="shopId" separator=" and " open="and (" close=")">
                g.`cog_shop_id` != #{shopId}
            </foreach>
        </if>
        <!-- 天猫超市 -->
        <if test="typeList!=null">
            <foreach collection="typeList" item="type" open=" and (" separator=" or " close=")">
                v.`hb_type`=#{type}
            </foreach>
        </if>
        AND v.`hb_id` IS NOT NULL
        AND (co.`co_state`=1 OR co.`co_state`=2 OR co.`co_state`=3)
        <if test="minDate!=null">
            AND co.co_third_create_time>=#{minDate}
        </if>
        GROUP BY co.`co_order_no`,co.`co_order_goods_id`
        ) a GROUP BY goodsId
        ) b WHERE b.c>=#{minSameGoodsOrderCount}
    </select>
    <select id="listSameGoodsIdByUidAndHongBaoType" resultType="Long">
        SELECT b.goodsId FROM
        (
            SELECT a.goodsId,COUNT(*) AS c FROM
            (
            SELECT co.`co_order_goods_id` AS goodsId,co.`co_order_no` FROM yeshi_ec_common_order co
            LEFT JOIN yeshi_ec_hongbao_order ho ON co.`co_id`=ho.`ho_order_id`
            LEFT JOIN yeshi_ec_hongbao_v2 v ON v.`hb_id`=ho.`ho_hongbao_id`
            LEFT JOIN yeshi_ec_common_order_goods g ON co.`co_order_goods_id`=g.`cog_id`
            WHERE co.`co_uid`=#{uid}
            <if test="excludeShopIds!=null">
                <foreach collection="excludeShopIds" item="shopId" separator=" and " open="and (" close=")">
                    g.`cog_shop_id` != #{shopId}
                </foreach>
            </if>
            <!-- 天猫超市 -->
            <if test="typeList!=null">
                <foreach collection="typeList" item="type" open=" and (" separator=" or " close=")">
                    v.`hb_type`=#{type}
                </foreach>
            </if>
            AND v.`hb_id` IS NOT NULL
            AND (co.`co_state`=1 OR co.`co_state`=2 OR co.`co_state`=3)
            <if test="minDate!=null">
                AND co.co_third_create_time>=#{minDate}
            </if>
            GROUP BY co.`co_order_no`,co.`co_order_goods_id`
            ) a GROUP BY goodsId
        ) b WHERE b.c>=#{minSameGoodsOrderCount}
    </select>
    <select id="getSameShopOrderByUidAndHongBaoType" resultType="Long">
        SELECT b.shopId FROM
        (
        SELECT a.*,COUNT(*) AS num FROM
        (
        SELECT co.*,COUNT(*) AS c,g.`cog_shop_id` AS shopId FROM yeshi_ec_common_order co
        LEFT JOIN yeshi_ec_hongbao_order ho ON co.`co_id`=ho.`ho_order_id`
        LEFT JOIN yeshi_ec_hongbao_v2 v ON v.`hb_id`=ho.`ho_hongbao_id`
        LEFT JOIN yeshi_ec_common_order_goods g ON co.`co_order_goods_id`=g.`cog_id`
        WHERE co.`co_uid`=#{uid}
        <if test="excludeShopIds!=null">
            <foreach collection="excludeShopIds" item="shopId" separator=" and " open="and (" close=")">
                g.`cog_shop_id` != #{shopId}
            </foreach>
        </if>
        <if test="typeList!=null">
            <foreach collection="typeList" item="type" open=" and (" separator=" or " close=")">
                v.`hb_type`=#{type}
            </foreach>
        </if>
        AND v.`hb_id` IS NOT NULL
        AND (co.`co_state`=1 OR co.`co_state`=2 OR co.`co_state`=3)
        AND g.`cog_shop_id`>0 GROUP BY co.`co_order_no`,co.`co_source_type`
        ) a GROUP BY a.shopId
        ) b WHERE b.num>=#{minSameShopGoodsCount};
    </select>
    <select id="getSameGoodsOrderByUidAndHongBaoType" resultType="Long">
        SELECT b.goodsId FROM
        (
        SELECT a.goodsId,COUNT(*) AS c FROM
        (
        SELECT co.`co_order_goods_id` AS goodsId,co.`co_order_no` FROM yeshi_ec_common_order co
        LEFT JOIN yeshi_ec_hongbao_order ho ON co.`co_id`=ho.`ho_order_id`
        LEFT JOIN yeshi_ec_hongbao_v2 v ON v.`hb_id`=ho.`ho_hongbao_id`
        LEFT JOIN yeshi_ec_common_order_goods g ON co.`co_order_goods_id`=g.`cog_id`
        WHERE co.`co_uid`=#{uid} AND g.`cog_shop_id` <![CDATA[<>]]> 725677994  <!-- 天猫超市 -->
        <if test="typeList!=null">
            <foreach collection="typeList" item="type" open=" and (" separator=" or " close=")">
                v.`hb_type`=#{type}
            </foreach>
        </if>
        AND v.`hb_id` IS NOT NULL
        AND (co.`co_state`=1 OR co.`co_state`=2 OR co.`co_state`=3)
        GROUP BY co.`co_order_no`,co.`co_order_goods_id`
        ) a GROUP BY goodsId
        ) b WHERE b.c>=#{minSameGoodsOrderCount}
    </select>
    <select id="countOderByUidAndDate" resultType="Integer">
        SELECT COUNT(1) FROM (SELECT d.`co_id` FROM `yeshi_ec_common_order` d
        WHERE d.`co_third_create_time`<![CDATA[<=]]> #{preDay} AND d.`co_uid` = #{uid} 
              AND (d.`co_state`=1 OR d.`co_state`=2) 
        GROUP BY d.`co_order_no`,d.`co_source_type`)A
    </select>
    <select id="countValidOrderByDay" resultMap="CountOrderMap">
    <select id="countValidOrderByDay" resultMap="CountOrderMap">
        SELECT co_uid AS uid ,totalOrder FROM (
            SELECT COUNT(d.`co_id`) AS totalOrder,d.`co_uid` FROM `yeshi_ec_common_order` d
            WHERE DATE_FORMAT(d.`co_third_create_time`,'%Y-%m-%d') = #{preDay} 
@@ -300,73 +364,73 @@
            GROUP BY d.`co_order_no`,d.`co_source_type`)A
        GROUP BY co_uid
    </select>
    <select id="getUidByValidOrderByDay"  resultType="Long">
    <select id="getUidByValidOrderByDay" resultType="Long">
        SELECT DISTINCT d.`co_uid` FROM `yeshi_ec_common_order` d
        WHERE TO_DAYS(co_third_create_time) = TO_DAYS(#{preDay}) AND (d.`co_state`=1 OR d.`co_state`=2)  
        GROUP BY d.`co_order_no`,d.`co_source_type`
    </select>
    <select id="countDownOrderUserByUidAndDate" resultType="Integer">
        SELECT COUNT(DISTINCT d.`co_uid`) FROM `yeshi_ec_common_order` d
        WHERE  d.`co_third_create_time`<![CDATA[<=]]> #{preDay} AND (d.`co_state`=1 OR d.`co_state`=2)
        <foreach collection="list" item="uid" open="AND (" separator="OR" close=")" >
            d.`co_uid` = #{uid}
        </foreach>
    </select>
    <select id="getDownOrderUserByListUidAndDate" resultType="Long">
        SELECT  d.`co_uid` FROM `yeshi_ec_common_order` d
        WHERE  d.`co_third_create_time`<![CDATA[<=]]> #{preDay} AND (d.`co_state`=1 OR d.`co_state`=2)
        <foreach collection="list" item="uid" open="AND (" separator="OR" close=")" >
            d.`co_uid` = #{uid}
        </foreach>
        GROUP BY d.`co_order_no`,d.`co_source_type`
    </select>
    <select id="countCommissionByDay" resultMap="CountOrderMap">
    <select id="countDownOrderUserByUidAndDate" resultType="Integer">
        SELECT COUNT(DISTINCT d.`co_uid`) FROM `yeshi_ec_common_order` d
        WHERE d.`co_third_create_time`<![CDATA[<=]]> #{preDay} AND (d.`co_state`=1 OR d.`co_state`=2)
        <foreach collection="list" item="uid" open="AND (" separator="OR" close=")">
            d.`co_uid` = #{uid}
        </foreach>
    </select>
    <select id="getDownOrderUserByListUidAndDate" resultType="Long">
        SELECT d.`co_uid` FROM `yeshi_ec_common_order` d
        WHERE d.`co_third_create_time`<![CDATA[<=]]> #{preDay} AND (d.`co_state`=1 OR d.`co_state`=2)
        <foreach collection="list" item="uid" open="AND (" separator="OR" close=")">
            d.`co_uid` = #{uid}
        </foreach>
        GROUP BY d.`co_order_no`,d.`co_source_type`
    </select>
    <select id="countCommissionByDay" resultMap="CountOrderMap">
        SELECT  SUM(IF(d.`co_eIncome` >0,d.`co_eIncome`,d.`co_estimate`)) AS commission,d.co_uid as uid FROM `yeshi_ec_common_order` d 
        WHERE TO_DAYS(d.`co_third_create_time`)= TO_DAYS(#{preDay}) AND (d.`co_state`=1 OR d.`co_state`=2)
        GROUP BY d.co_uid
    </select>
    <select id="countOderByDate" resultType="Integer">
    <select id="countOderByDate" resultType="Integer">
        SELECT COUNT(co_id) FROM (SELECT d.`co_id` FROM `yeshi_ec_common_order` d
        WHERE TO_DAYS(d.`co_third_create_time`)= TO_DAYS(#{preDay}) AND (d.`co_state`=1 OR d.`co_state`=2) 
        GROUP BY d.`co_order_no`,d.`co_source_type`)A
    </select>
    <select id="countCommissionByDate" resultType="BigDecimal">
    <select id="countCommissionByDate" resultType="BigDecimal">
        SELECT SUM(IF(d.`co_eIncome` >0,d.`co_eIncome`,d.`co_estimate`)) FROM `yeshi_ec_common_order` d
        WHERE TO_DAYS(d.`co_third_create_time`)= TO_DAYS(#{preDay}) AND (d.`co_state`=1 OR d.`co_state`=2)  
    </select>
    <select id="countOderByUidAndLess10" resultType="Integer">
    <select id="countOderByUidAndLess10" resultType="Integer">
        SELECT count(1) from (SELECT SUM(d.co_payment) as payment FROM `yeshi_ec_common_order` d
        where d.co_uid = #{uid} and d.co_source_type = 1  and d.co_state <![CDATA[<>]]> 4
        GROUP BY d.`co_order_no`
        ORDER BY d.co_third_create_time desc
        limit 100)A where A.payment<![CDATA[<]]> 10
    </select>
    <select id="countOrderBySourceAndNearDay" resultType="Long">
    <select id="countOrderBySourceAndNearDay" resultType="Long">
        SELECT COUNT(co_id) FROM (SELECT d.`co_id` FROM `yeshi_ec_common_order` d
            WHERE d.co_uid = #{uid} AND d.`co_source_type` = #{source} AND (d.`co_state`=1 OR d.`co_state`=2) 
                AND DATE_SUB(CURDATE(), INTERVAL #{day} DAY) <![CDATA[<=]]> DATE(d.`co_third_create_time`) 
        GROUP BY d.`co_order_no`,d.`co_source_type`)A
    </select>
    <select id="countHistoryOrderNum" resultType="Long">
    <select id="countHistoryOrderNum" resultType="Long">
        SELECT COUNT(hb_id) FROM (SELECT v2.`hb_id` FROM yeshi_ec_hongbao_v2 v2 
        LEFT JOIN yeshi_ec_hongbao_order ho ON IF(v2.hb_pid IS NULL,v2.hb_id,v2.hb_pid)=ho.`ho_hongbao_id`
        LEFT JOIN yeshi_ec_common_order co ON co.`co_id`=ho.`ho_order_id`
        WHERE v2.hb_uid = #{uid}
        GROUP BY co.`co_order_no`, co.`co_source_type`)A
    </select>
</mapper>
fanli/src/main/resource/mapping/order/CommonOrderMapper.xml
@@ -429,7 +429,7 @@
    <sql id="SELECT_PARAM_HONGBAO_STATE">
        <if test="state != null and state == 1">
            <!-- 未到账 -->
            AND (hb.hb_state = 1 or hb.hb_state = 2)
            AND (hb.hb_state = 1 or hb.hb_state = 2 or hb.hb_state = 5)
        </if>
        <if test="state != null and state == 2">
            <!-- 已到账 -->
@@ -693,7 +693,7 @@
        <include refid="SELECT_PARAM_HONGBAO_TYPE"/>
        <if test="state != null and state == 1">
            <!-- 未到账 -->
            AND (v2.hb_state = 1 or v2.hb_state = 2)
            AND (v2.hb_state = 1 or v2.hb_state = 2 or v2.hb_state =5)
        </if>
        <if test="state != null and state == 2">
            <!-- 已到账 -->
@@ -772,7 +772,7 @@
        <include refid="Hongbao_Column_List"/>
        FROM yeshi_ec_hongbao_v2 v2 WHERE v2.`hb_uid`=${uid}
        <include refid="SELECT_PARAM_HONGBAO_TYPE"/>
        AND (v2.hb_state = 1 or v2.hb_state = 2 or v2.hb_state = 3) ) hb ON
        AND (v2.hb_state = 1 or v2.hb_state = 2 or v2.hb_state = 5 or v2.hb_state = 3) ) hb ON
        IF(hb.hb_pid IS NULL,hb.hb_id,hb.hb_pid)=ho.`ho_hongbao_id` LEFT JOIN
        yeshi_ec_common_order co ON co.`co_id`=ho.`ho_order_id` WHERE hb.hb_id
        IS NOT NULL
@@ -791,7 +791,7 @@
        <include refid="Hongbao_Column_List"/>
        FROM yeshi_ec_hongbao_v2 v2 WHERE v2.`hb_uid`=${uid}
        <include refid="SELECT_PARAM_HONGBAO_TYPE"/>
        AND (v2.hb_state = 1 or v2.hb_state = 2 or v2.hb_state = 3) ) hb ON
        AND (v2.hb_state = 1 or v2.hb_state = 2 or v2.hb_state = 5 or v2.hb_state = 3) ) hb ON
        IF(hb.hb_pid IS NULL,hb.hb_id,hb.hb_pid)=ho.`ho_hongbao_id` LEFT JOIN
        yeshi_ec_common_order co ON co.`co_id`=ho.`ho_order_id` WHERE hb.hb_id
        IS NOT NULL
@@ -804,7 +804,7 @@
    <sql id="SELECT_HONGBAO_STATE">
        <if test="state != null and state == 1">
            <!-- 未到账 -->
            AND (v2.hb_state = 1 or v2.hb_state = 2)
            AND (v2.hb_state = 1 or v2.hb_state = 2 or v2.hb_state = 5)
        </if>
        <if test="state != null and state == 2">
            <!-- 已到账 -->
@@ -1269,4 +1269,18 @@
        ORDER BY d.co_third_create_time 
        LIMIT 1
    </select>
    <select id="listByGoodsIdAndUidAndMinThirdCreateTime" resultMap="BaseResultMap">
        SELECT * FROM `yeshi_ec_common_order` d
        WHERE d.co_uid = #{uid} and d.co_order_goods_id=#{goodsId}
        <if test="minThirdCreateTime!=null">
            and d.co_third_create_time>=#{minThirdCreateTime}
        </if>
        limit #{start},#{count}
    </select>
</mapper>
utils/src/main/java/org/yeshi/utils/JsonUtil.java
@@ -35,7 +35,6 @@
        object.put("code", 0);
        object.put("data", result);
        return object.toString();
    }
    public static String loadFalseResult(String error) {