From 3f45e8fdfa31d7b764d60a7c0cb5dd11944ed418 Mon Sep 17 00:00:00 2001
From: 刘帅 <rr.iii@qq.com>
Date: 星期一, 21 九月 2026 23:38:59 +0800
Subject: [PATCH] bug:统计数据修正

---
 cloud-server-account/src/main/java/com/dsh/account/service/impl/TAppUserServiceImpl.java | 1383 ++++++++++++++++++++++++++++++++++-----------------------
 1 files changed, 830 insertions(+), 553 deletions(-)

diff --git a/cloud-server-account/src/main/java/com/dsh/account/service/impl/TAppUserServiceImpl.java b/cloud-server-account/src/main/java/com/dsh/account/service/impl/TAppUserServiceImpl.java
index 979be10..f33edaf 100644
--- a/cloud-server-account/src/main/java/com/dsh/account/service/impl/TAppUserServiceImpl.java
+++ b/cloud-server-account/src/main/java/com/dsh/account/service/impl/TAppUserServiceImpl.java
@@ -12,14 +12,19 @@
 import com.alipay.api.response.AlipayTradeOrderSettleResponse;
 import com.alipay.api.response.AlipayTradeQueryResponse;
 import com.alipay.api.response.AlipayTradeRoyaltyRelationBindResponse;
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONObject;
 import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
 import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
 import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
 import com.dsh.account.dto.*;
 import com.dsh.account.entity.*;
 import com.dsh.account.enums.RechargeRecordEnum;
 import com.dsh.account.feignclient.activity.*;
 import com.dsh.account.feignclient.activity.model.*;
+import com.dsh.account.feignclient.communityWorldCup.WorldCupPaymentClinet;
+import com.dsh.account.feignclient.communityWorldCup.model.GetWorldCupPayment;
 import com.dsh.account.feignclient.competition.DeductionCompetitionsClient;
 import com.dsh.account.feignclient.competition.model.BillingDataRequestVo;
 import com.dsh.account.feignclient.course.CoursePackageClient;
@@ -27,13 +32,8 @@
 import com.dsh.account.feignclient.course.CoursePaymentClient;
 import com.dsh.account.feignclient.course.VideoOfCourseListClient;
 import com.dsh.account.feignclient.course.model.*;
-import com.dsh.account.feignclient.other.ImgConfigClient;
-import com.dsh.account.feignclient.other.RechargeConfigClient;
-import com.dsh.account.feignclient.other.SiteClient;
-import com.dsh.account.feignclient.other.StoreClient;
-import com.dsh.account.feignclient.other.model.Store;
-import com.dsh.account.feignclient.other.model.StoreDetailOfCourse;
-import com.dsh.account.feignclient.other.model.TImgConfig;
+import com.dsh.account.feignclient.other.*;
+import com.dsh.account.feignclient.other.model.*;
 import com.dsh.account.mapper.*;
 import com.dsh.account.model.*;
 import com.dsh.account.model.AppUserByNameAndPhoneDTO;
@@ -45,16 +45,18 @@
 import com.dsh.account.model.vo.classDetails.RegisteredCourse;
 import com.dsh.account.model.vo.classDetails.classInsVo.ClassInfoVo;
 import com.dsh.account.model.vo.userBenefitDetail.*;
-import com.dsh.account.service.TAppGiftService;
-import com.dsh.account.service.TAppUserService;
+import com.dsh.account.service.*;
 import com.dsh.account.util.*;
 import com.dsh.account.util.akeylogin.Md5Util;
+import com.dsh.account.util.wx.WxV3PayConfig;
 import com.dsh.account.vo.GroupCityInfoVO;
 import com.dsh.account.vo.entity.DayData;
 import com.dsh.account.vo.entity.MonthData;
 import com.dsh.account.vo.entity.WeekData;
 import com.dsh.account.vo.entity.YearData;
+import org.springframework.beans.BeanUtils;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
 import org.springframework.data.domain.Page;
 import org.springframework.data.domain.PageImpl;
 import org.springframework.data.domain.PageRequest;
