chenjiahe
2023-05-10 01fbcb62fbd9ac4d72d1bed3d87da5a6c73af698
phi_platform_user/src/main/java/com/hx/phip/service/order/impl/OrderRefundServiceImpl.java
@@ -12,7 +12,6 @@
import com.hx.phiappt.model.*;
import com.hx.phiappt.model.activity.ActivityAction;
import com.hx.phiappt.model.activity.ActivityRule;
import com.hx.phiappt.model.consume.ConsumePay;
import com.hx.phiappt.model.coupon.CouponOrderDiscountLog;
import com.hx.phiappt.model.order.*;
import com.hx.phiappt.model.performance.PerformanceInfo;
@@ -29,14 +28,18 @@
import com.hx.phip.service.refund.RefundRecordMethodService;
import com.hx.phip.service.refund.RefundRecordService;
import com.hx.phip.tool.CreateNo;
import com.hx.phip.tool.order.PaymentCountTool;
import com.hx.phip.util.api.*;
import com.hx.phip.tool.refund.OrderRefundCancelTool;
import com.hx.phip.tool.refund.PartialRefundUtil;
import com.hx.phip.tool.refund.PaymentCountTool;
import com.hx.phip.util.api.ApiOrderUtil;
import com.hx.phip.util.api.SendNoticeUtil;
import com.hx.phip.util.api.UserLevelUtil;
import com.hx.phip.util.api.UserMoneyUtil;
import com.hx.phip.vo.order.payment.PayMethodVo;
import com.hx.phip.vo.order.refund.DistributionRedundMethodVo;
import com.hx.phip.vo.order.refund.DistributionRedundVo;
import com.hx.resultTool.Result;
import com.hx.util.StringUtils;
import com.hz.crm.dto.OrderStatusDto;
import com.hz.crm.dto.order.refund.RefundAmountModelDto;
import com.hz.crm.dto.order.refund.RefundDto;
import com.hz.crm.dto.order.refund.RefundReturnDto;
@@ -47,6 +50,7 @@
import com.hz.his.dto.marketing.RefundProjectDto;
import com.hz.his.dto.order.*;
import com.hz.his.feign.service.marketing.MOrderService;
import com.hz.his.vo.order.refund.RefundCancelVo;
import com.platform.entity.ThirtApplication;
import com.platform.exception.PlatTipsException;
import com.platform.resultTool.PlatformCode;
@@ -78,10 +82,7 @@
    @Resource
    private OrderItemMapper orderItemMapper;
    @Resource
    private ConsumePayMapper consumePayMapper;
    @Resource
    private UserProjectItemMapper userProjectItemMapper;
    private RefundRecordMapper refundRecordMapper;
    @Resource
    private OrderItemSonMapper orderItemSonMapper;
    @Resource
@@ -134,6 +135,7 @@
     */
    @Override
    public List<Map<String, Object>> refundDetails(OrdersTotal ordersTotal) {
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> sqlMap = new HashMap<>();
        sqlSentence.setM(sqlMap);
@@ -141,7 +143,7 @@
        sqlMap.put("isDel", BaseEntity.NO);
        sqlMap.put("orderId", ordersTotal.getId());
        //一级子订单
        sqlSentence.sqlSentence("SELECT * FROM order_item WHERE  orderId = #{m.orderId} and  isDel = #{m.isDel}",sqlMap);
        sqlSentence.sqlSentence("SELECT * FROM order_item WHERE  orderId = #{m.orderId} AND isDel = #{m.isDel}",sqlMap);
        List<OrderItem> orderItemList = orderItemMapper.selectList(sqlSentence);
        List<Map<String, Object>> orderItems = new ArrayList<>();
@@ -177,14 +179,8 @@
     * 处理一级是项目的
     */
    public void handleOrderItemIsProject(List<Map<String, Object>> orderItems, OrderItem orderItem) {
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> sqlMap = new HashMap<>();
        //获取用户项目
        sqlMap.put("commonId",orderItem.getId());
        sqlSentence.sqlSentence("SELECT * FROM user_project_item upi WHERE upi.isDel = 0 AND upi.commonId = #{m.commonId} AND upi.isTransfer = 0",sqlMap);
        UserProjectItem userProjectItem = userProjectItemMapper.selectOne(sqlSentence);
        UserProjectItem userProjectItem = PartialRefundUtil.getUserProject(orderItem.getId(),commonService);
        if(userProjectItem == null){
            throw new TipsException("用户项目获取失败!");
        }
@@ -241,36 +237,20 @@
        Map<String,Object> sqlMap = new HashMap<>();
        //获取用户卡项
        List<UserCard> userCardList = getRefundCard(orderItem.getId());
        List<UserCard> userCardList = PartialRefundUtil.getRefundCard(orderItem.getId(),UserProjectConstants.EFF_STATUS_YES,commonService);
        //信息封装
        Map<String,Object> itemData = itemRefandDataPackage(orderItem,null,null,userCardList);
        //获取卡项的详细条目
        sqlMap.put("commonId",orderItem.getCommonId());
        sqlSentence.sqlSentence(" SELECT groupName,shareMoney FROM card_equity WHERE cardItemId = #{m.commonId} ",sqlMap);
        List<Map<String, Object>> cardEquitys = cardEquityMapper.selectListMap(sqlSentence);
        itemData.put("list", cardEquitys);
        orderItems.add(itemData);
    }
    /**获取可退款的用户卡项
     * @param sourceId 订单子单标识
     * @return 可退款的用户卡项
     */
    public List<UserCard> getRefundCard(String sourceId){
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> sqlMap = new HashMap<>();
        //获取用户卡项
        sqlMap.put("sourceId",sourceId);
        sqlMap.put("status",UserCard.TYPE_NO_USED);
        sqlMap.put("effectiveStatus",UserProjectConstants.EFF_STATUS_YES);
        sqlSentence.sqlSentence("SELECT * FROM user_card WHERE isDel = 0 AND sourceId = #{m.sourceId} AND status = #{m.status}" +
                " AND effectiveStatus = #{m.effectiveStatus}",sqlMap);
        return commonService.selectList(UserCardMapper.class,sqlSentence);
    }
    /**
     * 处理一级是促销的
@@ -351,15 +331,11 @@
     * 处理二级是项目的
     */
    public void handleOrderItemSonIsProject(List<Map<String, Object>> promotionList, OrderItemSon orderItemSon) {
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> sqlMap = new HashMap<>();
        //获取用户项目
        sqlMap.put("commonId",orderItemSon.getId());
        sqlSentence.sqlSentence("SELECT * FROM user_project_item upi WHERE upi.isDel = 0 AND upi.commonId = #{m.commonId} AND upi.isTransfer = 0",sqlMap);
        UserProjectItem userProjectItem = userProjectItemMapper.selectOne(sqlSentence);
        UserProjectItem userProjectItem = PartialRefundUtil.getUserProject(orderItemSon.getId(),commonService);
        if(userProjectItem == null){
            throw new TipsException("用户项目获取失败!");
            throw new TipsException("用户项目获取失败[24]!");
        }
        Map<String,Object> itemData = itemRefandDataPackage(null,orderItemSon,userProjectItem,null);
@@ -375,18 +351,13 @@
    }
    /**
     * 退款选择退款数量组装金额信息
     * 退款选择退款数量组装金额信息,退款里面这个非常重要
     * @param orderRefundDto 退款数量信息
     * @return 退款金额信息
     */
    @Override
    public OrderRefundDto nextStep(OrdersTotal ordersTotal,OrderRefundDto orderRefundDto) {
        logger.info("退款选择退款数量组装金额信息入参:{}", JSON.toJSONString(orderRefundDto));
        //返回集合
        OrderRefundDto returnRefund=new OrderRefundDto();
        returnRefund.setOrderId(ordersTotal.getId());
        //子单退款
        List<OrderItemRefundDto> refundList = orderRefundDto.getRefundList();
@@ -397,7 +368,10 @@
        if (OrderTotalConstants.TYPE_RECHARGE.equals(ordersTotal.getType())) {
            ///////充值订单退款
            refundPayMethods = rechargeRefundWay(ordersTotal,totalAmount);
            refundPayMethods = rechargeRefundWay(ordersTotal);
            for (OrderPayMethodDto orderPayMethodDto : refundPayMethods) {
                totalAmount = totalAmount.add(orderPayMethodDto.getPayTotal()).setScale(2,RoundingMode.HALF_UP);
            }
        }else{
            //////其他订单类型
            //整合支付方式退款金额
@@ -418,6 +392,7 @@
                if(!orderItem.getOrderId().equals(ordersTotal.getId())){
                    throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到退款项[012]");
                }
                //判断这个项目能不能显示处理
                switch (orderItem.getType()) {
                    case OrderItemConstants.TYPE_PROJECT:
@@ -464,47 +439,35 @@
        }
        //支付方式
        returnRefund.setPayMethodList(refundPayMethods);
        //优惠卷
        orderRefundDto.setPayMethodList(refundPayMethods);
        //可退总金额
        orderRefundDto.setTotalAmount(totalAmount);
        //优惠券
        List<OrderCouponRefunDto> couponList = nextStepIsCoupon(ordersTotal.getId());
        returnRefund.setPayCouponList(couponList);
        orderRefundDto.setPayCouponList(couponList);
        returnRefund.setRefundList(refundList);
        returnRefund.setTotalAmount(totalAmount);
        return returnRefund;
        return orderRefundDto;
    }
    /**获取充值单的退款方式金额*/
    public List<OrderPayMethodDto> rechargeRefundWay(OrdersTotal ordersTotal,BigDecimal totalAmount){
    public List<OrderPayMethodDto> rechargeRefundWay(OrdersTotal ordersTotal){
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> sqlMap = new HashMap<>();
        sqlSentence.setM(sqlMap);
        sqlMap.put("isDel", BaseEntity.NO);
        sqlMap.put("orderId", ordersTotal.getId());
        //获取订单的支付记录
        sqlSentence.sqlSentence("SELECT numberNo,ANY_VALUE(name) AS name,ROUND(SUM(actualTotal-refundTotal),2) AS pTotal,ROUND(SUM(actualTotal),2),ROUND(SUM(refundTotal),2)" +
                " FROM  consume_pay WHERE orderId = #{m.orderId} AND isDel = #{m.isDel} GROUP BY numberNo ORDER BY createTime DESC",sqlMap);
        List<ConsumePay> consumePayList = consumePayMapper.selectList(sqlSentence);
        //获取总支付方式
        List<PayMethodVo> payMethodVoList = refundMapper.getConsumePayGroupByNumberNo(ordersTotal.getId());
        List<OrderPayMethodDto> consumeList = new ArrayList<>();
        OrderPayMethodDto orderPayMethodDto;
        //充值订单只能全退
        for (ConsumePay consumePay:consumePayList) {
        for (PayMethodVo payMethodVo:payMethodVoList) {
            //支付方式可退金额
            orderPayMethodDto=new OrderPayMethodDto();
            orderPayMethodDto.setPayMethodNo(consumePay.getNumberNo());
            orderPayMethodDto.setRefundNumberNo(consumePay.getNumberNo());
            orderPayMethodDto.setPayMethodName(consumePay.getName());
            orderPayMethodDto.setRefundNumberName(consumePay.getName());
            orderPayMethodDto.setPayTotal(consumePay.getpTotal());
            orderPayMethodDto.setPayMethodNo(payMethodVo.getNumberNo());
            orderPayMethodDto.setPayMethodName(payMethodVo.getName());
            orderPayMethodDto.setRefundNumberNo(payMethodVo.getNumberNo());
            orderPayMethodDto.setRefundNumberName(payMethodVo.getName());
            orderPayMethodDto.setPayTotal(payMethodVo.getSurplusTotal());
            orderPayMethodDto.setMoney(orderPayMethodDto.getPayTotal());
            consumeList.add(orderPayMethodDto);
            //退款总金额
            totalAmount = totalAmount.add(orderPayMethodDto.getMoney()).setScale(2,RoundingMode.HALF_UP);
        }
        return consumeList;
    }
@@ -518,7 +481,8 @@
        sqlMap.put("isDel", BaseEntity.NO);
        sqlMap.put("orderId", orderId);
        sqlSentence.sqlSentence("SELECT id,title FROM coupon_order_discount_log WHERE orderId=#{m.orderId} AND isDel=  #{m.isDel} ",sqlMap);
        sqlMap.put("status", BaseEntity.NO);
        sqlSentence.sqlSentence("SELECT id,title FROM coupon_order_discount_log WHERE orderId=#{m.orderId} AND status = #{m.status} AND isDel=  #{m.isDel} ",sqlMap);
        List<CouponOrderDiscountLog> couponOrderDiscountLogs = couponOrderDiscountLogMapper.selectList(sqlSentence);
        //拼接返回参数
        List<OrderCouponRefunDto> consumeList=new ArrayList<>();
@@ -559,9 +523,7 @@
        if(OrderItemConstants.TYPE_PROJECT.equals(orderItem.getType())){
            //////项目
            sqlMap.put("commonId",orderItem.getId());
            sqlSentence.sqlSentence("SELECT * FROM user_project_item upi WHERE upi.isDel = 0 AND upi.commonId = #{m.commonId} AND upi.isTransfer = 0",sqlMap);
            UserProjectItem userProjectItem = userProjectItemMapper.selectOne(sqlSentence);
            UserProjectItem userProjectItem = PartialRefundUtil.getUserProject(orderItem.getId(),commonService);
            if(userProjectItem == null){
                //buyNum = orderItem.getUsedTotal();
                //surplusNum = orderItem.getUsedTotal() - orderItem.getHasReNum();
@@ -577,20 +539,25 @@
        }else if(OrderItemConstants.TYPE_CARD.equals(orderItem.getType())){
            ///////卡项
            //获取可退款的卡项次数
            List<UserCard> userCardList = getRefundCard(orderItem.getId());
            List<UserCard> userCardList = PartialRefundUtil.getRefundCard(orderItem.getId(),UserProjectConstants.EFF_STATUS_YES,commonService);
            buyNum = orderItem.getBuyNum();
            surplusNum = userCardList.size();
            if(orderItemRefundDto.getRefundNum() > surplusNum){
                throw new TipsException("退款数量与可退数量不符!");
            }
            //替换成子单的剩余数量
            surplusNum = orderItem.getBuyNum() - orderItem.getHasReNum();
        }else{
            buyNum = orderItem.getBuyNum();
            //替换成子单的剩余数量
            surplusNum = orderItem.getBuyNum() - orderItem.getHasReNum();
        }
        if(orderItemRefundDto.getRefundNum() > surplusNum){
            throw new TipsException("退款数量与可退数量不符!");
        }
        //获取该子单的支付方式,相同的支付方式算和返回
        List<PayMethodVo> payMethodVoList = refundMapper.selectConsumePayOneList(orderItem.getId());
        //获取该子单的支付方式,相同的支付方式求和返回
        List<PayMethodVo> payMethodVoList = refundMapper.getConsumePayOneGroupByNumberNo(orderItem.getId());
        //获取已退款的金额
        sqlMap.clear();
@@ -602,8 +569,9 @@
        RefundRecordItem refundRecordItem = commonService.selectOne(RefundRecordItemMapper.class,sqlSentence);
        //计算退款方式金额
        DistributionRedundVo distributionRedundVo = PaymentCountTool.countMakeWay(orderItem.getActualTotal(),refundRecordItem==null?BigDecimal.ZERO:refundRecordItem.getOccupyRefundTotal()
                ,buyNum,surplusNum,orderItemRefundDto.getRefundNum(),payMethodVoList);
        DistributionRedundVo distributionRedundVo = PaymentCountTool.countMakeWay(orderItem.getId(),orderItem.getActualTotal(),refundRecordItem==null?BigDecimal.ZERO:refundRecordItem.getOccupyRefundTotal()
                ,buyNum,surplusNum,null,orderItemRefundDto.getRefundNum(),payMethodVoList,commonService);
        distributionRedundVo.setGoodsType(orderItem.getType());
        distributionRedundVo.setGoodsName(orderItem.getGoodsName());
@@ -625,6 +593,11 @@
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"退款数量不能小于1");
        }
        ////算数量
        //总数量
        Integer buyNum;
        //剩余数量
        Integer surplusNum;
        //获取用户项目
        SqlSentence sqlSentence = new SqlSentence();
@@ -633,37 +606,28 @@
        UserProjectItem userProjectItem = null;
        if(OrderItemConstants.TYPE_PROJECT.equals(goodsType)){
            //获取用户项目
            sqlMap.put("commonId",orderItemSon.getId());
            sqlSentence.sqlSentence("SELECT * FROM user_project_item upi WHERE upi.isDel = 0 AND upi.commonId = #{m.commonId} AND upi.isTransfer = 0",sqlMap);
            userProjectItem = userProjectItemMapper.selectOne(sqlSentence);
            userProjectItem = PartialRefundUtil.getUserProject(orderItemSon.getId(),commonService);
            if(userProjectItem == null){
                throw new TipsException("用户项目获取失败!");
            }
        }
        ////算数量
        //总数量
        Integer buyNum;
        //剩余数量
        Integer surplusNum;
        if(userProjectItem != null){
            buyNum = userProjectItem.getUsedTotal();
            surplusNum = userProjectItem.getNotUsedNum();
        }else{
            if(OrderItemConstants.TYPE_PROJECT.equals(orderItemSon.getType())){
                buyNum = orderItemSon.getUsedTotal();
                surplusNum = orderItemSon.getUsedTotal() - orderItemSon.getHasReNum();
            }else{
                buyNum = orderItemSon.getBuyNum();
                surplusNum = orderItemSon.getBuyNum() - orderItemSon.getHasReNum();
            if(orderItemSourceRefundDto.getRefundNum() > surplusNum){
                throw new TipsException("退款数量与可退数量不符!");
            }
            //替换成子单
            surplusNum = orderItemSon.getUsedTotal() - orderItemSon.getHasReNum();
        }else{
            buyNum = orderItemSon.getBuyNum();
            surplusNum = orderItemSon.getBuyNum() - orderItemSon.getHasReNum();
        }
        if(orderItemSourceRefundDto.getRefundNum() > surplusNum){
            throw new TipsException("退款数量与可退数量不符!");
        }
        //获取该子单的支付方式,相同的支付方式算和返回
        List<PayMethodVo> payMethodVoList = refundMapper.selectConsumePayTwoList(orderItemSon.getId());
        List<PayMethodVo> payMethodVoList = refundMapper.getConsumePayTwoGroupByNumberNo(orderItemSon.getId());
        //获取已退款的金额
        sqlMap.clear();
@@ -674,8 +638,8 @@
                " WHERE rris.isDel = 0 AND rris.orderItemSonId = #{m.orderItemSonId}",sqlMap);
        RefundRecordItemSource refundRecordItemSource = commonService.selectOne(RefundRecordItemSourceMapper.class,sqlSentence);
        //计算退款方式金额
        DistributionRedundVo distributionRedundVo = PaymentCountTool.countMakeWay(orderItemSon.getActualTotal(),refundRecordItemSource==null?BigDecimal.ZERO:refundRecordItemSource.getOccupyRefundTotal()
                ,buyNum,surplusNum,orderItemSourceRefundDto.getRefundNum(),payMethodVoList);
        DistributionRedundVo distributionRedundVo = PaymentCountTool.countMakeWay(orderItemSon.getId(),orderItemSon.getActualTotal(),refundRecordItemSource==null?BigDecimal.ZERO:refundRecordItemSource.getOccupyRefundTotal()
                ,buyNum,surplusNum,null,orderItemSourceRefundDto.getRefundNum(),payMethodVoList,commonService);
        distributionRedundVo.setGoodsType(orderItemSon.getType());
        distributionRedundVo.setGoodsName(orderItemSon.getGoodsName());
        return distributionRedundVo;
@@ -788,9 +752,6 @@
                OrderTotalConstants.STATUS_REFUND_PART != ordersTotal.getRefundStatus()){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"订单退款状态不正确!");
        }
        if (OrderTotalConstants.TYPE_RECHARGE.equals(ordersTotal.getType())) {
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"充值订单不支持部分退款!");
        }
        //先优先改成申请退款中
        SqlSentence sqlSentence = new SqlSentence();
