浏览代码

联合丽格改版

zhijiezhao 2 年之前
父节点
当前提交
f8ffae30fa
共有 35 个文件被更改,包括 2540 次插入109 次删除
  1. 15 5
      pom.xml
  2. 2 5
      src/main/java/com/caimei/modules/club/controller/CmOperationUserController.java
  3. 3 8
      src/main/java/com/caimei/modules/club/controller/CmUserOrganizeController.java
  4. 0 3
      src/main/java/com/caimei/modules/club/service/impl/NewCmClubServiceImpl.java
  5. 4 1
      src/main/java/com/caimei/modules/order/constant/Constant.java
  6. 63 10
      src/main/java/com/caimei/modules/order/controller/OrderPayShopController.java
  7. 1 11
      src/main/java/com/caimei/modules/order/controller/OrganizeOrderController.java
  8. 4 0
      src/main/java/com/caimei/modules/order/dao/NewOrderDao.java
  9. 3 0
      src/main/java/com/caimei/modules/order/dao/NewShopOrderDao.java
  10. 24 0
      src/main/java/com/caimei/modules/order/dao/PayShopDao.java
  11. 5 2
      src/main/java/com/caimei/modules/order/entity/NewOrder.java
  12. 5 1
      src/main/java/com/caimei/modules/order/entity/NewShopOrder.java
  13. 24 3
      src/main/java/com/caimei/modules/order/entity/OrderPayShop.java
  14. 7 2
      src/main/java/com/caimei/modules/order/entity/OrderPayShopDetail.java
  15. 59 0
      src/main/java/com/caimei/modules/order/entity/SettleRecord.java
  16. 81 0
      src/main/java/com/caimei/modules/order/entity/SettleResult.java
  17. 11 1
      src/main/java/com/caimei/modules/order/service/PayShopService.java
  18. 1 6
      src/main/java/com/caimei/modules/order/service/impl/CmReceiptOrderRelationServiceImpl.java
  19. 1 3
      src/main/java/com/caimei/modules/order/service/impl/CmReturnedPurchaseServiceImpl.java
  20. 2 5
      src/main/java/com/caimei/modules/order/service/impl/NewOrderServiceImpl.java
  21. 68 12
      src/main/java/com/caimei/modules/order/service/impl/PayShopServiceImpl.java
  22. 172 0
      src/main/java/com/caimei/modules/order/util/OrderUtils.java
  23. 1 3
      src/main/java/com/caimei/modules/products/controller/CmMallProductsClassifyController.java
  24. 1 5
      src/main/java/com/caimei/modules/products/service/impl/CmMallOrganizeProductsServiceImpl.java
  25. 1 2
      src/main/java/com/caimei/modules/products/service/impl/CmMallProductsClassifyServiceImpl.java
  26. 295 0
      src/main/java/com/caimei/utils/RedisService.java
  27. 601 0
      src/main/java/com/caimei/utils/payUtil/Base64.java
  28. 166 0
      src/main/java/com/caimei/utils/payUtil/Digest.java
  29. 110 0
      src/main/java/com/caimei/utils/payUtil/MyBeanUtils.java
  30. 405 0
      src/main/java/com/caimei/utils/payUtil/RSA.java
  31. 69 0
      src/main/java/com/caimei/utils/payUtil/SettlePostFormUtil.java
  32. 1 1
      src/main/resources/mapper/CmReceiptOrderRelationMapper.xml
  33. 86 4
      src/main/resources/mapper/NewOrderMapper.xml
  34. 125 4
      src/main/resources/mapper/NewShopOrderMapper.xml
  35. 124 12
      src/main/resources/mapper/PayShopDao.xml

+ 15 - 5
pom.xml

@@ -37,12 +37,27 @@
             <scope>test</scope>
         </dependency>
 
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-data-redis</artifactId>
+        </dependency>
+
         <dependency>
             <groupId>com.github.xiaoymin</groupId>
             <artifactId>knife4j-spring-boot-starter</artifactId>
             <version>3.0.2</version>
         </dependency>
 
+        <dependency>
+            <groupId>org.bouncycastle</groupId>
+            <artifactId>bcprov-jdk15to18</artifactId>
+            <version>1.69</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.commons</groupId>
+            <artifactId>commons-lang3</artifactId>
+            <version>3.3.2</version>
+        </dependency>
         <!-- 添加mybatis的核心包 -->
         <dependency>
             <groupId>org.mybatis.spring.boot</groupId>
@@ -73,11 +88,6 @@
             <version>1.2.76</version>
         </dependency>
 
-        <dependency>
-            <groupId>com.caimei</groupId>
-            <artifactId>caimei-common</artifactId>
-            <version>0.0.1-SNAPSHOT</version>
-        </dependency>
 
         <!-- 分页插件 -->
         <dependency>

+ 2 - 5
src/main/java/com/caimei/modules/club/controller/CmOperationUserController.java

@@ -11,9 +11,6 @@ import com.caimei.utils.SMSUtils;
 import com.github.pagehelper.PageHelper;
 import com.github.pagehelper.util.StringUtil;
 import lombok.RequiredArgsConstructor;
-import org.apache.commons.collections.CollectionUtils;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Controller;
 import org.springframework.web.bind.annotation.*;
 import org.thymeleaf.util.StringUtils;
 