@@ -85,6 +87,10 @@
 @Service
 public class TAppUserServiceImpl extends ServiceImpl<TAppUserMapper, TAppUser> implements TAppUserService {
 
+    private static final String SMS_COOLDOWN_KEY_PREFIX = "security:sms:cooldown:";
+    private static final String SMS_PHONE_QUOTA_KEY_PREFIX = "security:sms:phone-quota:";
+    private static final String SMS_IP_QUOTA_KEY_PREFIX = "security:sms:ip-quota:";
+
 
     @Resource
     private TStudentMapper tsmapper;
@@ -97,6 +103,15 @@
 
     @Autowired
     private RedisUtil redisUtil;
+
+    @Value("${security.sms.cooldown-seconds:60}")
+    private int smsCooldownSeconds;
+
+    @Value("${security.sms.phone-max-per-day:5}")
+    private int smsPhoneMaxPerDay;
+
+    @Value("${security.sms.ip-max-per-day:10}")
+    private int smsIpMaxPerDay;
 
     @Autowired
     private GDMapGeocodingUtil gdMapGeocodingUtil;
@@ -116,7 +131,6 @@
     @Resource
     private ImgConfigClient icfgClient;
 
-
     @Resource
     private VideoOfCourseListClient voclClient;
 
@@ -131,6 +145,7 @@
 
     @Resource
     private UserConponClient ucponClient;
+
 
     @Resource
     private CoursePackageClient cpageClient;
@@ -149,16 +164,22 @@
 
     @Resource
     private SiteClient stClient;
-    @Autowired
+
+    @Resource
     private TAppUserMapper appUserMapper;
+    @Autowired
+    private UserAuditService userAuditService;
 
     @Autowired
     private TAppGiftService appGiftService;
 
-    @Autowired
+    @Resource
     private IntroduceRewardsClient introduceRewardsClient;
 
+
     private String aliAppid = "2021004105665036";//支付宝appid
+    // 默认头像
+    private String headImg = "https://we-park-life.oss-cn-beijing.aliyuncs.com/img/f7fbeaed277a45ab9591b70dc5699cab.jpg";
 
     private String appPrivateKey = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCi5i9nW/hGLJ3A06cZxTQdviFC7THpdSihoTYGLr9q006hu0V26ecBMY/o4w5bvIX0Ok/yofmZsVcCJpAPvbXL/uqVrIjnRRxXiaeBFThlxoBUTdunvbUSDYfzlEhJr5NvUKI6H6lz2niXlQGx4qy8Hau4ccWit9kM8jwUvsBVQoFgJA+xrjMvooA7YLopQtpOD+UJr5thApTSf1xrnr1W12yolTLEH15JmNV372cqXrYUuqnY0QsaPtxeqJUGAOcGdVLllQ7easEznP8DFBvDdHATcmp2SHNQDUEWN6MCVPbMgY06NQVqAXxqjTAYSVh+6TRu6bofPmpYC3TZB003AgMBAAECggEBAJAcR2+PA3NBYUYHeFrqBRMS8uX8ZR19kjZ7IgoSLTFaQsP9opRylPSPXhrPVBKAE5leRQAHn4MCSlESwHvMfxo7KFjFTFAc6dffZZpipYQUOc9bGampwJh58/3e/pyBgVMG6J23CPf/HJQtNFSkjd/V9+ayb/9l2dUEL3bC0fAZ/dbx8HsxdLw8wn3fLlWLj68hOMqa2deCZe3JdSVsPbeWqkh56FFsMLug0Nd+Ar4TgRl9/jnhXF0JWiD0LmPUYLhboY7EfUBzN4w1iYbDi1P+3zvoOYsiVKAXox9GMhQ2VzOO2UcSTuizSza2e98mGpabl/GpKmCz+RDFjtkX6eECgYEA2MyCij65eO3aGIm3FUe93DULRBYTfX8qJQSJq2WOWA3mmQlEW6L3O2B5/lG2h+8WmN6iLEs9eHpgycGYp7vAqgrANEn16ACVcuyx0scFtrZfZ+kmHMzFfiUWxJjVYk/6YngsGVBLdw6ueM42C8TTP67X9tU5TdVGoGWuqEj4W98CgYEAwFqwprXOch5Pqk/RPbb49r0Ou03K/UbciWnWWKzUhFFNS8MdlQPoDvQZbMwHLeWsa2VhaKITK3x5biLQb3U+0GLOn6lTvEyrEUH+ucREyLgVYTRAvwBPtnvlrzpyxPk2HnslQjju8WrvvLLBMKWUjlTrTOzhaHT21gz3pHMiOakCgYEAhLmfaXdBITGshb054sNLDtdCkGpbgEcrzAHdLps769iGxkYQHXHFngpQZUwtTUcoNGqIKknd1jZFrv7gsD+XkgKG7PwimehRlkwmCX5ilxtLiVgJRzRt6+5U5AMVD90a0tHzXYP0z2yjj73fBJF5KtGl0a10KZxaYrQdm1UhB00CgYBZZgzx/k9rtHC8LAqIj1CYhHejT92G53c6Gkl3vyOqN4sgKhfGmSEySfrDGPRBPZxr8ZtbIPCd5mUdberH0osWGMYFaJI1UsCy7aQwvGpniz7MhZeN7dweaOjwDs8mgtjHQ96mL4XGCDhR0BZ/wIURvZ/6iaGdhbbu9unlsWj3uQKBgQCmZYdsbbZkd3ev6f8rwyvMz+DrCQyYpY44cegBYuJgrZiQnL2fJioeN7ixX0UM48SfwsZEIrzshP/LGAwnc2MdjxKUl4jLN8SEe0NAjXOnz9Zaw740+aOmLpXcLWdP4uM2gIhWsvW1tEkQZCXmm7c9s/RsU8Pmzv+YL3+fSijOzA==";//支付宝开发者应用私钥
 
@@ -178,8 +199,17 @@
     @Resource
     private UserCouponPaymentClient userCouponPaymentClient;
 
+    @Autowired
+    private IRefereeService refereeService;
 
+    @Resource
+    private WorldCupPaymentClinet worldCupPaymentClinet;
 
+    @Autowired
+    private UserIntegralChangesService userIntegralChangesService;
+
+    @Resource
+    private GameRecordClient gameRecordClient;
 
 
     // 对数据进行分页处理的方法
@@ -401,13 +431,31 @@
      * @throws Exception
      */
     @Override
-    public ResultUtil getSMSCode(Integer type, String phone) throws Exception {
+    public ResultUtil getSMSCode(Integer type, String phone, String clientIp) throws Exception {
         if (type == 2) {
             TAppUser tAppUser = this.baseMapper.selectOne(new QueryWrapper<TAppUser>().eq("phone", phone).ne("state", 3));
             if (null != tAppUser) {
                 return ResultUtil.error("账号已存在");
             }
         }
+        String cooldownKey = SMS_COOLDOWN_KEY_PREFIX + phone;
+        if (!redisUtil.setIfAbsent(cooldownKey, "1", smsCooldownSeconds)) {
+            return ResultUtil.error("短信发送过于频繁,请稍后重试");
+        }
+
+        String phoneQuotaKey = SMS_PHONE_QUOTA_KEY_PREFIX + phone;
+        if (!redisUtil.tryAcquireFixedWindow(phoneQuotaKey, smsPhoneMaxPerDay, 24 * 60 * 60)) {
+            redisUtil.remove(cooldownKey);
+            return ResultUtil.error("该手机号24小时内短信发送次数已达上限");
+        }
+
+        String ipQuotaKey = SMS_IP_QUOTA_KEY_PREFIX + clientIp;
+        if (!redisUtil.tryAcquireFixedWindow(ipQuotaKey, smsIpMaxPerDay, 24 * 60 * 60)) {
+            redisUtil.remove(cooldownKey);
+            redisUtil.releaseFixedWindow(phoneQuotaKey);
+            return ResultUtil.error("当前网络24小时内短信发送次数已达上限");
+        }
+
         String numberRandom = UUIDUtil.getNumberRandom(6);
         String templateCode = "";
         if (type == 1 || type == 2) {
@@ -416,9 +464,29 @@
         if (type == 3 || type == 4) {
             templateCode = "SMS_160960014";
         }
-        aLiSendSms.sendSms(phone, templateCode, "{\"code\":\"" + numberRandom + "\"}");
-        redisUtil.setStrValue(phone, numberRandom, 300);
-        return ResultUtil.success();
+        boolean providerAccepted = false;
+        try {
+            String sendResult = aLiSendSms.sendSms(phone, templateCode, "{\"code\":\"" + numberRandom + "\"}");
+            com.alibaba.fastjson.JSONObject response = com.alibaba.fastjson.JSONObject.parseObject(sendResult);
+            if (response == null || !"OK".equalsIgnoreCase(response.getString("Code"))) {
+                releaseSmsLimit(cooldownKey, phoneQuotaKey, ipQuotaKey);
+                return ResultUtil.error("短信发送失败,请稍后重试");
+            }
+            providerAccepted = true;
+            redisUtil.setStrValue(phone, numberRandom, 300);
+            return ResultUtil.success();
+        } catch (Exception e) {
+            if (!providerAccepted) {
+                releaseSmsLimit(cooldownKey, phoneQuotaKey, ipQuotaKey);
+            }
+            throw e;
+        }
+    }
+
+    private void releaseSmsLimit(String cooldownKey, String phoneQuotaKey, String ipQuotaKey) {
+        redisUtil.remove(cooldownKey);
+        redisUtil.releaseFixedWindow(phoneQuotaKey);
+        redisUtil.releaseFixedWindow(ipQuotaKey);
     }
 
     /**
@@ -451,51 +519,52 @@
         tAppUser.setProvinceCode("");
         tAppUser.setCity("");
         tAppUser.setCityCode("");
+        tAppUser.setHeadImg(headImg);
         // 注册用户
         int insert = this.baseMapper.insert(tAppUser);
+        String s = generateNickname(tAppUser.getId());
+        tAppUser.setName(s);
+        this.baseMapper.updateById(tAppUser);
         // 介绍有礼
         if (addAppUserVo.getReferralUserId() != null || ToolUtil.isNotEmpty(addAppUserVo.getInvitePhone())) {
             if (ToolUtil.isEmpty(addAppUserVo.getLat()) || ToolUtil.isEmpty(addAppUserVo.getLon())) {
                 return ResultUtil.error("请先开启定位", "");
             }
             Map<String, String> geocode = gdMapGeocodingUtil.geocode(addAppUserVo.getLon(), addAppUserVo.getLat());
-            Integer num = 0;
-            Integer activityId = null;
             if (null != geocode) {
-                String province = geocode.get("province");
-                String provinceCode = geocode.get("provinceCode");
-                String city = geocode.get("city");
                 String cityCode = geocode.get("cityCode");
                 // 根据所在市code 查询是否有介绍有礼活动
-                IntroduceRewards res = introduceRewardsClient.getGiftList(cityCode);
+                List<IntroduceRewards> res = introduceRewardsClient.getGiftList(cityCode);
                 if (res != null) {
-                    num = res.getGiveClass();
-                    activityId = res.getId();
-                    if (ToolUtil.isNotEmpty(addAppUserVo.getInvitePhone())) {
-                        List<TAppUser> tAppUsers = this.baseMapper.selectList(new LambdaQueryWrapper<TAppUser>()
-                                .eq(TAppUser::getPhone, addAppUserVo.getInvitePhone()));
-                        if (tAppUsers.size() > 0) {
-                            addAppUserVo.setReferralUserId(tAppUsers.get(0).getId());
+                    for (IntroduceRewards re : res) {
+                        Integer num = re.getGiveClass();
+                        Integer activityId = re.getId();
+                        if (ToolUtil.isNotEmpty(addAppUserVo.getInvitePhone())) {
+                            List<TAppUser> tAppUsers = this.baseMapper.selectList(new LambdaQueryWrapper<TAppUser>()
+                                    .eq(TAppUser::getPhone, addAppUserVo.getInvitePhone()));
+                            if (tAppUsers.size() > 0) {
+                                addAppUserVo.setReferralUserId(tAppUsers.get(0).getId());
+                            }
                         }
-                    }
-                    if (num != 0) {
-                        TAppGift tAppGift = new TAppGift();
-                        TAppUser phone = appUserService.getOne(new QueryWrapper<TAppUser>()
-                                .eq("phone", addAppUserVo.getInvitePhone()));
-                        if (phone == null) {
-                            return ResultUtil.error("推荐人手机号未注册玩湃会员!");
-                        } else {
-                            tAppGift.setUserName(phone.getName());
-                            tAppGift.setUserPhone(phone.getPhone());
+                        if (num != 0) {
+                            TAppGift tAppGift = new TAppGift();
+                            TAppUser phone = appUserService.getOne(new QueryWrapper<TAppUser>()
+                                    .eq("phone", addAppUserVo.getInvitePhone()));
+                            if (phone == null) {
+                                return ResultUtil.error("推荐人手机号未注册玩湃会员!");
+                            } else {
+                                tAppGift.setUserName(phone.getName());
+                                tAppGift.setUserPhone(phone.getPhone());
+                            }
+                            tAppGift.setUserId(addAppUserVo.getReferralUserId());
+                            tAppGift.setNum(num);
+                            tAppGift.setShareUserId(tAppUser.getId());
+                            tAppGift.setShareUserName(tAppUser.getPhone());
+                            tAppGift.setShareUserPhone(tAppUser.getPhone());
+                            tAppGift.setActivityId(activityId);
+                            tAppGift.setInsertTime(new Date());
+                            appGiftService.save(tAppGift);
                         }
-                        tAppGift.setUserId(addAppUserVo.getReferralUserId());
-                        tAppGift.setNum(num);
-                        tAppGift.setShareUserId(tAppUser.getId());
-                        tAppGift.setShareUserName(tAppUser.getPhone());
-                        tAppGift.setShareUserPhone(tAppUser.getPhone());
-                        tAppGift.setActivityId(activityId);
-                        tAppGift.setInsertTime(new Date());
-                        appGiftService.save(tAppGift);
                     }
                 }
             }
@@ -543,6 +612,7 @@
             return ResultUtil.error("验证码无效", "");
         }
         TAppUser tAppUser = this.baseMapper.selectOne(new QueryWrapper<TAppUser>().eq("phone", loginSMSCodeVo.getPhone()).ne("state", 3));
+//        System.out.println(tAppUser.getId()+"!!!!!!!!");
         if (null == tAppUser) {
             tAppUser = new TAppUser();
             tAppUser.setCode(UUIDUtil.getNumberRandom(16));
@@ -550,13 +620,19 @@
             tAppUser.setPassword(Md5Util.MD5Encode("111111", null));
             tAppUser.setIsVip(0);
             tAppUser.setState(1);
+            tAppUser.setHeadImg(headImg);
             tAppUser.setInsertTime(new Date());
             this.baseMapper.insert(tAppUser);
+            String s = generateNickname(tAppUser.getId());
+            tAppUser.setName(s);
+            this.baseMapper.updateById(tAppUser);
         }
         if (tAppUser.getState() == 2) {
             return ResultUtil.error("您的账号已被冻结", "");
         }
         String token = getToken(tAppUser);
+
+        System.out.println("token"+token);
         return ResultUtil.success(token);
     }
 
@@ -579,8 +655,8 @@
                 tAppUser.setPhone(loginWechatVo.getPhone());
                 tAppUser.setPassword(Md5Util.MD5Encode("111111", null));
                 tAppUser.setIsVip(0);
-                tAppUser.setName(loginWechatVo.getNickname());
-                tAppUser.setHeadImg(loginWechatVo.getHeadimgurl());
+//                tAppUser.setName(loginWechatVo.getNickname());
+                tAppUser.setHeadImg(headImg);
                 tAppUser.setGender(loginWechatVo.getSex());
                 tAppUser.setState(1);
                 tAppUser.setInsertTime(new Date());
@@ -589,6 +665,11 @@
                 tAppUser.setCity("");
                 tAppUser.setCityCode("");
                 this.baseMapper.insert(tAppUser);
+                // 设置用户昵称为用户+id 保留6位小数 补0
+                String s = generateNickname(tAppUser.getId());
+                tAppUser.setName(s);
+                this.baseMapper.updateById(tAppUser);
+
             }
         }
         if (tAppUser.getState() == 2) {
@@ -614,6 +695,26 @@
         }
         return ResultUtil.success(map);
     }
+    /**
+     * 根据用户ID生成固定格式的昵称
+     * @param userId 用户ID
+     * @return 格式化的昵称
+     */
+    public static String generateNickname(Integer userId) {
+        if (userId == null) {
+            return null;
+        }
+
+        // 将用户ID转换为字符串
+        String userIdStr = String.valueOf(userId);
+
+        // 使用String.format确保总长度为6位,不足的前面补0
+        String formattedId = String.format("%06d", Long.parseLong(userIdStr));
+
+        // 返回"用户" + 格式化后的ID
+        return "用户" + formattedId;
+    }
+
 
     /**
      * 获取JWT token和存储个人信息
@@ -730,6 +831,9 @@
             Store s = null;
             Double d = 0D;
             for (Store store : stores) {
+                if (store == null || !isValidCoordinate(store.getLon(), store.getLat())) {
+                    continue;
+                }
                 Map<String, Double> distance = GeodesyUtil.getDistance(lon + "," + lat, store.getLon() + "," + store.getLat());
                 Double wgs84 = distance.get("WGS84");
                 if (s == null || d > wgs84) {
@@ -737,23 +841,39 @@
                     d = wgs84;
                 }
             }
-            joinPlayPaiVo.setName(s.getName());
-            joinPlayPaiVo.setLon(s.getLon());
-            joinPlayPaiVo.setLat(s.getLat());
-            joinPlayPaiVo.setStoreId(s.getId());
-            joinPlayPaiVo.setPhone(s.getPhone());
-            joinPlayPaiVo.setProvince(s.getProvince());
-            joinPlayPaiVo.setProvinceCode(s.getProvinceCode());
-            joinPlayPaiVo.setCity(s.getCity());
-            joinPlayPaiVo.setCityCode(s.getCityCode());
+            if (s != null) {
+                joinPlayPaiVo.setName(s.getName());
+                joinPlayPaiVo.setLon(s.getLon());
+                joinPlayPaiVo.setLat(s.getLat());
+                joinPlayPaiVo.setStoreId(s.getId());
+                joinPlayPaiVo.setPhone(s.getPhone());
+                joinPlayPaiVo.setProvince(s.getProvince());
+                joinPlayPaiVo.setProvinceCode(s.getProvinceCode());
+                joinPlayPaiVo.setCity(s.getCity());
+                joinPlayPaiVo.setCityCode(s.getCityCode());
+            }
         }
         return joinPlayPaiVo;
+    }
+
+    private boolean isValidCoordinate(String lon, String lat) {
+        if (ToolUtil.isEmpty(lon) || ToolUtil.isEmpty(lat)) {
+            return false;
+        }
+        try {
+            double longitude = Double.parseDouble(lon.trim());
+            double latitude = Double.parseDouble(lat.trim());
+            return Double.isFinite(longitude) && Double.isFinite(latitude)
+                    && longitude >= -180 && longitude <= 180
+                    && latitude >= -90 && latitude <= 90;
+        } catch (NumberFormatException e) {
+            return false;
+        }
     }
 
     @Override
     public IndexOfUserBenefirVo queryBenefitDetails(Integer appUserId, String lon, String lat) {
         IndexOfUserBenefirVo benefirVo = new IndexOfUserBenefirVo();
-
         TAppUser appUser = this.getById(appUserId);
         if (appUser.getHeadImg() != null) {
             benefirVo.setUserHeadImg(appUser.getHeadImg());
@@ -763,7 +883,7 @@
         benefirVo.setUserName(appUser.getName());
         benefirVo.setWpCoin(ToolUtil.isEmpty(appUser.getPlayPaiCoins()) ? 0 : appUser.getPlayPaiCoins());
         benefirVo.setUserIntegral(ToolUtil.isEmpty(appUser.getIntegral()) ? 0 : appUser.getIntegral());
-        if (appUser.getIsVip() == 1) {
+        if (appUser.getIsVip()!=null&& appUser.getIsVip() == 1) {
             benefirVo.setIsMember("年度会员");
         } else {
             benefirVo.setIsMember("普通用户");
@@ -775,6 +895,8 @@
         List<IntegralCommodity> convertibleGoods = mcClient.getConvertibleGoods(location);
         benefirVo.setCommodities(convertibleGoods);
         benefirVo.setImage(icfgClient.getImageConfig());
+        Referee referee = refereeService.getOne(new QueryWrapper<Referee>().eq("phone", appUser.getPhone()).eq("state", 1));
+        benefirVo.setReferee(null == referee ? 0 : 1);
         return benefirVo;
     }
 
@@ -807,6 +929,7 @@
                 consumeDetail.setConsumeTime(paymentCompetition.getTime());
                 consumeDetail.setConsumeAmount("-" + paymentCompetition.getAmount());
                 consumeDetail.setType(2);
+                consumeDetail.setDateTime(paymentCompetition.getDateTime());
                 details.add(consumeDetail);
             }
         }
@@ -819,37 +942,21 @@
                 consumeDetail.setConsumeTime(paymentCompetition.getTime());
                 consumeDetail.setConsumeAmount("+" + paymentCompetition.getAmount());
                 consumeDetail.setType(1);
+                consumeDetail.setDateTime(paymentCompetition.getDateTime());
                 details.add(consumeDetail);
             }
         }
-//            3.课包购买
-//        BillingRequestVo amountPayRecord = paymentClient.getAmountPayRecord(requestVo);
-//        if (ToolUtil.isNotEmpty(amountPayRecord.getRequests())){
-//            for (BillingRequest coursePackagePayment : amountPayRecord.getRequests()) {
-//                ConsumeDetail consumeDetail = new ConsumeDetail();
-//                consumeDetail.setConsumeName(RechargeRecordEnum.COURSE_PACKAGE_PURCHASE.getMsg());
-//                consumeDetail.setConsumeTime(coursePackagePayment.getTime());
-//                consumeDetail.setConsumeAmount("-" + coursePackagePayment.getAmount());
-//                consumeDetail.setType(2);
-//                details.add(consumeDetail);
-//            }
-//        }
 
-        //2.0
-        List<CourseCounsum> courseCounsums = paymentClient.getConsumes(requestVo);
+        //3.课包购买
+        List<CoursePackageOrder> coursePackageOrder = paymentClient.getCoursePackageOrder(requestVo);
 
-        for (CourseCounsum courseCounsum : courseCounsums) {
+        for (CoursePackageOrder order : coursePackageOrder) {
             ConsumeDetail consumeDetail = new ConsumeDetail();
-            String[] split = courseCounsum.getReason().split(";");
-            consumeDetail.setConsumeName(split[0]);
-            consumeDetail.setConsumeTime(simpleDateFormat.format(courseCounsum.getInsertTime()));
-//            if (courseCounsum.getChangeType()==3){
-            consumeDetail.setConsumeAmount("-" + split[1]);
+            consumeDetail.setConsumeName("课程报名");
+            consumeDetail.setConsumeTime(simpleDateFormat.format(order.getInsertTime()));
+            consumeDetail.setConsumeAmount("-" + order.getCashPayment());
             consumeDetail.setType(2);
-//            }
-//
-//            consumeDetail.setConsumeAmount("-" + coursePackagePayment.getAmount());
-//            consumeDetail.setType(2);
+            consumeDetail.setDateTime(order.getInsertTime().getTime());
             details.add(consumeDetail);
         }
 
@@ -864,27 +971,44 @@
                     consumeDetail.setConsumeAmount("-" + booking.getAmount());
                     consumeDetail.setConsumeTime(booking.getTime());
                     consumeDetail.setType(2);
+                    consumeDetail.setDateTime(booking.getDateTime());
                     details.add(consumeDetail);
                 } else {
                     ConsumeDetail consumeDetail1 = new ConsumeDetail();
                     consumeDetail1.setConsumeName(RechargeRecordEnum.CANCEL_VENUE_RESERVATION.getMsg());
                     consumeDetail1.setConsumeAmount("+" + booking.getAmount());
                     consumeDetail1.setConsumeTime(booking.getTime());
+                    consumeDetail1.setDateTime(booking.getDateTime());
                     consumeDetail1.setType(1);
                     details.add(consumeDetail1);
+
                     ConsumeDetail consumeDetail2 = new ConsumeDetail();
                     consumeDetail2.setConsumeName(RechargeRecordEnum.VENUE_RESERVATION.getMsg());
                     consumeDetail2.setConsumeAmount("-" + booking.getAmount());
                     consumeDetail2.setConsumeTime(booking.getTime1());
                     consumeDetail2.setType(2);
+                    consumeDetail2.setDateTime(booking.getDateTime());
                     details.add(consumeDetail2);
-
                 }
-//                details.add(consumeDetail);
             }
         }
 
 //            5.智慧球场
+        GetTGameRecord getTGameRecord = new GetTGameRecord();
+        getTGameRecord.setAppUserId(appUserId);
+        getTGameRecord.setStartTiem(monthStart);
+        getTGameRecord.setEndTime(monthEnd);
+        List<TGameRecord> tGameRecord = gameRecordClient.getTGameRecord(getTGameRecord);
+        for (TGameRecord gameRecord : tGameRecord) {
+            ConsumeDetail consumeDetail = new ConsumeDetail();
+            consumeDetail.setConsumeName(RechargeRecordEnum.SMART_STADIUM.getMsg());
+            consumeDetail.setConsumeTime(simpleDateFormat.format(gameRecord.getTime()));
+            consumeDetail.setConsumeAmount("-" + gameRecord.getMoney());
+            consumeDetail.setType(2);
+            consumeDetail.setDateTime(gameRecord.getTime().getTime());
+            details.add(consumeDetail);
+        }
+
 //            6.年度会员
         List<VipPayment> vipPayments = vipPaymentMapper.selectList(new QueryWrapper<VipPayment>()
                 .eq("payStatus", 2)
@@ -897,6 +1021,7 @@
                 consumeDetail.setConsumeTime(simpleDateFormat.format(vipPayment.getInsertTime()));
                 consumeDetail.setConsumeAmount("-" + vipPayment.getAmount());
                 consumeDetail.setType(2);
+                consumeDetail.setDateTime(vipPayment.getPayTime().getTime());
                 details.add(consumeDetail);
             }
         }
@@ -912,6 +1037,7 @@
                 consumeDetail.setConsumeTime(simpleDateFormat.format(rechargeRecord.getInsertTime()));
                 consumeDetail.setConsumeAmount("-" + rechargeRecord.getAmount());
                 consumeDetail.setType(2);
+                consumeDetail.setDateTime(rechargeRecord.getPayTime().getTime());
                 details.add(consumeDetail);
             }
         }
@@ -922,21 +1048,47 @@
         details.addAll(consumeDetails);
 
 
+        //世界杯
+        GetWorldCupPayment getWorldCupPayment = new GetWorldCupPayment();
+        getWorldCupPayment.setAppUserId(appUserId);
+        getWorldCupPayment.setPayType("1,2");
+        getWorldCupPayment.setStartTime(monthStart);
+        getWorldCupPayment.setEndTime(monthEnd);
+        List<WorldCupPayment> worldCupPayment = worldCupPaymentClinet.getWorldCupPayment(getWorldCupPayment);
+        for (WorldCupPayment cupPayment : worldCupPayment) {
+            ConsumeDetail consumeDetail = new ConsumeDetail();
+            if (cupPayment.getPayStatus() != 3) {
+                consumeDetail.setConsumeName(RechargeRecordEnum.WORLD_CIP_PAYMENT.getMsg());
+                consumeDetail.setConsumeTime(simpleDateFormat.format(cupPayment.getCreateTime()));
+                consumeDetail.setConsumeAmount("-" + cupPayment.getAmount());
+                consumeDetail.setType(2);
+                consumeDetail.setDateTime(cupPayment.getPayTime().getTime());
+                details.add(consumeDetail);
+            } else {
+                consumeDetail = new ConsumeDetail();
+                consumeDetail.setConsumeName(RechargeRecordEnum.WORLD_CIP_PAYMENT.getMsg());
+                consumeDetail.setConsumeTime(simpleDateFormat.format(cupPayment.getCreateTime()));
+                consumeDetail.setConsumeAmount("-" + cupPayment.getAmount());
+                consumeDetail.setType(2);
+                consumeDetail.setDateTime(cupPayment.getPayTime().getTime());
+                details.add(consumeDetail);
+
+                consumeDetail = new ConsumeDetail();
+                consumeDetail.setConsumeName(RechargeRecordEnum.CANCEL_WORLD_CIP_PAYMENT.getMsg());
+                consumeDetail.setConsumeTime(simpleDateFormat.format(cupPayment.getCreateTime()));
+                consumeDetail.setConsumeAmount("+" + cupPayment.getRefundAmount());
+                consumeDetail.setType(1);
+                consumeDetail.setDateTime(cupPayment.getRefundTime().getTime());
+                details.add(consumeDetail);
+            }
+        }
+
+
         if (details.size() > 0) {
             Collections.sort(details, new Comparator<ConsumeDetail>() {
                 @Override
                 public int compare(ConsumeDetail record1, ConsumeDetail record2) {
-                    SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd HH:mm");
-                    Date date1 = null;
-                    Date date2 = null;
-                    try {
-                        date1 = dateFormat.parse(record1.getConsumeTime());
-                        date2 = dateFormat.parse(record2.getConsumeTime());
-                    } catch (ParseException e) {
-                        e.printStackTrace();
-                    }
-                    // 倒序排序
-                    return date2.compareTo(date1);
+                    return record1.getDateTime().compareTo(record2.getDateTime()) * -1;
                 }
             });
 
@@ -946,6 +1098,7 @@
                         .collect(Collectors.toList());
             }
         }
+
         return details;
     }
 
@@ -987,6 +1140,7 @@
         CommodityRequest commodityRequest = new CommodityRequest();
         commodityRequest.setLon(request.getLon());
         commodityRequest.setLat(request.getLat());
+        commodityRequest.setShopId(request.getShopId());
         PointMerchandiseVo vicinityGoods = mcClient.getVicinityGoods(commodityRequest);
         if (ToolUtil.isNotEmpty(vicinityGoods.getMerchandises())) {
             for (PointsMerchandise vicinityGood : vicinityGoods.getMerchandises()) {
@@ -1088,14 +1242,6 @@
                         .collect(Collectors.toList());
             }
         }
-        // 2.0 门店筛选
-        if (request.getShopId() != null) {
-            if (goods.size() > 0) {
-                goods = goods.stream()
-                        .filter(merchandise -> (merchandise.getGoodsType() == 1 && merchandise.getUseScope() == 2) || (merchandise.getGoodsType() == 1 && merchandise.getUseScope() == 1) || (merchandise.getGoodsType() == 4 && merchandise.getUseScope() == 2) || (merchandise.getGoodsType() == 4 && merchandise.getUseScope() == 1) || merchandise.getShopIds().contains(request.getShopId()))
-                        .collect(Collectors.toList());
-            }
-        }
 
         if (null != request.getRank()) {
             switch (request.getRank()) {
@@ -1175,6 +1321,7 @@
         if (tAppUser.getState() == 2) {
             return ResultUtil.error("您的账号已被冻结");
         }
+        boolean newUser = false;
         List<TAppUser> tAppUsers1 = appUserMapper.selectList(new LambdaQueryWrapper<TAppUser>().eq(TAppUser::getPhone, dto.getPhone()).eq(TAppUser::getState, 1));
         if (tAppUsers1.size() > 0) {
             TAppUser tAppUser1 = tAppUsers1.get(0);
@@ -1192,62 +1339,83 @@
             appUserMapper.updateById(tAppUser);
             token = getToken(tAppUser);
             map.put("token", token);
-
+            newUser = true;
         }
 
-//        tAppUser.setPhone(dto.getPhone());
-
-        if (ToolUtil.isNotEmpty(dto.getInvitePhone())) {
+        if (newUser && ToolUtil.isNotEmpty(dto.getInvitePhone())) {
             if (ToolUtil.isEmpty(dto.getLat()) || ToolUtil.isEmpty(dto.getLon())) {
                 return ResultUtil.error("请先开启定位");
             }
-            TAppUser tAppUser1 = appUserMapper.selectOne(new LambdaQueryWrapper<TAppUser>().eq(TAppUser::getPhone, dto.getInvitePhone()).eq(TAppUser::getState, 1));
-            if (tAppUser1 != null) {
-                Map<String, String> geocode = null;
-                try {
-                    geocode = gdMapGeocodingUtil.geocode(dto.getLon(), dto.getLat());
-                } catch (Exception e) {
-                    e.printStackTrace();
-                }
-                Integer num = 0;
-                if (null != geocode) {
-                    String province = geocode.get("province");
-                    String provinceCode = geocode.get("provinceCode");
-                    String city = geocode.get("city");
-                    String cityCode = geocode.get("cityCode");
-                    IntroduceRewards giftList = introduceRewardsClient.getGiftList(cityCode);
-                    num = giftList.getGiveClass();
-                }
-                Integer userId = null;
-                if (ToolUtil.isNotEmpty(dto.getInvitePhone())) {
-                    List<TAppUser> tAppUsers = this.baseMapper.selectList(new LambdaQueryWrapper<TAppUser>().eq(TAppUser::getPhone, dto.getInvitePhone()));
-                    if (tAppUsers.size() > 0) {
-                        userId = tAppUsers.get(0).getId();
-                    }
-                }
-                if (userId != null) {
-                    TAppGift one = appGiftService.getOne(new LambdaQueryWrapper<TAppGift>().eq(TAppGift::getUserId, userId));
-                    if (one != null) {
-                        one.setNum(one.getNum() + num);
-                        appGiftService.updateById(one);
-                    } else {
-                        TAppGift tAppGift = new TAppGift();
-                        tAppGift.setUserId(userId);
-                        tAppGift.setNum(num);
-                        appGiftService.save(tAppGift);
+            TAppUser tAppUser1 = appUserMapper.selectOne(new LambdaQueryWrapper<TAppUser>()
+                    .eq(TAppUser::getPhone, dto.getInvitePhone()).eq(TAppUser::getState, 1));
+            if (null == tAppUser1) {
+                return ResultUtil.error("邀请人还未注册账号");
+            }
+            Map<String, String> geocode = null;
+            try {
+                geocode = gdMapGeocodingUtil.geocode(dto.getLon(), dto.getLat());
+            } catch (Exception e) {
+                e.printStackTrace();
+            }
+            if (null != geocode) {
+                String cityCode = geocode.get("cityCode");
+                // 根据所在市code 查询是否有介绍有礼活动
+                List<IntroduceRewards> res = introduceRewardsClient.getGiftList(cityCode);
+                if (res != null) {
+                    for (IntroduceRewards re : res) {
+                        Integer num = re.getGiveClass();
+                        Integer activityId = re.getId();
+                        if (num != 0) {
+                            TAppGift tAppGift = new TAppGift();
+                            tAppGift.setUserName(tAppUser1.getName());
+                            tAppGift.setUserPhone(tAppUser1.getPhone());
+                            tAppGift.setUserId(tAppUser1.getId());
+                            tAppGift.setNum(num);
+                            tAppGift.setShareUserId(tAppUser.getId());
+                            tAppGift.setShareUserName(tAppUser.getPhone());
+                            tAppGift.setShareUserPhone(tAppUser.getPhone());
+                            tAppGift.setActivityId(activityId);
+                            tAppGift.setInsertTime(new Date());
+                            appGiftService.save(tAppGift);
+                        }
                     }
                 }
             }
         }
-
-//        appUserMapper.updateById(tAppUser);
-
         return ResultUtil.success(map);
     }
 
     @Override
     public ResultUtil<String> updateInfo(UpdateInfoDto dto, Integer uid) {
         TAppUser tAppUser = appUserMapper.selectById(uid);
+        if (StringUtils.hasLength(dto.getName())){
+            if (!tAppUser.getName().equals(dto.getName())){
+                TUserAudit userAudit = userAuditService
+                        .lambdaQuery().eq(TUserAudit::getType, 1)
+                        .eq(TUserAudit::getAppUserId, tAppUser.getId())
+                        .ne(TUserAudit::getState, 2).last("limit 1").one();
+                if (userAudit!=null){
+                    userAudit.setState(1);
+                    userAudit.setName(dto.getName());
+                    UpdateWrapper<TUserAudit> tUserAuditUpdateWrapper = new UpdateWrapper<>();
+                    tUserAuditUpdateWrapper.eq("id",userAudit.getId());
+                    tUserAuditUpdateWrapper.set("state",1);
+                    tUserAuditUpdateWrapper.set("name",dto.getName());
+                    tUserAuditUpdateWrapper.set("remarks",null);
+                    tUserAuditUpdateWrapper.set("auditId",null);
+                    tUserAuditUpdateWrapper.set("auditTime",null);
+                    userAuditService.update(tUserAuditUpdateWrapper);
+                }else{
+                    TUserAudit tUserAudit = new TUserAudit();
+                    tUserAudit.setAppUserId(tAppUser.getId());
+                    tUserAudit.setName(dto.getName());
+                    tUserAudit.setType(1);
+                    tUserAudit.setInsertTime(new Date());
+                    userAuditService.save(tUserAudit);
+
+                }
+            }
+        }
         if (ToolUtil.isNotEmpty(dto.getName())) {
             tAppUser.setName(dto.getName());
         }
@@ -1264,6 +1432,7 @@
         if (ToolUtil.isNotEmpty(dto.getGender())) {
             tAppUser.setGender(dto.getGender());
         }
+        tAppUser.setName(null);
         appUserMapper.updateById(tAppUser);
         return ResultUtil.success();
     }
@@ -1312,6 +1481,10 @@
     @Override
     @Transactional
     public synchronized ResultUtil productRedemptionOperation(Integer userIdFormRedis, GoodsExchangeVo exchangeType) {
+        // 兼容前端历史参数 chooseCouponId,内部统一使用 couponId。
+        if (exchangeType.getCouponId() == null && exchangeType.getChooseCouponId() != null) {
+            exchangeType.setCouponId(exchangeType.getChooseCouponId());
+        }
         ReturnModel returnModel = new ReturnModel();
         Long returnId = null;
         //如果是兑换优惠卷
@@ -1328,11 +1501,9 @@
             }
             //查询该用户是否超出限领数量
             Integer usercounts = userConponClient.queryCounts1(queryIds);
-
             if (usercounts == coupon.getPickUpQuantity()) {
                 return new ResultUtil<>(0, "限领数量已达最大");
             }
-
             SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
             String code = sdf.format(new Date()) + UUIDUtil.getNumberRandom(5);
             //生成支付订单
@@ -1348,7 +1519,7 @@
             userCouponPayment.setInsertTime(new Date());
 
             //积分兑换
-            if(coupon.getRedemptionMethod() == 1){
+            if (coupon.getRedemptionMethod() == 1) {
                 UserCoupon userCoupon = new UserCoupon();
                 userCoupon.setCouponId(exchangeType.getGoodId());
                 userCoupon.setUserId(userIdFormRedis);
@@ -1369,13 +1540,13 @@
                 return ResultUtil.success(returnId);
             }
             //积分+现金
-            if(coupon.getRedemptionMethod() == 2){
+            if (coupon.getRedemptionMethod() == 2) {
                 userCouponPaymentClient.addUserCouponPayment(userCouponPayment);
                 try {
-                    if(exchangeType.getPayType() == 1){
+                    if (exchangeType.getPayType() == 1) {
                         return weChatPaymentCoupon("购买优惠券", userCouponPayment);
                     }
-                    if(exchangeType.getPayType() == 2){
+                    if (exchangeType.getPayType() == 2) {
                         return aliPaymentCoupon("购买优惠券", userCouponPayment);
                     }
                 } catch (Exception e) {
@@ -1383,16 +1554,14 @@
                 }
             }
         }
-
-
-        System.out.println(exchangeType);
+        System.out.println("兑换积分商品" + exchangeType);
         try {
             SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
             String code = sdf.format(new Date()) + UUIDUtil.getNumberRandom(5);
             PointsMerchandise merchandise = new PointsMerchandise();
-            if(exchangeType.getGoodsType() != 4){
+            if (exchangeType.getGoodsType() != 4) {
                 merchandise = mcClient.selectPointsMerchandiseById(exchangeType.getGoodId());
-            }else{
+            } else {
                 Coupon coupon = ucponClient.queryCouponById(exchangeType.getGoodId());
                 merchandise.setId(coupon.getId());
                 merchandise.setUserPopulation(coupon.getUserPopulation());
@@ -1407,6 +1576,51 @@
 
             if (ToolUtil.isEmpty(merchandise)) {
                 return ResultUtil.error("商品不存在");
+            }
+
+            BigDecimal cashAmount = merchandise.getCash() == null ? BigDecimal.ZERO : merchandise.getCash();
+            // 门票优惠后的订单现金应付总额;支付参数必须使用该金额,不能再使用商品原价。
+            BigDecimal ticketPayableCashAmount = null;
+            UserCoupon usedCoupon = null;
+            if (exchangeType.getGoodsType() == 3 && exchangeType.getCouponId() != null && exchangeType.getCouponId() != 0) {
+                if (exchangeType.getExchangeType() == 1) {
+                    return ResultUtil.error("积分兑换不能使用优惠券");
+                }
+                usedCoupon = userConponClient.queryUserCouponById(
+                        new QueryUserCouponByIdAndUserId(exchangeType.getCouponId(), userIdFormRedis));
+                if (usedCoupon == null || !Integer.valueOf(1).equals(usedCoupon.getStatus())) {
+                    return ResultUtil.error("优惠券不可用");
+                }
+                Coupon coupon = userConponClient.queryCouponById(usedCoupon.getCouponId());
+                if (coupon == null || coupon.getEndTime() == null || !coupon.getEndTime().after(new Date())) {
+                    return ResultUtil.error("优惠券已过期");
+                }
+                if (Integer.valueOf(3).equals(coupon.getUseScope())
+                        && (exchangeType.getStoreId() == null || !userConponClient.getCouponStoreIds(coupon.getId()).contains(exchangeType.getStoreId()))) {
+                    return ResultUtil.error("该优惠券不适用于所选门店");
+                }
+                BigDecimal orderCash = cashAmount.multiply(BigDecimal.valueOf(exchangeType.getNums() == null ? 1 : exchangeType.getNums()));
+                JSONObject rule = JSON.parseObject(coupon.getContent());
+                if (Integer.valueOf(1).equals(coupon.getType())) {
+                    BigDecimal condition = rule.getBigDecimal("conditionalAmount");
+                    BigDecimal deduction = rule.getBigDecimal("deductionAmount");
+                    if (condition == null || deduction == null || orderCash.compareTo(condition) < 0) {
+                        return ResultUtil.error("该优惠券无法使用");
+                    }
+                    cashAmount = orderCash.subtract(deduction).max(BigDecimal.ZERO)
+                            .divide(BigDecimal.valueOf(exchangeType.getNums() == null ? 1 : exchangeType.getNums()), 2, java.math.RoundingMode.HALF_UP);
+                } else if (Integer.valueOf(2).equals(coupon.getType())) {
+                    BigDecimal deduction = rule.getBigDecimal("conditionalAmount");
+                    if (deduction == null || deduction.compareTo(BigDecimal.ZERO) <= 0) {
+                        return ResultUtil.error("该优惠券无法使用");
+                    }
+                    // 代金券可覆盖全部订单金额,超出订单金额的部分不找零。
+                    ticketPayableCashAmount = orderCash.subtract(deduction).max(BigDecimal.ZERO);
+                    cashAmount = ticketPayableCashAmount
+                            .divide(BigDecimal.valueOf(exchangeType.getNums() == null ? 1 : exchangeType.getNums()), 2, java.math.RoundingMode.HALF_UP);
+                } else {
+                    return ResultUtil.error("该优惠券不支持购买门票");
+                }
             }
 
             TAppUser tAppUser = this.baseMapper.selectById(userIdFormRedis);
@@ -1433,6 +1647,9 @@
             } else {
                 goodsNums = exchangeType.getNums();
             }
+            BigDecimal cashPaymentAmount = ticketPayableCashAmount == null
+                    ? cashAmount.multiply(BigDecimal.valueOf(goodsNums))
+                    : ticketPayableCashAmount;
 
             TAppUser user = appUserService.getById(userIdFormRedis);
             if (merchandise.getIntegral() != null) {
@@ -1454,130 +1671,204 @@
                 return ResultUtil.error("超过发放数量");
             }
 
-
-            for (int i = 0; i < goodsNums; i++) {
-//            新增积分商品兑换记录
-                UserPointsMerchandise pointsMerchandise = new UserPointsMerchandise();
-                pointsMerchandise.setPointsMerchandiseId(exchangeType.getGoodId());
-                pointsMerchandise.setUserId(userIdFormRedis);
+            //新增积分商品兑换记录
+            UserPointsMerchandise pointsMerchandise = new UserPointsMerchandise();
+            pointsMerchandise.setPointsMerchandiseId(exchangeType.getGoodId());
+            pointsMerchandise.setUserId(userIdFormRedis);
+            pointsMerchandise.setGoodsNumber(goodsNums);
+            if (exchangeType.getGoodsType() == 2) {
+                pointsMerchandise.setStatus(2);
+                pointsMerchandise.setVerificationTime(new Date());
+            } else {
+                pointsMerchandise.setStatus(1);
+            }
+            pointsMerchandise.setState(1);
+            if (exchangeType.getExchangeType() == 1) {
+                pointsMerchandise.setPayStatus(2);
+                pointsMerchandise.setPaymentTime(new Date());
+            } else if (cashPaymentAmount.compareTo(BigDecimal.ZERO) == 0) {
+                // 优惠券将现金部分完全抵扣时,不能向第三方支付发起 0 元或原价支付。
+                pointsMerchandise.setPayStatus(2);
+                pointsMerchandise.setPaymentTime(new Date());
+            } else {
+                pointsMerchandise.setPayStatus(1);
+            }
+            if (merchandise.getUseScope() == 3) {
                 if (exchangeType.getGoodsType() == 2) {
-                    pointsMerchandise.setStatus(2);
-                    pointsMerchandise.setVerificationTime(new Date());
+                    CoursePackage coursePackage = cpageClient.queryCoursePackageById(merchandise.getCoursePackageId());
+                    pointsMerchandise.setStoreId(coursePackage.getStoreId());
                 } else {
-                    pointsMerchandise.setStatus(1);
+                    pointsMerchandise.setStoreId(exchangeType.getStoreId());
                 }
-                pointsMerchandise.setState(1);
-                if (exchangeType.getExchangeType() == 1) {
-                    pointsMerchandise.setPayStatus(2);
-                } else {
-                    pointsMerchandise.setPayStatus(1);
-                }
-                if (merchandise.getUseScope() == 3) {
-                    if (exchangeType.getGoodsType() == 2) {
-                        CoursePackage coursePackage = cpageClient.queryCoursePackageById(merchandise.getCoursePackageId());
-                        pointsMerchandise.setStoreId(coursePackage.getStoreId());
-                    } else {
-                        pointsMerchandise.setStoreId(exchangeType.getStoreId());
-                    }
-                }
-                pointsMerchandise.setCode(code);
-                pointsMerchandise.setInsertTime(new Date());
-                returnId = mcClient.saveDetailsUserPointMercase(pointsMerchandise);
+            }
+            pointsMerchandise.setCode(code);
+            pointsMerchandise.setInsertTime(new Date());
+            pointsMerchandise.setPayType(exchangeType.getExchangeType());
+            pointsMerchandise.setUserCouponId(exchangeType.getGoodsType() == 3 ? exchangeType.getCouponId() : null);
+            if (null != merchandise.getIntegral()) {
+                pointsMerchandise.setIntegral(merchandise.getIntegral() * goodsNums);
+            }
+            if (exchangeType.getExchangeType() == 2 || exchangeType.getExchangeType() == 3) {
+                pointsMerchandise.setCash(exchangeType.getGoodsType() == 3 ? cashPaymentAmount : cashAmount);
+                pointsMerchandise.setCashPayType(exchangeType.getPayType());
             }
 
+            Double m = new BigDecimal((merchandise.getIntegral() == null ? 0 : merchandise.getIntegral())).add(cashAmount).doubleValue();
+            if ((m * goodsNums) == 0) {
+                pointsMerchandise.setPayStatus(2);
+                pointsMerchandise.setPaymentTime(new Date());
+            }
+            returnId = mcClient.saveDetailsUserPointMercase(pointsMerchandise);
+            if (usedCoupon != null) {
+                usedCoupon.setStatus(2);
+                userConponClient.updateUserCoupon(usedCoupon);
+            }
+            if(goodsNums>1){
+                System.err.println("购买商品数量"+goodsNums);
+                List<UserPointsMerchandise> userPointsMerchandises = new ArrayList<>();
+                for (int i = 1; i < goodsNums; i++) {
+                    UserPointsMerchandise userPointsMerchandise = new UserPointsMerchandise();
+                    BeanUtils.copyProperties(pointsMerchandise, userPointsMerchandise);
+                    // 一笔订单只能关联一次优惠券,避免拆分门票后重复计入优惠金额。
+                    userPointsMerchandise.setUserCouponId(null);
+                    if (exchangeType.getGoodsType() == 3) {
+                        // 门票拆单后仅首条保留订单总实付金额,避免支付/收入统计重复累加。
+                        userPointsMerchandise.setCash(BigDecimal.ZERO);
+                    }
+                    userPointsMerchandises.add(userPointsMerchandise);
+                }
+                System.err.println("新增额外购买记录"+userPointsMerchandises);
+                Boolean b = mcClient.saveDetailsUserPointMercaseList(userPointsMerchandises);
+                if (b){
+                    System.err.println("多条商品新增成功");
+                }else{
+                    System.err.println("多条商品新增失败");
+                }
+
+            }
+            if (pointsMerchandise.getPayStatus() == 2 && exchangeType.getExchangeType() != 1
+                    && cashPaymentAmount.compareTo(BigDecimal.ZERO) == 0) {
+                // 积分+现金商品被优惠券抵扣为零元时,仍需扣除积分;不等待支付回调。
+                if (exchangeType.getExchangeType() == 2 && merchandise.getIntegral() != null
+                        && merchandise.getIntegral() > 0
+                        && !dealAppUserIntegral(userIdFormRedis, tAppUser, merchandise.getIntegral() * goodsNums)) {
+                    return ResultUtil.error("用户积分不足!");
+                }
+                returnModel.setReturnId(returnId);
+                returnModel.setPaySuccess(true);
+                return ResultUtil.success(returnModel);
+            }
+
+            System.err.println("兑换方式" + exchangeType);
             switch (exchangeType.getExchangeType()) {
 //            积分
                 case 1:
-                    boolean b = true;
-                    for (int i = 0; i < goodsNums; i++) {
-                        b = dealAppUserIntegral(userIdFormRedis, tAppUser, merchandise.getIntegral());
+                    boolean b = dealAppUserIntegral(userIdFormRedis, tAppUser, merchandise.getIntegral() * goodsNums);
+                    if (b) switch (exchangeType.getGoodsType()) {
+                        case 2:
+                            code = sdf.format(new Date()) + UUIDUtil.getNumberRandom(5);
+                            List<CoursePackagePaymentConfig> courseConfigList = cpconClient.getCourseConfigList(merchandise.getCoursePackageId());
+                            CoursePackageOrder coursePackageOrder = new CoursePackageOrder();
+                            coursePackageOrder.setCode(code);
+                            coursePackageOrder.setAppUserId(userIdFormRedis);
+                            String ids = exchangeType.getStuIds().stream().map(s -> {
+                                return String.valueOf(s);
+                            }).collect(Collectors.joining(";"));
+                            coursePackageOrder.setStudentIds(ids);
+                            coursePackageOrder.setCoursePackageId(merchandise.getCoursePackageId());
+                            coursePackageOrder.setPayType(4);
+                            CoursePackagePaymentConfig config = null;
+                            for (CoursePackagePaymentConfig coursePackagePaymentConfig : courseConfigList) {
+                                if (coursePackagePaymentConfig.getId().compareTo(merchandise.getCoursePackageConfigId()) == 0) {
+                                    coursePackageOrder.setClassHours(coursePackagePaymentConfig.getClassHours());
+                                    coursePackageOrder.setOriginalPrice(coursePackagePaymentConfig.getCashPayment());
+
+                                    config = coursePackagePaymentConfig;
+                                    break;
+                                }
+                            }
+                            coursePackageOrder.setPlayPaiCoin(merchandise.getIntegral());
+                            coursePackageOrder.setPayUserType(1);
+                            coursePackageOrder.setPayStatus(2);
+                            coursePackageOrder.setPayUserId(userIdFormRedis);
+                            coursePackageOrder.setStatus(1);
+                            coursePackageOrder.setState(1);
+                            coursePackageOrder.setInsertTime(new Date());
+                            coursePackageOrder.setOrderType(2);
+                            Long coursePackageOrderId = paymentClient.savePaymentCoursePackage(coursePackageOrder);
+
+                            AddCoursePackageOrderStudent addCoursePackageOrderStudent = new AddCoursePackageOrderStudent();
+                            addCoursePackageOrderStudent.setCoursePackageOrderId(coursePackageOrderId);
+                            addCoursePackageOrderStudent.setCoursePackagePaymentConfig(config);
+                            paymentClient.addCoursePackageOrderStudent(addCoursePackageOrderStudent);
+                            break;
+                        case 4:
+                            for (int i = 0; i < goodsNums; i++) {
+                                UserCoupon coupon = new UserCoupon();
+                                coupon.setCouponId(exchangeType.getGoodId());
+                                coupon.setUserId(userIdFormRedis);
+                                coupon.setStatus(1);
+                                coupon.setInsertTime(new Date());
+                                ucponClient.insertToAppuserCoupon(coupon);
+                            }
+                            break;
+                        default:
+                            break;
                     }
-                    if (b) {
-                        switch (exchangeType.getGoodsType()) {
-                            case 2:
-                                Integer stuNums = 0;
-                                if (ToolUtil.isNotEmpty(exchangeType.getStuIds())) {
-                                    stuNums = exchangeType.getStuIds().size();
-                                } else {
-                                    stuNums = 1;
-                                }
-                                for (int i = 0; i < stuNums; i++) {
-                                    List<CoursePackagePaymentConfig> courseConfigList = cpconClient.getCourseConfigList(merchandise.getCoursePackageId());
-                                    TCoursePackagePayment packagePayment = new TCoursePackagePayment();
-                                    packagePayment.setAppUserId(userIdFormRedis);
-                                    packagePayment.setStudentId(exchangeType.getStuIds().get(i));
-                                    packagePayment.setCoursePackageId(merchandise.getCoursePackageId());
-                                    for (CoursePackagePaymentConfig coursePackagePaymentConfig : courseConfigList) {
-                                        if (Objects.equals(coursePackagePaymentConfig.getId(), merchandise.getCoursePackageConfigId())) {
-                                            packagePayment.setClassHours(coursePackagePaymentConfig.getClassHours());
-                                            packagePayment.setTotalClassHours(coursePackagePaymentConfig.getClassHours());
-                                            packagePayment.setLaveClassHours(coursePackagePaymentConfig.getClassHours());
-                                            packagePayment.setOriginalPrice(coursePackagePaymentConfig.getCashPayment());
-                                            break;
-                                        }
-                                    }
-                                    packagePayment.setPlayPaiCoin(merchandise.getIntegral());
-                                    packagePayment.setAbsencesNumber(0);
-                                    packagePayment.setPayUserType(1);
-                                    packagePayment.setPayStatus(2);
-                                    packagePayment.setPayUserId(userIdFormRedis);
-                                    packagePayment.setStatus(1);
-                                    packagePayment.setState(1);
-                                    packagePayment.setCode(code);
-                                    packagePayment.setInsertTime(new Date());
-//                                    paymentClient.savePaymentCoursePackage(packagePayment);
-
-                                    OrderDto orderDto = new OrderDto();
-                                    orderDto.setAppUserId(userIdFormRedis);
-                                    String joinedString = String.join(",", exchangeType.getStuIds().stream().map(Object::toString).collect(Collectors.toList()));
-                                    orderDto.setStuIds(joinedString);
-                                    orderDto.setClassId(merchandise.getCoursePackageId());
-                                    orderDto.setClassHours(packagePayment.getClassHours());
-                                    paymentClient.orderClass(orderDto);
-
-
-                                }
-                                break;
-                            case 4:
-                                for (int i = 0; i < goodsNums; i++) {
-                                    UserCoupon coupon = new UserCoupon();
-                                    coupon.setCouponId(exchangeType.getGoodId());
-                                    coupon.setUserId(userIdFormRedis);
-                                    coupon.setStatus(1);
-                                    coupon.setInsertTime(new Date());
-                                    ucponClient.insertToAppuserCoupon(coupon);
-                                }
-                                break;
-                            default:
-                                break;
-                        }
-                    } else {
+                    else {
                         return ResultUtil.error("用户积分不足!");
                     }
                     break;
                 case 2:
 //                积分+现金
-                    boolean dealt = true;
-                    for (int i = 0; i < goodsNums; i++) {
-                        dealt = dealAppUserIntegral(userIdFormRedis, tAppUser, merchandise.getIntegral());
-                    }
-
                     switch (exchangeType.getPayType()) {
                         case 1:
                             try {
                                 if (merchandise.getType() == 2) {
-                                    return WechatPayment(merchandise.getCash().multiply(new BigDecimal(exchangeType.getStuIds().size())), code);
-                                } else {
-                                    return WechatPayment(merchandise.getCash().multiply(new BigDecimal(goodsNums)), code);
+                                    List<CoursePackagePaymentConfig> courseConfigList = cpconClient.getCourseConfigList(merchandise.getCoursePackageId());
+                                    CoursePackageOrder coursePackageOrder = new CoursePackageOrder();
+                                    coursePackageOrder.setCode(code);
+                                    coursePackageOrder.setAppUserId(userIdFormRedis);
+                                    String ids = exchangeType.getStuIds().stream().map(s -> {
+                                        return String.valueOf(s);
+                                    }).collect(Collectors.joining(";"));
+                                    coursePackageOrder.setStudentIds(ids);
+                                    coursePackageOrder.setCoursePackageId(merchandise.getCoursePackageId());
+                                    coursePackageOrder.setPayType(5);
+                                    CoursePackagePaymentConfig config = null;
+                                    for (CoursePackagePaymentConfig coursePackagePaymentConfig : courseConfigList) {
+                                        if (coursePackagePaymentConfig.getId().compareTo(merchandise.getCoursePackageConfigId()) == 0) {
+                                            coursePackageOrder.setClassHours(coursePackagePaymentConfig.getClassHours());
+                                            coursePackageOrder.setOriginalPrice(coursePackagePaymentConfig.getCashPayment());
+                                            break;
+                                        }
+                                    }
+                                    coursePackageOrder.setCashPayment(cashAmount.multiply(new BigDecimal(exchangeType.getStuIds().size())));
+                                    coursePackageOrder.setPlayPaiCoin(merchandise.getIntegral() * exchangeType.getStuIds().size());
+                                    coursePackageOrder.setPayUserType(1);
+                                    coursePackageOrder.setPayStatus(1);
+                                    coursePackageOrder.setPayUserId(userIdFormRedis);
+                                    coursePackageOrder.setStatus(1);
+                                    coursePackageOrder.setState(1);
+                                    coursePackageOrder.setInsertTime(new Date());
+                                    coursePackageOrder.setOrderType(2);
+                                    paymentClient.savePaymentCoursePackage(coursePackageOrder);
+                                    return WechatPayment(merchandise.getType(), cashAmount.multiply(new BigDecimal(exchangeType.getStuIds().size())), code, merchandise.getId());
+                                } else if (merchandise.getType() == 1) {
+                                    return WechatPayment(merchandise.getType(), cashAmount.multiply(new BigDecimal(goodsNums)), code, merchandise.getId());
+                                } else if (merchandise.getType() == 3) {
+                                    return WechatPayment(merchandise.getType(), cashPaymentAmount, code, merchandise.getId());
                                 }
                             } catch (Exception e) {
                                 return ResultUtil.runErr();
                             }
                         case 2:
                             if (merchandise.getType() == 2) {
-                                return AlipayPayment(merchandise.getCash().multiply(new BigDecimal(exchangeType.getStuIds().size())), code, returnId);
+                                return AlipayPayment(merchandise.getType(), cashAmount.multiply(new BigDecimal(exchangeType.getStuIds().size())), code, merchandise.getId());
+                            } else if (merchandise.getType() == 3) {
+                                return AlipayPayment(merchandise.getType(), cashPaymentAmount, code, merchandise.getId());
                             } else {
-                                return AlipayPayment(merchandise.getCash().multiply(new BigDecimal(goodsNums)), code, returnId);
+                                return AlipayPayment(merchandise.getType(), cashAmount.multiply(new BigDecimal(goodsNums)), code, merchandise.getId());
                             }
                         default:
                             break;
@@ -1588,18 +1879,22 @@
                         case 1:
                             try {
                                 if (merchandise.getType() == 2) {
-                                    return WechatPayment(merchandise.getCash().multiply(new BigDecimal(exchangeType.getStuIds().size())), code);
+                                    return WechatPayment(merchandise.getType(), cashAmount.multiply(new BigDecimal(exchangeType.getStuIds().size())), code, merchandise.getId());
+                                } else if (merchandise.getType() == 3) {
+                                    return WechatPayment(merchandise.getType(), cashPaymentAmount, code, merchandise.getId());
                                 } else {
-                                    return WechatPayment(merchandise.getCash().multiply(new BigDecimal(goodsNums)), code);
+                                    return WechatPayment(merchandise.getType(), cashAmount.multiply(new BigDecimal(goodsNums)), code, merchandise.getId());
                                 }
                             } catch (Exception e) {
                                 return ResultUtil.runErr();
                             }
                         case 2:
                             if (merchandise.getType() == 2) {
-                                return AlipayPayment(merchandise.getCash().multiply(new BigDecimal(exchangeType.getStuIds().size())), code, returnId);
+                                return AlipayPayment(merchandise.getType(), cashAmount.multiply(new BigDecimal(exchangeType.getStuIds().size())), code, merchandise.getId());
+                            } else if (merchandise.getType() == 3) {
+                                return AlipayPayment(merchandise.getType(), cashPaymentAmount, code, merchandise.getId());
                             } else {
-                                return AlipayPayment(merchandise.getCash().multiply(new BigDecimal(goodsNums)), code, returnId);
+                                return AlipayPayment(merchandise.getType(), cashAmount.multiply(new BigDecimal(goodsNums)), code, merchandise.getId());
                             }
                         default:
                             break;
@@ -1610,6 +1905,7 @@
             }
 
             returnModel.setReturnId(returnId);
+            returnModel.setPaySuccess(pointsMerchandise.getPayStatus() == 2);
             return ResultUtil.success(returnModel);
         } catch (Exception e) {
             e.printStackTrace();
@@ -1618,9 +1914,9 @@
 
     }
 
-
     /**
      * 优惠券微信支付
+     *
      * @param body
      * @param userCouponPayment
      * @return
@@ -1629,75 +1925,34 @@
     public ResultUtil weChatPaymentCoupon(String body, UserCouponPayment userCouponPayment) throws Exception {
         String code = userCouponPayment.getCode();
         Double cash = userCouponPayment.getCash();
-        ResultUtil weixinpay = payMoneyUtil.weixinpay(body, "", code, cash.toString(), "/base/coupon/weChatPaymentCouponCallback", "APP", "");
-        if (weixinpay.getCode() == 200) {
-            new Thread(new Runnable() {
-                @Override
-                public void run() {
-                    try {
-                        int num = 1;
-                        int wait = 0;
-                        while (num <= 10) {
-                            int min = 5000;
-                            wait += (min * num);
-                            Thread.sleep(wait);
-                            UserCouponPayment userCouponPayment1 = userCouponPaymentClient.getUserCouponPayment(code);
-                            if (userCouponPayment1.getStatus() == 2) {
-                                break;
-                            }
-                            ResultUtil<Map<String, String>> resultUtil = payMoneyUtil.queryWXOrder(code, "");
-                            if (resultUtil.getCode() == 200 && userCouponPayment1.getStatus() == 1) {
-                                /**
-                                 * SUCCESS—支付成功,
-                                 * REFUND—转入退款,
-                                 * NOTPAY—未支付,
-                                 * CLOSED—已关闭,
-                                 * REVOKED—已撤销(刷卡支付),
-                                 * USERPAYING--用户支付中,
-                                 * PAYERROR--支付失败(其他原因,如银行返回失败)
-                                 */
-                                Map<String, String> data1 = resultUtil.getData();
-                                String s = data1.get("trade_state");
-                                String transaction_id = data1.get("transaction_id");
-                                if ("REFUND".equals(s) || "NOTPAY".equals(s) || "CLOSED".equals(s) || "REVOKED".equals(s) || "PAYERROR".equals(s) || num == 10) {
-                                    //有待支付的订单,这里不处理
-                                    userCouponPayment1.setStatus(-1);
-                                    userCouponPaymentClient.updateUserCouponPayment(userCouponPayment1);
-                                    break;
-                                }
-                                if ("SUCCESS".equals(s)) {
-                                    userCouponPayment1.setStatus(2);
-                                    userCouponPayment1.setPaymentTime(new Date());
-                                    userCouponPayment1.setOrderNumber(transaction_id);
-                                    userCouponPaymentClient.updateUserCouponPayment(userCouponPayment1);
+        Integer couponId = userCouponPayment.getCouponId();
+        Coupon coupon = userConponClient.queryCouponById(couponId);
+        List<Integer> couponStoreIds = userConponClient.getCouponStoreIds(couponId);
+        System.err.println("购买优惠券");
+        if (coupon != null) {
+            if (!couponStoreIds.isEmpty() && !couponStoreIds.contains(-1)) {
+                Store store = storeClient.queryStoreById(couponStoreIds.get(0));
+                // 微信商户号
+                String s2 = storeClient.getmerchantNumberByOperatorId(store.getOperatorId());
+                System.err.println("微信商户号" + s2);
 
-                                    UserCoupon userCoupon = new UserCoupon();
-                                    userCoupon.setCouponId(userCouponPayment1.getCouponId());
-                                    userCoupon.setUserId(userCouponPayment1.getUserId());
-                                    userCoupon.setStatus(1);
-                                    userCoupon.setInsertTime(new Date());
-                                    userConponClient.insertToAppuserCoupon(userCoupon);
-
-                                    if(null != userCouponPayment1.getIntegral() && 0 != userCouponPayment1.getIntegral()){
-                                        //扣积分
-                                        TAppUser user = appUserService.getById(userCouponPayment1.getUserId());
-                                        user.setIntegral(user.getIntegral() - userCouponPayment1.getIntegral().intValue());
-                                        appUserService.updateById(user);
-                                    }
-                                    break;
-                                }
-                                if ("USERPAYING".equals(s)) {
-                                    num++;
-                                }
-                            }
-                        }
-                    } catch (Exception e) {
-                        e.printStackTrace();
-                    }
+                if (!StringUtils.hasLength(s2)) {
+                    return ResultUtil.error("运营商未配置微信商户号,获取支付失败!");
                 }
-            }).start();
+                ResultUtil weixinpay = payMoneyUtil.weixinpayV3(s2, "购买优惠券",
+                        code, "/base/coupon/weChatPaymentCouponCallback1",
+                        cash.toString());
+                return weixinpay;
+
+            } else {
+                // 平台发布
+                ResultUtil weixinpay = payMoneyUtil.weixinpay(body, "", code, cash.toString(),
+                        "/base/coupon/weChatPaymentCouponCallback", "APP", "");
+                return weixinpay;
+            }
         }