@@ -804,7 +765,7 @@
            throw new TipsException("操作失败,当前订单退款状态不能再次发起退款!");
        }
        //校验参数,和获取系统参数
        //校验参数和获取系统参数,非常重要
        orderRefundDto = parameterVerification(ordersTotal,orderRefundDto);
        return handlePartRefund(ordersTotal,orderRefundDto,thirtApplication);
@@ -815,12 +776,16 @@
     */
    public OrderRefundDto  parameterVerification(OrdersTotal ordersTotal,OrderRefundDto orderRefundDto){
        if(orderRefundDto.getRefundPayMethod() == null){
            throw new TipsException("退款方式结构不能空");
        }
        //怕被获取到项目信息收到被改了项目价格,重新去获取一下项目价格
        orderRefundDto =  nextStep(ordersTotal,orderRefundDto);
        //支付格式,key值:支付编号-是否现金-是否划扣
        //可退款支付格式,key值:支付编号
        Map<String,OrderPayMethodDto> orderPayMethodDtoMap = new HashMap<>();
        for (OrderPayMethodDto orderPayMethodDto : orderRefundDto.getRefundPayMethod()) {
        for (OrderPayMethodDto orderPayMethodDto : orderRefundDto.getPayMethodList()) {
            orderPayMethodDtoMap.put(orderPayMethodDto.getPayMethodNo(),orderPayMethodDto);
        }
@@ -830,32 +795,43 @@
        //校验金额
        OrderPayMethodDto payMethodDto;
        //遍历系统获取到的可退款方式
        for (OrderPayMethodDto orderPayMethodDto : orderRefundDto.getPayMethodList()) {
        OrderPayMethodDto orderPayMethodDto;
        for (int i = orderRefundDto.getRefundPayMethod().size()-1; i>=0 ;i--) {
            orderPayMethodDto = orderRefundDto.getRefundPayMethod().get(i);
            //获取是传值过来的金额数据
            payMethodDto = orderPayMethodDtoMap.get(orderPayMethodDto.getPayMethodNo());
            if(payMethodDto == null){
                throw new TipsException("未找到["+orderPayMethodDto.getPayMethodName()+"]支付方式!");
            }
            if(payMethodDto.getMoney() == null){
            //判断退款方式
            PaymentMethod refundMethod = paymentMethodService.selectNumberNoUncheckUp(orderPayMethodDto.getRefundNumberNo());
            if(refundMethod==null){
                throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到该转换方式:"+orderPayMethodDto.getRefundNumberName()+"["+orderPayMethodDto.getRefundNumberNo()+"]");
            }
            if(orderPayMethodDto.getMoney() == null){
                throw new TipsException("["+orderPayMethodDto.getPayMethodName()+"]退款金额必填!");
            }
            if(payMethodDto.getMoney().compareTo(BigDecimal.ZERO) < 0){
            if(orderPayMethodDto.getMoney().compareTo(BigDecimal.ZERO) < 0){
                throw new TipsException("["+orderPayMethodDto.getPayMethodName()+"]退款金额错误!");
            }
            if (payMethodDto.getMoney().compareTo(orderPayMethodDto.getPayTotal()) > 0){
            if (orderPayMethodDto.getMoney().compareTo(payMethodDto.getPayTotal()) > 0){
                throw new TipsException("当前退款方式["+orderPayMethodDto.getPayMethodName()+"]金额超出可退金额!");
            }
            payMethodDto.setPayMethodName(orderPayMethodDto.getPayMethodName());
            payMethodDto.setPayMethodNo(orderPayMethodDto.getRefundNumberNo());
            payMethodDto.setPayTotal(orderPayMethodDto.getPayTotal());
            //退款金额是0元,去掉退款方式
            if(orderPayMethodDto.getMoney().compareTo(BigDecimal.ZERO) == 0){
                orderRefundDto.getRefundPayMethod().remove(i);
            }
            orderPayMethodDto.setPayMethodName(payMethodDto.getPayMethodName());
            orderPayMethodDto.setPayMethodNo(payMethodDto.getPayMethodNo());
            orderPayMethodDto.setPayTotal(payMethodDto.getPayTotal());
            refundTotal = refundTotal.add(payMethodDto.getMoney()).setScale(2,RoundingMode.HALF_UP);
            refundTotal = refundTotal.add(orderPayMethodDto.getMoney()).setScale(2,RoundingMode.HALF_UP);
        }
        orderRefundDto.setRefundTotal(refundTotal);
        if(orderRefundDto.getRefundTotal().compareTo(orderRefundDto.getTotalAmount()) > 0){
            throw new TipsException("退款金额不能大于可退金额!");
            throw new TipsException("退款金额不能大于可退金额[004]!");
        }
        return orderRefundDto;
@@ -880,7 +856,7 @@
        //退款总记录
        orderNodeBuilder.append("-处理退款总记录");
        //保存退款信息,不是真正的退款
        //保存退款信息,不是真正的退款,提前扣减用户资金
        RefundRecord refundRecord = insertRefundInfo(orderRefundDto,ordersTotal,orderNodeBuilder,thirtApplication);
        //判断已支付订单是否需要营销助手审批
@@ -888,25 +864,7 @@
        CancelOrder cancelOrder = handleCancelOrder(ordersTotal,orderRefundDto);
        if (orderRefundDto.getIsApproval().equals(BaseEntity.YES)){
            //调用审批成功
            //判断是否是充值订单,是的话先冻结储值金,就是扣掉,审批通过就不处理储值金了,不通过还原资金
            if(OrderTotalConstants.TYPE_RECHARGE.equals(ordersTotal.getType())){
                //判断金额不等于0,才执行操作,不然操作余额的时候会爆操作数量或金额不能为0
                if(ordersTotal.getTotal().compareTo(BigDecimal.ZERO)!=0){
                    String operationId=operator.get("operatorId");
                    String operatorName=operator.get("operatorName");
                    UserMoneyUtil.setNewUserMoneyUnclaimed(refundRecord.getUserId(),refundRecord.getRemarks(),"充值单:"+ordersTotal.getOrderNo()+"申请退款,预扣除金额:"+ordersTotal.getTotal(),operationId,refundRecord.getOrderId(),ordersTotal.getAppIdCode(),refundRecord.getId(),new BigDecimal(String.valueOf(ordersTotal.getTotal())).negate(), UserMoneyUnclaimed.FUND_TYPE_STORED_VALUE_FUND, OperationReasonConstants.OP_REASON_RECHARGE_REFUND,commonService,UserMoneyUnclaimed.NO);
                    OrderLog orderLog = RefundToolUtil.setOrderLog(refundRecord, operationId, operatorName, "充值单:"+ordersTotal.getOrderNo()+"申请退款,预扣除金额:"+ordersTotal.getTotal(), 0, OrderLogConstants.LOG_TYPE_REFUND);
                    commonService.insert(OrderLogMapper.class,orderLog);
                    //活动规则退款处理
                    map.put("orderId", ordersTotal.getId());
                    sqlSentence.sqlSentence("select * from orders_info where isDel=0 and orderId=#{m.orderId}",map);
                    OrderInfo orderInfo=commonService.selectOne(OrderInfoMapper.class,sqlSentence);
                    handActivityRule(commonService, operationId, operatorName, sqlSentence, map, refundRecord,ordersTotal,orderInfo,0);
                }
            }
            //调用审批功能
            return handleApproval(ordersNodeLog,orderNodeBuilder,ordersTotal,cancelOrder,refundRecord);
        }
@@ -918,22 +876,27 @@
    /**保存退款信息
     * 保存退款信息,并没有真正退款
     */
    public RefundRecord insertRefundInfo(OrderRefundDto orderRefundDto,OrdersTotal ordersTotal,StringBuilder orderNodeBuilder
            , ThirtApplication thirtApplication){
    public RefundRecord insertRefundInfo(OrderRefundDto orderRefundDto,OrdersTotal ordersTotal
            ,StringBuilder orderNodeBuilder, ThirtApplication thirtApplication){
        //操作人
        Employee employee = commonService.selectOneByKey(EmployeeMapper.class,orderRefundDto.getOperatorId());
        if(employee == null){
            throw new TipsException("操作人标识错误!");
        }
        ///////退款总表数据填充
        //生成退款编号
        String totalCode = createNoService.createNo("R",System.currentTimeMillis()+"",8);
        RefundRecord refundRecord=new RefundRecord(totalCode,ordersTotal.getShopId(),ordersTotal.getShopName(),orderRefundDto.getRefundTotal()
                , RefundStatus.STATUS_APPLY_REFUND,0, RefundSoruceConstants.TYPE_SOURCE_ORDER,orderRefundDto.getRemarks(),ordersTotal.getId(),ordersTotal.getUserId());
        //操作人信息
        refundRecord.setOperatorType(RefundRecord.OPERATOR_TYPE_EMPLOYEE);
        Employee employee = commonService.selectOneByKey(EmployeeMapper.class,orderRefundDto.getOperatorId());
        if(employee == null){
            throw new TipsException("操作人标识错误!");
        }
        refundRecord.setOperatorId(employee.getId());
        refundRecord.setRefundOperationType(orderRefundDto.getRefundOperationType());
        refundRecord.setOperatorNo(employee.getEmployeeNo());
        refundRecord.setOperatorName(employee.getCnName());
        refundRecord.setRefundOperationType(orderRefundDto.getRefundOperationType());
        /////退款的备注
        refundRecord.setRemarks(orderRefundDto.getRemarks());
        refundRecord.setRefundReason(orderRefundDto.getRefundReason());
@@ -943,34 +906,199 @@
        refundRecordService.insert(refundRecord);
        //退款方式处理
        List<RefundRecordMethod> refundRecordMethodList = null;
        if(orderRefundDto.getRefundPayMethod() !=null && orderRefundDto.getRefundPayMethod().size()>0){
            refundRecordMethodList = handleRefundPayMethod(orderRefundDto,orderNodeBuilder,ordersTotal,refundRecord);
        if(orderRefundDto.getRefundPayMethod() !=null && orderRefundDto.getRefundPayMethod().size() > 0){
            handleRefundPayMethod(orderRefundDto,orderNodeBuilder,ordersTotal,refundRecord);
        }
        //退款的子项处理
        if(orderRefundDto.getRefundList()!=null && orderRefundDto.getRefundList().size()>0){
            handleRefundRecordItem(orderRefundDto,orderNodeBuilder,ordersTotal,refundRecord,refundRecordMethodList);
            insertRefundRecordItem(orderRefundDto,orderNodeBuilder,refundRecord);
        }
        //回退的优惠卷处理
        if(orderRefundDto.getCouponList() != null && orderRefundDto.getCouponList().size()>0){
            handleOrderCouponRefunDto(orderRefundDto.getCouponList(),orderNodeBuilder,ordersTotal,refundRecord);
        }
        //*******扣减赠送的账户资金,如果订单有老带新的赠送规则,那么如果申请退款,就优先把老带新的退回来*****
        //获取老带新记录
        oldBlingNewRefund(refundRecord,orderNodeBuilder,commonService);
        //判断是否是充值订单,是的话先冻结储值金,就是扣掉,审批通过就不处理储值金了,不通过还原资金
        if(OrderTotalConstants.TYPE_RECHARGE.equals(ordersTotal.getType())){
            OrderRefundCancelTool.rechargeHandle(ordersTotal,refundRecord,OrderRefundCancelTool.OPT_TYPE_EXECUTE,commonService);
        }
        //活动处理
        OrderRefundCancelTool.activityRuleHandle(ordersTotal,refundRecord,OrderRefundCancelTool.OPT_TYPE_EXECUTE,commonService);
        return refundRecord;
    }
    /**
     * 退款-处理活动规则增值金和积分
     * @param commonService 映射对象
     * @param operationId 操作人标识
     * @param operationNme 操作人名称
     * @param sqlSentence 映射对象
     * @param map 映射对象
     * @param refundRecord 退款记录
     * @param ordersTotal 订单
     * @param optType 操作:"0"减 1加
     */
    /**老带新的订单退款,佣金处理*/
    public void oldBlingNewRefund(RefundRecord refundRecord,StringBuilder orderNodeBuilder,CommonService commonService){
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> values = new HashMap<>();
        //查找老带新记录,未删除且有效的,没有退回的
        values.put("operationReason",OperationReasonConstants.OP_REASON_BRING_NEW_USER_GIFT);
        values.put("orderId",refundRecord.getOrderId());
        sqlSentence.sqlSentence("SELECT * FROM user_money_unclaimed mu WHERE mu.isDel = 0 AND mu.isValid = 1 AND mu.operationReason = #{m.operationReason}" +
                " AND mu.orderId = #{m.orderId} AND NOT EXISTS(SELECT * FROM refund_user_assets rua WHERE rua.isDel = 0 AND rua.status = 1" +
                " AND rua.amountStatus IN (1,3) AND rua.userMoneyUnclaimedId = mu.id)",values);
        List<UserMoneyUnclaimed> userMoneyUnclaimedList = commonService.selectList(UserMoneyUnclaimedMapper.class,sqlSentence);
        RefundUserAssets refundUserAssets;
        UserMoney userMoney;
        User user;
        BigDecimal amount;
        for (UserMoneyUnclaimed userMoneyUnclaimed:userMoneyUnclaimedList){
            amount = BigDecimal.ZERO;
            //生成记录
            refundUserAssets = new RefundUserAssets();
            refundUserAssets.setType(userMoneyUnclaimed.getOperationReason());
            refundUserAssets.setStatus(RefundUserAssets.STATUS_NORMAL);
            refundUserAssets.setAmountType(userMoneyUnclaimed.getFundType());
            refundUserAssets.setAmount(userMoneyUnclaimed.getOpNumber().negate());
            refundUserAssets.setOperatorId(refundRecord.getOperatorId());
            refundUserAssets.setOperatorNo(refundRecord.getOperatorNo());
            refundUserAssets.setOperatorName(refundRecord.getOperatorName());
            refundUserAssets.setOrderId(refundRecord.getOrderId());
            refundUserAssets.setRefundRecordId(refundRecord.getId());
            refundUserAssets.setUserMoneyUnclaimedId(userMoneyUnclaimed.getId());
            refundUserAssets.setUserId(userMoneyUnclaimed.getUserId());
            user = commonService.selectOneByKey(UserMapper.class,refundUserAssets.getUserId());
            orderNodeBuilder.append("-退款处理老带新,扣减用户:").append(user.getName()).append(",CIQ:").append(user.getCIQ()).append(",");
            orderNodeBuilder.append(RefundUserAssets.amountTypeName(refundUserAssets.getAmountType())).append(refundUserAssets.getAmount());
            if(userMoneyUnclaimed.getStatus() == UserMoneyUnclaimed.STATUS_WAI){
                refundUserAssets.setAmountStatus(RefundUserAssets.AMOUNT_STATUS_NOT_RECEIVE);
                //用户未领取,那么直接作废,作废是逻辑删除
                values.put("id",userMoneyUnclaimed.getId());
                values.put("status",UserMoneyUnclaimed.STATUS_WAI);
                sqlSentence.sqlUpdate("isDel = 1,isValid = 0 WHERE id = #{m.id} AND isDel = 0 AND isValid = 1 AND status = #{m.status}",values);
                if(commonService.updateWhere(UserMoneyUnclaimedMapper.class,sqlSentence) != 1){
                    throw new TipsException("老带新资产记录状态已变化!");
                }
                orderNodeBuilder.append(",用户未领取,作废领取记录");
            }else if(userMoneyUnclaimed.getStatus() == UserMoneyUnclaimed.STATUS_SUCCEED){
                //用户已经领取了,那么要扣掉,但是,要先判断用户是否够,如果不够,那么也生成记录,显示未操作资金
                values.clear();
                values.put("userId",userMoneyUnclaimed.getUserId());
                sqlSentence.sqlSentence("SELECT * FROM user_money WHERE isDel = 0 AND userId = #{m.userId}",values);
                userMoney = commonService.selectOne(UserMoneyMapper.class,sqlSentence);
                if(userMoneyUnclaimed.getFundType() == UserMoneyUnclaimed.FUND_TYPE_STORED_VALUE_FUND){
                    //储值金
                    if(userMoney.getStoredValueFund() != null){
                        amount = new BigDecimal(userMoney.getStoredValueFund());
                    }
                }else if(userMoneyUnclaimed.getFundType() == UserMoneyUnclaimed.FUND_TYPE_VALUE_ADDED_FUND){
                    //增值金
                    if(userMoney.getValueAddedFund() != null){
                        amount = new BigDecimal(userMoney.getValueAddedFund());
                    }
                }else if(userMoneyUnclaimed.getFundType() == UserMoneyUnclaimed.FUND_TYPE_INTEGRAL){
                    //预定金
                    if(userMoney.getDeposit() != null){
                        amount = new BigDecimal(userMoney.getDeposit());
                    }
                }else if(userMoneyUnclaimed.getFundType() == UserMoneyUnclaimed.FUND_TYPE_DEPOSIT){
                    //积分
                    if(userMoney.getIntegral() != null){
                        amount = new BigDecimal(userMoney.getIntegral());
                    }
                }else{
                    throw new TipsException("老带新资产记录金额类型未知!");
                }
                if(amount.compareTo(refundUserAssets.getAmount()) >= 0){
                    //用户资产够减
                    orderNodeBuilder.append(",扣减成功");
                    refundUserAssets.setAmountStatus(RefundUserAssets.AMOUNT_STATUS_NORMAL);
                }else {
                    orderNodeBuilder.append(",余额不足,扣减失败");
                    //用户资产不够减
                    refundUserAssets.setAmountStatus(RefundUserAssets.AMOUNT_STATUS_NOT);
                }
            }else{
                throw new TipsException("老带新资产记录状态错误!");
            }
            if(refundUserAssets.getAmountStatus() == RefundUserAssets.AMOUNT_STATUS_NORMAL
                    || refundUserAssets.getAmountStatus() == RefundUserAssets.AMOUNT_STATUS_NOT_RECEIVE ){
                //保存记录,正常扣减和未领取才去保存这个记录
                commonService.insert(RefundUserAssetsMapper.class,refundUserAssets);
            }
            //用户资金操作
            if(refundUserAssets.getAmountStatus() == RefundUserAssets.AMOUNT_STATUS_NORMAL){
                UserMoneyUtil.setNewUserMoneyUnclaimed(refundUserAssets.getUserId(),refundRecord.getRemarks(),"退款:老带新资金回退",refundUserAssets.getOperatorId()
                        ,refundRecord.getOrderId(),refundRecord.getOperatorAppCode(),refundUserAssets.getId(),refundUserAssets.getAmount(),refundUserAssets.getAmountType()
                        ,OperationReasonConstants.OP_REASON_BRING_NEW_USER_GIFT_RETRUN,commonService,UserMoneyUnclaimed.YES);
            }
        }
    }
    /**老带新的订单退款不通过或者作废,佣金处理*/
    public void oldBlingNewRefundFail(RefundRecord refundRecord,StringBuilder orderNodeBuilder,CommonService commonService) {
        ////订单退款状态是没有退款才退回
        //获取回退记录
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> values = new HashMap<>();
        values.put("orderId",refundRecord.getOrderId());
        sqlSentence.sqlSentence("SELECT * FROM refund_user_assets rua WHERE rua.isDel = 0 AND rua.status = 1 AND rua.amountStatus IN(1,3) AND rua.orderId = #{m.orderId}",values);
        List<RefundUserAssets> refundUserAssetsList = commonService.selectList(RefundUserAssetsMapper.class,sqlSentence);
        User user;
        for(RefundUserAssets refundUserAssets:refundUserAssetsList){
            user = commonService.selectOneByKey(UserMapper.class,refundUserAssets.getUserId());
            orderNodeBuilder.append("-退款处理老带新,回退资金到用户:").append(user.getName()).append(",CIQ:").append(user.getCIQ()).append(",");
            orderNodeBuilder.append(RefundUserAssets.amountTypeName(refundUserAssets.getAmountType())).append(refundUserAssets.getAmount());
            //是否有扣减用户资产
            if(refundUserAssets.getAmountStatus() == RefundUserAssets.AMOUNT_STATUS_NORMAL){
                orderNodeBuilder.append(",增加成功");
                UserMoneyUtil.setNewUserMoneyUnclaimed(refundUserAssets.getUserId(),refundRecord.getRemarks(),"退款作废:老带新资金回退作废",refundUserAssets.getOperatorId()
                        ,refundRecord.getOrderId(),refundRecord.getOperatorAppCode(),refundUserAssets.getId(),refundUserAssets.getAmount().negate(),refundUserAssets.getAmountType()
                        ,OperationReasonConstants.OP_REASON_BRING_NEW_USER_GIFT_RETRU_CANCEL,commonService,UserMoneyUnclaimed.YES);
            }else if(refundUserAssets.getAmountStatus() == RefundUserAssets.AMOUNT_STATUS_NOT_RECEIVE){
                //用户未领取记录,还原
                orderNodeBuilder.append(",用户未领取,作废的领取记录还原");
                values.clear();
                values.put("id",refundUserAssets.getUserMoneyUnclaimedId());
                values.put("status",UserMoneyUnclaimed.STATUS_WAI);
                sqlSentence.sqlUpdate("isDel = 0,isValid = 1 WHERE id = #{m.id} AND isDel = 1 AND isValid = 0 AND status = #{m.status}",values);
                if(commonService.updateWhere(UserMoneyUnclaimedMapper.class,sqlSentence) != 1){
                    throw new TipsException("老带新资产记录状态已变化[作废]!");
                }
            }
            //记录作废
            values.clear();
            values.put("id",refundUserAssets.getId());
            values.put("status",RefundUserAssets.STATUS_CANCEL);
            values.put("oldStatus",RefundUserAssets.STATUS_NORMAL);
            sqlSentence.sqlSentence("status = #{m.status} WHERE id = #{m.id} AND status = #{m.oldStatus}",values);
            if(commonService.updateWhere(RefundUserAssetsMapper.class,sqlSentence) != 1){
                throw new TipsException("老带新资产退款记录状态已变化[作废]!");
            }
        }
    }
        /**
         * 退款-处理活动规则增值金和积分
         * @param commonService 映射对象
         * @param operationId 操作人标识
         * @param operationNme 操作人名称
         * @param sqlSentence 映射对象
         * @param map 映射对象
         * @param refundRecord 退款记录
         * @param ordersTotal 订单
         * @param optType 操作:"0"减 1加
         */
    private static void handActivityRule(CommonService commonService, String operationId, String operationNme, SqlSentence sqlSentence,
                                         Map<String, Object> map, RefundRecord refundRecord, OrdersTotal ordersTotal, OrderInfo orderInfo,int optType) {
        if(orderInfo!=null && StringUtils.noNull(orderInfo.getActivityId())){
@@ -1006,7 +1134,6 @@
                }
            }
        }
    }
    /**
@@ -1119,23 +1246,20 @@
        //记录取消日志
        CancelOrder cancelOrder=new CancelOrder();
        cancelOrder.setOrderId(ordersTotal.getId());
        Employee employee = commonService.selectOneByKey(EmployeeMapper.class,orderRefundDto.getOperatorId());
        if(employee==null){
            cancelOrder.setOperatorId(orderRefundDto.getOperatorId());
            cancelOrder.setOperatorName("找不到对应员工");
        }else {
        if(StringUtils.noNull(orderRefundDto.getOperatorId())){
            Employee employee = commonService.selectOneByKey(EmployeeMapper.class,orderRefundDto.getOperatorId());
            if(employee==null){
                throw new TipsException("操作人标识错误!");
            }
            cancelOrder.setOperatorId(employee.getId());
            cancelOrder.setOperatorName(employee.getCnName());
        }
        EmployeeRole employeeRole=commonService.selectOneByKey(EmployeeRoleMapper.class,orderRefundDto.getRoleId());
        if(employeeRole==null){
            cancelOrder.setRoleId(orderRefundDto.getRoleId());
            cancelOrder.setRoleStr("找不到对应角色");
            cancelOrder.setShopId(employeeRole.getShopId());
            cancelOrder.setShopName("找不到对应的门店");
        }else {
        if(StringUtils.noNull(orderRefundDto.getRoleId())){
            EmployeeRole employeeRole=commonService.selectOneByKey(EmployeeRoleMapper.class,orderRefundDto.getRoleId());
            if(employeeRole==null){
                throw new TipsException("操作角色标识错误!");
            }
            cancelOrder.setRoleId(employeeRole.getRoleTypeId());
            cancelOrder.setRoleStr(employeeRole.getRoleUniqueStr());
            Shop shop=commonService.selectOneByKey(ShopMapper.class,employeeRole.getShopId());
@@ -1146,8 +1270,8 @@
                cancelOrder.setShopId(shop.getId());
                cancelOrder.setShopName(shop.getName());
            }
        }
        cancelOrder.setIsApproval(orderRefundDto.getIsApproval());
        cancelOrder.setIsRefund(orderRefundDto.getIsRefund());
        cancelOrder.setPlatformSource(orderRefundDto.getPlatformSource());
@@ -1162,25 +1286,24 @@
    public List<RefundRecordMethod> handleRefundPayMethod(OrderRefundDto orderRefundDto,StringBuilder orderNodeBuilder,OrdersTotal ordersTotal,RefundRecord refundRecord){
        orderNodeBuilder.append("-记录退款方式:");
        //获取订单可退款方式
        List<PayMethodVo> payMethodVoList = refundMapper.selectConsumePayList(ordersTotal.getId());
        //获取订单可退款方式,就是支付方式总表的信息,已经支付编号求和
        List<PayMethodVo> payMethodVoList = refundMapper.getConsumePayGroupByNumberNo(ordersTotal.getId());
        Map<String, PayMethodVo> payMethodVoMap = payMethodVoList.stream().collect(
                Collectors.toMap(PayMethodVo::getNumberNo,(a) -> a));
        //用map装载,后面根据支付编号直接获取便可
        Map<String, PayMethodVo> payMethodVoMap = payMethodVoList.stream().collect(Collectors.toMap(PayMethodVo::getNumberNo,(a) -> a));
        List<RefundRecordMethod> refundRecordMethodList = new ArrayList<>();
        PayMethodVo payMethodVo;
        RefundRecordMethod refundRecordMethod=null;
        RefundMethodTransformation refundMethodTransformation=null;
        RefundRecordMethod refundRecordMethod;
        for (OrderPayMethodDto orderPayMethodDto : orderRefundDto.getRefundPayMethod()) {
            payMethodVo = payMethodVoMap.get(orderPayMethodDto.getPayMethodNo());
            //判断是不是在支付方式里面的
            if (payMethodVo == null){
                throw new PlatTipsException(PlatformCode.ERROR_TIPS,"可退支付方式未找到对应的支付:"+orderPayMethodDto.getPayMethodName()+"["+orderPayMethodDto.getPayMethodNo()+"]");
                throw new PlatTipsException(PlatformCode.ERROR_TIPS,"可退支付方式未找到:"+orderPayMethodDto.getPayMethodName()+"["+orderPayMethodDto.getPayMethodNo()+"]");
            }
            //判断退款方式
            //判断支付方式
            PaymentMethod payMethod = paymentMethodService.selectNumberNoUncheckUp(orderPayMethodDto.getPayMethodNo());
            if(payMethod == null){
                throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到对应的支付:"+orderPayMethodDto.getPayMethodName()+"["+orderPayMethodDto.getPayMethodNo()+"]");
@@ -1188,38 +1311,35 @@
            //判断退款方式
            PaymentMethod refundMethod = paymentMethodService.selectNumberNoUncheckUp(orderPayMethodDto.getRefundNumberNo());
            if(refundMethod==null){
                throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到该转换方式:"+orderPayMethodDto.getPayMethodName()+"["+orderPayMethodDto.getPayMethodName()+"]");
                throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到退款方式:"+orderPayMethodDto.getRefundNumberName()+"["+orderPayMethodDto.getRefundNumberNo()+"]");
            }
            if(orderPayMethodDto.getMoney() == null){
                throw new PlatTipsException(PlatformCode.ERROR_TIPS,"请先写退款方式["+orderPayMethodDto.getPayMethodName()+"["+orderPayMethodDto.getPayMethodNo()+"]"+"]金额");
                throw new PlatTipsException(PlatformCode.ERROR_TIPS,"请填写退款方式["+orderPayMethodDto.getPayMethodName()+"["+orderPayMethodDto.getPayMethodNo()+"]"+"]金额");
            }
            //判断金额
            if(payMethodVo.getSurplusTotal().compareTo(orderPayMethodDto.getMoney()) < 0){
                throw new PlatTipsException(PlatformCode.ERROR_TIPS,"退款金额错误:"+orderPayMethodDto.getPayMethodName()+"["+orderPayMethodDto.getPayMethodNo()+"]");
            }
            //新增转换表记录
            refundMethodTransformation = new RefundMethodTransformation();
            BeanUtils.copyProperties(orderPayMethodDto, refundMethodTransformation);
            refundMethodTransformation.setRefundTotal(orderPayMethodDto.getMoney());
            refundMethodTransformation.setRefundRecordId(refundRecord.getId());
            refundMethodTransformationMapper.insert(refundMethodTransformation);
            //退回客户的支付方式
            ////退款方式数据填充
            refundRecordMethod = new RefundRecordMethod();
            refundRecordMethod.setType(refundRecord.getSourceType());
            refundRecordMethod.setActualTotal(orderPayMethodDto.getMoney());
            //支付方式信息
            refundRecordMethod.setNumberNo(payMethod.getNumberNo());
            refundRecordMethod.setPaymentMethodId(payMethod.getId());
            refundRecordMethod.setName(payMethod.getName());
            refundRecordMethod.setIsMoneyPay(payMethodVo.getIsMoneyPay());
            refundRecordMethod.setIsExecute(payMethodVo.getIsExecute());
            //退款方式信息
            refundRecordMethod.setRefundNumberNo(refundMethod.getNumberNo());
            refundRecordMethod.setRefundName(refundMethod.getName());
            refundRecordMethod.setRefundMethodId(refundMethod.getId());
            refundRecordMethod.setActualTotal(orderPayMethodDto.getMoney());
            refundRecordMethod.setRefundMethodId(refundMethod.getId());
            refundRecordMethod.setIsMoneyPayRefund(refundMethod.getIsMoneyPay());
            refundRecordMethod.setIsExecuteRefund(refundMethod.getIsExecute());
            //refundRecordMethod.setConsumePayId(consumePay.getId());
            refundRecordMethod.setRefundMethodTransId(refundMethodTransformation.getId());
            //refundRecordMethod.setRealRefundTotal(money);//实退款总金额 后期需要修改
            refundRecordMethod.setRefundRecordId(refundRecord.getId());
            refundRecordMethod.setOrderId(ordersTotal.getId());
            refundRecordMethod.setRemarks(orderPayMethodDto.getRemarks());
            refundRecordMethodService.insert(refundRecordMethod);
@@ -1231,16 +1351,11 @@
    /**
     * 退款记录子项
     */
    public void handleRefundRecordItem(OrderRefundDto orderRefundDto,StringBuilder orderNodeBuilder,OrdersTotal ordersTotal,RefundRecord refundRecord,List<RefundRecordMethod> refundRecordMethodList){
    public void insertRefundRecordItem(OrderRefundDto orderRefundDto,StringBuilder orderNodeBuilder,RefundRecord refundRecord){
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> map=new HashMap<>();
        sqlSentence.sqlSentence(" select * from user_project_item where commonId=#{m.commonId}  and isDel=0 AND isTransfer = 0 ",map);
        map.put("userId", ordersTotal.getUserId());
        orderNodeBuilder.append("-记录退款详情");
        //计算金额占比
        //计算金额占比,客户选择退款总金额和可退总金额占比
        BigDecimal percentage;
        if(orderRefundDto.getTotalAmount().compareTo(BigDecimal.ZERO) < 1){
            percentage = BigDecimal.ZERO;
@@ -1248,21 +1363,19 @@
            percentage = orderRefundDto.getRefundTotal().divide(orderRefundDto.getTotalAmount(),15,RoundingMode.HALF_UP);
        }
        //退款总金额,用于后面计算分摊金额
        //总退款金额,用于后面计算分摊金额
        BigDecimal refundTotal = refundRecord.getRefundTotal();
        //装载参数
        List<RefundRecordItemMethod> refundRecordItemMethodList;
        //后面设计分配金额问题,要进行升序排序,避免到最后不够
        List<OrderItemRefundDto> refundList = orderRefundDto.getRefundList();
        refundList = refundList.stream().sorted(Comparator.comparing(OrderItemRefundDto::getApproveRefundTotal)).collect(Collectors.toList());
        /////引用参数
        RefundRecordItem refundRecordItem;
        OrderItemRefundDto orderItemRefundDto;
        RefundRecordItemMethod refundRecordItemMethod;
        RefundRecordMethod refundRecordMethod;
        OrderItem orderItem;
        for(int i = 0;i<orderRefundDto.getRefundList().size();i++){
            orderItemRefundDto = orderRefundDto.getRefundList().get(i);
            refundRecordItemMethodList = new ArrayList<>();
        for(int i = 0;i < refundList.size();i++){
            orderItemRefundDto = refundList.get(i);
            orderItem = orderItemMapper.selectOneByKey(orderItemRefundDto.getOrderItemId());
            if(orderItem == null){
@@ -1273,10 +1386,14 @@
            refundRecordItem = new RefundRecordItem();
            refundRecordItem.setType(orderItem.getType());
            refundRecordItem.setGoodsNo(orderItem.getGoodsNo());
            refundRecordItem.setGoodsName(orderItem.getGoodsName());
            refundRecordItem.setSpecs(orderItem.getSpecs());
            refundRecordItem.setCommonId(orderItem.getCommonId());
            refundRecordItem.setHeadPrice(orderItem.getCurPrice());
            refundRecordItem.setRefundNum(orderItemRefundDto.getRefundNum());
            if(PartialRefundUtil.CONTAIN_SON_TYPE_SET.contains(orderItem.getType())){
                refundRecordItem.setRefundNum(0);
            }else{
                refundRecordItem.setRefundNum(orderItemRefundDto.getRefundNum());
            }
            refundRecordItem.setRefundRecordId(refundRecord.getId());
            refundRecordItem.setOrderItemId(orderItem.getId());
            refundRecordItem.setOccupyRefundTotal(orderItemRefundDto.getApproveRefundTotal());
@@ -1285,13 +1402,13 @@
                orderItemRefundDto.setRemarks(refundRecord.getRemarks());
            }
            if(StringUtils.isEmpty(orderItemRefundDto.getRefundReason())){
                orderItemRefundDto.setRemarks(refundRecord.getRefundReason());
                orderItemRefundDto.setRefundReason(orderItemRefundDto.getRefundReason());
            }
            refundRecordItem.setRemarks(orderItemRefundDto.getRemarks());
            refundRecordItem.setRefundReason(orderItemRefundDto.getRefundReason());
            //计算退款金额
            if(i == orderRefundDto.getRefundList().size()-1){
            //////////分配退款金额
            if(i == refundList.size()-1){
                refundRecordItem.setRefundMoney(refundTotal);
            }else{
                refundRecordItem.setRefundMoney(orderItemRefundDto.getApproveRefundTotal().multiply(percentage).setScale(2,RoundingMode.UP));
@@ -1299,74 +1416,45 @@
            if(refundRecordItem.getRefundMoney().compareTo(orderItemRefundDto.getApproveRefundTotal()) > 0){
                refundRecordItem.setRefundMoney(orderItemRefundDto.getApproveRefundTotal());
            }
            //判断与未分配剩余金额
            if(refundRecordItem.getRefundMoney().compareTo(refundTotal) > 0){
                refundRecordItem.setRefundMoney(refundTotal);
            }
            refundTotal = refundTotal.subtract(refundRecordItem.getRefundMoney()).setScale(2,RoundingMode.HALF_UP);
            refundRecordItem.setRealRefundNum(refundRecordItem.getRefundNum());
            refundRecordItem.setRealRefundTotal(refundRecordItem.getRefundMoney());
            refundRecordItemService.insert(refundRecordItem);
            //////金额分配
            //退款方式金额分配
            if(refundRecordMethodList != null && refundRecordMethodList.size() > 0){
                BigDecimal refundTotalItem = refundRecordItem.getRefundMoney();
                for(int j = 0;j <refundRecordMethodList.size();i++){
                    refundRecordMethod = refundRecordMethodList.get(j);
                    ////子项退款方式填充
                    refundRecordItemMethod = new RefundRecordItemMethod();
                    refundRecordItemMethod.setNumberNo(refundRecordMethod.getNumberNo());
                    refundRecordItemMethod.setName(refundRecordMethod.getName());
                    //支付方式
                    refundRecordItemMethod.setPaymentMethodId(refundRecordMethod.getPaymentMethodId());
                    refundRecordItemMethod.setIsMoneyPay(refundRecordMethod.getIsMoneyPay());
                    refundRecordItemMethod.setIsExecute(refundRecordMethod.getIsExecute());
                    refundRecordItemMethod.setIsPay(refundRecordMethod.getIsPay());
                    //退款方式
                    refundRecordItemMethod.setRefundNumberNo(refundRecordMethod.getRefundNumberNo());
                    refundRecordItemMethod.setRefundName(refundRecordMethod.getRefundName());
                    refundRecordItemMethod.setRefundMethodId(refundRecordMethod.getRefundMethodId());
                    //退款金额
                    if(j == refundRecordMethodList.size()-1){
                        ////最后一个
                        refundRecordItemMethod.setActualTotal(refundTotalItem);
                    }else {
                        ////不是最后一个
                        refundRecordItemMethod.setActualTotal(refundRecordMethod.getActualTotal().multiply(percentage).setScale(2,RoundingMode.UP));
                    }
                    if(refundRecordItemMethod.getActualTotal().compareTo(refundRecordMethod.getActualTotal()) > 0){
                        refundRecordItemMethod.setActualTotal(refundRecordMethod.getActualTotal());
                    }
                    if(refundRecordItemMethod.getActualTotal().compareTo(refundTotalItem) > 0){
                        refundRecordItemMethod.setActualTotal(refundTotalItem);
                    }
                    refundTotalItem = refundTotalItem.subtract(refundRecordItemMethod.getActualTotal()).setScale(2,RoundingMode.HALF_UP);
                    refundRecordItemMethod.setCommonType(OrderSourceConstans.TYPE_PROJECT);
                    refundRecordItemMethod.setCommonId(refundRecordItem.getOrderItemId());
                    refundRecordItemMethod.setOrderId(refundRecordMethod.getOrderId());
                    refundRecordItemMethod.setRefundRecordItemId(refundRecordItem.getId());
                    refundRecordItemMethod.setRefundRecordId(refundRecord.getId());
                    refundRecordItemMethodMapper.insert(refundRecordItemMethod);
                    refundRecordItemMethodList.add(refundRecordItemMethod);
                }
            //减去已经分配的退款金额
            refundTotal = refundTotal.subtract(refundRecordItem.getRefundMoney()).setScale(2,RoundingMode.HALF_UP);
            if(PartialRefundUtil.CONTAIN_SON_TYPE_SET.contains(orderItem.getType())){
                //子单子项处理
                insertRefundRecordItemTwo(refundRecordItem,refundRecord,orderItemRefundDto.getOrderItemSourceRefundDtos());
            }
            //子单子项处理
            itemTwoRefundHandle(refundRecordItem,refundRecord,orderItemRefundDto.getOrderItemSourceRefundDtos()
                    , refundRecordItemMethodList, percentage);
        }
        //处理每个项目每个支付方式的分摊金额
        //handleRefundRecordItemMethod(refundRecord, refundRecordItems);
        if(refundTotal.compareTo(BigDecimal.ZERO) > 0){
            throw new TipsException("退款金额分配错误[01]!");
        }
    }
    /**二级子单处理*/
    public void itemTwoRefundHandle(RefundRecordItem recordItem,RefundRecord refundRecord,List<OrderItemSourceRefundDto> orderItemSourceRefundDtos
            ,List<RefundRecordItemMethod> refundRecordItemMethodList,BigDecimal percentage){
    public void insertRefundRecordItemTwo(RefundRecordItem recordItem,RefundRecord refundRecord,List<OrderItemSourceRefundDto> orderItemSourceRefundDtos){
        if(orderItemSourceRefundDtos == null || orderItemSourceRefundDtos.size() == 0){
            return;
        }
        //计算占比
        BigDecimal percentage;
        if(recordItem.getOccupyRefundTotal().compareTo(BigDecimal.ZERO) > 0){
            percentage = recordItem.getRefundMoney().divide(recordItem.getOccupyRefundTotal(),15,RoundingMode.HALF_UP);
        }else{
            percentage = BigDecimal.ZERO;
        }
        //进行升序排序,避免后面不够
        orderItemSourceRefundDtos = orderItemSourceRefundDtos.stream().sorted(Comparator.comparing(OrderItemSourceRefundDto::getApproveRefundTotal)).collect(Collectors.toList());
        //退款总金额
        BigDecimal refundTotal = recordItem.getRefundMoney();
@@ -1374,7 +1462,7 @@
        OrderItemSon orderItemSon;
        OrderItemSourceRefundDto orderItemSourceRefundDto;
        RefundRecordItemSource refundRecordItemSource;
        RefundRecordItemMethod refundRecordItemMethod;
        for(int i = 0;i<orderItemSourceRefundDtos.size();i++){
            orderItemSourceRefundDto = orderItemSourceRefundDtos.get(i);
@@ -1387,19 +1475,20 @@
            refundRecordItemSource = new RefundRecordItemSource();
            refundRecordItemSource.setType(orderItemSon.getType());
            refundRecordItemSource.setGoodsNo(orderItemSon.getGoodsNo());
            refundRecordItemSource.setGoodsName(orderItemSon.getGoodsName());
            refundRecordItemSource.setSpecs(orderItemSon.getSpecs());
            refundRecordItemSource.setCommonId(orderItemSon.getGoodsId());
            refundRecordItemSource.setHeadPrice(orderItemSon.getCurPrice());
            refundRecordItemSource.setRefundNum(orderItemSourceRefundDto.getRefundNum());
            refundRecordItemSource.setRefundRecordId(orderItemSon.getId());
            refundRecordItemSource.setRefundRecordId(refundRecord.getId());
            refundRecordItemSource.setOrderItemSonId(orderItemSon.getId());
            refundRecordItemSource.setOccupyRefundTotal(orderItemSourceRefundDto.getApproveRefundTotal());
            refundRecordItemSource.setRefundRecordItemId(recordItem.getId());
            ////退款备注
            if(StringUtils.isEmpty(orderItemSourceRefundDto.getRemarks())){
                orderItemSourceRefundDto.setRemarks(refundRecord.getRemarks());
            }
            if(StringUtils.isEmpty(orderItemSourceRefundDto.getRefundReason())){
                orderItemSourceRefundDto.setRemarks(refundRecord.getRefundReason());
                orderItemSourceRefundDto.setRefundReason(refundRecord.getRefundReason());
            }
            refundRecordItemSource.setRemarks(orderItemSourceRefundDto.getRemarks());
            refundRecordItemSource.setRefundReason(orderItemSourceRefundDto.getRefundReason());
@@ -1416,56 +1505,18 @@
            if(refundRecordItemSource.getRefundMoney().compareTo(refundTotal) > 0){
                refundRecordItemSource.setRefundMoney(refundTotal);
            }
            refundTotal = refundTotal.subtract(refundRecordItemSource.getRefundMoney()).setScale(2,RoundingMode.HALF_UP);
            refundRecordItemSource.setRealRefundNum(refundRecordItemSource.getRefundNum());
            refundRecordItemSource.setRealRefundTotal(refundRecordItemSource.getRefundMoney());
            refundRecordItemSourceMapper.insert(refundRecordItemSource);
            //////金额分配
            //退款方式金额分配
            if(refundRecordItemMethodList != null && refundRecordItemMethodList.size() > 0){
                BigDecimal refundTotalItem = refundRecordItemSource.getRefundMoney();
                for(int j = 0;j <refundRecordItemMethodList.size();i++){
                    refundRecordItemMethod = refundRecordItemMethodList.get(j);
                    ////子项退款方式填充
                    refundRecordItemMethod = new RefundRecordItemMethod();
                    refundRecordItemMethod.setNumberNo(refundRecordItemMethod.getNumberNo());
                    refundRecordItemMethod.setName(refundRecordItemMethod.getName());
                    //支付方式
                    refundRecordItemMethod.setPaymentMethodId(refundRecordItemMethod.getPaymentMethodId());
                    refundRecordItemMethod.setIsMoneyPay(refundRecordItemMethod.getIsMoneyPay());
                    refundRecordItemMethod.setIsExecute(refundRecordItemMethod.getIsExecute());
                    refundRecordItemMethod.setIsPay(refundRecordItemMethod.getIsPay());
                    //退款方式
                    refundRecordItemMethod.setRefundNumberNo(refundRecordItemMethod.getRefundNumberNo());
                    refundRecordItemMethod.setRefundName(refundRecordItemMethod.getRefundName());
                    refundRecordItemMethod.setRefundMethodId(refundRecordItemMethod.getRefundMethodId());
                    //退款金额
                    if(j == refundRecordItemMethodList.size()-1){
                        ////最后一个
                        refundRecordItemMethod.setActualTotal(refundTotalItem);
                    }else {
                        ////不是最后一个
                        refundRecordItemMethod.setActualTotal(refundRecordItemMethod.getActualTotal().multiply(percentage).setScale(2,RoundingMode.UP));
                    }
                    if(refundRecordItemMethod.getActualTotal().compareTo(refundRecordItemMethod.getActualTotal()) > 0){
                        refundRecordItemMethod.setActualTotal(refundRecordItemMethod.getActualTotal());
                    }
                    if(refundRecordItemMethod.getActualTotal().compareTo(refundTotalItem) > 0){
                        refundRecordItemMethod.setActualTotal(refundTotalItem);
                    }
                    refundTotalItem = refundTotalItem.subtract(refundRecordItemMethod.getActualTotal()).setScale(2,RoundingMode.HALF_UP);
                    refundRecordItemMethod.setCommonType(OrderSourceConstans.TYPE_RETAIL);
                    refundRecordItemMethod.setCommonId(refundRecordItemSource.getOrderItemSonId());
                    refundRecordItemMethod.setOrderId(refundRecordItemMethod.getOrderId());
                    refundRecordItemMethod.setRefundRecordItemId(refundRecordItemSource.getId());
                    refundRecordItemMethod.setRefundRecordId(refundRecord.getId());
                    refundRecordItemMethodMapper.insert(refundRecordItemMethod);
                    refundRecordItemMethodList.add(refundRecordItemMethod);
                }
            }
            //减去已经分配退款金额
            refundTotal = refundTotal.subtract(refundRecordItemSource.getRefundMoney()).setScale(2,RoundingMode.HALF_UP);
            System.out.println("refundRecordItemSource.getRefundMoney():"+refundRecordItemSource.getRefundMoney());
        }
        System.out.println("refundTotal:"+refundTotal);
        if(refundTotal.compareTo(BigDecimal.ZERO) > 0){
            throw new TipsException("退款金额分配错误[02]!");
        }
    }
@@ -1474,12 +1525,12 @@
     * 记录退款记录优惠卷
     */
    public void handleOrderCouponRefunDto(List<OrderCouponRefunDto> couponList,StringBuilder orderNodeBuilder,OrdersTotal ordersTotal,RefundRecord refundRecord){
        CouponOrderDiscountLog couponOrderDiscountLog=null;
        RefundRecordCoupon refundRecordCoupon=null;
        CouponOrderDiscountLog couponOrderDiscountLog;
        RefundRecordCoupon refundRecordCoupon;
        orderNodeBuilder.append("-处理退款优惠卷");
        for (OrderCouponRefunDto orderCouponRefunDto : couponList) {
            couponOrderDiscountLog=couponOrderDiscountLogMapper.selectOneByKey(orderCouponRefunDto.getOrderCouponId());
            if(couponOrderDiscountLog==null){
            if( couponOrderDiscountLog == null){
                throw new PlatTipsException(PlatformCode.ERROR_TIPS,"订单优惠卷标识不正确");
            }
            refundRecordCoupon=new  RefundRecordCoupon(ordersTotal.getId(),refundRecord.getId(),ordersTotal.getUserId(),1,1,couponOrderDiscountLog.getId(),
@@ -1493,23 +1544,24 @@
    /**真正退款,是对钱和状态的回退到账开始操作
     * 进行退款操作,退款用户项目,商品,促销,卡项,卡包
     */
    public Map<String,Object> handleRefundOrder(Map<String, String> operator,RefundRecord refundRecord,OrdersTotal ordersTotal,OrdersNodeLog ordersNodeLog,StringBuilder orderNodeBuilder,CancelOrder cancelOrder ){
    public Map<String,Object> handleRefundOrder(Map<String, String> operator,RefundRecord refundRecord,OrdersTotal ordersTotal
            ,OrdersNodeLog ordersNodeLog,StringBuilder orderNodeBuilder,CancelOrder cancelOrder ){
        String operationId=operator.get("operatorId");
        String operatorName=operator.get("operatorName");
        //处理主业务
        orderNodeBuilder.append("-处理退款支付方式,用户待执行项目");
        ordersTotal=  PartialRefundUtil.refundProcess(commonService, operationId, operatorName, refundRecord.getId(), customParameter);
        //处理主业务
        ordersTotal =  PartialRefundUtil.refundProcess(commonService, operationId, operatorName, refundRecord.getId());
        //返回数据
        Map<String,Object> data=new HashMap<>();
        data.put("refundRecordId",refundRecord.getId());
        data.put("refundRecordCode",refundRecord.getCode());
        //处理次业务,报错不影响主业务
        refundRecord=refundRecordService.selectOneByKey(refundRecord.getId());
        refundRecord = refundRecordService.selectOneByKey(refundRecord.getId());
        /**
         * 用户升降级(调用航爷) 金额=用户支付的实付现金金额(不包含储值金)
         */
@@ -1524,55 +1576,17 @@
        BigDecimal total=new BigDecimal(String.valueOf(totalMap.get("total"))) ;
        if(BigDecimal.ZERO.compareTo(total) < 0){
            try {
                orderNodeBuilder.append("-开始处理用户升降级,金额:"+total.negate());
                orderNodeBuilder.append("-开始处理用户升降级,金额:").append(total.negate());
                UserLevelUtil.refund(ordersTotal.getUserId(),ordersTotal.getId(),total.negate(),ordersTotal.getAppIdCode());
                orderNodeBuilder.append("-处理用户升降级成功");
            }catch (Exception e){
                String snapshot="处理用户升降级失败";
                orderNodeBuilder.append("-处理用户升降级失败,异常原因:"+e.getMessage());
                orderNodeBuilder.append("-处理用户升降级失败,异常原因:").append(e.getMessage());
                logger.error("处理用户升降级失败:" + e.getMessage());
                //发送企业微信通知给工作人员
                SendNoticeUtil.failOrderSendNotice(ordersTotal,e.getMessage(),snapshot,commonService,customParameter);
            }
        }
        //判断本次是否需要退回储值金,有的话需要开单同步到领建
       /* map.put("refundNumberNo", PayMethodTypeConstants.PAY_STORED);
        sqlSentence.setSqlSentence(" SELECT CAST(COALESCE(sum(realRefundTotal),0) as  DECIMAL(11,2)) as total FROM refund_record_method   " +
                "WHERE refundRecordId=#{m.refundRecordId} and refundNumberNo=#{m.refundNumberNo}");
        Map<String,Object> moneyMap =commonService.selectOneMap(RefundRecordMethodMapper.class,sqlSentence);
        BigDecimal money=new BigDecimal(String.valueOf(moneyMap.get("total"))) ;
        if(BigDecimal.ZERO.compareTo(money) < 0  && !StringUtils.isEmpty(ordersTotal.getHisOrderId())){
            try {
                orderNodeBuilder.append("-开始处理增加储值金开充值单到领建,金额:"+money);
                orderRefundNewService.handStroedValue(ordersTotal,operationId,money);
                orderNodeBuilder.append("-处理增加储值金成功");
            }catch (Exception e){
                orderNodeBuilder.append("-处理增加储值金失败:"+e.getMessage());
            }
        }*/
        //判断订单是否是充值订单,如果是的话,需要同步储值金到领建去
       /* if(OrderTotalConstants.TYPE_RECHARGE.equals(ordersTotal.getType())  && !StringUtils.isEmpty(ordersTotal.getHisOrderId())){
            try {
                orderNodeBuilder.append("-开始处理扣减储值金开充值单到领建,金额:"+ordersTotal.getTotal());
                orderRefundNewService.deductionsStroedValue(ordersTotal,operationId,ordersTotal.getTotal());
                orderNodeBuilder.append("-处理扣减储值金成功");
            }catch (Exception e){
                orderNodeBuilder.append("-处理扣减储值金失败:"+e.getMessage());
            }
        }*/
        //同步领建,处理订单状态,未执行项目,卡包
       /* if(!StringUtils.isEmpty(ordersTotal.getHisOrderId())){
            try {
                orderNodeBuilder.append("-开始处理his数据同步");
                OrderCancelUtil.hisPartOrder(commonService,syncOrderService,syncExecutionRecordService,ordersTotal,syncUserCardService,customParameter,orderNodeBuilder, refundRecord);
                orderNodeBuilder.append("-结束处理his数据同步");
            }catch (Exception e){
                orderNodeBuilder.append("-处理his数据同步失败,异常原因:"+e.getMessage());
                logger.error("处理his数据同步失败:" + e.getMessage());
            }
        }*/
        try{
            orderNodeBuilder.append("-开始记录收入确认表");
            PerformanceInfoTool.handRefundPerformanceInfo(commonService,refundRecord);
@@ -1586,7 +1600,8 @@
        if(CancelOrderDto.HIS_ASSISTANT.equals(cancelOrder.getPlatformSource())){
            //如果是his自动处理退款单原路退回
            hisAssistantNoteList(ordersTotal,refundRecord.getId(),operationId,orderNodeBuilder);
            //CRM的操作也在这里
            hisAssistantNoteList(ordersTotal,refundRecord,operationId,orderNodeBuilder);
        }
        //记录操作日志
@@ -1607,13 +1622,14 @@
    /**
     * his助手原路退回退款单
     */
    public void hisAssistantNoteList(OrdersTotal ordersTotal,String refundRecordId,String operationId,StringBuilder orderNodeBuilder){
    public void hisAssistantNoteList(OrdersTotal ordersTotal,RefundRecord refundRecord,String operationId,StringBuilder orderNodeBuilder){
        OrderRefundNoteListDto orderRefundNoteListDto=new OrderRefundNoteListDto();
        orderRefundNoteListDto.setOperationId(operationId);
        orderRefundNoteListDto.setOrderId(ordersTotal.getId());
        //统一在crm取消订单
        // 没有现金支付, 如果是crm的订单则调用crm取消订单的方法
        if("crm".equals(ordersTotal.getAppIdCode()) && OrderTotalConstants.STATUS_CANCEL == ordersTotal.getStatus()){
    /*    if("crm".equals(ordersTotal.getAppIdCode()) && OrderTotalConstants.STATUS_CANCEL == ordersTotal.getStatus()){
            //通知crm
            if(OrderTotalConstants.STATUS_REFUND_FINSH==ordersTotal.getRefundStatus()){
                //全部退款完成
@@ -1638,13 +1654,13 @@
                }
            }
        }
        }*/
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> map=new HashMap<>();
        sqlSentence.setM(map);
        map.put("orderId",ordersTotal.getId());
        map.put("refundRecordId",refundRecordId);
        map.put("refundRecordId",refundRecord.getId());
        sqlSentence.sqlSentence("SELECT * FROM refund_note WHERE orderId=#{m.orderId} and  refundRecordId=#{m.refundRecordId} and isDel=0 ",map);
        List<RefundNote> refundNotes=refundNoteMapper.selectList(sqlSentence);
        if(refundNotes==null || refundNotes.size()==0){
@@ -1663,11 +1679,12 @@
        }
        orderRefundNoteListDto.setOrderRefundNoteDtos(orderRefundNoteDtos);
        noteConfirm(orderRefundNoteListDto, ordersTotal,orderNodeBuilder);
        noteConfirm(orderRefundNoteListDto, ordersTotal,refundRecord,orderNodeBuilder);
    }
    public PlatformResult noteConfirm(OrderRefundNoteListDto orderRefundNoteListDto,OrdersTotal ordersTotal,StringBuilder orderNodeBuilder) {
        logger.info("退款单确认打印参数:{}",JSON.toJSONString(orderRefundNoteListDto));
    public PlatformResult noteConfirm(OrderRefundNoteListDto orderRefundNoteListDto,OrdersTotal ordersTotal,RefundRecord refundRecord
            ,StringBuilder orderNodeBuilder) {
        logger.info("退款单确认打印参数CRM:{}",JSON.toJSONString(orderRefundNoteListDto));
        Map<String, String> operator = ApiOrderUtil.getOperator(commonService, orderRefundNoteListDto.getOperationId());//获取操作人信息
        String operatorId= operator.get("operatorId");
        String operatorName=  operator.get("operatorName");
@@ -1681,7 +1698,7 @@
        List<OrderRefundNoteDto> orderRefundNoteDtos=orderRefundNoteListDto.getOrderRefundNoteDtos();
        if("crm".equals(ordersTotal.getAppIdCode())){
            //CRM退款
            handleCrmRefundOrder(orderRefundNoteDtos,ordersTotal,operatorId,operatorName,orderNodeBuilder);
            handleCrmRefundOrder(orderRefundNoteDtos,ordersTotal,refundRecord,operatorId,operatorName,orderNodeBuilder);
        }else {
            sqlSentence.sqlSentence(" refundroute=#{m.refundroute},refundNumberNo=#{m.refundNumberNo},refundName=#{m.refundName}, " +
                    " refundStoredTotal=#{m.refundStoredTotal},refundStatus=#{m.refundStatus},remarks=#{m.remarks},shopId=#{m.shopId}, " +
@@ -1723,7 +1740,8 @@
        return PlatformResult.success();
    }
    /**处理crm退款*/
    public void handleCrmRefundOrder(List<OrderRefundNoteDto> orderRefundNoteDtos,OrdersTotal ordersTotal,String operatorId, String operatorName,StringBuilder orderNodeBuilder){
    public void handleCrmRefundOrder(List<OrderRefundNoteDto> orderRefundNoteDtos,OrdersTotal ordersTotal,RefundRecord refundRecord
            ,String operatorId, String operatorName,StringBuilder orderNodeBuilder){
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> map=new HashMap<>();
        sqlSentence.setM(map);
@@ -1755,6 +1773,14 @@
            refundDto.setIsWholeOrder(0);
            refundDto.setRemarks("phis退款单退款,订单号:"+ordersTotal.getOrderNo());
            refundDto.setAmountModelList(amountModelList);
            refundDto.setOperatorId(operatorId);
            refundDto.setOperatorName(operatorName);
            if(OrderTotalConstants.STATUS_REFUND_FINSH==ordersTotal.getRefundStatus() &&
                    OrderTotalConstants.STATUS_CANCEL == ordersTotal.getStatus()){
                //全部退款完成则取消订单
                refundDto.setIsCancelOrder(BaseEntity.YES);
            }
            logger.info("调用crm退款入参:{}",JSONObject.toJSONString(refundDto));
            Result result= fOderService.refundOrder(refundDto);;
            logger.info("调用crm退款返回:{}",JSONObject.toJSONString(result));
@@ -1762,13 +1788,14 @@
                result.checkTips();
                if("100".equals(result.getCode())){
                    RefundReturnDto refundReturnDto=JSON.parseObject(JSONObject.toJSONString(result.getData()),RefundReturnDto.class);
                    if (RefundReturnDto.REFUND_STATUS_SUECCESS==refundReturnDto.getRefundStatus()){
                    if (RefundReturnDto.REFUND_STATUS_SUECCESS == refundReturnDto.getRefundStatus()){
                        orderNodeBuilder.append("-调用CRM退款金额:"+crmAmount+",返回成功返回流水号:"+refundReturnDto.getRefundNo()+",json:"+result);
                        logger.info("crm退款成功进行下面操作");
                    }else {
                        throw new PlatTipsException(PlatformCode.ERROR_TIPS,"请求crm退款接口报错,退款失败!退款状态不是成功状态");
                    }
                    //生成CRM回执记录
                    createCrmRefundReceipt(refundReturnDto,refundRecord,commonService);
                }else{
                    throw new PlatTipsException(PlatformCode.ERROR_TIPS,"请求crm退款接口报错,接口返回错误!:code不是100");
                }
@@ -1778,28 +1805,6 @@
        }
        logger.info("订单状态为:{}",ordersTotal.getRefundStatus());
        //通知crm
/*        if(OrderTotalConstants.STATUS_REFUND_FINSH==ordersTotal.getRefundStatus()){
            //全部退款完成
            //通知crm订单取消成功了
            OrderStatusDto orderStatusDto=new OrderStatusDto();
            orderStatusDto.setId(ordersTotal.getId());
            orderStatusDto.setOpName(operatorName);
            orderStatusDto.setOpId(operatorId);
            orderStatusDto.setCancelInfo("phis取消退款");
            orderStatusDto.setOpDetail("phis取消退款");
            try {
                logger.info("通知CRM订单号:{}退款成功请求参数:{}",ordersTotal.getOrderNo(),JSONObject.toJSONString(orderStatusDto));
                Result result=  fOderService.cancelOrder(orderStatusDto);
                logger.info("通知CRM订单号:{}退款成功返回参数:{}",ordersTotal.getOrderNo(),JSONObject.toJSONString(result));
                orderNodeBuilder.append("通知crm退款状态返回成功");
            }catch (Exception e){
                logger.info("通知crm订单号:{}退款成功错误:{}",ordersTotal.getOrderNo(),e.getMessage());
                orderNodeBuilder.append("通知crm退款状态返回失败");
            }
        }*/
        sqlSentence.sqlSentence(" refundroute=#{m.refundroute},refundNumberNo=#{m.refundNumberNo},refundName=#{m.refundName}, " +
                " refundStoredTotal=#{m.refundStoredTotal},refundStatus=#{m.refundStatus},remarks=#{m.remarks},shopId=#{m.shopId}, " +
@@ -1842,6 +1847,69 @@
    }
    /**
     * 生成CRM退款回执
     * @param refundReturnDto crm退款返回总结构
     * @param refundRecord 退款总单
     * @param commonService 映射
     */
    public static void createCrmRefundReceipt(RefundReturnDto refundReturnDto,RefundRecord refundRecord,CommonService commonService){
        try{
            if (RefundReturnDto.REFUND_STATUS_SUECCESS==refundReturnDto.getRefundStatus()
                    ||RefundReturnDto.REFUND_STATUS_PART==refundReturnDto.getRefundStatus()){
                StringBuilder crmReturnData = new StringBuilder();
                crmReturnData.append("<p>【CRM退款】</p>");
                crmReturnData.append("<p>CRM退款流水号:").append(refundReturnDto.getRefundNo()).append("</p>");
                crmReturnData.append("<p>已退款总金额:");
                crmReturnData.append(refundReturnDto.getRefundTotal());
                crmReturnData.append(";");
                crmReturnData.append("已退款其他金额:");
                crmReturnData.append(refundReturnDto.getRefundAmountTotal());
                crmReturnData.append(";");
                crmReturnData.append("已退款储值金:");
                crmReturnData.append(refundReturnDto.getRefundRecharge());
                crmReturnData.append(";");
                crmReturnData.append("已退款增值金:");
                crmReturnData.append(refundReturnDto.getRefundIncrement());
                crmReturnData.append(";");
                crmReturnData.append("已退款积分:");
                crmReturnData.append(refundReturnDto.getRefundIntegral());
                crmReturnData.append("</p>");
                crmReturnData.append("<p>退款方式:</p>");
                if(refundReturnDto.getRefundAmountModelDtoList() != null && refundReturnDto.getRefundAmountModelDtoList().size() > 0){
                    for(RefundAmountModelDto refundAmountModelDto1:refundReturnDto.getRefundAmountModelDtoList()){
                        crmReturnData.append("<p>");
                        switch (refundAmountModelDto1.getRefundType()){
                            case RefundAmountModelDto.REFUND_TYPE_WX:
                                crmReturnData.append("微信[CRM]:").append(refundAmountModelDto1.getAmountTotal());
                                break;
                            case RefundAmountModelDto.REFUND_TYPE_ZFB:
                                crmReturnData.append("支付宝[CRM]:").append(refundAmountModelDto1.getAmountTotal());
                                break;
                            default:
                                crmReturnData.append("[").append(refundAmountModelDto1.getRefundType()).append("]");
                                crmReturnData.append("未知方式[CRM]:").append(refundAmountModelDto1.getAmountTotal());
                        }
                        crmReturnData.append("</p>");
                    }
                }
                RefundRecordReceipt refundRecordReceipt = new RefundRecordReceipt();
                refundRecordReceipt.setReceiptSource(RefundRecordReceipt.RECEIPT_SOURCE_CRM);
                refundRecordReceipt.setReceiptSourceNo(refundReturnDto.getRefundNo());
                refundRecordReceipt.setReceiptSourceData(JSON.toJSONString(refundReturnDto));
                refundRecordReceipt.setReceiptType(RefundRecordReceipt.RECEIPT_TYPE_REFUND);
                refundRecordReceipt.setRemarks(crmReturnData.toString());
                refundRecordReceipt.setOperatorId(refundRecord.getOperatorId());
                refundRecordReceipt.setOperatorNo(refundRecord.getOperatorNo());
                refundRecordReceipt.setOperatorName(refundRecord.getOperatorName());
                refundRecordReceipt.setRefundRecordId(refundRecord.getId());
                commonService.insert(RefundRecordReceiptMapper.class,refundRecordReceipt);
            }
        }catch (Exception e){
            logger.error("退款生成CRM回执报错:{}",e);
        }
    }
    /**
     * 营销中心回调审批处理接口
     * @param aduitDto
     * @return
@@ -1855,7 +1923,7 @@
        map.put("applyId",aduitDto.getApplyId());
        sqlSentence.sqlSentence("SELECT * FROM cancel_order WHERE applyId=#{m.applyId} and isDel=0 ",map);
        CancelOrder cancelOrder=commonService.selectOne(CancelOrderMapper.class,sqlSentence);
        if(cancelOrder==null){
        if( cancelOrder == null ){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到该审核标识");
        }
        if(!CancelOrder.PENDING.equals(cancelOrder.getApprovalstatus())){
@@ -1882,7 +1950,15 @@
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到该审核的退款记录");
        }
        //订单节点日志
        OrdersNodeLog ordersNodeLog = new OrdersNodeLog();
        StringBuilder orderNodeBuilder = new StringBuilder();
        if(BaseEntity.NO.equals(aduitDto.getType())){
            orderNodeBuilder.append("审核不通过");
            orderNodeBuilder.append("-最后审核人:").append(aduitDto.getExamEmplName());
            //审核不通过
            cancelOrder.setApprovalstatus(CancelOrder.FAIL);
            cancelOrder.setEditTime(new Date());
@@ -1916,6 +1992,11 @@
            refundRecord.setEditTime(new Date());
            commonService.updateAll(RefundRecordMapper.class,refundRecord);
            //处理老带新的佣金,没有退款才退
            if(ordersTotal.getRefundStatus() == OrderTotalConstants.STATUS_REFUND_NONE){
                oldBlingNewRefundFail(refundRecord,orderNodeBuilder,commonService);
            }
            //拒绝审批需要还原回去储值金
            //判断是否是充值订单,是的话需要把前面预扣的还原
            if(OrderTotalConstants.TYPE_RECHARGE.equals(ordersTotal.getType())){
@@ -1933,6 +2014,12 @@
                }
            }
            ordersNodeLog.setCommonType(OrdersNodeLog.TYPE_COMMON_ORDER_REFUND);
            ordersNodeLog.setContent(orderNodeBuilder.toString());
            ordersNodeLog.setOrderId(ordersTotal.getId());
            commonService.insert(OrdersNodeLogMapper.class,ordersNodeLog);
            return PlatformResult.success("拒绝取消审核通过");
        }
@@ -1940,9 +2027,6 @@
        cancelOrder.setApprovalstatus(CancelOrder.SUCCESS);
        commonService.updateAll(CancelOrderMapper.class,cancelOrder);
        //订单节点日志
        OrdersNodeLog ordersNodeLog = new OrdersNodeLog();
        StringBuilder orderNodeBuilder = new StringBuilder();
        orderNodeBuilder.append("审核通过,开始处理退款");
@@ -1963,6 +2047,7 @@
        //获取该笔订单的项目详情
        List<Map<String, Object>> refundDetails=refundDetails(ordersTotal);
        // 退款信息集合
        List<OrderItemRefundDto> refundList=new ArrayList<>();
        //退款二级子订单信息集合
@@ -1972,7 +2057,7 @@
        OrderItemRefundDto orderItemRefundDto;
        OrderItemSourceRefundDto orderItemSourceRefundDto;
        for (Map<String, Object> refundDetail : refundDetails) {
            orderItemRefundDto=new OrderItemRefundDto();
            orderItemRefundDto = new OrderItemRefundDto();
            orderItemRefundDto.setOrderItemId(String.valueOf(refundDetail.get("id")));
            orderItemRefundDto.setType(String.valueOf(refundDetail.get("type")));
@@ -1980,7 +2065,8 @@
            orderItemRefundDto.setRemarks(orderRefundDto.getRemarks());
            orderItemRefundDto.setRefundReason(orderRefundDto.getRefundReason());
            if(OrderItemConstants.TYPE_PROMOTION.equals(orderItemRefundDto.getType()) || OrderItemConstants.CARD_BAG.equals(orderItemRefundDto.getType())){
            if(OrderItemConstants.TYPE_PROMOTION.equals(orderItemRefundDto.getType())
                    || OrderItemConstants.CARD_BAG.equals(orderItemRefundDto.getType())){
                orderItemRefundDto.setRefundNum(0);
                refundSonDetails= (List<Map<String, Object>>) refundDetail.get("list");
                orderItemSourceRefundDtos=new ArrayList<>();
@@ -2013,6 +2099,20 @@
        parameter.setRoleId(orderRefundDto.getRoleId());
        parameter.setPlatformSource(orderRefundDto.getPlatformSource());
        parameter.setRefundOperationType(BaseEntity.NO);
        parameter.setRemarks(orderRefundDto.getRemarks());
        parameter.setRefundReason(orderRefundDto.getRefundReason());
        parameter.setCouponList(parameter.getPayCouponList());
        //退款金额
        List<OrderPayMethodDto> refundPayMethodList = parameter.getPayMethodList();
        for(OrderPayMethodDto orderPayMethodDto:refundPayMethodList){
            orderPayMethodDto.setRefundNumberNo(orderPayMethodDto.getPayMethodNo());
            orderPayMethodDto.setRefundNumberName(orderPayMethodDto.getPayMethodName());
            orderPayMethodDto.setMoney(orderPayMethodDto.getPayTotal());
        }
        parameter.setRefundPayMethod(refundPayMethodList);
        //调用退款处理退款逻辑
        return partRefund(ordersTotal,parameter,thirtApplication);
    }
@@ -2175,9 +2275,7 @@
                if(OrderTotalConstants.STATUS_REFUND_FINSH==orderItemSon.getRefundStatus()){
                    oldRefundStatus=OrderTotalConstants.STATUS_REFUND_FINSH;
                    sqlMap.put("commonId", orderItemSon.getId());
                    sqlSentence.sqlSentence("SELECT * FROM  user_project_item   WHERE  commonId = #{m.commonId} AND isTransfer = 0  and  isDel = #{m.isDel} LIMIT 1 ",sqlMap);
                    userProjectItem=userProjectItemMapper.selectOne(sqlSentence);
                    userProjectItem = PartialRefundUtil.getUserProject(orderItemSon.getId(),commonService);
                    if(userProjectItem.getNotUsedNum()>0){
                        newRefundStatus=OrderTotalConstants.STATUS_REFUND_PART;
@@ -2212,9 +2310,7 @@
            for (OrderItem orderItem : orderItemList) {
                oldRefundStatus=OrderTotalConstants.STATUS_REFUND_FINSH;
                sqlMap.put("commonId", orderItem.getId());
                sqlSentence.sqlSentence("SELECT * FROM  user_project_item WHERE commonId = #{m.commonId} AND isTransfer = 0  and  isDel = #{m.isDel} LIMIT 1 ",sqlMap);
                userProjectItem=userProjectItemMapper.selectOne(sqlSentence);
                userProjectItem = PartialRefundUtil.getUserProject(orderItem.getId(),commonService);
                if(userProjectItem.getNotUsedNum()>0){
                    newRefundStatus=OrderTotalConstants.STATUS_REFUND_PART;
@@ -2258,4 +2354,143 @@
        commonService.updateAll(OrdersTotalMapper.class,ordersTotal);
    }
    /**作废退款*/
    @Override
    public void refundCancel(RefundCancelVo refundCancelVo, RefundRecord refundRecord,Employee employee,EmployeeRole employeeRole
            , ThirtApplication thirtApplication) {
        //判断退款单状态
        if(refundRecord.getRefundStatus() != RefundStatus.STATUS_SUCC_REFUND){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"操作失败,退款单状态错误!");
        }
        //获取订单信息
        OrdersTotal ordersTotal = ordersTotalMapper.selectOneByKey(refundRecord.getOrderId());
        if(ordersTotal == null){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"操作失败,获取订单信息失败!");
        }
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> values = new HashMap<>();
        StringBuilder sql = new StringBuilder();
        //填充数据,后面会用到
        refundRecord.setInvalidType(RefundRecord.OPERATOR_TYPE_EMPLOYEE);
        refundRecord.setInvalidRemarks(refundCancelVo.getRemarks());
        //****更新退款单信息,更新完退款单再去做剩下的操作
        values.put("refundStatus",RefundStatus.STATUS_REFUND_CANCEL);
        values.put("refundStatusOld",RefundStatus.STATUS_SUCC_REFUND);
        values.put("id",refundRecord.getId());
        values.put("invalidTime",new Date());
        values.put("invalidType",RefundRecord.OPERATOR_TYPE_EMPLOYEE);
        values.put("invalidRemarks",refundCancelVo.getRemarks());
        sql.append("refundStatus = #{m.refundStatus},invalidTime = #{m.invalidTime},invalidRemarks = #{m.invalidRemarks},invalidType = #{m.invalidType}");
        if(employee != null){
            refundRecord.setInvalidId(employee.getId());
            refundRecord.setInvalidNo(employee.getEmployeeNo());
            refundRecord.setInvalidName(employee.getCnName());
            values.put("invalidId",employee.getId());
            values.put("invalidNo",employee.getEmployeeNo());
            values.put("invalidName",employee.getCnName());
            sql.append(",invalidId = #{m.invalidId},invalidNo = #{m.invalidNo},invalidName = #{m.invalidName}");
        }
        if(employeeRole != null){
            refundRecord.setInvalidRoleNo(employeeRole.getRoleUniqueStr());
            refundRecord.setInvalidRoleName(employeeRole.getRoleName());
            values.put("invalidRoleNo",employeeRole.getRoleUniqueStr());
            values.put("invalidRoleName",employeeRole.getRoleName());
            sql.append(",invalidRoleNo = #{m.invalidRoleNo},invalidRoleName = #{m.invalidRoleName}");
        }
        if(thirtApplication != null){
            refundRecord.setInvalidAppId(thirtApplication.getAppId());
            refundRecord.setInvalidAppCode(thirtApplication.getAppIdCode());
            refundRecord.setInvalidAppName(thirtApplication.getName());
            values.put("invalidAppId",thirtApplication.getAppId());
            values.put("invalidAppCode",thirtApplication.getAppIdCode());
            values.put("invalidAppName",thirtApplication.getName());
            sql.append(",invalidAppId = #{m.invalidAppId},invalidAppCode = #{m.invalidAppCode},invalidAppName = #{m.invalidAppName}");
        }
        sql.append(" WHERE id = #{m.id} AND refundStatus = #{m.refundStatusOld}");
        sqlSentence.sqlUpdate(sql.toString(),values);
        if(refundRecordMapper.updateWhere(sqlSentence) != 1){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"操作失败,退款单状态已发生变化!");
        }
        //判断订单类型
        if(OrderTotalConstants.TYPE_RECHARGE.equals(ordersTotal.getType())){
            //充值订单
            OrderRefundCancelTool.rechargeHandle(ordersTotal,refundRecord,1,commonService);
        }else{
            //处理子单
            OrderRefundCancelTool.refundRecordItemHandle(ordersTotal,refundRecord,commonService);
        }
        //处理订单活动
        OrderRefundCancelTool.activityRuleHandle(ordersTotal,refundRecord,1,commonService);
        //处理订单优惠券
        OrderRefundCancelTool.handCoupon(ordersTotal,refundRecord,commonService);
        //处理总退款方式
        OrderRefundCancelTool.refundRecordMotnedHandle(refundRecord,ordersTotal,commonService);
        //****更改总订单退款状态
        values.clear();
        values.put("orderId",ordersTotal.getId());
        sqlSentence.sqlSentence("select * from order_item WHERE orderId=#{m.orderId} and isDel=0",values);
        List<OrderItem> orderItemList=commonService.selectList(OrderItemMapper.class,sqlSentence);
        values.clear();
        values.put("oldStatus",ordersTotal.getStatus());
        values.put("oldRefundStatus",ordersTotal.getRefundStatus());
        List<Integer> collect = orderItemList.stream().map(OrderItem::getRefundStatus).collect(Collectors.toList());
        if(collect.contains(OrderTotalConstants.STATUS_REFUND_PART)){
            ordersTotal.setStatus(OrderTotalConstants.STATUS_PAY);
            ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_PART);
            ordersTotal.setReTotal(orderItemList.stream().map(OrderItem::getReTotal).reduce(BigDecimal.ZERO,BigDecimal::add));
        }else if (collect.contains(OrderTotalConstants.STATUS_REFUND_NONE) && collect.contains(OrderTotalConstants.STATUS_REFUND_FINSH)){
            ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_PART);
            ordersTotal.setStatus(OrderTotalConstants.STATUS_PAY);
            ordersTotal.setReTotal(orderItemList.stream().map(OrderItem::getReTotal).reduce(BigDecimal.ZERO,BigDecimal::add));
        }else if (collect.contains(OrderTotalConstants.STATUS_REFUND_NONE)){
            ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_NONE);
            ordersTotal.setStatus(OrderTotalConstants.STATUS_PAY);
            ordersTotal.setReTotal(BigDecimal.ZERO);
        }else if (collect.contains(OrderTotalConstants.STATUS_REFUND_FINSH)){
            ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_FINSH);
            ordersTotal.setStatus(OrderTotalConstants.STATUS_CANCEL);
            ordersTotal.setReTotal(orderItemList.stream().map(OrderItem::getReTotal).reduce(BigDecimal.ZERO,BigDecimal::add));
        }else {
            if(OrderTotalConstants.TYPE_RECHARGE.equals(ordersTotal.getType())){
                if(ordersTotal.getReTotal().compareTo(refundRecord.getRefundTotal()) == 0){
                    ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_NONE);
                    ordersTotal.setStatus(OrderTotalConstants.STATUS_PAY);
                    ordersTotal.setReTotal(ordersTotal.getReTotal().subtract(refundRecord.getRefundTotal()));
                }else if(ordersTotal.getReTotal().compareTo(refundRecord.getRefundTotal()) > 0){
                    ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_PART);
                    ordersTotal.setStatus(OrderTotalConstants.STATUS_PAY);
                    ordersTotal.setReTotal(ordersTotal.getReTotal().subtract(refundRecord.getRefundTotal()));
                }
            }else{
                ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_NONE);
                ordersTotal.setStatus(OrderTotalConstants.STATUS_PAY);
                ordersTotal.setReTotal(ordersTotal.getReTotal().subtract(refundRecord.getRefundTotal()));
            }
        }
        ordersTotal.setIsSyncOrder(BaseEntity.NO);
        values.put("isSyncOrder",BaseEntity.NO);
        values.put("status",ordersTotal.getStatus());
        values.put("refundStatus",ordersTotal.getRefundStatus());
        values.put("reTotal",ordersTotal.getReTotal());
        values.put("id",ordersTotal.getId());
        sqlSentence.sqlUpdate("isSyncOrder = #{m.isSyncOrder},status = #{m.status},refundStatus = #{m.refundStatus},reTotal = #{m.reTotal}" +
                " WHERE id = #{m.id} AND status = #{m.oldStatus} AND refundStatus = #{m.oldRefundStatus}",values);
        if(commonService.updateWhere(OrdersTotalMapper.class,sqlSentence) != 1){
            throw new TipsException("作废失败,订单状态已发生改变!");
        }
    }
}