@@ -57,7 +54,7 @@ public class CmOperationUserController {
         JsonModel jsonModel = JsonModel.newInstance();
         //判断该运营人手机号是否已存在
         List<CmOperationUser> listBuyBindMobile1 = cmOperationUserService.findListBuyBindMobile(cmOperationUser);
-        if (CollectionUtils.isNotEmpty(listBuyBindMobile1) && listBuyBindMobile1.size() > 0) {
+        if (null != listBuyBindMobile1 && listBuyBindMobile1.size() > 0) {
             return jsonModel.error("该手机号码已被使用");
         }
         Date date = new Date();
@@ -104,7 +101,7 @@ public class CmOperationUserController {
         CmOperationUser opUser = new CmOperationUser();
         opUser.setInvitationCode(String.valueOf(flag));
         List<CmOperationUser> listByInvitationCode = cmOperationUserService.getListByInvitationCode(opUser);
-        if (CollectionUtils.isNotEmpty(listByInvitationCode) && listByInvitationCode.size() > 0) {//存在邀请码重新获取
+        if (null != listByInvitationCode && listByInvitationCode.size() > 0) {//存在邀请码重新获取
             getInvitationCode();
         }
         return flag;

+ 3 - 8
src/main/java/com/caimei/modules/club/controller/CmUserOrganizeController.java

@@ -1,21 +1,16 @@
 package com.caimei.modules.club.controller;
 
-import com.caimei.modules.club.dao.NewCmClubDao;
 import com.caimei.modules.club.entity.*;
+import com.caimei.modules.club.entity.Page;
 import com.caimei.modules.club.service.CmUserOrganizeService;
 import com.caimei.modules.club.service.CmUserService;
 import com.caimei.modules.club.service.NewCmClubService;
 import com.caimei.utils.*;
 import com.github.pagehelper.PageHelper;
 import lombok.RequiredArgsConstructor;
-import org.apache.commons.collections.CollectionUtils;
-import org.junit.Assert;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Controller;
-import org.springframework.transaction.annotation.Transactional;
 import org.springframework.web.bind.annotation.*;
 
-import javax.annotation.Resource;
+
 import java.text.SimpleDateFormat;
 import java.util.Date;
 import java.util.List;
@@ -98,7 +93,7 @@ public class CmUserOrganizeController {
         //判断该会所手机号是否已存在
         cmUser.setBindMobile(contractMobile);
         List<CmUser> listBuyBindMobile = cmUserService.findListBuyBindMobile(cmUser);
-        if (CollectionUtils.isNotEmpty(listBuyBindMobile) && listBuyBindMobile.size() > 0) {
+        if (null != listBuyBindMobile && listBuyBindMobile.size() > 0) {
             return jsonModel.error("该手机号码已被使用");
         }
         //添加用户信息(新增或修改通用)

+ 0 - 3
src/main/java/com/caimei/modules/club/service/impl/NewCmClubServiceImpl.java

@@ -3,12 +3,9 @@ package com.caimei.modules.club.service.impl;
 import com.caimei.modules.club.dao.NewCmClubDao;
 import com.caimei.modules.club.entity.NewCmClub;
 import com.caimei.modules.club.service.NewCmClubService;
-import org.apache.commons.collections.CollectionUtils;
-import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 
 import javax.annotation.Resource;
-import java.util.List;
 
 @Service
 public class NewCmClubServiceImpl implements NewCmClubService {

+ 4 - 1
src/main/java/com/caimei/modules/order/constant/Constant.java

@@ -14,7 +14,10 @@ public class Constant {
 
     //快捷支付请求地址
     public static final String REQUEST_URL_QUICKPAY = "http://quickpay.trx.helipay.com/trx/quickPayApi/interface.action";
-
+    /**
+     * 联合丽格商户号
+     */
+    public static final String LHLGCUSTOMERNUM = "E1807782723";
     /**
      * 专票 信息 测试佣金暂入信息  308785626@qq.com vip/二手暂入信息
      */

+ 63 - 10
src/main/java/com/caimei/modules/order/controller/OrderPayShopController.java

@@ -1,8 +1,6 @@
 package com.caimei.modules.order.controller;
 
-import com.caimei.modules.order.entity.OrderPayShop;
-import com.caimei.modules.order.entity.OrderPayShopDetail;
-import com.caimei.modules.order.entity.ReceiptVo;
+import com.caimei.modules.order.entity.*;
 import com.caimei.modules.order.service.PayShopService;
 import com.caimei.utils.ResponseJson;
 import com.github.pagehelper.PageInfo;
@@ -14,7 +12,6 @@ import io.swagger.annotations.ApiOperation;
 import lombok.RequiredArgsConstructor;
 import org.springframework.web.bind.annotation.*;
 
-import java.util.Date;
 import java.util.List;
 
 /**
@@ -53,6 +50,27 @@ public class OrderPayShopController {
         return ResponseJson.success(payShopService.findPayList(orderPayShop, pageNum, pageSize));
     }
 
+    @ApiOperation("申请付款列表")
+    @GetMapping("/payOrder/list")
+    @ApiImplicitParams({
+            @ApiImplicitParam(required = false, name = "orderId", value = "订单Id"),
+            @ApiImplicitParam(required = false, name = "orderNo", value = "订单编号"),
+            @ApiImplicitParam(required = false, name = "shopOrderId", value = "子订单Id"),
+            @ApiImplicitParam(required = false, name = "shopOrderNo", value = "子订单编号"),
+            @ApiImplicitParam(required = false, name = "orderStartTime", value = "下单起始时间"),
+            @ApiImplicitParam(required = false, name = "orderEndTime", value = "下单终止时间"),
+            @ApiImplicitParam(required = false, name = "shopName", value = "供应商名称"),
+            @ApiImplicitParam(required = false, name = "clubName", value = "机构名称"),
+            @ApiImplicitParam(required = true, name = "listType", value = "列表类型 1申请付款 2子订单分账 3子订单结算"),
+            @ApiImplicitParam(required = true, name = "organizeId", value = "组织Id"),
+            @ApiImplicitParam(required = true, name = "pageNum", value = "当前页码"),
+            @ApiImplicitParam(required = true, name = "pageSize", value = "每页大小")
+    })
+    public ResponseJson<PageInfo<NewShopOrder>> payOrderList(OrderPayShop orderPayShop,
+                                                             @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
+                                                             @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
+        return ResponseJson.success(payShopService.findPayOrderList(orderPayShop, pageNum, pageSize));
+    }
 
     @ApiOperation("付款单详情")
     @ApiImplicitParam(required = true, name = "id", value = "付款单Id")
@@ -61,6 +79,13 @@ public class OrderPayShopController {
         return ResponseJson.success(payShopService.getPayShopDetail(id));
     }
 
+    @ApiOperation("批量申请付款单")
+    @ApiImplicitParam(required = true, name = "shopOrderIds", value = "子订单IdList")
+    @PostMapping("/apply/pays")
+    public ResponseJson<OrderPayShopDetail> applyPayList(@RequestBody List<Integer> shopOrderIds) {
+        return ResponseJson.success(payShopService.applyPayList(shopOrderIds));
+    }
+
     @ApiOperation("审核付款单")
     @ApiImplicitParams({
             @ApiImplicitParam(required = true, name = "id", value = "付款单Id"),
@@ -68,7 +93,8 @@ public class OrderPayShopController {
             @ApiImplicitParam(required = true, name = "passCode", value = "1审核通过/2审核不通过")
     })
     @GetMapping("/pay/check/{id}/{payType}/{passCode}")
-    public ResponseJson checkPass(@PathVariable("id") Integer id, @PathVariable("payType") Integer payType,
+    public ResponseJson checkPass(@PathVariable("id") Integer id,
+                                  @PathVariable("payType") Integer payType,
                                   @PathVariable("passCode") Integer passCode) throws Exception {
         return payShopService.checkPass(id, payType, passCode);
     }
@@ -83,10 +109,13 @@ public class OrderPayShopController {
             @ApiImplicitParam(required = true, name = "cmBankAccount", value = "付采美帐号"),
             @ApiImplicitParam(required = true, name = "cmBankName", value = "付采美账号的开户行"),
             @ApiImplicitParam(required = true, name = "cmBankAccountName", value = "付采美账号的户名"),
-            @ApiImplicitParam(required = true, name = "type", value = "付款账号的类型 0公账, 1私账")
+            @ApiImplicitParam(required = true, name = "type", value = "付款账号的类型 0公账, 1私账"),
+            @ApiImplicitParam(required = true, name = "cmType", value = "付采美账号的类型 0公账, 1私账"),
+            @ApiImplicitParam(required = true, name = "waitPayCmAmount", value = "待付采美"),
+            @ApiImplicitParam(required = true, name = "waitPayShop", value = "待付供应商")
     })
     @PostMapping("/pay/apply")
-    public ResponseJson applyPay(OrderPayShopDetail payShop) throws Exception {
+    public ResponseJson<Integer> applyPay(@RequestBody OrderPayShopDetail payShop) throws Exception {
         return payShopService.applyPay(payShop);
     }
 
@@ -98,9 +127,33 @@ public class OrderPayShopController {
     }
 
     @ApiOperation("申请分账")
-    @ApiImplicitParam(name = "shopOrderIds", value = "子订单IdList", required = true, allowMultiple=true, dataType="int", paramType = "query")
-    @GetMapping("/pay/cancel")
-    public ResponseJson splitShopOrders(List<Integer> shopOrderIds) {
+    @ApiImplicitParam(name = "shopOrderIds", value = "子订单IdList", required = true, allowMultiple = true, dataType = "int", paramType = "query")
+    @PostMapping("/pay/split")
+    public ResponseJson splitShopOrders(@RequestBody List<Integer> shopOrderIds) {
         return payShopService.splitShopOrders(shopOrderIds);
     }
+
+    @ApiOperation("申请结算")
+    @ApiImplicitParams({
+            @ApiImplicitParam(required = true, name = "splitCode", value = "分帐号"),
+            @ApiImplicitParam(required = true, name = "waitPayCmAmount", value = "待付采美"),
+            @ApiImplicitParam(required = true, name = "waitPayShop", value = "待付供应商")
+    })
+    @PostMapping("/pay/settle")
+    public ResponseJson settleShopOrders(@RequestBody OrderPayShopDetail payShop) {
+        return payShopService.settleShopOrders(payShop);
+    }
+
+    @ApiOperation("订单财务信息列表")
+    @ApiImplicitParams({
+            @ApiImplicitParam(required = true, name = "organizeId", value = "组织Id"),
+            @ApiImplicitParam(required = true, name = "pageNum", value = "当前页码"),
+            @ApiImplicitParam(required = true, name = "pageSize", value = "每页大小")
+    })
+    @GetMapping
+    public ResponseJson<PageInfo<NewOrder>> orderPayInfoList(@RequestBody OrderPayShop orderPayShop,
+                                                             @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
+                                                             @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
+        return payShopService.orderPayInfoList(orderPayShop, pageNum, pageSize);
+    }
 }

+ 1 - 11
src/main/java/com/caimei/modules/order/controller/OrganizeOrderController.java

@@ -1,18 +1,15 @@
 package com.caimei.modules.order.controller;
 
+import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
 import com.caimei.modules.club.entity.Page;
 import com.caimei.modules.order.entity.*;
 import com.caimei.modules.order.service.*;
 import com.caimei.utils.JsonModel;
 import lombok.RequiredArgsConstructor;
-import org.apache.commons.collections.CollectionUtils;
 import org.apache.commons.lang3.StringUtils;
 import org.junit.Assert;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Controller;
 import org.springframework.web.bind.annotation.*;
 
-import java.text.SimpleDateFormat;
 import java.util.*;
 
 /**
@@ -96,13 +93,6 @@ public class OrganizeOrderController {
         if (ids != null && ids.size() > 0) {
             order.setToAudit("1");
         }
-        //一个子订单只有一个商品时,不可拆分
-        int count = 0;
-        for (NewShopOrder newShopOrder : order.getNewShopOrders()) {
-            if (newShopOrder.getShopId() != 998) {
-                count++;
-            }
-        }
         if (order.getProductCount() == null) {
             order.setProductCount(1);
         }

+ 4 - 0
src/main/java/com/caimei/modules/order/dao/NewOrderDao.java

@@ -35,4 +35,8 @@ public interface NewOrderDao {
     List<NewOrderProduct> getOrderProductByShopOrderId(Integer shopOrderId);
 
     Double getOrderProductPaidAmount(Integer orderProductId);
+
+    Double findPayAmount(Integer s);
+
+    List<NewOrder> findListByPayShop(OrderPayShop orderPayShop);
 }

+ 3 - 0
src/main/java/com/caimei/modules/order/dao/NewShopOrderDao.java

@@ -1,6 +1,7 @@
 package com.caimei.modules.order.dao;
 
 import com.caimei.modules.order.entity.NewShopOrder;
+import com.caimei.modules.order.entity.OrderPayShop;
 import org.apache.ibatis.annotations.Mapper;
 
 import java.util.List;
@@ -23,4 +24,6 @@ public interface NewShopOrderDao {
     Integer getPayingStatus(Integer id);
 
     void inPaying(Integer payShopId);
+
+    List<NewShopOrder> findPayShopOrderList(OrderPayShop orderPayShop);
 }

+ 24 - 0
src/main/java/com/caimei/modules/order/dao/PayShopDao.java

@@ -42,4 +42,28 @@ public interface PayShopDao {
     void updateShopAccount(Integer shopId, String bankAccount, String bankAccountName, String bankName);
 
     void deleteRecords(Integer id);
+
+    List<String> findShopOrderNosByPayShop(Integer payShopId);
+
+    List<String> findOrderNos(Integer payShopId);
+
+    void insertSettleRecord(SettleRecord settleRecord);
+
+    void updateSettleStatus(Integer shopOrderId, int i);
+
+    Double findShouldPayShopAmount(Integer shopOrderId);
+
+    Double findSettleSum(Integer shopOrderId);
+
+    void updateShopOrderSettleStatus(Integer shopOrderId, int i);
+
+    List<CmReceiptOrderRelation> findOrderRelations(Integer shopOrderId);
+
+    Double findTotalAmount(Integer shopOrderId);
+
+    List<NewOrderProduct> findOrderProductPrice(Integer shopOrderId);
+
+    String findSplitCode(Integer shopOrderId);
+
+    List<NewShopOrder> findPayShopOrderByShopOrderIds(List<Integer> shopOrderIds);
 }

+ 5 - 2
src/main/java/com/caimei/modules/order/entity/NewOrder.java

@@ -1,15 +1,17 @@
 package com.caimei.modules.order.entity;
 
+import io.swagger.annotations.ApiModel;
+import io.swagger.annotations.ApiModelProperty;
 import lombok.Data;
+import org.springframework.format.annotation.DateTimeFormat;
 
 import java.io.Serializable;
 import java.util.List;
 
 /**
- * @author lwt
- * @date 2018-07-24
  * @description 主订单表
  */
+@ApiModel("主订单实体")
 @Data
 public class NewOrder implements Serializable {
 
@@ -82,6 +84,7 @@ public class NewOrder implements Serializable {
     /**
      * 订单提交时间
      */
+    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
     private String orderTime;
     /**
      * 订单确认时间

+ 5 - 1
src/main/java/com/caimei/modules/order/entity/NewShopOrder.java

@@ -54,7 +54,9 @@ public class NewShopOrder {
     @ApiModelProperty("买家/客户")
     private String buyer;
     @ApiModelProperty("子订单收款状态:1待收款、2部分收款、3已收款")
-    private String receiptStatus;
+    private Integer receiptStatus;
+    @ApiModelProperty("主订单收款状态:1待收款、2部分收款、3已收款")
+    private Integer orderReceiptStatus;
 
     @ApiModelProperty("子订单Id")
     private Integer shopOrderId;
@@ -151,4 +153,6 @@ public class NewShopOrder {
     private Double payed;
     @ApiModelProperty("分帐号")
     private String splitCode;
+    @ApiModelProperty("结算状态 1未结算2部分结算3已结算")
+    private Integer settleStatus;
 }

+ 24 - 3
src/main/java/com/caimei/modules/order/entity/OrderPayShop.java

@@ -6,11 +6,12 @@ import lombok.Data;
 import org.springframework.format.annotation.DateTimeFormat;
 
 import java.io.Serializable;
+import java.util.List;
 
 /**
  * @author zzj
  */
-@ApiModel("付款列表实体")
+@ApiModel("付款/申请付款/订单财务信息列表实体")
 @Data
 public class OrderPayShop implements Serializable {
 
@@ -53,6 +54,8 @@ public class OrderPayShop implements Serializable {
     private Integer orderId;
     @ApiModelProperty("主订单编号")
     private String orderNo;
+    @ApiModelProperty("付款金额")
+    private Double totalAmount;
 
     @ApiModelProperty("查询字段:申请起始时间")
     private String applyStartTime;
@@ -62,6 +65,24 @@ public class OrderPayShop implements Serializable {
     private String payStartTime;
     @ApiModelProperty("查询字段:付款终止时间")
     private String payEndTime;
-
-
+    @ApiModelProperty("申请付款列表/订单财务信息查询字段:下单起始时间")
+    private String orderStartTime;
+    @ApiModelProperty("申请付款列表/订单财务信息查询字段:下单终止时间")
+    private String orderEndTime;
+    @ApiModelProperty("申请付款列表/订单财务信息查询字段:机构名称")
+    private String clubName;
+    @ApiModelProperty("列表类型 1申请付款 2子订单分账 3子订单结算")
+    private Integer listType;
+    @ApiModelProperty("子订单编号")
+    private List<String> shopOrderNos;
+    @ApiModelProperty("订单编号")
+    private List<String> orderNos;
+    @ApiModelProperty("订单财务信息列表 查询字段:收款状态 1待收款、2部分收款、3已收款")
+    private Integer receiptStatus;
+    @ApiModelProperty("订单财务信息列表 查询字段:结算状态 1未结算、2部分结算、3已结算")
+    private Integer settleStatus;
+    @ApiModelProperty("订单财务信息列表 查询字段:付款状态:1待付款、2部分付款、3已付款")
+    private Integer payStatus;
+    @ApiModelProperty("订单财务信息列表 查询字段:退款状态:0无退款、1部分退款、2已退款")
+    private Integer refundStatus;
 }

+ 7 - 2
src/main/java/com/caimei/modules/order/entity/OrderPayShopDetail.java

@@ -23,6 +23,8 @@ public class OrderPayShopDetail implements Serializable {
     private String bankAccount;
     @ApiModelProperty("供应商付款账号的开户行")
     private String bankName;
+    @ApiModelProperty("付供应商账号的类型 0公账, 1私账")
+    private Integer type;
 
     @ApiModelProperty("付采美账号的户名")
     private String cmBankAccountName;
@@ -30,6 +32,8 @@ public class OrderPayShopDetail implements Serializable {
     private String cmBankAccount;
     @ApiModelProperty("付采美账号的开户行")
     private String cmBankName;
+    @ApiModelProperty("付采美账号的类型 0公账, 1私账")
+    private Integer cmType;
 
     @ApiModelProperty("shopId")
     private Integer shopId;
@@ -41,6 +45,8 @@ public class OrderPayShopDetail implements Serializable {
     private String shopName;
     @ApiModelProperty("付供应商总金额")
     private Double totalAmount;
+    @ApiModelProperty("付采美总金额")
+    private Double payCmTotalAmount;
     @ApiModelProperty("付款银行")
     private Integer payType;
     @ApiModelProperty("付款银行名称")
@@ -68,6 +74,5 @@ public class OrderPayShopDetail implements Serializable {
     private String reason;
     @ApiModelProperty("付款单关联的子订单")
     private List<NewShopOrder> shopOrders;
-    @ApiModelProperty("付款账号的类型 0公账, 1私账")
-    private Integer type;
+
 }

+ 59 - 0
src/main/java/com/caimei/modules/order/entity/SettleRecord.java

@@ -0,0 +1,59 @@
+package com.caimei.modules.order.entity;
+
+import com.fasterxml.jackson.annotation.JsonFormat;
+
+import java.io.Serializable;
+import java.util.Date;
+
+public class SettleRecord implements Serializable {
+
+    private Double settleAmount;
+    /**
+     * 结算类型 1供应商成本,2佣金
+     */
+    private Integer settleType;
+    private Integer shopOrderId;
+    private String splitCode;
+    private Date settleTime;
+
+    public Double getSettleAmount() {
+        return settleAmount;
+    }
+
+    public void setSettleAmount(Double settleAmount) {
+        this.settleAmount = settleAmount;
+    }
+
+    public Integer getSettleType() {
+        return settleType;
+    }
+
+    public void setSettleType(Integer settleType) {
+        this.settleType = settleType;
+    }
+
+    public Integer getShopOrderId() {
+        return shopOrderId;
+    }
+
+    public void setShopOrderId(Integer shopOrderId) {
+        this.shopOrderId = shopOrderId;
+    }
+
+    public String getSplitCode() {
+        return splitCode;
+    }
+
+    public void setSplitCode(String splitCode) {
+        this.splitCode = splitCode;
+    }
+
+    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
+    public Date getSettleTime() {
+        return settleTime;
+    }
+
+    public void setSettleTime(Date settleTime) {
+        this.settleTime = settleTime;
+    }
+}

+ 81 - 0
src/main/java/com/caimei/modules/order/entity/SettleResult.java

@@ -0,0 +1,81 @@
+package com.caimei.modules.order.entity;
+
+import com.google.common.collect.ImmutableSet;
+
+import java.io.Serializable;
+import java.util.Set;
+
+public class SettleResult implements Serializable{
+    private String rt1_bizType;
+    private String rt2_retCode;
+    private String rt3_retMsg;
+    private String rt4_customerNumber;
+    private String rt5_orderId;
+    private String sign;
+
+    /**
+     * 需要加签的属性参数
+     * 看接口文档
+     */
+    public static final Set<String> NEED_SIGN_PARAMS = ImmutableSet.of("rt1_bizType", "rt2_retCode", "rt4_customerNumber", "rt5_orderId");
+
+    public String getRt1_bizType() {
+        return rt1_bizType;
+    }
+
+    public void setRt1_bizType(String rt1_bizType) {
+        this.rt1_bizType = rt1_bizType;
+    }
+
+    public String getRt2_retCode() {
+        return rt2_retCode;
+    }
+
+    public void setRt2_retCode(String rt2_retCode) {
+        this.rt2_retCode = rt2_retCode;
+    }
+
+    public String getRt3_retMsg() {
+        return rt3_retMsg;
+    }
+
+    public void setRt3_retMsg(String rt3_retMsg) {
+        this.rt3_retMsg = rt3_retMsg;
+    }
+
+    public String getRt4_customerNumber() {
+        return rt4_customerNumber;
+    }
+
+    public void setRt4_customerNumber(String rt4_customerNumber) {
+        this.rt4_customerNumber = rt4_customerNumber;
+    }
+
+    public String getRt5_orderId() {
+        return rt5_orderId;
+    }
+
+    public void setRt5_orderId(String rt5_orderId) {
+        this.rt5_orderId = rt5_orderId;
+    }
+
+    public String getSign() {
+        return sign;
+    }
+
+    public void setSign(String sign) {
+        this.sign = sign;
+    }
+
+    @Override
+    public String toString() {
+        return "SettleResult{" +
+                "rt1_bizType='" + rt1_bizType + '\'' +
+                ", rt2_retCode='" + rt2_retCode + '\'' +
+                ", rt3_retMsg='" + rt3_retMsg + '\'' +
+                ", rt4_customerNumber='" + rt4_customerNumber + '\'' +
+                ", rt5_orderId='" + rt5_orderId + '\'' +
+                ", sign='" + sign + '\'' +
+                '}';
+    }
+}

+ 11 - 1
src/main/java/com/caimei/modules/order/service/PayShopService.java

@@ -1,5 +1,7 @@
 package com.caimei.modules.order.service;
 
+import com.caimei.modules.order.entity.NewOrder;
+import com.caimei.modules.order.entity.NewShopOrder;
 import com.caimei.modules.order.entity.OrderPayShop;
 import com.caimei.modules.order.entity.OrderPayShopDetail;
 import com.caimei.utils.ResponseJson;
@@ -18,9 +20,17 @@ public interface PayShopService {
 
     ResponseJson checkPass(Integer id, Integer payType, Integer passCode) throws Exception;
 
-    ResponseJson applyPay(OrderPayShopDetail payShop) throws Exception;
+    ResponseJson<Integer> applyPay(OrderPayShopDetail payShop) throws Exception;
 
     ResponseJson cancelPay(Integer id);
 
     ResponseJson splitShopOrders(List<Integer> shopOrderIds);
+
+    ResponseJson settleShopOrders(OrderPayShopDetail payShop);
+
+    PageInfo<NewShopOrder> findPayOrderList(OrderPayShop orderPayShop, Integer pageNum, Integer pageSize);
+
+    OrderPayShopDetail applyPayList(List<Integer> shopOrderIds);
+
+    ResponseJson<PageInfo<NewOrder>> orderPayInfoList(OrderPayShop orderPayShop, Integer pageNum, Integer pageSize);
 }

+ 1 - 6
src/main/java/com/caimei/modules/order/service/impl/CmReceiptOrderRelationServiceImpl.java

@@ -4,7 +4,6 @@ import com.caimei.modules.order.dao.CmReceiptOrderRelationDao;
 import com.caimei.modules.order.entity.CmReceiptOrderRelation;
 import com.caimei.modules.order.service.CmReceiptOrderRelationService;
 import com.caimei.utils.ReceivablesType;
-import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 
 import javax.annotation.Resource;
@@ -23,10 +22,6 @@ public class CmReceiptOrderRelationServiceImpl implements CmReceiptOrderRelation
 
     @Override
     public List<CmReceiptOrderRelation> findByOrderId(Integer orderId) {
-        List<CmReceiptOrderRelation> list= cmReceiptOrderRelationDao.findByOrderId(orderId);
-        for(CmReceiptOrderRelation bean : list){
-            bean.setPayType(ReceivablesType.getReceivablesType(Integer.parseInt(bean.getPayType())));
-        }
-        return list;
+        return cmReceiptOrderRelationDao.findByOrderId(orderId);
     }
 }

+ 1 - 3
src/main/java/com/caimei/modules/order/service/impl/CmReturnedPurchaseServiceImpl.java

@@ -7,8 +7,6 @@ import com.caimei.modules.order.entity.*;
 import com.caimei.modules.order.service.CmReturnedPurchaseService;
 import com.caimei.modules.order.service.NewShopOrderService;
 import com.caimei.utils.AppUtils;
-import org.apache.commons.collections.CollectionUtils;
-import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.stereotype.Service;
 
@@ -55,7 +53,7 @@ public class CmReturnedPurchaseServiceImpl implements CmReturnedPurchaseService
                     purchaseProduct.setShopOrderId(item.getShopOrderId());
                     purchaseProduct.setProductId(item.getProductId());
                     List<CmReturnedPurchaseProduct> cmReturnedPurchaseProductList = cmReturnedPurchaseProductDao.getCmReturnedPurchaseProductList(purchaseProduct);
-                    if (CollectionUtils.isNotEmpty(cmReturnedPurchaseProductList)) {
+                    if (null != cmReturnedPurchaseProductList && cmReturnedPurchaseProductList.size() > 0) {
                         for (CmReturnedPurchaseProduct c : cmReturnedPurchaseProductList) {
                             returnedPurchaseProductNum += c.getActualReturnedNum();
                             cancelProductNum += c.getActualCancelNum();

+ 2 - 5
src/main/java/com/caimei/modules/order/service/impl/NewOrderServiceImpl.java

@@ -1,5 +1,6 @@
 package com.caimei.modules.order.service.impl;
 
+import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
 import com.caimei.modules.club.entity.Page;
 import com.caimei.modules.order.dao.*;
 import com.caimei.modules.order.entity.*;
@@ -9,7 +10,6 @@ import com.caimei.utils.AppKeys;
 import com.caimei.utils.AppUtils;
 import com.caimei.utils.NewOrderStatus;
 import com.github.pagehelper.PageHelper;
-import org.apache.commons.collections.CollectionUtils;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.stereotype.Service;
 
@@ -21,6 +21,7 @@ import java.util.stream.Collectors;
 
 @Service
 public class NewOrderServiceImpl implements NewOrderService {
+
     @Resource
     private NewOrderDao newOrderDao;
     @Resource
@@ -67,16 +68,12 @@ public class NewOrderServiceImpl implements NewOrderService {
             if (shopOrders != null && shopOrders.size() == 1) {
                 order.setShopName(shopOrders.get(0).getShopName());
             }
-            int count = 0;
             for (NewShopOrder shopOrder : order.getNewShopOrders()) {
                 shopOrder.setOrderId(order.getOrderId());
                 shopOrder.setOrderNo(order.getOrderNo());
                 shopOrder.setReceiver(order.getReceiver());
                 shopOrder.setOrderTime(order.getOrderTime());
                 shopOrder.setBuyer(order.getBuyer());
-                if (shopOrder.getShopId() != 998) {
-                    count++;
-                }
                 //子订单Id
                 Integer shopOrderId = shopOrder.getShopOrderId();
                 //通过子订单Id查询子订单信息

+ 68 - 12
src/main/java/com/caimei/modules/order/service/impl/PayShopServiceImpl.java

@@ -8,17 +8,17 @@ import com.caimei.modules.order.dao.NewShopOrderDao;
 import com.caimei.modules.order.dao.PayShopDao;
 import com.caimei.modules.order.entity.*;
 import com.caimei.modules.order.service.PayShopService;
+import com.caimei.modules.order.util.OrderUtils;
 import com.caimei.modules.shiro.entity.CmMallAdminUser;
-import com.caimei.po.OrderProductV;
-import com.caimei.utils.DateUtils;
-import com.caimei.utils.Disguiser;
-import com.caimei.utils.MathUtil;
-import com.caimei.utils.ResponseJson;
+import com.caimei.utils.*;
+import com.caimei.utils.payUtil.MyBeanUtils;
+import com.caimei.utils.payUtil.RSA;
+import com.caimei.utils.payUtil.SettlePostFormUtil;
 import com.github.pagehelper.PageHelper;
 import com.github.pagehelper.PageInfo;
-import com.google.common.util.concurrent.AtomicDouble;
 import lombok.extern.slf4j.Slf4j;
 import okhttp3.*;
+import org.apache.commons.collections.CollectionUtils;
 import org.apache.shiro.SecurityUtils;
 import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Transactional;
@@ -32,8 +32,8 @@ import java.text.SimpleDateFormat;
 import java.util.*;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
 
-import com.caimei.redis.RedisService;
 
 /**
  * @author zzj
@@ -56,11 +56,18 @@ public class PayShopServiceImpl implements PayShopService {
     private NewShopOrderDao newShopOrderDao;
     @Resource
     private NewOrderDao newOrderDao;
+    @Resource
+    private OrderUtils orderUtils;
+
 
     @Override
     public PageInfo<OrderPayShop> findPayList(OrderPayShop orderPayShop, int pageNum, int pageSize) {
         PageHelper.startPage(pageNum, pageSize);
         List<OrderPayShop> payShops = payShopDao.findPayShops(orderPayShop);
+        payShops.forEach(p -> {
+            p.setOrderNos(payShopDao.findShopOrderNosByPayShop(p.getPayShopId()));
+            p.setShopOrderNos(payShopDao.findOrderNos(p.getPayShopId()));
+        });
         PageInfo<OrderPayShop> pageInfo = new PageInfo(payShops);
         return pageInfo;
     }
@@ -140,7 +147,7 @@ public class PayShopServiceImpl implements PayShopService {
 
     @Transactional(readOnly = false, rollbackFor = Exception.class)
     @Override
-    public ResponseJson applyPay(OrderPayShopDetail payShop) throws Exception {
+    public ResponseJson<Integer> applyPay(OrderPayShopDetail payShop) throws Exception {
         CmMallAdminUser user = (CmMallAdminUser) SecurityUtils.getSubject().getPrincipal();
         payShop.setApplicant(user.getId());
         List<NewShopOrder> shopOrders = payShop.getShopOrders();
@@ -187,7 +194,7 @@ public class PayShopServiceImpl implements PayShopService {
             });
             payShopDao.updatePayShopDetail(payShop);
         }
-        return ResponseJson.success("申请成功");
+        return ResponseJson.success(payShop.getPayShopId());
     }
 
     @Transactional(readOnly = false)
@@ -283,7 +290,6 @@ public class PayShopServiceImpl implements PayShopService {
                                 for (SplitAccountPo account : splitAccountList) {
                                     // 本次付供应商金额(分账金额)
                                     Double splitAmount = account.getSplitAccount();
-                                    orderId = account.getOrderId();
                                     Integer shopId = account.getShopId();
                                     for (NewShopOrder shop : shopOrderList) {
                                         if (shopId.equals(shop.getShopId())) {
@@ -404,7 +410,7 @@ public class PayShopServiceImpl implements PayShopService {
                     } else {
                         // 没有佣金分账,全是成本,本笔交易已分帐
                         newOrderDao.updateBySplitStatus(orderRelation.getMbOrderId());
-                        //没有佣金分账也解锁
+                        // 没有佣金分账也解锁
                         redisService.remove("XSFZMDS");
                     }
                 }
@@ -413,6 +419,56 @@ public class PayShopServiceImpl implements PayShopService {
         return ResponseJson.success();
     }
 
+    @Override
+    public ResponseJson settleShopOrders(OrderPayShopDetail payShop) {
+        List<NewShopOrder> shopOrders = payShop.getShopOrders();
+        String format = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss.SSS").format(new Date());
+        String substring = format.substring(20);
+        shopOrders.forEach(s -> {
+            try {
+                orderUtils.settleOrder("JSCB" + s.getShopOrderId() + substring, s.getWaitPayShop(), s.getSplitCode(), s.getShopOrderId(), 1);
+                orderUtils.settleOrder("JSCMYJ" + s.getShopOrderId() + substring, s.getPayCmAmount(), Constant.CUSTOMERNUM2, s.getShopOrderId(), 2);
+                orderUtils.settleOrder("JSYJ" + s.getShopOrderId() + substring, s.getPayCmAmount(), Constant.LHLGCUSTOMERNUM, s.getShopOrderId(), 3);
+            } catch (Exception e) {
+                e.printStackTrace();
+            }
+        });
+        return ResponseJson.success();
+    }
+
+
+    @Override
+    public PageInfo<NewShopOrder> findPayOrderList(OrderPayShop orderPayShop, Integer pageNum, Integer pageSize) {
+        PageHelper.startPage(pageNum, pageSize);
+        List<NewShopOrder> shopOrders = newShopOrderDao.findPayShopOrderList(orderPayShop);
+        shopOrders.forEach(s -> {
+            s.setNewOrderProducts(payShopDao.findPayOrderProducts(s.getShopOrderId()));
+        });
+        PageInfo<NewShopOrder> pageInfo = new PageInfo(shopOrders);
+        return pageInfo;
+    }
+
+    @Override
+    public OrderPayShopDetail applyPayList(List<Integer> shopOrderIds) {
+        OrderPayShopDetail detail = new OrderPayShopDetail();
+        List<NewShopOrder> shopOrders = payShopDao.findPayShopOrderByShopOrderIds(shopOrderIds);
+        shopOrders.forEach(s -> {
+            s.setShopOrderNos(payShopDao.findShopOrderNos(s.getOrderId()));
+            s.setNewOrderProducts(payShopDao.findPayOrderProducts(s.getShopOrderId()));
+        });
+        detail.setShopId(shopOrders.get(0).getShopId());
+        detail.setShopName(shopOrders.get(0).getShopName());
+        detail.setShopOrders(shopOrders);
+        return detail;
+    }
+
+    @Override
+    public ResponseJson<PageInfo<NewOrder>> orderPayInfoList(OrderPayShop orderPayShop, Integer pageNum, Integer pageSize) {
+        PageHelper.startPage(pageNum, pageSize);
+        List<NewOrder> orderList = newOrderDao.findListByPayShop(orderPayShop);
+        return null;
+    }
+
     public void setSplitAccountDetail(NewShopOrder shopOrder, PayParamBo payParam, List<SplitAccountPo> list) {
         // 待分账总金额 = 本次支付金额,单位/元
         double splitAmount = payParam.getAllPay();
@@ -488,7 +544,7 @@ public class PayShopServiceImpl implements PayShopService {
             /**
              * 目前写死为联合丽格,后续有其他组织再做改动
              */
-            splitAccount.setSubUserNo("E1807782723");
+            splitAccount.setSubUserNo(Constant.LHLGCUSTOMERNUM);
             log.info("组织佣金分账参数------------->" + splitAccount);
             list.add(splitAccount);
         }

+ 172 - 0
src/main/java/com/caimei/modules/order/util/OrderUtils.java

@@ -0,0 +1,172 @@
+package com.caimei.modules.order.util;
+
+import com.caimei.modules.order.constant.Constant;
+import com.caimei.modules.order.dao.NewShopOrderDao;
+import com.caimei.modules.order.dao.PayShopDao;
+import com.caimei.modules.order.entity.*;
+import com.caimei.utils.Disguiser;
+import com.caimei.utils.MathUtil;
+import com.caimei.utils.payUtil.MyBeanUtils;
+import com.caimei.utils.payUtil.RSA;
+import com.caimei.utils.payUtil.SettlePostFormUtil;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Component;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.annotation.Resource;
+import java.math.BigDecimal;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicReference;
+
+/**
+ * @author zzj
+ */
+@Slf4j
+@Component
+public class OrderUtils {
+
+    @Resource
+    private PayShopDao payShopDao;
+    @Resource
+    private NewShopOrderDao shopOrderDao;
+
+    /**
+     * 计算应付供应商
+     *
+     * @param shopOrderId
+     */
+    public Map<String, Double> getOrderCharge(Integer shopOrderId) {
+        List<NewOrderProduct> products = payShopDao.findOrderProductPrice(shopOrderId);
+        AtomicReference<BigDecimal> organizeFee = new AtomicReference<>();
+        AtomicReference<BigDecimal> shopFee = new AtomicReference<>();
+        AtomicReference<BigDecimal> totalAmount = new AtomicReference<>();
+        products.forEach(p -> {
+            // 商品总价 * 供应商成本比例 - 手续费 = 应付供应商
+            shopFee.set(MathUtil.add(MathUtil.mul(p.getTotalAmount(), p.getShopPercent(), 2), shopFee.get()));
+            // 商品总价 * 组织佣金比例 = 应付组织
+            organizeFee.set(MathUtil.add(MathUtil.mul(p.getTotalAmount(), p.getOrganizePercent(), 2), organizeFee.get()));
+            totalAmount.set(MathUtil.add(p.getTotalAmount(), totalAmount.get()));
+        });
+        // 子订单总额 - 付供应商成本 - 付组织 = 应付采美
+        Double cmFee = MathUtil.sub(totalAmount.get(), MathUtil.add(shopFee.get(), organizeFee.get())).doubleValue();
+
+        List<CmReceiptOrderRelation> relations = payShopDao.findOrderRelations(shopOrderId);
+        AtomicReference<Double> total = new AtomicReference<>();
+        relations.forEach(r -> {
+            double charge = 0;
+            if (12 == r.getPayType()) {
+                // 企业网银
+                charge = 10;
+            } else if (8 == r.getPayType() || 13 == r.getPayType() || 15 == r.getPayType()) {
+                charge = Math.max(MathUtil.mul(r.getAssociateAmount(), 0.0065, 2).doubleValue(), 0.01);
+            } else if (29 == r.getPayType()) {
+                // 快捷支付借记卡
+
+                charge = Math.max(MathUtil.mul(r.getAssociateAmount(), 0.003, 2).doubleValue(), 0.1);
+            } else if (30 == r.getPayType()) {
+                // 快捷支付贷记卡
+                charge = Math.max(MathUtil.mul(r.getAssociateAmount(), 0.006, 2).doubleValue(), 0.1);
+            } else if (17 == r.getPayType()) {
+                // 个人网银
+                charge = Math.max(MathUtil.mul(r.getAssociateAmount(), 0.002, 2).doubleValue(), 0.1);
+            } else if (14 == r.getPayType()) {
+                // 支付宝
+                charge = Math.max(MathUtil.mul(r.getAssociateAmount(), 0.0025, 2).doubleValue(), 0.01);
+            }
+            total.set(MathUtil.add(total.get(), charge).doubleValue());
+        });
+        Double v = MathUtil.sub(shopFee.get(), total.get()).doubleValue();
+        HashMap<String, Double> feeMap = new HashMap<>(3);
+        feeMap.put("organizeFee", organizeFee.get().doubleValue());
+        feeMap.put("shopFee", shopFee.get().doubleValue());
+        feeMap.put("cmFee", cmFee);
+        return feeMap;
+    }
+
+    /**
+     * @param P2_orderId        结算合利宝订单Id
+     * @param settleAmount      结算金额
+     * @param P3_customerNumber 结算帐号
+     * @param shopOrderId       子订单Id
+     * @param settleFlag        结算类型
+     * @throws Exception
+     */
+    @Transactional(readOnly = false, rollbackFor = Exception.class)
+    public void settleOrder(String P2_orderId, Double settleAmount, String P3_customerNumber, Integer shopOrderId, Integer settleFlag) throws Exception {
+        //子订单id,结算金额
+        Map<String, String> sPara = new HashMap<String, String>();
+        sPara.put("P1_bizType", "MerchantSettlement");
+        sPara.put("P2_orderId", P2_orderId);
+        sPara.put("P3_customerNumber", P3_customerNumber);
+        sPara.put("P4_amount", settleAmount.toString());
+        sPara.put("P5_summary", "订单结算");
+        sPara.put("signType", "RSA");
+        StringBuffer sb = new StringBuffer();
+        sb.append(Constant.SPLIT).append("MerchantSettlement").append(Constant.SPLIT).append(P2_orderId).append(Constant.SPLIT)
+                .append(P3_customerNumber).append(Constant.SPLIT).append(settleAmount).append(Constant.SPLIT).append("订单结算")
+                .append(Constant.SPLIT).append("RSA");
+        String sign = RSA.sign(sb.toString(), RSA.getPrivateKey(Constant.signKey_setttlement));
+        sPara.put("sign", sign);
+        log.info("发送结算参数-----------------------》" + sPara);
+        SettleResult settleResult = SettlePostFormUtil.postForm(sPara, Constant.JS, sign, SettleResult.class);
+        if (!"0000".equals(settleResult.getRt2_retCode())) {
+            log.info("settleResult----------------->" + settleResult.toString());
+            throw new Exception("结算失败!");
+        } else {
+            String assemblyRespOriSign = "";
+            assemblyRespOriSign = MyBeanUtils.getSignedByPresetParameter(settleResult, SettleResult.NEED_SIGN_PARAMS);
+            assemblyRespOriSign += Constant.JIESUAN;
+            String checkSign = Disguiser.disguiseMD5(assemblyRespOriSign.trim());
+            if (!checkSign.equals(settleResult.getSign())) {
+                log.info("settleResult----------------->" + settleResult.toString());
+                throw new Exception("结算验签失败!");
+            } else {
+                SettleRecord settleRecord = new SettleRecord();
+                //存结算表,改子订单结算状态
+                if (1 == settleFlag) {
+                    //成本结算
+                    settleRecord.setSettleType(settleFlag);
+                    settleRecord.setSettleAmount(settleAmount);
+                    settleRecord.setSplitCode(P3_customerNumber);
+                    settleRecord.setShopOrderId(shopOrderId);
+                    payShopDao.insertSettleRecord(settleRecord);
+                    // 修改cm_split_account settlestatus
+                    payShopDao.updateSettleStatus(shopOrderId, 1);
+                    //计算供应商成本,结算金额,修改结算状态
+                    Double shouldPayShopAmount = payShopDao.findShouldPayShopAmount(shopOrderId);
+                    Double settleSum = payShopDao.findSettleSum(shopOrderId);
+                    if (shouldPayShopAmount > settleSum) {
+                        //成本>结算金额,部分结算
+                        payShopDao.updateShopOrderSettleStatus(shopOrderId, 2);
+                    } else {
+                        //成本=结算金额 全部结算
+                        payShopDao.updateShopOrderSettleStatus(shopOrderId, 3);
+                    }
+                } else {
+                    // 采美佣金结算
+                    settleRecord.setSettleType(settleFlag);
+                    settleRecord.setSettleAmount(settleAmount);
+                    settleRecord.setSplitCode(P3_customerNumber);
+                    settleRecord.setShopOrderId(shopOrderId);
+                    payShopDao.insertSettleRecord(settleRecord);
+                    if (3 == settleFlag) {
+                        // 最后佣金结算修改cm_split_account settlestatus
+                        payShopDao.updateSettleStatus(shopOrderId, 3);
+                    }
+                }
+            }
+        }
+    }
+
+
+    public List<NewOrder> setOrderListValue(List<NewOrder> orderList){
+        orderList.forEach(o->{
+            o.setNewShopOrders(shopOrderDao.findListByOrderId(o.getOrderId()));
+        });
+        return null;
+    }
+
+
+}

+ 1 - 3
src/main/java/com/caimei/modules/products/controller/CmMallProductsClassifyController.java

@@ -1,5 +1,6 @@
 package com.caimei.modules.products.controller;
 
+import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
 import com.caimei.modules.club.entity.Page;
 import com.caimei.modules.products.entity.CmMallOrganizeProducts;
 import com.caimei.modules.products.entity.CmMallProductsClassify;
@@ -8,10 +9,7 @@ import com.caimei.modules.products.service.CmMallProductsClassifyService;
 import com.caimei.utils.JsonModel;
 import com.github.pagehelper.PageHelper;
 import lombok.RequiredArgsConstructor;
-import org.apache.commons.collections.CollectionUtils;
 import org.apache.commons.lang3.StringUtils;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Controller;
 import org.springframework.web.bind.annotation.*;
 
 import java.util.Date;

+ 1 - 5
src/main/java/com/caimei/modules/products/service/impl/CmMallOrganizeProductsServiceImpl.java

@@ -1,22 +1,18 @@
 package com.caimei.modules.products.service.impl;
 
+import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
 import com.caimei.modules.club.entity.Page;
 import com.caimei.modules.products.dao.CmMallOrganizeProductsDao;
-import com.caimei.modules.products.dao.CmMallProductLadderPriceDao;
 import com.caimei.modules.products.entity.CmMallOrganizeProducts;
 import com.caimei.modules.products.entity.CmMallPageModules;
-import com.caimei.modules.products.entity.CmMallProductLadderPrice;
 import com.caimei.modules.products.entity.Sku;
 import com.caimei.modules.products.service.CmMallOrganizeProductsService;
 import com.caimei.utils.AppUtils;
 import com.github.pagehelper.PageHelper;
-import org.apache.commons.collections.CollectionUtils;
-import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.stereotype.Service;
 
 import javax.annotation.Resource;
-import java.util.Date;
 import java.util.List;
 
 @Service

+ 1 - 2
src/main/java/com/caimei/modules/products/service/impl/CmMallProductsClassifyServiceImpl.java

@@ -1,12 +1,11 @@
 package com.caimei.modules.products.service.impl;
 
+import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
 import com.caimei.modules.products.dao.CmMallProductsClassifyDao;
 import com.caimei.modules.products.entity.CmMallOrganizeProducts;
 import com.caimei.modules.products.entity.CmMallProductsClassify;
 import com.caimei.modules.products.service.CmMallOrganizeProductsService;
 import com.caimei.modules.products.service.CmMallProductsClassifyService;
-import org.apache.commons.collections.CollectionUtils;
-import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 
 import javax.annotation.Resource;

+ 295 - 0
src/main/java/com/caimei/utils/RedisService.java

@@ -0,0 +1,295 @@
+package com.caimei.utils;
+
+import com.baomidou.mybatisplus.core.toolkit.StringUtils;
+import lombok.extern.slf4j.Slf4j;
+
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.data.redis.core.ValueOperations;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.io.Serializable;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Redis 服务工具类
+ *
+ * @author : Charles
+ * @date : 2021/3/4
+ */
+@Slf4j
+@Service
+public class RedisService {
+
+	@Resource
+	private RedisTemplate<Serializable, Object> redisTemplate;
+
+    /**
+     * 批量删除
+     * @param keys
+     */
+	public void remove(String... keys) {
+		for(String key :keys){
+			remove(key);
+		}
+	}
+
+    /**
+     * 批量删除正则匹配到的
+     * @param pattern
+     */
+	public void removePattern(String pattern) {
+		Set<Serializable> keys = redisTemplate.keys(pattern);
+        assert keys != null;
+        if (keys.size() > 0){
+			redisTemplate.delete(keys);
+		}
+	}
+
+    /**
+     * 删除
+     * @param key
+     */
+	public void remove(String key) {
+		if (exists(key)) {
+			redisTemplate.delete(key);
+		}
+	}
+
+    /**
+     * 判断缓存中是否存在
+     * @param key
+     * @return boolean
+     */
+	public boolean exists(String key) {
+		return StringUtils.isBlank(key) ? false : redisTemplate.hasKey(key);
+	}
+
+    /**
+     * 读取缓存
+     * @param key
+     * @return
+     */
+	public Object get(String key) {
+		Object result = null;
+		ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
+		result = operations.get(key);
+		return result;
+	}
+
+    /**
+     * 写入缓存
+     * @param key
+     * @param value
+     * @return
+     */
+	public boolean set(String key, Object value) {
+		boolean result = false;
+		try {
+			ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
+			operations.set(key, value);
+			result = true;
+		} catch (Exception e) {
+			e.printStackTrace();
+		}
+		return result;
+	}
+
+    /**
+     * 写入缓存并加上过期时间(秒)
+     * @param key
+     * @param value
+     * @param expireTimeSeconds
+     * @return
+     */
+	public boolean set(String key, Object value, Long expireTimeSeconds) {
+		boolean result = false;
+		try {
+			ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
+			operations.set(key, value);
+			redisTemplate.expire(key, expireTimeSeconds, TimeUnit.SECONDS);
+			result = true;
+		} catch (Exception e) {
+			e.printStackTrace();
+		}
+		return result;
+	}
+    /**
+     * 写入过期时间(秒)
+     * @param key
+     * @param expireTimeSeconds
+     * @return
+     */
+	public boolean expire(String key, Long expireTimeSeconds) {
+		boolean result = false;
+		try {
+			redisTemplate.expire(key, expireTimeSeconds, TimeUnit.SECONDS);
+			result = true;
+		} catch (Exception e) {
+			e.printStackTrace();
+		}
+		return result;
+	}
+    /* **************************** 针对list操作的方法 **************************** */
+    /**
+     * 在key对应list的尾部添加
+     * @param key
+     * @param value
+     * @return
+     */
+	public long rightPushForList(String key, Object value) {
+		return redisTemplate.opsForList().rightPush(key, value);
+	}
+
+    /**
+     * 在key对应list的头部添加
+     * @param key
+     * @param value
+     * @return
+     */
+	public long leftPushForList(String key, Object value) {
+		return redisTemplate.opsForList().leftPush(key, value);
+	}
+
+    /**
+     * key对应list的长度
+     * @param key
+     * @return
+     */
+	public long listSize(String key) {
+		return redisTemplate.opsForList().size(key);
+	}
+
+    /**
+     * 获取list集合
+     * @param Key
+     * @param begin
+     * @param end
+     * @return
+     */
+	public List<?> getList(String Key, int begin, int end) {
+		return redisTemplate.opsForList().range(Key, begin, end);
+	}
+
+    /**
+     * 在key对应list的尾部移除
+     * @param key
+     * @return
+     */
+	public Object rightPopForList(String key) {
+		return redisTemplate.opsForList().rightPop(key);
+	}
+
+    /**
+     * 在key对应list的头部移除
+     * @param key
+     * @return
+     */
+	public Object leftPopForList(String key) {
+		return redisTemplate.opsForList().leftPop(key);
+	}
+
+    /**
+     * 移除list的index位置上的值
+     * @param Key
+     * @param index
+     * @param value
+     */
+	public void removeList(String Key, long index, Object value) {
+		redisTemplate.opsForList().remove(Key, index, value);
+	}
+
+    /**
+     * 重置list的index位置上的值
+     * @param Key
+     * @param index
+     * @param value
+     */
+	public void setList(String Key, long index, Object value) {
+		redisTemplate.opsForList().set(Key, index, value);
+	}
+
+
+    /**
+     * 写入list
+     * @param key
+     * @param list
+     */
+	public void setList(String key, List list) {
+		if(list!=null&&list.size()>0){
+			for (Object object : list) {
+				rightPushForList(key,object);
+			}
+		}
+	}
+
+    /**
+     * 写入map
+     * @param key
+     * @param map
+     */
+	public void setMap(String key, Map<String, Object> map) {
+		redisTemplate.opsForHash().putAll(key, map);
+	}
+
+    /**
+     * 获取map
+     * @param key
+     * @param mapKey
+     * @return
+     */
+	public Object get(String key, String mapKey) {
+		return redisTemplate.opsForHash().get(key, mapKey);
+	}
+
+    /**
+     * 写入map
+     * @param key
+     * @param hashKey
+     * @param hashValue
+     */
+	public void setMapByKV(String key, Object hashKey, Object hashValue) {
+		redisTemplate.opsForHash().put(key, hashKey,hashValue);
+	}
+
+    /**
+     * 删除map中的某个key-value
+     * @param key
+     * @param hashKey
+     */
+	public void removeHash(String key, String hashKey) {
+		redisTemplate.opsForHash().delete(key, hashKey);
+	}
+
+    /**
+     *
+     * @param key
+     * @return
+     */
+	public Map<Object, Object> getEntries(String key) {
+		return redisTemplate.opsForHash().entries(key);
+	}
+
+    /**
+     *
+     * @param key
+     * @param step
+     * @return
+     */
+	public long increase(String key, long step) {
+		return redisTemplate.opsForValue().increment(key, step);
+	}
+
+    /**
+     * 获取失效时间
+     * @param key
+     * @return
+     */
+	public long getExpireTime(String key) {
+		return redisTemplate.getExpire(key, TimeUnit.SECONDS);
+	}
+
+}

+ 601 - 0
src/main/java/com/caimei/utils/payUtil/Base64.java

@@ -0,0 +1,601 @@
+package com.caimei.utils.payUtil;
+
+import java.io.UnsupportedEncodingException;
+
+public class Base64 {
+    /**
+     * Chunk size per RFC 2045 section 6.8.
+     *
+     * <p>The {@value} character limit does not count the trailing CRLF, but counts
+     * all other characters, including any equal signs.</p>
+     *
+     * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 6.8</a>
+     */
+    static final int CHUNK_SIZE = 76;
+
+    /**
+     * Chunk separator per RFC 2045 section 2.1.
+     *
+     * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 2.1</a>
+     */
+    static final byte[] CHUNK_SEPARATOR = "\r\n".getBytes();
+
+    /**
+     * The base length.
+     */
+    static final int BASELENGTH = 255;
+
+    /**
+     * Lookup length.
+     */
+    static final int LOOKUPLENGTH = 64;
+
+    /**
+     * Used to calculate the number of bits in a byte.
+     */
+    static final int EIGHTBIT = 8;
+
+    /**
+     * Used when encoding something which has fewer than 24 bits.
+     */
+    static final int SIXTEENBIT = 16;
+
+    /**
+     * Used to determine how many bits data contains.
+     */
+    static final int TWENTYFOURBITGROUP = 24;
+
+    /**
+     * Used to get the number of Quadruples.
+     */
+    static final int FOURBYTE = 4;
+
+    /**
+     * Used to test the sign of a byte.
+     */
+    static final int SIGN = -128;
+
+    /**
+     * Byte used to pad output.
+     */
+    static final byte PAD = (byte) '=';
+
+    // Create arrays to hold the base64 characters and a
+    // lookup for base64 chars
+    private static byte[] base64Alphabet = new byte[BASELENGTH];
+    private static byte[] lookUpBase64Alphabet = new byte[LOOKUPLENGTH];
+
+    // Populating the lookup and character arrays
+    static {
+        for (int i = 0; i < BASELENGTH; i++) {
+            base64Alphabet[i] = (byte) -1;
+        }
+        for (int i = 'Z'; i >= 'A'; i--) {
+            base64Alphabet[i] = (byte) (i - 'A');
+        }
+        for (int i = 'z'; i >= 'a'; i--) {
+            base64Alphabet[i] = (byte) (i - 'a' + 26);
+        }
+        for (int i = '9'; i >= '0'; i--) {
+            base64Alphabet[i] = (byte) (i - '0' + 52);
+        }
+
+        base64Alphabet['+'] = 62;
+        base64Alphabet['/'] = 63;
+
+        for (int i = 0; i <= 25; i++) {
+            lookUpBase64Alphabet[i] = (byte) ('A' + i);
+        }
+
+        for (int i = 26, j = 0; i <= 51; i++, j++) {
+            lookUpBase64Alphabet[i] = (byte) ('a' + j);
+        }
+
+        for (int i = 52, j = 0; i <= 61; i++, j++) {
+            lookUpBase64Alphabet[i] = (byte) ('0' + j);
+        }
+
+        lookUpBase64Alphabet[62] = (byte) '+';
+        lookUpBase64Alphabet[63] = (byte) '/';
+    }
+
+    private static boolean isBase64(byte octect) {
+        if (octect == PAD) {
+            return true;
+        } else if (base64Alphabet[octect] == -1) {
+            return false;
+        } else {
+            return true;
+        }
+    }
+
+    /**
+     * Tests a given byte array to see if it contains
+     * only valid characters within the Base64 alphabet.
+     *
+     * @param arrayOctect byte array to test
+     * @return true if all bytes are valid characters in the Base64
+     * alphabet or if the byte array is empty; false, otherwise
+     */
+    public static boolean isArrayByteBase64(byte[] arrayOctect) {
+
+        arrayOctect = discardWhitespace(arrayOctect);
+
+        int length = arrayOctect.length;
+        if (length == 0) {
+            // shouldn't a 0 length array be valid base64 data?
+            // return false;
+            return true;
+        }
+        for (int i = 0; i < length; i++) {
+            if (!isBase64(arrayOctect[i])) {
+                return false;
+            }
+        }
+        return true;
+    }
+
+    /**
+     * Encodes binary data using the base64 algorithm but
+     * does not chunk the output.
+     *
+     * @param binaryData binary data to encode
+     * @return Base64 characters
+     */
+    public static byte[] encodeBase64(byte[] binaryData) {
+        return encodeBase64(binaryData, false);
+    }
+
+    /**
+     * Encodes binary data using the base64 algorithm and chunks
+     * the encoded output into 76 character blocks
+     *
+     * @param binaryData binary data to encode
+     * @return Base64 characters chunked in 76 character blocks
+     */
+    public static byte[] encodeBase64Chunked(byte[] binaryData) {
+        return encodeBase64(binaryData, true);
+    }
+
+    /**
+     * Decodes a byte[] containing containing
+     * characters in the Base64 alphabet.
+     *
+     * @param pArray A byte array containing Base64 character data
+     * @return a byte array containing binary data
+     */
+    public static byte[] decode(byte[] pArray) {
+        return decodeBase64(pArray);
+    }
+
+    /**
+     * Encodes binary data using the base64 algorithm, optionally
+     * chunking the output into 76 character blocks.
+     *
+     * @param binaryData Array containing binary data to encode.
+     * @param isChunked  if isChunked is true this encoder will chunk
+     *                   the base64 output into 76 character blocks
+     * @return Base64-encoded data.
+     */
+    public static byte[] encodeBase64(byte[] binaryData, boolean isChunked) {
+        int lengthDataBits = binaryData.length * EIGHTBIT;
+        int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;
+        int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;
+        byte encodedData[] = null;
+        int encodedDataLength = 0;
+        int nbrChunks = 0;
+
+        if (fewerThan24bits != 0) {
+            //data not divisible by 24 bit
+            encodedDataLength = (numberTriplets + 1) * 4;
+        } else {
+            // 16 or 8 bit
+            encodedDataLength = numberTriplets * 4;
+        }
+
+        // If the output is to be "chunked" into 76 character sections,
+        // for compliance with RFC 2045 MIME, then it is important to
+        // allow for extra length to account for the separator(s)
+        if (isChunked) {
+
+            nbrChunks =
+                    (CHUNK_SEPARATOR.length == 0 ? 0 : (int) Math.ceil((float) encodedDataLength / CHUNK_SIZE));
+            encodedDataLength += nbrChunks * CHUNK_SEPARATOR.length;
+        }
+
+        encodedData = new byte[encodedDataLength];
+
+        byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;
+
+        int encodedIndex = 0;
+        int dataIndex = 0;
+        int i = 0;
+        int nextSeparatorIndex = CHUNK_SIZE;
+        int chunksSoFar = 0;
+
+        //log.debug("number of triplets = " + numberTriplets);
+        for (i = 0; i < numberTriplets; i++) {
+            dataIndex = i * 3;
+            b1 = binaryData[dataIndex];
+            b2 = binaryData[dataIndex + 1];
+            b3 = binaryData[dataIndex + 2];
+
+            //log.debug("b1= " + b1 +", b2= " + b2 + ", b3= " + b3);
+
+            l = (byte) (b2 & 0x0f);
+            k = (byte) (b1 & 0x03);
+
+            byte val1 =
+                    ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
+            byte val2 =
+                    ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
+            byte val3 =
+                    ((b3 & SIGN) == 0) ? (byte) (b3 >> 6) : (byte) ((b3) >> 6 ^ 0xfc);
+
+            encodedData[encodedIndex] = lookUpBase64Alphabet[val1];
+            //log.debug( "val2 = " + val2 );
+            //log.debug( "k4   = " + (k<<4) );
+            //log.debug(  "vak  = " + (val2 | (k<<4)) );
+            encodedData[encodedIndex + 1] =
+                    lookUpBase64Alphabet[val2 | (k << 4)];
+            encodedData[encodedIndex + 2] =
+                    lookUpBase64Alphabet[(l << 2) | val3];
+            encodedData[encodedIndex + 3] = lookUpBase64Alphabet[b3 & 0x3f];
+
+            encodedIndex += 4;
+
+            // If we are chunking, let's put a chunk separator down.
+            if (isChunked) {
+                // this assumes that CHUNK_SIZE % 4 == 0
+                if (encodedIndex == nextSeparatorIndex) {
+                    System.arraycopy(
+                            CHUNK_SEPARATOR,
+                            0,
+                            encodedData,
+                            encodedIndex,
+                            CHUNK_SEPARATOR.length);
+                    chunksSoFar++;
+                    nextSeparatorIndex =
+                            (CHUNK_SIZE * (chunksSoFar + 1)) +
+                                    (chunksSoFar * CHUNK_SEPARATOR.length);
+                    encodedIndex += CHUNK_SEPARATOR.length;
+                }
+            }
+        }
+
+        // form integral number of 6-bit groups
+        dataIndex = i * 3;
+
+        if (fewerThan24bits == EIGHTBIT) {
+            b1 = binaryData[dataIndex];
+            k = (byte) (b1 & 0x03);
+            //log.debug("b1=" + b1);
+            //log.debug("b1<<2 = " + (b1>>2) );
+            byte val1 =
+                    ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
+            encodedData[encodedIndex] = lookUpBase64Alphabet[val1];
+            encodedData[encodedIndex + 1] = lookUpBase64Alphabet[k << 4];
+            encodedData[encodedIndex + 2] = PAD;
+            encodedData[encodedIndex + 3] = PAD;
+        } else if (fewerThan24bits == SIXTEENBIT) {
+
+            b1 = binaryData[dataIndex];
+            b2 = binaryData[dataIndex + 1];
+            l = (byte) (b2 & 0x0f);
+            k = (byte) (b1 & 0x03);
+
+            byte val1 =
+                    ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
+            byte val2 =
+                    ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
+
+            encodedData[encodedIndex] = lookUpBase64Alphabet[val1];
+            encodedData[encodedIndex + 1] =
+                    lookUpBase64Alphabet[val2 | (k << 4)];
+            encodedData[encodedIndex + 2] = lookUpBase64Alphabet[l << 2];
+            encodedData[encodedIndex + 3] = PAD;
+        }
+
+        if (isChunked) {
+            // we also add a separator to the end of the final chunk.
+            if (chunksSoFar < nbrChunks) {
+                System.arraycopy(
+                        CHUNK_SEPARATOR,
+                        0,
+                        encodedData,
+                        encodedDataLength - CHUNK_SEPARATOR.length,
+                        CHUNK_SEPARATOR.length);
+            }
+        }
+
+        return encodedData;
+    }
+
+    /**
+     * Decodes Base64 data into octects
+     *
+     * @param base64Data Byte array containing Base64 data
+     * @return Array containing decoded data.
+     */
+    public static byte[] decodeBase64(byte[] base64Data) {
+        // RFC 2045 requires that we discard ALL non-Base64 characters
+        base64Data = discardNonBase64(base64Data);
+
+        // handle the edge case, so we don't have to worry about it later
+        if (base64Data.length == 0) {
+            return new byte[0];
+        }
+
+        int numberQuadruple = base64Data.length / FOURBYTE;
+        byte decodedData[] = null;
+        byte b1 = 0, b2 = 0, b3 = 0, b4 = 0, marker0 = 0, marker1 = 0;
+
+        // Throw away anything not in base64Data
+
+        int encodedIndex = 0;
+        int dataIndex = 0;
+        {
+            // this sizes the output array properly - rlw
+            int lastData = base64Data.length;
+            // ignore the '=' padding
+            while (base64Data[lastData - 1] == PAD) {
+                if (--lastData == 0) {
+                    return new byte[0];
+                }
+            }
+            decodedData = new byte[lastData - numberQuadruple];
+        }
+
+        for (int i = 0; i < numberQuadruple; i++) {
+            dataIndex = i * 4;
+            marker0 = base64Data[dataIndex + 2];
+            marker1 = base64Data[dataIndex + 3];
+
+            b1 = base64Alphabet[base64Data[dataIndex]];
+            b2 = base64Alphabet[base64Data[dataIndex + 1]];
+
+            if (marker0 != PAD && marker1 != PAD) {
+                //No PAD e.g 3cQl
+                b3 = base64Alphabet[marker0];
+                b4 = base64Alphabet[marker1];
+
+                decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
+                decodedData[encodedIndex + 1] =
+                        (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
+                decodedData[encodedIndex + 2] = (byte) (b3 << 6 | b4);
+            } else if (marker0 == PAD) {
+                //Two PAD e.g. 3c[Pad][Pad]
+                decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
+            } else if (marker1 == PAD) {
+                //One PAD e.g. 3cQ[Pad]
+                b3 = base64Alphabet[marker0];
+
+                decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
+                decodedData[encodedIndex + 1] =
+                        (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
+            }
+            encodedIndex += 3;
+        }
+        return decodedData;
+    }
+
+    /**
+     * Discards any whitespace from a base-64 encoded block.
+     *
+     * @param data The base-64 encoded data to discard the whitespace
+     *             from.
+     * @return The data, less whitespace (see RFC 2045).
+     */
+    static byte[] discardWhitespace(byte[] data) {
+        byte groomedData[] = new byte[data.length];
+        int bytesCopied = 0;
+
+        for (int i = 0; i < data.length; i++) {
+            switch (data[i]) {
+                case (byte) ' ':
+                case (byte) '\n':
+                case (byte) '\r':
+                case (byte) '\t':
+                    break;
+                default:
+                    groomedData[bytesCopied++] = data[i];
+            }
+        }
+
+        byte packedData[] = new byte[bytesCopied];
+
+        System.arraycopy(groomedData, 0, packedData, 0, bytesCopied);
+
+        return packedData;
+    }
+
+    /**
+     * Discards any characters outside of the base64 alphabet, per
+     * the requirements on page 25 of RFC 2045 - "Any characters
+     * outside of the base64 alphabet are to be ignored in base64
+     * encoded data."
+     *
+     * @param data The base-64 encoded data to groom
+     * @return The data, less non-base64 characters (see RFC 2045).
+     */
+    static byte[] discardNonBase64(byte[] data) {
+        byte groomedData[] = new byte[data.length];
+        int bytesCopied = 0;
+
+        for (int i = 0; i < data.length; i++) {
+            if (isBase64(data[i])) {
+                groomedData[bytesCopied++] = data[i];
+            }
+        }
+
+        byte packedData[] = new byte[bytesCopied];
+
+        System.arraycopy(groomedData, 0, packedData, 0, bytesCopied);
+
+        return packedData;
+    }
+
+    /**
+     * Encodes a byte[] containing binary data, into a byte[] containing
+     * characters in the Base64 alphabet.
+     *
+     * @param pArray a byte array containing binary data
+     * @return A byte array containing only Base64 character data
+     */
+    public static byte[] encode(byte[] pArray) {
+        return encodeBase64(pArray, false);
+    }
+
+    public static String encode(String str) throws UnsupportedEncodingException {
+        String baseStr = new String(encode(str.getBytes("UTF-8")));
+        String tempStr = Digest.digest(str).toUpperCase();
+        String result = tempStr + baseStr;
+        return new String(encode(result.getBytes("UTF-8")));
+    }
+
+    public static String decode(String cryptoStr) throws
+            UnsupportedEncodingException {
+        if (cryptoStr.length() < 40)
+            return "";
+        try {
+            String tempStr = new String(decode(cryptoStr.getBytes("UTF-8")));
+            String result = tempStr.substring(40, tempStr.length());
+            return new String(decode(result.getBytes("UTF-8")));
+        } catch (ArrayIndexOutOfBoundsException ex) {
+            return "";
+        }
+    }
+
+
+    /**
+     * Decodes Base64 data into octects
+     *
+     * @param encoded string containing Base64 data
+     * @return Array containind decoded data.
+     */
+    public static byte[] decode2(String encoded) {
+
+        if (encoded == null) {
+            return null;
+        }
+
+        char[] base64Data = encoded.toCharArray();
+        // remove white spaces
+        int len = removeWhiteSpace(base64Data);
+
+        if (len % FOURBYTE != 0) {
+            return null;//should be divisible by four
+        }
+
+        int numberQuadruple = (len / FOURBYTE);
+
+        if (numberQuadruple == 0) {
+            return new byte[0];
+        }
+
+        byte decodedData[] = null;
+        byte b1 = 0, b2 = 0, b3 = 0, b4 = 0;
+        char d1 = 0, d2 = 0, d3 = 0, d4 = 0;
+
+        int i = 0;
+        int encodedIndex = 0;
+        int dataIndex = 0;
+        decodedData = new byte[(numberQuadruple) * 3];
+
+        for (; i < numberQuadruple - 1; i++) {
+
+            if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))
+                    || !isData((d3 = base64Data[dataIndex++]))
+                    || !isData((d4 = base64Data[dataIndex++]))) {
+                return null;
+            }//if found "no data" just return null
+
+            b1 = base64Alphabet[d1];
+            b2 = base64Alphabet[d2];
+            b3 = base64Alphabet[d3];
+            b4 = base64Alphabet[d4];
+
+            decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
+            decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
+            decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
+        }
+
+        if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))) {
+            return null;//if found "no data" just return null
+        }
+
+        b1 = base64Alphabet[d1];
+        b2 = base64Alphabet[d2];
+
+        d3 = base64Data[dataIndex++];
+        d4 = base64Data[dataIndex++];
+        if (!isData((d3)) || !isData((d4))) {//Check if they are PAD characters
+            if (isPad(d3) && isPad(d4)) {
+                if ((b2 & 0xf) != 0)//last 4 bits should be zero
+                {
+                    return null;
+                }
+                byte[] tmp = new byte[i * 3 + 1];
+                System.arraycopy(decodedData, 0, tmp, 0, i * 3);
+                tmp[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
+                return tmp;
+            } else if (!isPad(d3) && isPad(d4)) {
+                b3 = base64Alphabet[d3];
+                if ((b3 & 0x3) != 0)//last 2 bits should be zero
+                {
+                    return null;
+                }
+                byte[] tmp = new byte[i * 3 + 2];
+                System.arraycopy(decodedData, 0, tmp, 0, i * 3);
+                tmp[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
+                tmp[encodedIndex] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
+                return tmp;
+            } else {
+                return null;
+            }
+        } else { //No PAD e.g 3cQl
+            b3 = base64Alphabet[d3];
+            b4 = base64Alphabet[d4];
+            decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
+            decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
+            decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
+
+        }
+
+        return decodedData;
+    }
+
+    private static boolean isWhiteSpace(char octect) {
+        return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9);
+    }
+
+    private static boolean isData(char octect) {
+        return (octect < BASELENGTH && base64Alphabet[octect] != -1);
+    }
+
+    private static boolean isPad(char octect) {
+        return (octect == PAD);
+    }
+
+    /**
+     * remove WhiteSpace from MIME containing encoded Base64 data.
+     *
+     * @param data the byte array of base64 data (with WS)
+     * @return the new length
+     */
+    private static int removeWhiteSpace(char[] data) {
+        if (data == null) {
+            return 0;
+        }
+
+        // count characters that's not whitespace
+        int newSize = 0;
+        int len = data.length;
+        for (int i = 0; i < len; i++) {
+            if (!isWhiteSpace(data[i])) {
+                data[newSize++] = data[i];
+            }
+        }
+        return newSize;
+    }
+}

+ 166 - 0
src/main/java/com/caimei/utils/payUtil/Digest.java

@@ -0,0 +1,166 @@
+package com.caimei.utils.payUtil;
+
+import com.caimei.utils.ConvertUtils;
+
+import java.io.UnsupportedEncodingException;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.Arrays;
+
+public class Digest {
+    public static final String ENCODE = "UTF-8";
+
+    public static String signMD5(String aValue, String encoding) {
+        try {
+            byte[] input = aValue.getBytes(encoding);
+            MessageDigest md = MessageDigest.getInstance("MD5");
+            return ConvertUtils.toHex(md.digest(input));
+        } catch (NoSuchAlgorithmException e) {
+            e.printStackTrace();
+            return null;
+        } catch (UnsupportedEncodingException e) {
+            e.printStackTrace();
+            return null;
+        }
+    }
+
+    public static String hmacSign(String aValue) {
+        try {
+            byte[] input = aValue.getBytes();
+            MessageDigest md = MessageDigest.getInstance("MD5");
+            return ConvertUtils.toHex(md.digest(input));
+        } catch (NoSuchAlgorithmException e) {
+            e.printStackTrace();
+            return null;
+        }
+    }
+
+    public static String hmacSign(String aValue, String aKey) {
+        return hmacSign(aValue, aKey, ENCODE);
+    }
+
+    public static String hmacSign(String aValue, String aKey, String encoding) {
+        byte k_ipad[] = new byte[64];
+        byte k_opad[] = new byte[64];
+        byte keyb[];
+        byte value[];
+        try {
+            keyb = aKey.getBytes(encoding);
+            value = aValue.getBytes(encoding);
+        } catch (UnsupportedEncodingException e) {
+            keyb = aKey.getBytes();
+            value = aValue.getBytes();
+        }
+        Arrays.fill(k_ipad, keyb.length, 64, (byte) 54);
+        Arrays.fill(k_opad, keyb.length, 64, (byte) 92);
+        for (int i = 0; i < keyb.length; i++) {
+            k_ipad[i] = (byte) (keyb[i] ^ 0x36);
+            k_opad[i] = (byte) (keyb[i] ^ 0x5c);
+        }
+
+        MessageDigest md = null;
+        try {
+            md = MessageDigest.getInstance("MD5");
+        } catch (NoSuchAlgorithmException e) {
+            e.printStackTrace();
+            return null;
+        }
+        md.update(k_ipad);
+        md.update(value);
+        byte dg[] = md.digest();
+        md.reset();
+        md.update(k_opad);
+        md.update(dg, 0, 16);
+        dg = md.digest();
+        return ConvertUtils.toHex(dg);
+    }
+
+    public static String hmacSHASign(String aValue, String aKey, String encoding) {
+        byte k_ipad[] = new byte[64];
+        byte k_opad[] = new byte[64];
+        byte keyb[];
+        byte value[];
+        try {
+            keyb = aKey.getBytes(encoding);
+            value = aValue.getBytes(encoding);
+        } catch (UnsupportedEncodingException e) {
+            keyb = aKey.getBytes();
+            value = aValue.getBytes();
+        }
+        Arrays.fill(k_ipad, keyb.length, 64, (byte) 54);
+        Arrays.fill(k_opad, keyb.length, 64, (byte) 92);
+        for (int i = 0; i < keyb.length; i++) {
+            k_ipad[i] = (byte) (keyb[i] ^ 0x36);
+            k_opad[i] = (byte) (keyb[i] ^ 0x5c);
+        }
+
+        MessageDigest md = null;
+        try {
+            md = MessageDigest.getInstance("SHA");
+        } catch (NoSuchAlgorithmException e) {
+            e.printStackTrace();
+            return null;
+        }
+        md.update(k_ipad);
+        md.update(value);
+        byte dg[] = md.digest();
+        md.reset();
+        md.update(k_opad);
+        md.update(dg, 0, 20);
+        dg = md.digest();
+        return ConvertUtils.toHex(dg);
+    }
+
+    public static String digest(String aValue) {
+        return digest(aValue, ENCODE);
+
+    }
+
+    public static String digest(String aValue, String encoding) {
+        aValue = aValue.trim();
+        byte value[];
+        try {
+            value = aValue.getBytes(encoding);
+        } catch (UnsupportedEncodingException e) {
+            value = aValue.getBytes();
+        }
+        MessageDigest md = null;
+        try {
+            md = MessageDigest.getInstance("SHA");
+        } catch (NoSuchAlgorithmException e) {
+            e.printStackTrace();
+            return null;
+        }
+        return ConvertUtils.toHex(md.digest(value));
+    }
+
+
+    public static String digest(String aValue, String alg, String encoding) {
+        aValue = aValue.trim();
+        byte value[];
+        try {
+            value = aValue.getBytes(encoding);
+        } catch (UnsupportedEncodingException e) {
+            value = aValue.getBytes();
+        }
+        MessageDigest md = null;
+        try {
+            md = MessageDigest.getInstance(alg);
+        } catch (NoSuchAlgorithmException e) {
+            e.printStackTrace();
+            return null;
+        }
+        return ConvertUtils.toHex(md.digest(value));
+    }
+
+    public static String udpSign(String aValue) {
+        try {
+            byte[] input = aValue.getBytes("UTF-8");
+            MessageDigest md = MessageDigest.getInstance("SHA1");
+            return new String(Base64.encode(md.digest(input)), ENCODE);
+        } catch (Exception e) {
+            return null;
+        }
+    }
+
+}

+ 110 - 0
src/main/java/com/caimei/utils/payUtil/MyBeanUtils.java

@@ -0,0 +1,110 @@
+package com.caimei.utils.payUtil;
+
+
+import org.apache.commons.beanutils.BeanUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.beans.IntrospectionException;
+import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ *
+ */
+public class MyBeanUtils extends BeanUtils{
+
+    private static final Logger LOGGER = LoggerFactory.getLogger(MyBeanUtils.class);
+
+    private MyBeanUtils(){ }
+
+    public static Map convertBean(Object bean, Map retMap)
+            throws IntrospectionException, IllegalAccessException, InvocationTargetException {
+        Class clazz = bean.getClass();
+        Field[] fields = clazz.getDeclaredFields();
+        for (Field f : fields) {
+            f.setAccessible(true);
+        }
+        for (Field f : fields) {
+            String key = f.toString().substring(f.toString().lastIndexOf(".") + 1);
+            if (StringUtils.equalsIgnoreCase("NEED_SIGN_PARAMS", key)) {
+                continue;
+            }
+            Object value = f.get(bean);
+            if (value == null)
+                value = "";
+            retMap.put(key, value);
+        }
+        return retMap;
+    }
+
+    public static String getSigned(Map<String, String> map, String[] excludes){
+        StringBuffer sb = new StringBuffer();
+        Set<String> excludeSet = new HashSet<String>();
+        excludeSet.add("sign");
+        if(excludes != null){
+            for(String exclude : excludes){
+                excludeSet.add(exclude);
+            }
+        }
+        for(String key : map.keySet()){
+            if(!excludeSet.contains(key)){
+                String value = map.get(key);
+                value = (value == null ? "" : value);
+                sb.append("&");
+                sb.append(value);
+            }
+        }
+        sb.append("&");
+        return sb.toString();
+    }
+
+    public static String getSigned(Object bean, String[] excludes) throws IllegalAccessException, IntrospectionException, InvocationTargetException {
+        Map map  = convertBean(bean, new LinkedHashMap());
+        String signedStr = getSigned(map, excludes);
+        return signedStr;
+    }
+
+    /**
+     * new style
+     *
+     * @param bean
+     * @param needSignParams
+     */
+    public static String getSignedByPresetParameter(Object bean, Set<String> needSignParams) throws IllegalAccessException,
+            IntrospectionException, InvocationTargetException {
+        Map map = convertBean(bean, new LinkedHashMap<>());
+        return getSignedByPresetParameter(map, needSignParams);
+    }
+
+    /**
+     * new style
+     *
+     * @param map
+     * @param needSignParams
+     * @return
+     */
+    public static String getSignedByPresetParameter(Map<String, String> map, Set<String> needSignParams) {
+        StringBuffer sb = new StringBuffer();
+        if (needSignParams == null || needSignParams.isEmpty()) {
+            throw new RuntimeException("needSignParams is required");
+        }
+        for (String key : map.keySet()) {
+            if (needSignParams.contains(key)) {
+                // do sign
+                String value = map.get(key);
+                value = (value == null ? "" : value);
+                sb.append("&");
+                sb.append(value);
+            }
+        }
+        sb.append("&");
+        return sb.toString();
+    }
+
+}

+ 405 - 0
src/main/java/com/caimei/utils/payUtil/RSA.java

@@ -0,0 +1,405 @@
+package com.caimei.utils.payUtil;
+
+
+import org.apache.commons.lang3.ArrayUtils;
+import sun.misc.BASE64Encoder;
+
+
+import javax.crypto.BadPaddingException;
+import javax.crypto.Cipher;
+import javax.crypto.IllegalBlockSizeException;
+import javax.crypto.NoSuchPaddingException;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.security.*;
+import java.security.cert.Certificate;
+import java.security.cert.CertificateFactory;
+import java.security.spec.InvalidKeySpecException;
+import java.security.spec.PKCS8EncodedKeySpec;
+import java.security.spec.X509EncodedKeySpec;
+import java.util.Arrays;
+import java.util.Enumeration;
+
+/**
+ * 私钥签名,私钥签名(只有私钥能签),公钥验证签名,确认发起人是私钥持有人
+ * 公钥加密,公钥加密只有私钥能解密
+ * @author datou
+ *
+ */
+public class RSA {
+	
+	 /** 
+     * String to hold name of the encryption padding. 
+     */  
+    public static final String NOPADDING = "RSA/NONE/NoPadding";
+    
+    public static final String RSANONEPKCS1PADDING = "RSA/NONE/PKCS1Padding";
+    
+    public static final String RSAECBPKCS1PADDING = "RSA/ECB/PKCS1Padding";
+	
+	public static final String PROVIDER = "BC";
+	
+	static{
+		Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
+	}
+	
+	/**
+	 * 验证签名
+	 * 
+	 * @param data
+	 *            数据
+	 * @param sign
+	 *            签名
+	 * @param pubicKey
+	 *            公钥
+	 * @return
+	 */
+	public static boolean verifySign(byte[] data, byte[] sign,
+			PublicKey publicKey) {
+		try {
+			Signature signature = Signature
+					.getInstance("MD5withRSA");
+			signature.initVerify(publicKey);
+			signature.update(data);
+			boolean result = signature.verify(sign);
+			return result;
+		} catch (Exception e) {
+
+			throw new RuntimeException("verifySign fail!", e);
+		}
+	}
+
+	/**
+	 * 验证签名
+	 * 
+	 * @param data
+	 *            数据
+	 * @param sign
+	 *            签名
+	 * @param pubicKey
+	 *            公钥
+	 * @return
+	 */
+	public static boolean verifySign(String data, String sign,
+			PublicKey pubicKey) {
+		try {
+			byte[] dataByte = data
+					.getBytes("UTF-8");
+			byte[] signByte = Base64.decode(sign
+					.getBytes("UTF-8"));
+			return verifySign(dataByte, signByte, pubicKey);
+		} catch (UnsupportedEncodingException e) {
+
+			throw new RuntimeException("verifySign fail! data["+data+"] sign["+sign+"]", e);
+		}
+	}
+
+	/**
+	 * 签名
+	 * 
+	 * @param data
+	 * @param key
+	 * @return
+	 */
+	public static byte[] sign(byte[] data, PrivateKey key) {
+		try {
+			Signature signature = Signature
+					.getInstance("MD5withRSA");
+			signature.initSign(key);
+			signature.update(data);
+			return signature.sign();
+		} catch (Exception e) {
+			throw new RuntimeException("sign fail!", e);
+		}
+	}
+
+	/**
+	 * 签名
+	 * 
+	 * @param data
+	 * @param key
+	 * @return
+	 */
+	public static String sign(String data, PrivateKey key) {
+		System.out.println("原文:" + data);
+		try {
+			byte[] dataByte = data.getBytes("UTF-8");
+			return new String(Base64.encode(sign(dataByte, key)));
+		} catch (UnsupportedEncodingException e) {
+			throw new RuntimeException("sign fail!", e);
+		}
+	}
+
+	/**
+	 * 加密
+	 * 
+	 * @param data
+	 * @param key
+	 * @return
+	 */
+	public static byte[] encrypt(byte[] data, Key key,String padding) {
+		try {
+            final Cipher cipher = Cipher.getInstance(padding, PROVIDER);
+			cipher.init(Cipher.ENCRYPT_MODE, key);
+			return cipher.doFinal(data);
+		} catch (Exception e) {
+
+			throw new RuntimeException("encrypt fail!", e);
+		}
+	}
+	
+	/**
+	 * 加密
+	 * 
+	 * @param data
+	 * @param key
+	 * @return
+	 */
+	public static String encryptToBase64(String data, Key key,String padding) {
+		try {
+			return new String(Base64.encode(encrypt(
+					data.getBytes("UTF-8"),
+					key,padding)));
+		} catch (Exception e) {
+			throw new RuntimeException("encrypt fail!", e);
+		}
+	}
+
+	/**
+	 * 解密
+	 * 
+	 * @param data
+	 * @param key
+	 * @return
+	 */
+	public static byte[] decrypt(byte[] data, Key key,String padding) {
+		try {
+            final Cipher cipher = Cipher.getInstance(padding, PROVIDER); 
+			cipher.init(Cipher.DECRYPT_MODE, key);
+			return cipher.doFinal(data);
+		} catch (Exception e) {
+			throw new RuntimeException("encrypt fail!", e);
+		}
+	}
+
+	/**
+	 * 解密
+	 * 
+	 * @param data
+	 * @param key
+	 * @return
+	 */
+	public static String decryptFromBase64(String data, Key key,String padding) {
+		try {
+			return new String(decrypt(Base64.decode(data.getBytes()), key,padding),
+					"UTF-8");
+		} catch (Exception e) {
+			throw new RuntimeException("encrypt fail!", e);
+		}
+	}
+	
+	public static void createKeyPairs(int size) throws Exception {  
+	    // create the keys  
+	    KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", PROVIDER);  
+	    generator.initialize(size, new SecureRandom());  
+	    KeyPair pair = generator.generateKeyPair();  
+	    PublicKey pubKey = pair.getPublic();  
+	    PrivateKey privKey = pair.getPrivate();  
+	    byte[] pk = pubKey.getEncoded();  
+	    byte[] privk = privKey.getEncoded();  
+	    String strpk = new String(Base64.encodeBase64(pk));
+	    String strprivk = new String(Base64.encodeBase64(privk));  
+	    System.out.println("公钥:" + Arrays.toString(pk));  
+	    System.out.println("私钥:" + Arrays.toString(privk));  
+	    System.out.println("公钥Base64编码:" + strpk);  
+	    System.out.println("私钥Base64编码:" + strprivk);  
+	  }
+	
+	public static PublicKey getPublicKey(String base64EncodePublicKey) throws Exception{
+		 KeyFactory keyf = KeyFactory.getInstance("RSA", PROVIDER);  
+		 X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(Base64.decodeBase64(base64EncodePublicKey.getBytes()));
+		 PublicKey pubkey = keyf.generatePublic(pubX509);  
+		 return pubkey;
+	}
+	
+	public static PrivateKey getPrivateKey(String base64EncodePrivateKey)throws Exception{
+		KeyFactory keyf = KeyFactory.getInstance("RSA", PROVIDER);  
+		 PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decodeBase64(base64EncodePrivateKey.getBytes()));
+		 PrivateKey privkey = keyf.generatePrivate(priPKCS8);
+		 return privkey;
+	}
+	
+	
+	 public static byte[] encode(String encodeString, Key key,String padding) throws Exception {
+		 final Cipher cipher = Cipher.getInstance(padding, PROVIDER);
+		  cipher.init(Cipher.ENCRYPT_MODE, key);
+		  byte[] bytes = encodeString.getBytes("UTF-8");
+		  byte[] encodedByteArray = new byte[] {};
+		  for (int i = 0; i < bytes.length; i += 117) {
+		   byte[] subarray = ArrayUtils.subarray(bytes, i, i + 117);
+		   byte[] doFinal = cipher.doFinal(subarray);
+		   encodedByteArray = ArrayUtils.addAll(encodedByteArray, doFinal);
+		  }
+		  return encodedByteArray;
+	}
+	 
+	 /**
+		 * 加密
+		 * 
+		 * @param data
+		 * @param key
+		 * @return
+		 */
+		public static String encodeToBase64(String data, Key key,String padding) {
+			try {
+				return new String(Base64.encode(encode(	data,
+						key,padding)));
+			} catch (Exception e) {
+				throw new RuntimeException("encrypt fail!", e);
+			}
+		}
+	 
+	 public static String decode(byte[] decodeByteArray, Key key,String padding) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, IOException, NoSuchProviderException {
+		 final Cipher cipher = Cipher.getInstance(padding, PROVIDER);
+		  cipher.init(Cipher.DECRYPT_MODE, key);
+		  StringBuilder sb = new StringBuilder();
+		  for (int i = 0; i < decodeByteArray.length; i += 128) {
+		   byte[] doFinal = cipher.doFinal(ArrayUtils.subarray(decodeByteArray, i, i + 128));
+		   sb.append(new String(doFinal));
+		  }
+		  return sb.toString();
+		 }
+	 
+	 /**
+		 * 解密
+		 * 
+		 * @param data
+		 * @param key
+		 * @return
+		 */
+		public static String decodeFromBase64(String data, Key key,String padding) {
+			try {
+				return new String(decode(Base64.decode(data.getBytes()), key,padding).getBytes(),
+						"UTF-8");
+			} catch (Exception e) {
+				throw new RuntimeException("encrypt fail!", e);
+			}
+		}
+		
+		/**
+		 * 得到密钥字符串(经过base64编码)
+		 * 
+		 * @return
+		 */
+		public static String getKeyString(Key key) throws Exception {
+			byte[] keyBytes = key.getEncoded();
+			String s = (new BASE64Encoder()).encode(keyBytes);
+			return s;
+		}
+		
+		public static String getKeyStringByCer(String path) throws Exception{
+			CertificateFactory cff = CertificateFactory.getInstance("X.509");
+			FileInputStream fis1 = new FileInputStream(path);
+			Certificate cf = cff.generateCertificate(fis1);
+			PublicKey pk1 = cf.getPublicKey();
+			String key = getKeyString(pk1);
+			System.out.println("public:\n" + key);
+			return key;
+		}
+		
+		public static String getKeyStringByPfx(String strPfx, String strPassword){  
+	        try {  
+	            KeyStore ks = KeyStore.getInstance("PKCS12");  
+	            FileInputStream fis = new FileInputStream(strPfx);  
+	            // If the keystore password is empty(""), then we have to set  
+	            // to null, otherwise it won't work!!!  
+	            char[] nPassword = null;  
+	            if ((strPassword == null) || strPassword.trim().equals("")){  
+	                nPassword = null;  
+	            }  
+	            else  
+	            {  
+	                nPassword = strPassword.toCharArray();  
+	            }  
+	            ks.load(fis, nPassword);  
+	            fis.close();  
+	            System.out.println("keystore type=" + ks.getType());  
+	            // Now we loop all the aliases, we need the alias to get keys.  
+	            // It seems that this value is the "Friendly name" field in the  
+	            // detals tab <-- Certificate window <-- view <-- Certificate  
+	            // Button <-- Content tab <-- Internet Options <-- Tools menu   
+	            // In MS IE 6.  
+	            Enumeration enumas = ks.aliases();  
+	            String keyAlias = null;  
+	            if (enumas.hasMoreElements())// we are readin just one certificate.  
+	            {  
+	                keyAlias = (String)enumas.nextElement();   
+	                System.out.println("alias=[" + keyAlias + "]");  
+	            }  
+	            // Now once we know the alias, we could get the keys.  
+	            System.out.println("is key entry=" + ks.isKeyEntry(keyAlias));  
+	            PrivateKey prikey = (PrivateKey) ks.getKey(keyAlias, nPassword);  
+	            Certificate cert = ks.getCertificate(keyAlias);  
+	            PublicKey pubkey = cert.getPublicKey();  
+	            
+	            String basePrikey = RSA.getKeyString(prikey);
+	            System.out.println("cert class = " + cert.getClass().getName());  
+	            System.out.println("cert = " + cert);  
+	            System.out.println("public key = " + pubkey);  
+	            System.out.println("private key = " + prikey); 
+	            System.out.println("pubkey key = " + RSA.getKeyString(pubkey));
+	            System.out.println("prikey key = " + RSA.getKeyString(prikey));
+	            System.out.println("pubkey key length = " + RSA.getKeyString(pubkey).length());
+	            System.out.println("prikey key length = " + RSA.getKeyString(prikey).length());
+	            return basePrikey;  
+	        }  
+	        catch (Exception e)  
+	        {  
+	            e.printStackTrace();  
+	        }  
+	        return null;  
+	    } 
+
+	/**
+	 * 512位PKCS#8
+	 * @param args
+	 * @throws Exception
+	 */
+	public static void main(String[] args) throws Exception {
+		//getKeyStringByCer("/usr/local/cjpayProductServerCertExpiryDate20170509.cer");
+		//String privatekey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDYNb+tFTFM+V4kzeeubf5iUPgKl50kxXuEJ57qrFJ0iC0eHpOlw3axqD+zjnWQ+/R1yWUl77SOqgvowmtbKz1qLgXyB57G2lAveL48tp0yyd+tfQMQkW1duT27lGp1bAj/lhwVulvUSzJPqlc4mBt0F+/jEGQ4VZRmR0NxhMbutj7pu61rawZDqS/FSrcnt872uHaUsF+b7c2JcOl7qyB3ySLcMjkJ6rAonYohMCfy0ZT9KruRJQMXtVAbuDLxS+BASDYeE1aOqbg+KPQRfCPdM6t0FX4Y0o6y6cwhd6GQ2OcM6o4lUoKIV6ggeZWG/CHwm85mQ5dbhb7JhMj80CMzAgMBAAECggEBANRC0E7IQ4JiPr67NvzUF63F9/3OIwR6rGxtyWJykvC80C6FrkZKwzhfCUrqTRltge4xLhA0aHq3DsIQPP1gUgbv7/5Q5NwscBRq4bkRPvshnWrhFCUr4MbmmWiSqIFm8t6ZLDFYp9afjGERxldVXX54EZZF/V4hBnPy+o9z3ylyC8skTpX91xTlx523UCGRPWG9cLID5OHrhnWfRybeO7ekGzTFSD7pMIZvQ24mrC6eTJZK6QmAMTB6UxEfyQ+scETO5RhwKOl1KngfQ7rjNSr8tfPcj7u5jdu9VbWYgrg/SKzQTkZCzoLeubwVmTdhMvKmN0KZx771sqVfCa21maECgYEA8+nUHAhJpP/iDJUyh0zksBRBlakI4/UR4/LoVzKQ2eQybXmKDFPSGRXse/YQUvFNirtWHYtxruRWmKxUOlbI8ByWo2sSEZZkQ/5/RLLa7GeH46B7iw19fE8kVv6m9uXHSP+DZqPZ+oyMGI1h9CFO9hnGuzR6ZMBtWBuPwAIX/z0CgYEA4ux8wKGMkPPUxmMLSb7nTjy1q9g8K2YdBWNDTed82H9wwTkVdkWRcDmS64PQEglaK3BCBdI5nN4xQ4p/xEaVVicKChl+1kFpErrHIRO0PEHj/X2+UVurGr19ayEimSBbkqP9s8Ilm867zVjgUbBPb5eEGwF2ZWvBzHp62x+90y8CgYB6gmakEdGTi2ZpdYKkjI2Mlw/98KHjhVMQEBB8w4wXtNNTQymAWZV8PhPCi2vVjReqZ7+wJTrbYhrQojXH+5D/cQyEViIELWp88FXSFpd5B+MsBI4o4IS3rDSPcWZBOlYnJxdDtWalvnQbXN/nM9eqKnYzzv7unewNxgIkqaiN7QKBgA3H5tub8/lplWZm5WyZF1r8/NtuylioXuLQ4Gl+wWo0cxiI6vC/0NFL7cw3uQ8fWkaBDsFjvvPz2nILmy7ESpVs0YNDgRxp5IOqrCUqGSv/pGTkmgY+1ulM0K0M2hkKigUhyGp+Q+Jub6FM4HKVjn1sai1prVMDdEWCuqtMBi8pAoGBAMAZp5m+dUkgG9nUk4Hek+zGhBTUe56NdgTRRX1m8LofW4G4wIG34nLNxEvGmklQjmgGfg1s/XhBQ+BrNUhD4fP+d5Q78qdNqQGzBamXHgjw3fGwUZJJqnatdTeQlf2hSwOSps6cwECezdB0jdxN8oiWCYFc22wP076jHOiMgU+J";
+		String publickey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDonLTXehZeFwmsg+zs8AHrsgGPkGXLS7Lhf2RMOHmAHC/MsvnrfHfu0GD0FcX7NuXKBJK7KsA0MWlEkHezuoRkZS2xZ79qQzImSVE3POO4g1ZVTsW2Bl9LNN2mkTAsum6ik/vodYzftbS0tT73SvgHk54mAm8cWdiQOEVmdX0yhQIDAQAB";
+//		System.err.println("-----------"+getKeyStringByCer("/usr/local/businessgate.cer"));
+//		String padding = RSAECBPKCS1PADDING;
+		//createKeyPairs(1024);
+//		String publickey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCN7fVkqM5hzcPg+xTKEOCsMQ2WQyqgaVbMd3atYN9zngW/biNqkt9vo5EWvoZ/WEByXPvanZRKWMPRFU39fxmtAxdl5TBoh+f4utd8TqdQ2c/uMRUzOecNXlvEZZNXN3Pgu/LLr1ss/H2ma+Lwkoq1WBkWzpY5BJqqhBKpQfWPRwIDAQAB";
+//		System.out.println(publickey.length());
+//		String privatekey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAI3t9WSozmHNw+D7FMoQ4KwxDZZDKqBpVsx3dq1g33OeBb9uI2qS32+jkRa+hn9YQHJc+9qdlEpYw9EVTf1/Ga0DF2XlMGiH5/i613xOp1DZz+4xFTM55w1eW8Rlk1c3c+C78suvWyz8faZr4vCSirVYGRbOljkEmqqEEqlB9Y9HAgMBAAECgYBREHDwpVn7ksMmZUJih3FL6FiSUpquNHxXHIS0UnhOWRt/UzD3Vhw4b3wXOYsogQeOSn2vSAHC1SBC86AwAcBvqXmKrmuCPoZX0MQkO4tVqfONgE4sq1jbuWHobwP14iZTGqdY69a13Vx6C4PFaOElOkzJbyDA4YkjTBvuR5IvAQJBAPCzgT4uhA73WMsntlI/YhKL7NteA/epUPJbL2UnY6Tf3vqSsvskU9ulgmJLUt1GBG7NFNYXQ6a6I/3GqOPdz7ECQQCW81Iv6Rpns5Ovz1zwpU/bZDwR2Mx+ARDv/DFPH3wJ4J+KJ1XLzEGn9+DLujAkSjrfb1OTNUK2723QOAPYX0R3AkAZwrxkUUok5+gC5h8nMk1mur8Aw1EdYmudZJDv/IU3khYlLyokosCu00nfBzy5HdM/oIdIWnkNEQLlGCvfJ1AhAkBcW2+zxKnVPThlXzh8PIkJsOBYAw/LIJfeXa1FvfvEh1zVyI9j7AtX2//8ZmTCL3Cp+JFoBjRVfVTxCvS/VDqtAkBSU/x90zjwVYDTYPUxyyLz9jYLVu3vHavaTRUTmMn4D4qHSmq3WahYOrrOpI80+Cwrf+bc08hKB+DgNBHpnE0E";
+//		System.err.println(publickey.length());
+//		System.err.println(privatekey.length());
+		PublicKey publicKey = RSA.getPublicKey(publickey);
+		//PrivateKey privateKey = RSA.getPrivateKey(privatekey);
+		System.out.println("1");
+//		String sign = sign("1234",privateKey);
+//		System.out.println(sign);
+		System.out.println(verifySign("#TransferSingle#M800029658#20161108105547054321#20161108105547054321#10#ICBC#6212261001064813709#test#B2C#PAYER#true", "RSRECZmnN4f1giR8EnUSaUY9dRf0RAVLWFAoL+IDenMd0QXU9YckvfrS5Xg/EhBPt8W11ee5cqmcIsjAshsV18gF4RcuHint4woMOBiA32tKCE7e4rkjD5/R2x4MRTUv+2eLSyjzOh4nNvFY184WcN7tJdo4tj0o6QVkUJRFqfo=", publicKey));
+//		String tmp = "104AE7ACA503EF4347DEA3EEFB5DB979747815526A0DD54168BB4B7197F776064CD6724542AFBFDA7B4B6F849B6130407E3709C280AF736CAF324D1D52010BD852BBCC1F5B9C668C1533BB747C1258761B80CA74AB0F2BA7E518A8A4BC7F407B531E7B8EFC877385503D4BE888DF5A113B1C6DC27EB94EFA16E112F23046B4ECE87B30EA62463A9CB0D94805A36D6239B9E587F95FF3E8F540132FE5FA590F52FEC9EC4FBB35C2108CA06F1F51AD6680199B51F85641EBDE5A7DC6127ED12237A86B5E025E0648217B7B8426F23348AF47DEA3EEFB5DB979AE85F4D79480DA150EE81C08064A010DBB900498D56FD7B432046000D768C2297CC3DD0AD15040DFD4EFC9FFCD7728984A4FADD66C8023FC0CF3780EA41D4080A8BC59E35FACBC20598B60BD0DE0C5414F0F380AECE38A98707A545C29D0D88E49A080904EF26202871D4BC06A49F1CEA977C5BC4DBB02786892E78AC3851EA233EE8D325757D64204EB1F637D5A609BC38E3BA2442BEFDE4DB0FD720BBC2F44BE9E0451A4425007C3706E9BF85A1F3F498DC6FFDD3EC2126C7F0EC61787ECF427A085AC5E3AD59E7E3C204BE6B0E89B31131043C210BC0947B51CE07CB37714048DDE18516F7D293969D714523D1F8096E59114409341897AB95064FA860C1E97A316D3D6CCADC2B8FA844541C58F457BCFEAFA022DA453BBB3142AF113CDCD125D1DF096E77244B47C150F3EE5BCDE5931C58C38D9C53C2222C08B0EA5C136EA1A4F2E512FF283430901D4F4212E3EA86B5E025E064821D4A1AE4629EEDDAD6000CD2CBAAE5B630712D23618975E838F620A31B788672896CEAF520A39CAEF37986D3F3CB1352DFDB75D2AAEF197D9F0142CF0FDE71082048F6024013895F461EB07B8A4C4897F7C32F38140BC42309D4E41D2F8F8DA277540506387A01118914B7C6D87ED185BC23CCC73C83B58C477579A1ADB3832678F2611BC14D24876";
+//		String s3 = RSA.decodeFromBase64(tmp, publicKey, padding);
+//		System.out.println(s3+"=====s3=====");
+//		System.out.println(s3.length()+"=====s3=====");
+//		String plain = "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567";
+//		System.out.println(plain.getBytes().length);
+//		byte[] encryptByte = RSA.encode(plain, privateKey,padding);
+//		System.err.println(encryptByte.length+"=====encryptByte=====");
+//		byte[] sign = RSA.sign(encryptByte, privateKey);
+//		System.out.println(RSA.verifySign(encryptByte,sign,publicKey));
+//		String s2 = RSA.decode(encryptByte, publicKey,padding);
+//		System.out.println(s2+"=====s2=====");
+//		System.out.println(s2.length()+"=====s2=====");
+//		String encryptString = RSA.encodeToBase64(plain, privateKey, padding);
+//		System.err.println(encryptString.length()+"=====encryptString====="+encryptString);
+		
+		
+	}
+}

+ 69 - 0
src/main/java/com/caimei/utils/payUtil/SettlePostFormUtil.java

@@ -0,0 +1,69 @@
+package com.caimei.utils.payUtil;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONObject;
+import okhttp3.FormBody;
+import okhttp3.OkHttpClient;
+import okhttp3.Request;
+import okhttp3.Response;
+
+import java.io.IOException;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * @author zzj
+ */
+
+
+public class SettlePostFormUtil {
+
+    public static OkHttpClient client = new OkHttpClient.Builder()
+            .connectTimeout(3, TimeUnit.SECONDS)
+            .readTimeout(20, TimeUnit.SECONDS)
+            .build();
+
+    public static <T> T postForm(Map<String, String> params, String url, String sign, Class<T> clazz) {
+        FormBody.Builder builder = new FormBody.Builder();
+        for (Map.Entry<String, String> entry : params.entrySet()) {
+            builder.add(entry.getKey(), entry.getValue());
+        }
+        builder.add("sign", sign);
+
+        Request request = new Request.Builder() // okHttp post
+                .url(url)
+                .post(builder.build())
+                .build();
+
+        Response response = null;
+        try {
+            response = client.newCall(request).execute();
+        } catch (IOException e) {
+            throw new IllegalStateException("请求出错", e);
+        }
+        if (!response.isSuccessful()) {
+            try {
+                System.out.println(response.body().string());
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+            throw new RuntimeException("请求失败了: http response code: " + response.code());
+        }
+
+        okhttp3.ResponseBody body = response.body();
+        String content = null;
+        try {
+            content = body.string();
+        } catch (IOException e) {
+            throw new IllegalStateException("IO异常", e);
+        }
+        JSONObject res = JSON.parseObject(content);
+        //结算response
+        if (!"接收成功".equals(res.getString("rt3_retMsg"))) {
+            System.out.println("结算失败响应------->"+res.toString());
+        }
+        /** rt4_success 为 true,需验签  **/
+        return res.toJavaObject(clazz);
+    }
+
+}

+ 1 - 1
src/main/resources/mapper/CmReceiptOrderRelationMapper.xml

@@ -16,7 +16,7 @@
 		  AND cror.orderID = #{orderId}
 	</select>
 
-	<select id="findByOrderID" resultType="com.caimei.modules.order.entity.CmReceiptOrderRelation">
+	<select id="findByOrderId" resultType="com.caimei.modules.order.entity.CmReceiptOrderRelation">
 		select
 		a.*,
 		b.payType as "payType",

+ 86 - 4
src/main/resources/mapper/NewOrderMapper.xml

@@ -556,13 +556,12 @@
                cop.cmFee,
                p.productCategory                                                  as productCategory,
                p.splitCode,
-               cmp.cmPercent,
-               cmp.organizePercent,
-               cmp.shopPercent
+               cop.cmPercent,
+               cop.organizePercent,
+               cop.shopPercent
         FROM cm_order_product cop
         LEFT JOIN product p ON cop.productID = p.productID
         left join cm_order co on co.orderID = cop.orderID
-        left join cm_mall_product_sku cmp on cop.organizeSkuId = cmp.id
         WHERE cop.shopOrderID = #{shopOrderId}
           AND IF(co.userBeans = 0, 1 = 1, cop.shopid != 998)
         ORDER BY cop.discountPrice DESC
@@ -575,4 +574,87 @@
           AND payStatus = 1
           AND productType = 1
     </select>
+
+    <select id="findPayAmount" resultType="java.lang.Double">
+        SELECT SUM(splitAccount)
+        FROM cm_split_account csa
+        LEFT JOIN cm_receipt_order_relation cror ON csa.shopOrderId = cror.shopOrderId
+        WHERE csa.shopOrderId = #{shopOrderId}
+          AND csa.type = 5
+          AND csa.settleStatus = 0
+          AND csa.productType = 3
+          AND cror.splitStatus = 1
+          AND cror.delflag = 0
+    </select>
+
+    <select id="findListByPayShop" resultType="com.caimei.modules.order.entity.NewOrder">
+        SELECT DISTINCT
+        co.orderId AS orderId,
+        co.orderNo AS orderNo,
+        co.status,
+        co.organizeId AS organizeId,
+        co.orderTotalFee AS orderTotalFee,
+        co.orderTime AS orderTime,
+        co.payTotalFee AS payTotalFee,
+        co.payStatus AS payStatus,
+        co.refundType AS refundType,
+        co.sendOutStatus AS sendOutStatus,
+        co.receiptStatus AS receiptStatus,
+        co.productCount AS productCount,
+        (SELECT IFNULL(sum(cop.shouldPayFee),0) FROM cm_order_product cop WHERE cop.orderId=co.orderId) AS
+        "shouldPayProduct",
+        co.status AS status,
+        co.postageOrderFlag AS postageOrderFlag,
+        c.name AS clubName
+        FROM cm_order co
+        LEFT JOIN cm_shop_order cso ON co.orderID = cso.orderID
+        LEFT JOIN club c ON c.userID = co.userID
+        <where>
+             co.organizeId = #{organizeId}
+            <if test="clubName != null and clubName != ''">
+                AND c.name like concat('%', #{clubName} ,'%')
+            </if>
+            <if test="orderId != null and orderId != ''">
+                AND co.orderId = #{orderId}
+            </if>
+            <if test="orderNo != null and orderNo != ''">
+                AND co.orderNo = #{orderNo}
+            </if>
+            <if test="shopOrderId != null and shopOrderId != ''">
+                AND cso.shopOrderID = #{shopOrderId}
+            </if>
+            <if test="shopOrderNo != null and shopOrderNo != ''">
+                AND cso.shopOrderNo like concat('%', #{shopOrderNo} ,'%')
+            </if>
+            <if test="orderTime != null and orderTime != ''">
+                AND co.orderTime = #{orderTime}
+            </if>
+            <if test="orderStartTime != null and orderStartTime != ''">
+                AND co.orderTime <![CDATA[  >=  ]]> #{orderStartTime}
+            </if>
+            <if test="orderEndTime != null and orderEndTime != ''">
+                AND co.orderTime <![CDATA[   <=  ]]> #{orderEndTime}
+            </if>
+            <if test="receiptStatus != null and receiptStatus != ''">
+                AND co.receiptStatus = #{receiptStatus}
+            </if>
+            <if test="payStatus != null and payStatus != ''">
+                AND co.payStatus = #{payStatus}
+            </if>
+            <if test="refundType != null and refundType != ''">
+                AND
+                <if test="refundType == 0">
+                    co.refundType = 0 or co.refundType is null
+                </if>
+                <if test="refundType == 1">
+                    co.refundType = 1
+                </if>
+                <if test="refundType == 2">
+                    co.refundType = 2
+                </if>
+            </if>
+            AND co.delFlag = 0
+        </where>
+        ORDER BY co.orderId DESC, co.orderTime DESC
+    </select>
 </mapper>

+ 125 - 4
src/main/resources/mapper/NewShopOrderMapper.xml

@@ -41,15 +41,11 @@
 			a.orderStatusFlag  AS orderStatusFlag,
 			a.orderSubmitType AS orderSubmitType,
 			a.orderTime AS orderTime,
-			a.deliveryTimeMills AS deliveryTimeMills,
 			a.presentNum AS presentNum,
 			a.preferential AS preferential,
 			a.outStoreNum AS outStoreNum,
 			IFNULL(a.outStoreTimes, 0) AS outStoreTimes,
-			a.autoReceiveTimeMills AS autoReceiveTimeMills,
-			a.autoOverTimeMills AS autoOverTimeMills,
     		a.receiveGoodsTime AS receiveGoodsTime,
-    		a.totalAddedValueTax AS totalAddedValueTax,
     		a.note AS note,
     		a.payStatus AS payStatus,
     		a.sendOutStatus AS sendOutStatus,
@@ -258,4 +254,129 @@
                  AND cpsr.shopOrderID IS NOT NULL)
           AND paying = 1
     </select>
+
+    <select id="findPayShopOrderList" resultType="com.caimei.modules.order.entity.NewShopOrder">
+        select
+        a.shopOrderID AS shopOrderId,
+        a.orderID AS orderId,
+        a.organizeID AS organizeId,
+        a.shopOrderNo AS shopOrderNo,
+        a.orderNo AS orderNo,
+        a.userID AS userId,
+        a.shopID AS shopId,
+        a.itemCount AS itemCount,
+        a.townID AS townId,
+        a.productAmount AS productAmount,
+        a.accountAmount AS accountAmount,
+        a.totalAmount AS totalAmount,
+        a.payTime AS payTime,
+        a.needPayAmount AS needPayAmount,
+        a.splitCode,
+        a.realPay AS realPay,
+        a.receiptAmount AS receiptAmount,
+        a.receiptStatus as receiptStatus,
+        a.refundAmount AS refundAmount,
+        a.clubID AS clubId,
+        a.spID AS spId,
+        a.canRefundFlag AS canRefundFlag,
+        a.freePostageFee AS freePostageFee,
+        a.brokerage AS brokerage,
+        a.refundsAmount AS refundsAmount,
+        a.orderStatusFlag AS orderStatusFlag,
+        a.orderType AS orderType,
+        a.orderTime AS orderTime,
+        a.presentNum AS presentNum,
+        a.preferential AS preferential,
+        a.receiveGoodsTime AS receiveGoodsTime,
+        a.note AS note,
+        a.payStatus AS payStatus,
+        a.sendOutStatus AS sendOutStatus,
+        a.shopProductAmount AS shopProductAmount,
+        a.shopPostFee AS shopPostFee,
+        a.shouldPayShopAmount AS shouldPayShopAmount,
+        a.payedShopAmount AS payedShopAmount,
+        a.paying AS paying,
+        a.settleStatus AS settleStatus,
+        a.differenceType AS differenceType,
+        co.payTotalFee AS payTotalFee,
+        co.status AS status,
+        co.receiptStatus as orderReceiptStatus,
+        bou.name AS buyer,
+        s.name AS shopName,
+        c.name AS clubName,
+        if(co.freePostFlag = 1,co.freight,co.freePostFlag) as freight,
+        (select
+        IFNULL(sum(associateAmount),0)
+        from cm_receipt_order_relation crpr
+        left join cm_discern_receipt b on crpr.receiptID = b.id
+        where crpr.orderID = a.orderId
+        AND b.receiptStatus = 3
+        AND b.delFlag = 0) as receiptTotalFee
+        from cm_shop_order a
+        left join bp_order_userinfo bou on bou.orderId = a.orderID
+        left join cm_order co on co.orderID = a.orderID
+        left join shop s on s.shopID = a.shopID
+        LEFT JOIN club c ON c.userID = a.userID
+        LEFT JOIN cm_receipt_order_relation cror ON cror.orderId = co.orderId
+        LEFT JOIN cm_discern_receipt cdr ON cror.receiptID = cdr.id
+        LEFT JOIN cm_split_account csa on csa.shopOrderId = a.shopOrderID
+        <where>
+            <if test="orderStartTime != null and orderStartTime != ''">
+                AND (a.orderTime &gt; #{startTime} OR a.orderTime = #{startTime})
+            </if>
+            <if test="orderEndTime != null and orderEndTime != ''">
+                AND (a.orderTime &lt; #{endTime} OR a.orderTime = #{endTime})
+            </if>
+            <if test="orderId != null and orderId != ''">
+                AND a.orderID = #{orderId}
+            </if>
+            <if test="orderNo != null and orderNo != ''">
+                AND a.orderNo like concat('%', #{orderNo} ,'%')
+            </if>
+            <if test="shopName != null and shopName != ''">
+                AND s.name like concat('%', #{shopName} ,'%')
+            </if>
+            <if test="clubName != null and clubName != ''">
+                AND c.name like concat('%', #{clubName} ,'%')
+            </if>
+            <if test="shopOrderId != null and shopOrderId != ''">
+                AND a.shopOrderID = #{shopOrderId}
+            </if>
+            <if test="shopOrderNo != null and shopOrderNo != ''">
+                AND a.shopOrderNo like concat('%', #{shopOrderNo} ,'%')
+            </if>
+            <if test="listType == 3">
+                AND cdr.payWay = 1
+                AND cdr.receiptDate <![CDATA[ <= ]]> NOW()
+                AND cror.relationType = 2
+                AND cror.delFlag = 0
+                AND cror.mbOrderId IS NOT NULL
+                AND cror.splitStatus = 0
+                AND a.receiptStatus=3
+            </if>
+            <if test="listType == 2">
+                AND co.refundType != 2
+                AND co.receiptStatus = 3
+                AND cdr.payWay = 1
+                AND cror.relationType = 2
+                AND a.settleStatus in (1,2)
+                AND csa.settleStatus = 0
+                AND cror.delFlag = 0
+                AND cror.mbOrderId IS NOT NULL
+                AND cror.splitStatus = 1
+            </if>
+            AND co.organizeID = #{organizeId}
+            and (co.confirmFlag = '1' or co.confirmFlag = '2')
+            and a.payStatus != 3 and co.status NOT IN (6,7)
+            and co.delFlag = 0
+            and a.delFlag = 0
+            and a.shopID != 998
+            and co.orderID not in (
+            SELECT orderID FROM cm_order_product WHERE productID IN
+            (6060, 6061, 6062, 6063, 6064, 6065, 6066, 6067, 6068, 6069) GROUP BY orderID
+            )
+        </where>
+        group by a.shopOrderID
+        ORDER BY a.shopOrderID DESC
+    </select>
 </mapper>

+ 124 - 12
src/main/resources/mapper/PayShopDao.xml

@@ -12,9 +12,9 @@
                                 bankAccount,
                                 bankName,
                                 type,
+                                cmType,
                                 totalAmount,
-                                balancePayFee,
-                                transferPayFee,
+                                payCmAmount,
                                 payType,
                                 applicant,
                                 applyTime,
@@ -29,9 +29,9 @@
                 #{bankAccount},
                 #{bankName},
                 #{type},
+                #{cmType},
                 #{totalAmount},
-                #{balancePayFee},
-                #{transferPayFee},
+                #{payCmTotalAmount},
                 #{payType},
                 #{applicant},
                 #{applyTime},
@@ -48,6 +48,10 @@
         values (#{shopId}, #{shopOrderId}, #{shopOrderNo}, #{payAmount}, #{payCmAmount}, 1, #{payType},
                 #{payShopId}, #{status}, #{payTime})
     </insert>
+    <insert id="insertSettleRecord">
+        INSERT INTO cm_settle_record(settleamount, settletype, shoporderid, splitcode, settletime)
+        VALUES (#{settleAmount}, #{settleType}, #{shopOrderId}, #{splitCode}, now())
+    </insert>
 
     <update id="updatePayRecord">
         UPDATE cm_pay_shop_record
@@ -124,6 +128,19 @@
         where payShopID = #{id}
     </update>
 
+    <update id="updateSettleStatus">
+        update cm_split_account
+        set settleStatus = 1
+        where shopOrderId = #{shopOrderId}
+          and productType = #{productType}
+    </update>
+
+    <update id="updateShopOrderSettleStatus">
+        update cm_shop_order
+        set settleStatus = #{settleStatus}
+        where shopOrderId = #{shopOrderId}
+    </update>
+
     <select id="findPayShops" resultType="com.caimei.modules.order.entity.OrderPayShop">
         SELECT
         a.id AS "payShopId",
@@ -141,7 +158,7 @@
         left join cm_mall_admin_user u2 on u2.id = a.reviewer
         left join shop s on s.shopID = a.shopID
         <where>
-            <if test="id != null and id != ''">
+            <if test="payShopId != null and payShopId != ''">
                 and a.id = #{payShopId}
             </if>
             <if test="shopName != null and shopName != ''">
@@ -234,7 +251,8 @@
                         a.payedShopAmount                               AS payedShopAmount,
                         co.payTotalFee                                  AS payTotalFee,
                         bou.name                                        AS buyer,
-                        s.name                                          AS shopName
+                        s.name                                          AS shopName,
+                        co.receiptStatus                                AS orderReceiptStatus
         FROM cm_shop_order a
                  LEFT JOIN cm_pay_shop_record cpsr ON a.shopOrderID = cpsr.shopOrderID
                  LEFT JOIN bp_order_userinfo bou ON bou.orderId = a.orderID
@@ -258,7 +276,7 @@
                cop.totalFee             AS totalFee,
                cop.costPrice            AS costPrice,
                cop.productType          AS productType,
-               cpo.touchPrice           AS touchPrice,
+               cop.price,
                (SELECT SUM(crpp.actualReturnedNum) + SUM(crpp.actualCancelNum)
                 FROM cm_returned_purchase_product crpp
                          LEFT JOIN cm_returned_purchase rp ON rp.id = crpp.returnedID
@@ -266,11 +284,10 @@
                   AND rp.status = '2'
                   AND rp.delFlag = '0') AS returnedNum
         from cm_order_product cop
-                 left join cm_sku cs on cop.skuId = cs.skuId
-                 left join cm_promotions_order cpo on (cop.orderPromotionsId = cpo.id and cpo.mode = 1)
-                 left join product p on p.productID = cop.productID
-                 left join cm_order co on co.orderID = cop.orderID
-                 left join user u on u.userID = co.userID
+        left join cm_sku cs on cop.skuId = cs.skuId
+        left join product p on p.productID = cop.productID
+        left join cm_order co on co.orderID = cop.orderID
+        left join user u on u.userID = co.userID
         where cop.shopOrderID = #{shopOrderId}
     </select>
 
@@ -298,4 +315,99 @@
                  LEFT JOIN cm_offline_collection f ON a.payType = f.type
         WHERE a.payShopID = #{id}
     </select>
+
+    <select id="findShopOrderNosByPayShop" resultType="java.lang.String">
+        SELECT distinct CONCAT(cso.shopOrderNo, '(', cso.shopOrderID, ')') AS result
+        FROM cm_shop_order cso
+                 left join cm_pay_shop_record cpsr on cso.shopOrderID = cpsr.shopOrderID
+        WHERE cpsr.payShopID = #{id}
+          and cso.shopId != 998
+    </select>
+
+    <select id="findOrderNos" resultType="java.lang.String">
+        SELECT distinct CONCAT(co.orderNo, '(', co.orderID, ')') AS result
+        FROM cm_pay_shop_record cpsr
+                 left join cm_shop_order cso on cpsr.shopOrderID = cso.shopOrderID
+                 left join cm_order co on cso.orderID = co.orderID
+        WHERE cpsr.payShopID = #{id}
+          and cso.shopId != 998
+    </select>
+
+    <select id="findShouldPayShopAmount" resultType="java.lang.Double">
+        select shouldPayShopAmount
+        from cm_shop_order
+        where shopOrderID = #{shopOrderId}
+    </select>
+
+    <select id="findSettleSum" resultType="java.lang.Double">
+        SELECT IFNULL(SUM(settleAmount), 0)
+        FROM cm_settle_record
+        WHERE settleType = 1
+          AND shopOrderId = #{shopOrderId}
+    </select>
+
+    <select id="findOrderRelations" resultType="com.caimei.modules.order.entity.CmReceiptOrderRelation">
+        select payType, associateAmount
+        from cm_receipt_order_relation cror
+                 left join cm_discern_receipt cdr on cror.receiptID = cdr.id
+        where cror.shopOrderId = #{shopOrderId}
+          and cror.delFlag = 0
+          and cdr.delFlag = 0
+    </select>
+
+    <select id="findTotalAmount" resultType="java.lang.Double">
+        select totalAmount
+        from cm_shop_order
+        where shopOrderId = #{shopOrderId}
+    </select>
+
+    <select id="findOrderProductPrice" resultType="com.caimei.modules.order.entity.NewOrderProduct">
+        select cop.price, cop.num, cop.shopPercent, cop.organizePercent, cop.cmPercent, cop.totalAmount
+        from cm_order_product cop
+        where shopOrderId = #{shopOrderId}
+    </select>
+
+    <select id="findSplitCode" resultType="java.lang.String">
+        select splitCode
+        from cm_shop_order
+        where shopOrderId = #{shopOrderId}
+    </select>
+
+    <select id="findPayShopOrderByShopOrderIds" resultType="com.caimei.modules.order.entity.NewShopOrder">
+        SELECT DISTINCT
+        a.shopOrderID AS shopOrderId,
+        a.orderID AS orderId,
+        a.organizeID AS organizeId,
+        a.shopOrderNo AS shopOrderNo,
+        a.orderNo AS orderNo,
+        a.totalAmount,
+        # todo
+        ROUND(a.totalAmount * 0.17, 2) AS brokerage,
+        ROUND(a.totalAmount * 0.03, 2) AS shouldPayCmAmount,
+        a.payCmAmount AS payCmAmount,
+        ROUND(a.totalAmount * 0.03, 2) - a.payCmAmount AS waitPayCmAmount,
+        a.receiptStatus AS receiptStatus,
+        a.orderTime AS orderTime,
+        a.payStatus AS payStatus,
+        a.shopProductAmount AS shopProductAmount,
+        a.shopPostFee AS shopPostFee,
+        ROUND(a.totalAmount * 0.8, 2) AS shouldPayShopAmount,
+        ROUND(a.totalAmount * 0.8, 2) - ifnull(payedShopAmount,0) AS waitPayShop,
+        a.payedShopAmount AS payedShopAmount,
+        co.payTotalFee AS payTotalFee,
+        bou.name AS buyer,
+        s.name AS shopName,
+        s.shopId,
+        co.receiptStatus AS orderReceiptStatus
+        FROM cm_shop_order a
+        LEFT JOIN cm_pay_shop_record cpsr ON a.shopOrderID = cpsr.shopOrderID
+        LEFT JOIN bp_order_userinfo bou ON bou.orderId = a.orderID
+        LEFT JOIN cm_order co ON co.orderID = a.orderID
+        LEFT JOIN shop s ON s.shopID = a.shopID
+        LEFT JOIN club c ON c.userID = a.userID
+        WHERE a.shopOrderId in
+        <foreach collection="shopOrderIds" open="(" close=")" item="oId" separator=",">
+            #{oId}
+        </foreach>
+    </select>
 </mapper>