-        return weixinpay;
+
+        return ResultUtil.error("支付失败!");
     }
 
 
@@ -1708,12 +1963,37 @@
      * @throws Exception
      */
     private String smid = "2088330203191220";//平台支付宝商户号
+
     public ResultUtil aliPaymentCoupon(String body, UserCouponPayment userCouponPayment) throws Exception {
+        ResultUtil alipay= ResultUtil.error("");
+        String smidRes = smid;// 结算资金到商户号
         String code = userCouponPayment.getCode();
         Double cash = userCouponPayment.getCash();
+        Integer couponId = userCouponPayment.getCouponId();
+        Coupon coupon = userConponClient.queryCouponById(couponId);
+        List<Integer> couponStoreIds = userConponClient.getCouponStoreIds(couponId);
+        if (coupon != null) {
+            if (!couponStoreIds.isEmpty() && !couponStoreIds.contains(-1)) {
+                // 门店 向上查询运营商
+                Store store = storeClient.queryStoreById(couponStoreIds.get(0));
+                if (store.getOperatorId() == null || store.getOperatorId() == 0) {
 
-        ResultUtil alipay = payMoneyUtil.alipay(smid, body, "",String.valueOf(userCouponPayment.getId()), code, cash.toString(), "/base/coupon/aliPaymentCouponCallback");
+                } else {
+                    // 支付宝商户号
+                    String s2 = storeClient.getmerchantNumberAliByOperatorId(store.getOperatorId());
+                    System.err.println("支付宝商户号" + s2);
+
+                    if (!StringUtils.hasLength(s2)) {
+                        return ResultUtil.error("运营商未配置支付宝商户号,获取支付失败!");
+                    }
+                    smidRes = s2;
+                }
+            }
+        }
+         alipay = payMoneyUtil.alipay(smidRes, body, "",String.valueOf(userCouponPayment.getId()), code, cash.toString(),
+                "/base/coupon/aliPaymentCouponCallback");
         if (alipay.getCode() == 200) {
+            String finalSmidRes = smidRes;
             new Thread(new Runnable() {
                 @Override
                 public void run() {
@@ -1745,10 +2025,7 @@
                                     //有待支付的订单,这里不处理
                                     userCouponPayment1.setStatus(-1);
                                     userCouponPaymentClient.updateUserCouponPayment(userCouponPayment1);
-                                    if ("TRADE_FINISHED".equals(s)) {
-                                        // todo 资金结算
 
-                                    }
                                     break;
                                 }
                                 if ("TRADE_SUCCESS".equals(s)) {
@@ -1768,9 +2045,9 @@
                                         user.setIntegral(user.getIntegral() - userCouponPayment1.getIntegral().intValue());
                                         appUserService.updateById(user);
                                     }
-                                    payMoneyUtil.confirm(smid,code,tradeNo,cash.toString());
+                                    Thread.sleep(30000);
+                                    payMoneyUtil.confirm(finalSmidRes,code,tradeNo,cash.toString());
                                     break;
-
                                 }
 
                                 if ("WAIT_BUYER_PAY".equals(s)) {
@@ -1789,12 +2066,14 @@
 
     /**
      * 支付回调
+     *
      * @param code
      * @param orderNumber
      * @return
      */
     @Override
-    public ResultUtil paymentCouponCallback(String code, String orderNumber) {
+    public ResultUtil paymentCouponCallback(String code, String orderNumber) throws Exception {
+        System.err.println("进入回调");
         UserCouponPayment userCouponPayment1 = userCouponPaymentClient.getUserCouponPayment(code);
         if (userCouponPayment1.getStatus() == 2) {
             return ResultUtil.success();
@@ -1811,12 +2090,17 @@
         userCoupon.setInsertTime(new Date());
         userConponClient.insertToAppuserCoupon(userCoupon);
 
-        if(null != userCouponPayment1.getIntegral() && 0 != userCouponPayment1.getIntegral()){
+        if (null != userCouponPayment1.getIntegral() && 0 != userCouponPayment1.getIntegral()) {
             //扣积分
-            TAppUser user = appUserService.getById(userCouponPayment1.getUserId());
-            user.setIntegral(user.getIntegral() - userCouponPayment1.getIntegral().intValue());
-            appUserService.updateById(user);
+            SaveUserIntegralChangesVo vo = new SaveUserIntegralChangesVo();
+            vo.setAppUserId(userCouponPayment1.getUserId());
+            vo.setIntegral(userCouponPayment1.getIntegral().intValue() * -1);
+            vo.setRemark("兑换优惠券");
+            vo.setType(2);
+            userIntegralChangesService.saveUserIntegralChanges(vo);
         }
+        Coupon coupon = ucponClient.queryCouponById(userCouponPayment1.getCouponId());
+        // 创建一个两分钟后执行的线程
         return ResultUtil.success();
     }
 
@@ -1843,8 +2127,62 @@
         }
     }
 
-    private ResultUtil AlipayPayment(BigDecimal cash, String code, Long returnId) {
-        ResultUtil alipay = payMoneyUtil.alipay(smid,"优惠卷", "优惠卷", String.valueOf(returnId), code, cash.toString(),
+    private ResultUtil AlipayPayment(Integer type, BigDecimal cash, String code, Integer returnId) {
+        ResultUtil alipay= ResultUtil.error("");
+        String smidRes = smid;// 结算资金到商户号
+        PointsMerchandise pointsMerchandise = mcClient.selectPointsMerchandiseById(returnId);
+        System.err.println("查询积分商品" + pointsMerchandise);
+        List<Integer> integers = mcsClient.queryPointMerStoreIds(pointsMerchandise.getId());
+        String name = (type == 1 ? "购买实体商品" : type == 2 ? "报名运动营" : type == 3 ? "购买门票" : "购买优惠券");
+        switch (type) {
+            case 1:
+                if (!integers.isEmpty()) {
+                    Store store1 = storeClient.queryStoreById(integers.get(0));
+                    if (store1.getOperatorId() == null || store1.getOperatorId() == 0) {
+
+                    } else {
+                        String s2 = storeClient.getmerchantNumberAliByOperatorId(store1.getOperatorId());
+                        System.err.println("支付宝商户号" + s2);
+
+                        if (!StringUtils.hasLength(s2)) {
+                            return ResultUtil.error("运营商未配置支付宝商户号,获取支付失败!");
+                        }
+                        smidRes = s2;
+                    }
+                }
+                break;
+            case 2:
+                // 判断课包属于平台还是运营商
+                CoursePackage coursePackage = cpageClient.queryCoursePackageById(pointsMerchandise.getCoursePackageId());
+                Store store = storeClient.queryStoreById(coursePackage.getStoreId());
+                if (store.getOperatorId() == null || store.getOperatorId() == 0) {
+                } else {
+                    String s2 = storeClient.getmerchantNumberAliByOperatorId(store.getOperatorId());
+                    System.err.println("支付宝商户号" + s2);
+
+                    if (!StringUtils.hasLength(s2)) {
+                        return ResultUtil.error("运营商未配置支付宝商户号,获取支付失败!");
+                    }
+                    smidRes = s2;
+                }
+                break;
+            case 3:
+                if (!integers.isEmpty()) {
+                    Store store1 = storeClient.queryStoreById(integers.get(0));
+                    if (store1.getOperatorId() == null || store1.getOperatorId() == 0) {
+
+                    } else {
+                        String s2 = storeClient.getmerchantNumberAliByOperatorId(store1.getOperatorId());
+                        System.err.println("支付宝商户号" + s2);
+                        if (!StringUtils.hasLength(s2)) {
+                            return ResultUtil.error("运营商未配置支付宝商户号,获取支付失败!");
+                        }
+                        smidRes = s2;
+                    }
+                }
+                break;
+        }
+        alipay = payMoneyUtil.alipay(smidRes, name, name, String.valueOf(returnId), code, cash.toString(),
                 "/base/pointMer/exchangeGoodPaymentAliCallback");
         if (alipay.getCode() == 200) {
             new Thread(new Runnable() {
@@ -1857,7 +2195,7 @@
                             int min = 5000;
                             wait += (min * num);
                             Thread.sleep(wait);
-                            System.out.println("code:" + code);
+                            System.out.println("支付宝查询code:" + code);
                             List<UserPointsMerchandise> userPointsMerchandises = mcClient.queryUserPointMerchaseByCode(code);
                             System.out.println("list-----" + userPointsMerchandises);
                             if (userPointsMerchandises.get(0).getPayStatus() == 2) {
@@ -1883,18 +2221,26 @@
                                 if ("TRADE_SUCCESS".equals(tradeStatus)) {
                                     for (UserPointsMerchandise userPointsMerchandise : userPointsMerchandises) {
                                         userPointsMerchandise.setPayStatus(2);
+                                        userPointsMerchandise.setPaymentTime(new Date());
                                         userPointsMerchandise.setOrderNumber(tradeNo);
-                                        userPointsMerchandise.setPayType(2);
+                                        userPointsMerchandise.setCashPayType(2);
                                         userPointsMerchandise.setInsertTime(null);
                                         userPointsMerchandise.setUserId(null);
                                         mcClient.updateDetailsUserPointMercase(userPointsMerchandise);
                                     }
-                                    moneyOut(tradeNo, tradeNo);
+                                    List<Integer> integers = mcsClient.queryPointMerStoreIds(pointsMerchandise.getId());
+                                    Store store1 = storeClient.queryStoreById(integers.get(0));
+                                    if (store1.getOperatorId()!=null && store1.getOperatorId() != 0){
+                                        String s2 = storeClient.getmerchantNumberAliByOperatorId(store1.getOperatorId());
+                                        System.err.println("查询支付宝商户号"+s2);
+                                        // todo 资金结算 支付宝推荐30s之后再进行结算
+                                        Thread.sleep(30000);
+                                        payMoneyUtil.confirm(s2,code, tradeNo,cash.toString());
+                                    }
                                     break;
                                 }
                                 if ("TRADE_FINISHED".equals(tradeStatus)) {
-                                    // todo 资金结算
-                                    payMoneyUtil.confirm(smid,code,tradeNo,cash.toString());
+
                                     break;
                                 }
 //                                if("REFUND".equals(tradeStatus) || "NOTPAY".equals(tradeStatus) || "CLOSED".equals(tradeStatus) || "REVOKED".equals(tradeStatus) || "PAYERROR".equals(tradeStatus) || num == 10){
@@ -1914,229 +2260,160 @@
                 }
             }).start();
         }
-        return alipay;
+        return appendPaySuccess(alipay);
     }
 
-    public void moneyOut(String outNum, String tradeNo) throws AlipayApiException {
-
-
-        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", aliAppid, appPrivateKey, "json", "UTF-8", alipay_public_key, "RSA2");
-        AlipayTradeOrderSettleRequest request = new AlipayTradeOrderSettleRequest();
-        AlipayTradeOrderSettleModel model = new AlipayTradeOrderSettleModel();
-        model.setOutRequestNo(outNum);
-        model.setTradeNo(tradeNo);
-        List<RoyaltyDetailInfos> royaltyDetailInfos = new ArrayList<>();
-//
-
-        AlipayTradeRoyaltyRelationBindRequest request1 = new AlipayTradeRoyaltyRelationBindRequest();
-
-
-        request1.setBizContent("{" +
-                "  \"receiver_list\":[" +
-                "    {" +
-                "      \"type\":\"loginName\"," +
-                "      \"account\":\"19522115070\"," +
-                "      \"name\":\"罗易胜\"," +
-                "      \"memo\":\"分账给测试商户\"," +
-                "    }" +
-                "  ]," +
-                "  \"out_request_no\":\"" + tradeNo + "\"" +
-                "}");
-        AlipayTradeRoyaltyRelationBindResponse response = alipayClient.execute(request1);
-        if (response.isSuccess()) {
-            System.out.println("绑定调用成功");
-        } else {
-            System.out.println("调用失败");
+    /**
+     * 支付宝、微信的成功响应仅表示已生成支付单,客户端仍需拉起第三方支付。
+     */
+    private ResultUtil appendPaySuccess(ResultUtil paymentResult) {
+        JSONObject data = paymentResult.getData() == null ? new JSONObject()
+                : JSON.parseObject(JSON.toJSONString(paymentResult.getData()));
+        if (data == null) {
+            data = new JSONObject();
         }
-
-
-//        RoyaltyDetailInfos royaltyDetailInfos1 = new RoyaltyDetailInfos();
-//        royaltyDetailInfos1.setTransOutType("loginName");
-//        royaltyDetailInfos1.setTransOut("happysports@weparklife.com");
-//        royaltyDetailInfos1.setTransInType("loginName");
-//        royaltyDetailInfos1.setTransIn("19522115070");
-////        royaltyDetailInfos1.setAmount("0.01");
-//        royaltyDetailInfos1.setAmountPercentage("100");
-
-//        royaltyDetailInfos.add(royaltyDetailInfos1);
-
-
-        List<UserPointsMerchandise> userPointsMerchandises = merChandiseClient.queryUserPointMerchaseByCode(outNum);
-//        PaymentCompetition code = paymentCompetitionService.getOne(new QueryWrapper<PaymentCompetition>().eq("code", outNum));
-        if(userPointsMerchandises.size() > 0){
-            Integer storeId = userPointsMerchandises.get(0).getStoreId();
-
-//        Competition byId1 = competitionService.getById(code.getCompetitionId());
-
-
-//        TCoursePackage byId = coursePackageService.getById(one.getCoursePackageId());
-
-
-            OperatorUser operatorUser = storeClient.queryByStoreId(storeId);
-
-
-//        Integer paymentCompetitions = competitionsClient.queryByCode(outTradeNo);
-//        Integer siteBookings = siteClient.queryByCode(outTradeNo);
-//        List<Integer> stores = new ArrayList<>();
-//        stores.add(coursePackagePayments);
-//        stores.add(paymentCompetitions);
-//        stores.add(siteBookings);
-//        OperatorUser operatorUser = siteClient.queryOperator(stores);
-
-
-            OpenApiRoyaltyDetailInfoPojo op = new OpenApiRoyaltyDetailInfoPojo();
-            op.setTransOutType("loginName");
-            op.setTransOut("happysports@weparklife.com");
-            op.setTransInType("userId");
-            op.setTransIn(operatorUser.getAlipayNum());
-            op.setAmountPercentage(Long.valueOf(operatorUser.getAlipayProportion()));
-
-            List<OpenApiRoyaltyDetailInfoPojo> ops = new ArrayList<>();
-            ops.add(op);
-            model.setRoyaltyParameters(ops);
-
-            request.setBizModel(model);
-
-
-            AlipayTradeOrderSettleResponse response1 = alipayClient.execute(request);
-            if (response1.isSuccess()) {
-                System.out.println("调用成功");
-            } else {
-                System.out.println("调用失败");
-            }
-        }
-
+        data.put("paySuccess", false);
+        return ResultUtil.getResult(paymentResult.getCode(), paymentResult.getMsg(), data);
     }
 
 
-    private ResultUtil WechatPayment(BigDecimal cash, String code) throws Exception {
-        ResultUtil weixinpay = payMoneyUtil.weixinpay("课包", "", code, cash.toString(),
-                "/base/pointMer/exchangeGoodPaymentWeChatCallback", "APP", "");
-        if (weixinpay.getCode() == 200) {
-            new Thread(new Runnable() {
-                @Override
-                public void run() {
-                    try {
-                        int num = 1;
-                        int wait = 0;
-                        while (num <= 10) {
-                            int min = 5000;
-                            wait += (min * num);
-                            Thread.sleep(wait);
-                            List<UserPointsMerchandise> userPointsMerchandises = mcClient.queryUserPointMerchaseByCode(code);
-                            if (userPointsMerchandises.get(0).getPayStatus() == 2) {
-                                break;
-                            }
-                            ResultUtil<Map<String, String>> resultUtil = payMoneyUtil.queryWXOrder(code, "");
-                            if (resultUtil.getCode() == 200 && userPointsMerchandises.get(0).getPayStatus() == 1) {
-                                /**
-                                 * SUCCESS—支付成功,
-                                 * REFUND—转入退款,
-                                 * NOTPAY—未支付,
-                                 * CLOSED—已关闭,
-                                 * REVOKED—已撤销(刷卡支付),
-                                 * USERPAYING--用户支付中,
-                                 * PAYERROR--支付失败(其他原因,如银行返回失败)
-                                 */
-                                Map<String, String> data1 = resultUtil.getData();
-                                String s = data1.get("trade_state");
-                                String transaction_id = data1.get("transaction_id");
-                                if ("REFUND".equals(s) || "NOTPAY".equals(s) || "CLOSED".equals(s) || "REVOKED".equals(s) || "PAYERROR".equals(s) || num == 10) {
-                                    mcClient.deletePaymentRecord(code);
-                                    break;
-                                }
-                                if ("SUCCESS".equals(s)) {
-                                    for (UserPointsMerchandise userPointsMerchandise : userPointsMerchandises) {
-                                        userPointsMerchandise.setPayStatus(2);
-                                        userPointsMerchandise.setOrderNumber(transaction_id);
-                                        userPointsMerchandise.setPayType(1);
-                                        mcClient.updateDetailsUserPointMercase(userPointsMerchandise);
-                                    }
-                                    break;
-                                }
-                                if ("USERPAYING".equals(s)) {
-                                    num++;
-                                }
-                            }
+
+
+    private ResultUtil WechatPayment(Integer type, BigDecimal cash, String code, Integer id) throws Exception {
+        String name = (type == 1 ? "购买实体商品" : type == 2 ? "报名运动营" : type == 3 ? "购买门票" : "购买优惠券");
+        System.err.println("微信支付:" + name);
+
+        PointsMerchandise pointsMerchandise = mcClient.selectPointsMerchandiseById(id);
+        System.err.println("查询积分商品" + pointsMerchandise);
+        List<Integer> integers = mcsClient.queryPointMerStoreIds(pointsMerchandise.getId());
+
+        switch (type) {
+            case 1:
+                if (!integers.isEmpty()) {
+                    Store store1 = storeClient.queryStoreById(integers.get(0));
+                    if (store1.getOperatorId() == null || store1.getOperatorId() == 0) {
+                        // 平台门票
+                        ResultUtil weixinpay = payMoneyUtil.weixinpay(name, "", code, cash.toString(),
+                                "/base/pointMer/exchangeGoodPaymentWeChatCallback", "APP", "");
+                        return appendPaySuccess(weixinpay);
+                    } else {
+                        String s2 = storeClient.getmerchantNumberByOperatorId(store1.getOperatorId());
+                        System.err.println("微信商户号" + s2);
+
+                        if (!StringUtils.hasLength(s2)) {
+                            return ResultUtil.error("运营商未配置微信商户号,获取支付失败!");
                         }
-                    } catch (Exception e) {
-                        e.printStackTrace();
+                        ResultUtil weixinpay = payMoneyUtil.weixinpayV3(s2, name, code,
+                                "/base/pointMer/exchangeGoodPaymentWeChatCallback1",
+                                cash.toString());
+                        return appendPaySuccess(weixinpay);
                     }
                 }
-            }).start();
+                break;
+            case 2:
+                // 判断课包属于平台还是运营商
+                CoursePackage coursePackage = cpageClient.queryCoursePackageById(pointsMerchandise.getCoursePackageId());
+                Store store = storeClient.queryStoreById(coursePackage.getStoreId());
+                if (store.getOperatorId() == null || store.getOperatorId() == 0) {
+                    // 平台课包
+                    ResultUtil weixinpay = payMoneyUtil.weixinpay(name, "", code, cash.toString(),
+                            "/base/pointMer/exchangeGoodPaymentWeChatCallback", "APP", "");
+                    return appendPaySuccess(weixinpay);
+                } else {
+                    String s2 = storeClient.getmerchantNumberByOperatorId(store.getOperatorId());
+                    System.err.println("微信商户号" + s2);
+
+                    if (!StringUtils.hasLength(s2)) {
+                        return ResultUtil.error("运营商未配置微信商户号,获取支付失败!");
+                    }
+                    ResultUtil weixinpay = payMoneyUtil.weixinpayV3(s2, name, code,
+                            "/base/pointMer/exchangeGoodPaymentWeChatCallback1",
+                            cash.toString());
+                    return appendPaySuccess(weixinpay);
+                }
+            case 3:
+                if (!integers.isEmpty()) {
+                    Store store1 = storeClient.queryStoreById(integers.get(0));
+                    if (store1.getOperatorId() == null || store1.getOperatorId() == 0) {
+                        // 平台门票
+                        ResultUtil weixinpay = payMoneyUtil.weixinpay(name, "", code, cash.toString(),
+                                "/base/pointMer/exchangeGoodPaymentWeChatCallback", "APP", "");
+                        return appendPaySuccess(weixinpay);
+                    } else {
+                        String s2 = storeClient.getmerchantNumberByOperatorId(store1.getOperatorId());
+                        System.err.println("微信商户号" + s2);
+
+                        if (!StringUtils.hasLength(s2)) {
+                            return ResultUtil.error("运营商未配置微信商户号,获取支付失败!");
+                        }
+                        ResultUtil weixinpay = payMoneyUtil.weixinpayV3(s2, name, code,
+                                "/base/pointMer/exchangeGoodPaymentWeChatCallback1",
+                                cash.toString());
+                        return appendPaySuccess(weixinpay);
+                    }
+                } else {
+                    // 平台门票
+                    ResultUtil weixinpay = payMoneyUtil.weixinpay(name, "", code, cash.toString(),
+                            "/base/pointMer/exchangeGoodPaymentWeChatCallback", "APP", "");
+                    return appendPaySuccess(weixinpay);
+
+                }
         }
-        return weixinpay;
+
+        return ResultUtil.error("支付失败");
     }
 
-    @Override
-    public ResultUtil exchangeAddPaymentCallback(String code, String orderNumber, Integer payType) {
-        List<UserPointsMerchandise> userPointsMerchandises = mcClient.queryUserPointMerchaseByCode(code);
-        if (userPointsMerchandises.get(0).getPayStatus() == 2) {
-            return ResultUtil.success();
-        }
-        if (userPointsMerchandises.size() > 1) {
-            for (int i = 0; i < userPointsMerchandises.size(); i++) {
-                userPointsMerchandises.get(i).setOrderNumber(orderNumber + "-" + (i + 1));
-                userPointsMerchandises.get(i).setPayType(payType);
-                userPointsMerchandises.get(i).setPayStatus(2);
-                mcClient.updateDetailsUserPointMercase(userPointsMerchandises.get(i));
 
-                Integer pointsMerchandiseId = userPointsMerchandises.get(i).getPointsMerchandiseId();
-                PointsMerchandise pointsMerchandise = mcClient.selectPointsMerchandiseById(pointsMerchandiseId);
-                switch (pointsMerchandise.getType()) {
-                    case 2:
-                        List<TCoursePackagePayment> coursePackagePaymentOfCode = paymentClient.getCoursePackagePaymentOfCode(code);
-                        for (TCoursePackagePayment coursePackagePayment : coursePackagePaymentOfCode) {
-                            coursePackagePayment.setPayStatus(2);
-                            coursePackagePayment.setPayType(payType);
-                            coursePackagePayment.setOrderNumber(orderNumber);
-                            coursePackagePayment.setCashPayment(pointsMerchandise.getCash());
-                            paymentClient.updatePaymentCoursePackage(coursePackagePayment);
-                        }
-                        break;
-                    case 4:
-                        UserCoupon coupon = new UserCoupon();
-                        coupon.setCouponId(userPointsMerchandises.get(0).getPointsMerchandiseId());
-                        coupon.setUserId(userPointsMerchandises.get(0).getUserId());
-                        coupon.setStatus(1);
-                        coupon.setInsertTime(new Date());
-                        ucponClient.insertToAppuserCoupon(coupon);
-                        break;
-                    default:
-                        break;
+    @Override
+    public ResultUtil exchangeAddPaymentCallback(String code, String orderNumber) throws AlipayApiException {
+        System.err.println("进入回调" + code);
+        List<UserPointsMerchandise> userPointsMerchandises = mcClient.queryUserPointMerchaseByCode(code);
+        for (UserPointsMerchandise userPointsMerchandise : userPointsMerchandises) {
+            System.err.println("商品" + userPointsMerchandise);
+            if (userPointsMerchandise.getPayStatus() == 2) {
+                return ResultUtil.success();
+            }
+
+            userPointsMerchandise.setOrderNumber(orderNumber);
+            userPointsMerchandise.setPayStatus(2);
+            userPointsMerchandise.setPaymentTime(new Date());
+            mcClient.updateDetailsUserPointMercase(userPointsMerchandise);
+
+            TAppUser tAppUser = baseMapper.selectById(userPointsMerchandise.getUserId());
+            dealAppUserIntegral(userPointsMerchandise.getUserId(), tAppUser, userPointsMerchandise.getIntegral());
+
+            Integer pointsMerchandiseId = userPointsMerchandise.getPointsMerchandiseId();
+            PointsMerchandise pointsMerchandise = mcClient.selectPointsMerchandiseById(pointsMerchandiseId);
+            if (pointsMerchandise.getType() == 2) {
+                //课程
+                CoursePackageOrder coursePackageOrder1 = paymentClient.getCoursePackageOrderByCode(code);
+                if (null != coursePackageOrder1) {
+                    coursePackageOrder1.setPayStatus(2);
+                    coursePackageOrder1.setOrderNumber(orderNumber);
+                    coursePackageOrder1.setAppUserId(null);
+                    paymentClient.updateCoursePackageOrder(coursePackageOrder1);
+
+                    GetCoursePackagePaymentConfig getCoursePackagePaymentConfig = new GetCoursePackagePaymentConfig();
+                    getCoursePackagePaymentConfig.setCoursePackageId(coursePackageOrder1.getCoursePackageId());
+                    getCoursePackagePaymentConfig.setClassHours(coursePackageOrder1.getClassHours());
+                    CoursePackagePaymentConfig coursePackagePaymentConfig = paymentClient.getCoursePackagePaymentConfig(getCoursePackagePaymentConfig);
+
+                    AddCoursePackageOrderStudent addCoursePackageOrderStudent = new AddCoursePackageOrderStudent();
+                    addCoursePackageOrderStudent.setCoursePackageOrderId(coursePackageOrder1.getId());
+                    addCoursePackageOrderStudent.setCoursePackagePaymentConfig(coursePackagePaymentConfig);
+                    paymentClient.addCoursePackageOrderStudent(addCoursePackageOrderStudent);
                 }
             }
-        } else {
-            userPointsMerchandises.get(0).setOrderNumber(orderNumber);
-            userPointsMerchandises.get(0).setPayType(payType);
-            userPointsMerchandises.get(0).setPayStatus(2);
-            mcClient.updateDetailsUserPointMercase(userPointsMerchandises.get(0));
-
-            Integer pointsMerchandiseId = userPointsMerchandises.get(0).getPointsMerchandiseId();
-            PointsMerchandise pointsMerchandise = mcClient.selectPointsMerchandiseById(pointsMerchandiseId);
-            switch (pointsMerchandise.getType()) {
-                case 2:
-                    List<TCoursePackagePayment> coursePackagePaymentOfCode = paymentClient.getCoursePackagePaymentOfCode(code);
-
-                    TCoursePackagePayment packagePayment = coursePackagePaymentOfCode.get(0);
-                    packagePayment.setPayStatus(2);
-                    packagePayment.setPayType(payType);
-                    packagePayment.setOrderNumber(orderNumber);
-                    packagePayment.setCashPayment(pointsMerchandise.getCash());
-                    paymentClient.updatePaymentCoursePackage(packagePayment);
-                    break;
-                case 4:
-                    UserCoupon coupon = new UserCoupon();
-                    coupon.setCouponId(userPointsMerchandises.get(0).getPointsMerchandiseId());
-                    coupon.setUserId(userPointsMerchandises.get(0).getUserId());
-                    coupon.setStatus(1);
-                    coupon.setInsertTime(new Date());
-                    ucponClient.insertToAppuserCoupon(coupon);
-                    break;
-                default:
-                    break;
-            }
-
+        }
+        UserPointsMerchandise userPointsMerchandise = userPointsMerchandises.get(0);
+        Integer pointsMerchandiseId = userPointsMerchandise.getPointsMerchandiseId();
+        PointsMerchandise pointsMerchandise = mcClient.selectPointsMerchandiseById(pointsMerchandiseId);
+        List<Integer> integers = mcsClient.queryPointMerStoreIds(pointsMerchandise.getId());
+        Store store1 = storeClient.queryStoreById(integers.get(0));
+        if (store1.getOperatorId() != null && store1.getOperatorId() != 0) {
+            String s2 = storeClient.getmerchantNumberAliByOperatorId(store1.getOperatorId());
+            System.err.println("支付宝商户号" + s2);
+            payMoneyUtil.confirm(s2, code, orderNumber, userPointsMerchandise.getCash().toString());
         }
         return ResultUtil.success();
     }

--
Gitblit v1.7.1