package com.bonus.core.order.common.business.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.NumberUtil;
import com.alibaba.nacos.shaded.com.google.common.collect.Lists;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.constant.LeConstants;
import com.bonus.core.allocation.api.AllocHolidayApi;
import com.bonus.core.allocation.api.AllocOrderMetadataApi;
import com.bonus.core.allocation.api.FlowApi;
import com.bonus.core.allocation.canteen.dto.AllocCanteenOrderDTO;
import com.bonus.core.allocation.flow.enums.FlowDefinitionEum;
import com.bonus.core.common.enums.MetadataModelTypeEnum;
import com.bonus.core.common.utils.JavaxValidateUtils;
import com.bonus.core.common.utils.LogUtil;
import com.bonus.core.drp.api.DrpServiceApi;
import com.bonus.core.drp.dto.RefundRepairInventoryDTO;
import com.bonus.core.drp.dto.RefundRepairInventoryDetailDTO;
import com.bonus.core.marketing.v2.api.MarketApi;
import com.bonus.core.menu.api.MenuDishesApi;
import com.bonus.core.menu.dto.MenuRecipeChangeSurplusNum;
import com.bonus.core.menu.model.AllocMealtimeModel;
import com.bonus.core.order.android.dto.business.OrderDishesAndroidBusiness;
import com.bonus.core.order.client.OrderModuleClient;
import com.bonus.core.order.client.po.CustPayInfoQueryParam;
import com.bonus.core.order.client.po.MealtimeQueryParam;
import com.bonus.core.order.client.po.MetaDataValueParam;
import com.bonus.core.order.common.business.OrderPlaceBusiness;
import com.bonus.core.order.common.business.OrderRefundBusiness;
import com.bonus.core.order.common.constants.*;
import com.bonus.core.order.common.dto.OrderDetailRefundDTO;
import com.bonus.core.order.common.dto.OrderRefundParam;
import com.bonus.core.order.common.model.*;
import com.bonus.core.order.common.service.*;
import com.bonus.core.order.common.vo.OrderRefundFeeConfigVO;
import com.bonus.core.order.common.vo.OrderRefundResultVO;
import com.bonus.core.order.custom.OrderCustomBusiness;
import com.bonus.core.order.utils.LeNumUtil;
import com.bonus.core.pay.api.PayApi;
import com.bonus.core.pay.api.TradeRecordApi;
import com.bonus.core.pay.api.dto.UnifyRefundDTO;
import com.bonus.core.pay.api.vo.UnifyRefundVO;
import com.bonus.core.pay.common.constants.PayStateEnum;
import com.bonus.core.supermarket.api.SupermarketApi;
import com.bonus.core.order.mq.OrderMessageSend;
import com.bonus.i18n.I18n;
import com.bonus.utils.id.Id;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class OrderRefundBusinessImpl implements OrderRefundBusiness {
   private static final Logger log = LoggerFactory.getLogger(OrderRefundBusinessImpl.class);
   @Lazy
   @Autowired
   protected OrderPlaceBusiness orderPlaceBusiness;
   @Lazy
   @Autowired
   protected OrderDishesAndroidBusiness orderDishesAndroidBusiness;
//   @Lazy
//   @Autowired
//   protected OrderWeightBusiness orderWeightBusiness;
   @Lazy
   @Autowired
   protected OrderCustomBusiness orderCustomBusiness;
   @Lazy
   @Autowired
   protected OrderInfoService orderInfoService;
   @Lazy
   @Autowired
   protected OrderRefundService orderRefundService;
   @Lazy
   @Autowired
   protected OrderDetailService orderDetailService;
   @Lazy
   @Autowired
   protected OrderRefundDetailService orderRefundDetailService;
//   @Lazy
//   @Autowired
//   protected OrdPrintBaseServiceImpl ordPrintBaseService;
   @Autowired
   @Lazy
   protected OrderDeliveryService orderDeliveryService;
   @Autowired
   @Lazy
   protected OrderAmountDetailService orderAmountDetailService;
   @Autowired
   @Lazy
   protected OrderAmountChangeService orderAmountChangeService;
   @Autowired
   @Lazy
   protected OrderModuleClient orderModuleClient;
   @Lazy
   @Autowired
   protected AllocOrderMetadataApi allocOrderMetadataApi;
   @Lazy
   @Autowired
   protected SupermarketApi supermarketApi;
   @Lazy
   @Autowired
   protected PayApi payApi;
   @Autowired
   @Lazy
   protected DrpServiceApi drpServiceApi;
   @Autowired
   @Lazy
   protected MenuDishesApi menuDishesApi;
   @Autowired
   @Lazy
   protected TradeRecordApi tradeRecordApi;
   @Autowired
   @Lazy
   protected MarketApi marketApi;
   @Autowired
   @Lazy
   protected FlowApi flowApi;
   @Autowired
   @Lazy
   protected AllocHolidayApi allocHolidayApi;

//   public void orderCancel(OrderInfo orderInfo) {
//      if (!this.orderCustomBusiness.refund().willCancelOrder(orderInfo)) {
//         this.orderCustomBusiness.refund().didCancelOrder(orderInfo);
//      } else {
//         orderInfo.setOrderState(OrderStateEnum.CANCEL.getKey());
//         orderInfo.setPayState(PayStateEnum.PAY_CLOSE.getKey());
//         this.orderInfoService.updateOrderState(orderInfo.getOrderId(), orderInfo.getOrderDate(), orderInfo.getPayState(), orderInfo.getOrderState(), (Integer)null, (String)null);
//         List<OrderDetail> orderDetailList = this.orderDetailService.getOrderDetailList(orderInfo.getOrderId(), orderInfo.getOrderDate());
//         this.marketApi.disableMarketRecord(CollUtil.toList(new Long[]{orderInfo.getOrderId()}));
//         this.orderPlaceBusiness.inventoryRestore(orderInfo, orderDetailList);
//         OrderMessageSend.orderV3Canceled(orderInfo, orderDetailList);
//         this.orderCustomBusiness.refund().didCancelOrder(orderInfo);
//      }
//   }

   public OrderRefundResultVO orderRefund(OrderRefundParam refundParam, OrderRefundBizEnum biz) {
      LogUtil.info("[订单退款]入参：", refundParam, biz);
      this.refuncParamCheck(refundParam, biz);
      OrderInfo orderInfo = LeNumUtil.isValidId(refundParam.getOrderId()) ? this.orderInfoService
              .checkAndGetOrderInfo(refundParam.getOrderId()) : this.orderInfoService
              .checkAndGetOrderInfoByMacOrderId(refundParam.getMacOrderId());
      this.orderPlaceBusiness.orderHandlerLock(orderInfo.getOrderId().toString(), 20);

      OrderRefundResultVO var8;
      try {
         List<OrderDetail> detailList = this.orderDetailService.getOrderDetailList(orderInfo.getOrderId(), orderInfo.getOrderDate());
         this.checkOrdRefundRule(orderInfo, detailList, refundParam, biz);
         OrderRefund orderRefund = this.packageOrderRefund(orderInfo, refundParam.getMacRefundId(), refundParam.getRemark(), refundParam.getResressPicurl(), refundParam.getNeedCheckFlag());
         List<OrderRefundDetail> refundDetailList = this.packageRefundDetailList(orderRefund.getOrderRefundId(), refundParam, detailList);
         this.orderCustomBusiness.refund().didPackageRefundInfo(orderInfo, detailList, orderRefund, refundDetailList, refundParam, biz);
         this.calcRefundDetailAmount(orderInfo, detailList, orderRefund, refundDetailList, refundParam.getRefundAmount(), refundParam.getNeedCheckFlag(), biz);
         OrderRefundFeeConfigVO feeVO = this.calcFeeRate(orderInfo, detailList, orderRefund, refundDetailList, biz);
         if (!LeConstants.COMMON_YES.equals(refundParam.getIfTrial())) {
            if (Boolean.TRUE.equals(refundParam.getNeedCheckFlag())) {
               this.createFlowIfNecessary(orderInfo, orderRefund, refundDetailList, detailList);
               this.saveOrderRefund(orderRefund, orderInfo, refundDetailList, detailList, biz);
               var8 = OrderRefundResultVO.of(orderInfo, orderRefund, feeVO);
               return var8;
            }

            this.calcRefundRealAmount(orderInfo, detailList, orderRefund, refundDetailList, refundParam.ifCustomRefundAmount());
            this.checkRefundAmountLimit(orderInfo, orderRefund);
            UnifyRefundDTO refundDTO = this.packagePayRefundDTO(orderInfo, orderRefund, detailList, refundDetailList);
            this.saveOrderRefund(orderRefund, orderInfo, refundDetailList, detailList, biz);
            this.orderCustomBusiness.refund().willPayRefund(refundDTO, orderInfo, detailList, orderRefund, refundDetailList, biz);
            UnifyRefundVO refundVO = this.payApi.refund(refundDTO);
            OrderRefundResultVO resultVO = this.payRefundResultHandler(refundVO, orderInfo, orderRefund, detailList, refundDetailList);
            resultVO.fillFeeConfigVO(feeVO);
            OrderRefundResultVO var11 = resultVO;
            return var11;
         }

         var8 = OrderRefundResultVO.of(orderInfo, orderRefund, feeVO);
      } catch (Exception var15) {
         log.error("[订单退款]退款失败，订单信息：{}，退款参数：{}，退款业务：{}", new Object[]{orderInfo, refundParam, biz, var15});
         throw var15;
      } finally {
         this.orderPlaceBusiness.orderHandlerUnLock(orderInfo.getOrderId().toString());
      }

      return var8;
   }

//   public void orderCorrect(OrderPartRefundDTO orderPartRefundDTO, OrderRefundBizEnum biz) {
//      if (CollUtil.isEmpty(orderPartRefundDTO.getDetailRefundList())) {
//         throw new LeException(I18n.getMessage("order.buffet.correct-lack-detail", new Object[0]));
//      } else if (ObjectUtil.isEmpty(orderPartRefundDTO.getMacOrderId())) {
//         throw new LeException(I18n.getMessage("order.buffet.correct-lack-mac-order-id", new Object[0]));
//      } else {
//         List<OrderInfo> orderInfoList = this.orderInfoService.listOrderInfoByMacOrderId(orderPartRefundDTO.getMacOrderId(), LocalDate.now().minusMonths(1L), LocalDate.now().plusMonths(1L));
//         if (CollUtil.isEmpty(orderInfoList)) {
//            throw new LeException(I18n.getMessage("order.no-order", new Object[0]));
//         } else if (!OrderStateEnum.isWaitPlaceState(((OrderInfo)orderInfoList.get(0)).getOrderState())) {
//            throw new LeException(OrderTips.orderStateWrong(((OrderInfo)orderInfoList.get(0)).getOrderState()));
//         } else {
//            List<Long> orderIds = (List)orderInfoList.stream().map(OrderInfo::getOrderId).collect(Collectors.toList());
//            List<LocalDate> orderDates = (List)orderInfoList.stream().map(OrderInfo::getOrderDate).collect(Collectors.toList());
//            Map<Long, OrderDetail> orderDetailMap = (Map)this.orderDetailService.getOrderDetailList((List)orderIds, (Collection)orderDates).stream().collect(Collectors.toMap(OrderDetail::getDetailId, Function.identity()));
//            if (orderPartRefundDTO.getDetailRefundList().stream().anyMatch((s) -> {
//               return orderDetailMap.get(s.getDetailId()) == null;
//            })) {
//               throw new LeException(OrderTips.refundDetailNotExists());
//            } else {
//               Iterator var7 = orderPartRefundDTO.getDetailRefundList().iterator();
//
//               while(var7.hasNext()) {
//                  OrderDetailRefundDTO detailRefundDTO = (OrderDetailRefundDTO)var7.next();
//                  this.orderRefundService.removeUnPassCorrectByMacOrderId(orderPartRefundDTO.getMacOrderId(), ((OrderDetailRefundDTO)orderPartRefundDTO.getDetailRefundList().get(0)).getDetailId());
//                  List<OrderRefundDetail> refundDetailList = new ArrayList();
//                  OrderDetail orderDetail = (OrderDetail)orderDetailMap.get(detailRefundDTO.getDetailId());
//                  OrderRefund refund = this.packageCorrect(orderPartRefundDTO, orderDetail.getOrderId());
//                  OrderRefundDetail refundDetail = new OrderRefundDetail(detailRefundDTO.getDetailId(), detailRefundDTO.getQuantity(), detailRefundDTO.getQuantity());
//                  refundDetail.setOrderRefundId(refund.getOrderRefundId());
//                  refundDetailList.add(refundDetail);
//                  this.orderRefundService.insertOrderRefundInfo(refund);
//                  this.orderRefundDetailService.batchInsertOrderRefundDetail(refundDetailList);
//                  if (!biz.ifFromUser()) {
//                     OrderCheckDTO orderCheckDTO = this.packOrderCheckDTOFromCorrect(refund, refundDetailList);
//                     this.orderCheck(orderCheckDTO);
//                  }
//               }
//
//            }
//         }
//      }
//   }
//
//   public void orderCheck(OrderCheckDTO orderCheckDTO) {
//      LogUtil.info("[退款审核] 入参：", orderCheckDTO);
//      JavaxValidateUtils.validate(orderCheckDTO);
//      OrderRefund orderRefund = this.getAndCheckOrderRefund(orderCheckDTO.getOrderRefundId());
//      if (ApplyTypeEnum.REFUND.getKey().equals(orderRefund.getApplyType())) {
//         this.orderRefundCheck(orderRefund, orderCheckDTO);
//      } else {
//         this.orderCorrectCheck(orderRefund, orderCheckDTO);
//         this.orderWeightBusiness.didUpdateCorrect(orderRefund.getMacOrderId());
//      }
//
//   }
//
//   public void didEndOrderRefundFlow(Long orderRefundId, boolean isPass, String remark) {
//      if (isPass) {
//         OrderRefund orderRefund = this.getAndCheckOrderRefund(orderRefundId);
//         List<OrderRefundDetail> refundDetailList = this.orderRefundDetailService.listByOrderRefundId(orderRefund.getOrderRefundId());
//         OrderInfo orderInfo = this.orderInfoService.getById(orderRefund.getOrderId());
//         List<OrderDetail> detailList = this.orderDetailService.getOrderDetailList(orderInfo.getOrderId(), orderInfo.getOrderDate());
//         UnifyRefundDTO refundDTO = this.packagePayRefundDTO(orderInfo, orderRefund, detailList, refundDetailList);
//         orderRefund.setCheckState(CheckStateEnum.REFUNDING.getKey());
//         this.orderRefundService.updateCheckState(orderRefund.getOrderRefundId(), CheckStateEnum.REFUNDING.getKey(), (String)null);
//         this.orderCustomBusiness.refund().willPayRefund(refundDTO, orderInfo, detailList, orderRefund, refundDetailList, OrderRefundBizEnum.CHECK_PASS);
//         UnifyRefundVO refundVO = this.payApi.refund(refundDTO);
//         this.payRefundResultHandler(refundVO, orderInfo, orderRefund, detailList, refundDetailList);
//      } else {
//         log.info("退款审核不通过流程结束，退款单id：{}，备注：{}", orderRefundId, remark);
//      }
//
//   }
//
//   public void transferUncheckCorrectAfterOrderCreated(String macOrderId) {
//      try {
//         List<OrderInfo> orderInfoList = this.orderInfoService.listOrderInfoByMacOrderId(macOrderId);
//         List<Long> orderIds = (List)orderInfoList.stream().map(OrderInfo::getOrderId).collect(Collectors.toList());
//         List<LocalDate> orderDates = (List)orderInfoList.stream().map(OrderInfo::getOrderDate).collect(Collectors.toList());
//         List<OrderRefund> waitCheckCorrectList = this.orderRefundService.listByOrderIds(orderIds, ApplyTypeEnum.CORRECT.getKey(), CheckStateEnum.WAIT.getKey());
//         if (CollUtil.isEmpty(waitCheckCorrectList)) {
//            return;
//         }
//
//         List<OrderRefundDetail> allOrderRefundDetails = this.orderRefundDetailService.listByOrderRefundIds((List)waitCheckCorrectList.stream().map(OrderRefund::getOrderRefundId).collect(Collectors.toList()));
//         List<OrderDetail> allOrderDetails = this.orderDetailService.getOrderDetailList((List)orderIds, (Collection)orderDates);
//         Iterator var8 = waitCheckCorrectList.iterator();
//
//         while(var8.hasNext()) {
//            OrderRefund orderRefund = (OrderRefund)var8.next();
//            OrderInfo orderInfo = (OrderInfo)orderInfoList.stream().filter((s) -> {
//               return s.getOrderId().equals(orderRefund.getOrderId());
//            }).findFirst().orElse((Object)null);
//            List<OrderDetail> detailList = (List)allOrderDetails.stream().filter((s) -> {
//               return s.getOrderId().equals(orderRefund.getOrderId());
//            }).collect(Collectors.toList());
//            List<OrderRefundDetail> refundDetailList = (List)allOrderRefundDetails.stream().filter((s) -> {
//               return s.getOrderRefundId().equals(orderRefund.getOrderRefundId());
//            }).collect(Collectors.toList());
//            this.updateCorrectToRefund(orderRefund, refundDetailList, detailList);
//            this.calcRefundDetailAmount(orderInfo, detailList, orderRefund, refundDetailList, (BigDecimal)null, true, OrderRefundBizEnum.MOBILE_PART);
//            this.calcFeeRate(orderInfo, detailList, orderRefund, refundDetailList, OrderRefundBizEnum.MOBILE_PART);
//            this.createFlowIfNecessary(orderInfo, orderRefund, refundDetailList, detailList);
//            this.orderRefundService.updateOrderRefundById(orderRefund);
//            this.orderRefundDetailService.updateRefundDetailQuantity(refundDetailList);
//         }
//      } catch (Exception var13) {
//         log.error("自助餐下单后，处理未审核的纠错失败，macOrderId：{}", macOrderId, var13);
//      }
//
//   }
//
//   protected void orderRefundCheck(OrderRefund orderRefund, OrderCheckDTO orderCheckDTO) {
//      LogUtil.printArgsIn("orderRefundCheck", orderRefund, orderCheckDTO);
//      JavaxValidateUtils.validate(orderCheckDTO);
//      OrderInfo orderInfo = this.orderInfoService.checkAndGetOrderInfo(orderRefund.getOrderId());
//      List<OrderDetail> detailList = this.orderDetailService.getOrderDetailList(orderInfo.getOrderId(), orderInfo.getOrderDate());
//      List<OrderRefundDetail> refundDetailList = this.orderRefundDetailService.listByOrderRefundId(orderRefund.getOrderRefundId());
//      this.orderCustomBusiness.refund().willCheckRefund(orderCheckDTO, orderInfo, detailList, orderRefund, refundDetailList);
//      if (CheckStateEnum.UN_PASS.getKey().equals(orderCheckDTO.getCheckState())) {
//         orderRefund.setCheckState(orderCheckDTO.getCheckState());
//         orderRefund.setCheckResult(orderCheckDTO.getCheckResult());
//         orderRefund.setCheckTime(LocalDateTime.now());
//         orderRefund.setCheckBy(SecurityUtils.getUser().getUsername());
//         orderRefund.setRealRefundAmount(BigDecimal.ZERO);
//         this.rejectFlowIfNecessary(orderRefund, refundDetailList, orderCheckDTO);
//         this.orderRefundService.updateOrderRefundById(orderRefund);
//         OrderMessageSend.orderV3Refunded(orderInfo, detailList, CollUtil.newArrayList(new OrderAmountDetail[0]), orderRefund, refundDetailList, "");
//      } else if (CollUtil.isEmpty(orderCheckDTO.getDetailRefundList())) {
//         throw new LeException(OrderTips.refundLackDetail());
//      } else {
//         Map<Long, OrderRefundDetail> refundDetailMap = (Map)refundDetailList.stream().collect(Collectors.toMap(OrderRefundDetail::getDetailId, Function.identity()));
//         Map<Long, OrderDetail> orderDetailMap = (Map)detailList.stream().collect(Collectors.toMap(OrderDetail::getDetailId, Function.identity()));
//         Iterator var8 = orderCheckDTO.getDetailRefundList().iterator();
//
//         OrderDetailRefundDTO orderDetailRefundDTO;
//         do {
//            if (!var8.hasNext()) {
//               this.calcRefundDetailAmount(orderInfo, detailList, orderRefund, refundDetailList, (BigDecimal)null, false, OrderRefundBizEnum.CHECK_PASS);
//               this.calcRefundRealAmount(orderInfo, detailList, orderRefund, refundDetailList, false);
//               this.checkRefundAmountLimit(orderInfo, orderRefund);
//               if (this.nextFlowIfNecessary(orderRefund, refundDetailList, orderCheckDTO)) {
//                  log.info("退款审核继续流程");
//                  return;
//               }
//
//               UnifyRefundDTO refundDTO = this.packagePayRefundDTO(orderInfo, orderRefund, detailList, refundDetailList);
//               orderRefund.setCheckTime(LocalDateTime.now());
//               orderRefund.setCheckBy(SecurityUtils.getUser().getUsername());
//               orderRefund.setCheckState(CheckStateEnum.REFUNDING.getKey());
//               this.orderRefundService.updateOrderRefundById(orderRefund);
//               this.orderCustomBusiness.refund().willPayRefund(refundDTO, orderInfo, detailList, orderRefund, refundDetailList, OrderRefundBizEnum.CHECK_PASS);
//               UnifyRefundVO refundVO = this.payApi.refund(refundDTO);
//               OrderRefundResultVO orderRefundResultVO = this.payRefundResultHandler(refundVO, orderInfo, orderRefund, detailList, refundDetailList);
//               if (!orderRefundResultVO.ifSuccess()) {
//                  throw new LeException(orderRefundResultVO.getResultCode(), orderRefundResultVO.getResultMsg());
//               }
//
//               return;
//            }
//
//            orderDetailRefundDTO = (OrderDetailRefundDTO)var8.next();
//            OrderRefundDetail orderRefundDetail = (OrderRefundDetail)refundDetailMap.get(orderDetailRefundDTO.getDetailId());
//            orderRefundDetail.setRealQuantity(orderDetailRefundDTO.getQuantity());
//            orderRefundDetail.setRestoreQuantity(orderDetailRefundDTO.getRestoreQuantity());
//         } while(orderDetailMap.get(orderDetailRefundDTO.getDetailId()) != null);
//
//         throw new LeException(OrderTips.refundDetailNotExists());
//      }
//   }
//
//   protected void orderCorrectCheck(OrderRefund orderRefund, OrderCheckDTO orderCheckDTO) {
//      log.info("发起纠错审核: {} {}", orderRefund, orderCheckDTO);
//      RedisUtil.lock(OrderCacheConstants.weightOrderHandleLockKey(orderRefund.getMacOrderId()));
//
//      try {
//         orderRefund.setCheckState(orderCheckDTO.getCheckState());
//         orderRefund.setCheckResult(orderCheckDTO.getCheckResult());
//         orderRefund.setCheckTime(LocalDateTime.now());
//         if (CheckStateEnum.UN_PASS.getKey().equals(orderCheckDTO.getCheckState())) {
//            this.orderRefundService.updateOrderRefundById(orderRefund);
//         } else if (CollUtil.isEmpty(orderCheckDTO.getDetailRefundList())) {
//            throw new LeException(OrderTips.refundLackDetail());
//         } else {
//            OrderInfo orderInfo = this.orderInfoService.checkAndGetOrderInfo(orderRefund.getOrderId());
//            if (!OrderStateEnum.isWaitPlaceState(orderInfo.getOrderState())) {
//               throw new LeException(OrderTips.correctOrderStateWrong(orderInfo.getOrderState()));
//            } else {
//               List<Long> refundDetailIds = (List)orderCheckDTO.getDetailRefundList().stream().map(OrderDetailRefundDTO::getDetailId).collect(Collectors.toList());
//               Map<Long, OrderRefundDetail> refundDetailMap = (Map)this.orderRefundDetailService.listByOrderRefundId(orderRefund.getOrderRefundId()).stream().filter((s) -> {
//                  return refundDetailIds.contains(s.getDetailId());
//               }).collect(Collectors.toMap(OrderRefundDetail::getDetailId, Function.identity()));
//               Map<Long, OrderDetail> orderDetailMap = (Map)this.orderDetailService.getOrderDetailList(orderInfo.getOrderId(), orderInfo.getOrderDate()).stream().collect(Collectors.toMap(OrderDetail::getDetailId, Function.identity()));
//               Iterator var7 = orderCheckDTO.getDetailRefundList().iterator();
//
//               while(var7.hasNext()) {
//                  OrderDetailRefundDTO orderDetailRefundDTO = (OrderDetailRefundDTO)var7.next();
//                  OrderRefundDetail orderRefundDetail = (OrderRefundDetail)refundDetailMap.get(orderDetailRefundDTO.getDetailId());
//                  orderRefundDetail.setRealQuantity(orderDetailRefundDTO.getQuantity());
//                  OrderDetail orderDetail = (OrderDetail)orderDetailMap.get(orderDetailRefundDTO.getDetailId());
//                  if (orderDetail == null) {
//                     throw new LeException(OrderTips.refundDetailNotExists());
//                  }
//
//                  orderDetail.setQuantity(orderRefundDetail.getRealQuantity());
//               }
//
//               this.orderPlaceBusiness.calcNeedPayAmount(CollUtil.toList(new OrderInfo[]{orderInfo}), ListUtil.toList(orderDetailMap.values()));
//               this.orderRefundService.updateOrderRefundById(orderRefund);
//               this.orderRefundDetailService.updateRefundDetailQuantity(ListUtil.toList(refundDetailMap.values()));
//               this.orderInfoService.updateOrderInfo(orderInfo);
//               orderDetailMap.values().forEach((s) -> {
//                  this.orderDetailService.updateOrderDetailQuantity(s.getDetailId(), s.getOrderDate(), s.getQuantity(), s.getTotalAmount(), s.getCalcTotalAmount());
//               });
//            }
//         }
//      } finally {
//         RedisUtil.safeUnLock(OrderCacheConstants.weightOrderHandleLockKey(orderRefund.getMacOrderId()));
//      }
//   }

   protected void refuncParamCheck(OrderRefundParam orderRefundDTO, OrderRefundBizEnum biz) {
      if (orderRefundDTO.getOrderId() == null && CharSequenceUtil.isEmpty(orderRefundDTO.getMacOrderId())) {
         throw new ServiceException("订单id和mac订单id不能同时为空");
      } else {
         if (!biz.ifWholeRefund()) {
            if (CollUtil.isEmpty(orderRefundDTO.getDetailRefundList())) {
               throw new ServiceException(OrderTips.refundLackDetail());
            }

            orderRefundDTO.getDetailRefundList().forEach(JavaxValidateUtils::validate);
         }

      }
   }

   protected void checkOrdRefundRule(OrderInfo orderInfo, List<OrderDetail> detailList, OrderRefundParam refundParam,
                                     OrderRefundBizEnum biz) {
      if (!this.orderCustomBusiness.refund().willCheckOrderRefund(orderInfo, detailList, refundParam, biz)) {
         this.orderCustomBusiness.refund().didCheckOrderRefund(orderInfo, detailList, refundParam, biz);
      } else if (!PayStateEnum.isPaidState(orderInfo.getPayState())) {
         throw new ServiceException(I18n.getMessage("order.refund.not-allow-un-pay", new Object[0]));
      } else if (this.orderRefundService.existUnCheckOrder(orderInfo.getOrderId())) {
         throw new ServiceException(I18n.getMessage("order.refund.exists-un-checked", new Object[0]));
      } else if (this.orderRefundService.existRefundingOrder(orderInfo.getOrderId())) {
         throw new ServiceException(I18n.getMessage("order.refund.exists-refunding", new Object[0]));
      } else if (CharSequenceUtil.isNotBlank(orderInfo.getCouponId())) {
         log.info("[退单]: {}餐券订单,退单失败", orderInfo.getOrderId());
         throw new ServiceException(I18n.getMessage("order.refund.not-allow-coupon", new Object[0]));
      } else if (biz.ifWholeRefund() && OrderRefundStateEnum.PART_SUCC.getKey().equals(orderInfo.getOrderRefundState())) {
         throw new ServiceException(I18n.getMessage("order.refund.not-allow-part-refund", new Object[0]));
      } else {
         if (refundParam.ifCustomRefundAmount()) {
            if (refundParam.getRefundAmount().compareTo(orderInfo.calcUnRefundAmount()) > 0) {
               throw new ServiceException(I18n.getMessage("order.refund.refund-money-limit", new Object[0]));
            }
         } else {
            if (OrderRefundStateEnum.FINISH.getKey().equals(orderInfo.getOrderRefundState())) {
               throw new ServiceException(I18n.getMessage("order.refund.not-allow-all-refunded", new Object[0]));
            }

            if (!biz.ifWholeRefund()) {
               Iterator var5 = refundParam.getDetailRefundList().iterator();

               while(var5.hasNext()) {
                  OrderDetailRefundDTO detailRefundDTO = (OrderDetailRefundDTO)var5.next();
                  OrderDetail orderDetail = (OrderDetail)detailList.stream().filter((s) -> {
                     return s.getDetailId().equals(detailRefundDTO.getDetailId());
                  }).findFirst().orElseThrow(() -> {
                     return new ServiceException(OrderTips.refundDetailNotExists());
                  });
                  if (detailRefundDTO.getQuantity() > orderDetail.calcUnRefundGoodsNum()) {
                     throw new ServiceException(I18n.getMessage("order.refund.refund-times-limit", new Object[0]));
                  }
               }
            }
         }

         boolean ifAllowRefund;
         if (biz.ifFromUser()) {
            if (OrderTypeEnum.isShopType(orderInfo.getOrderType())) {
               ifAllowRefund = this.supermarketApi.ifAllowRefund(orderInfo.getCanteenId(), orderInfo.getOrderTime());
               if (!ifAllowRefund) {
                  throw new ServiceException(I18n.getMessage("order.refund.not-allow-time", new Object[0]));
               }
            } else if (OrderTypeEnum.isReserveShopType(orderInfo.getOrderType())) {
               if (!DishesStateEnum.UN_MAKE.getKey().equals(orderInfo.getDishesState())) {
                  throw new ServiceException(I18n.getMessage("order.refund.not-allow", new Object[0]));
               }
            } else if (OrderTypeEnum.isCanteenCategory(orderInfo.getOrderType())) {
               this.checkMobileRefundMealtime(orderInfo);
            }
         }

         ifAllowRefund = false;
         if (biz.ifFromUser()) {
            String refundApprove = this.orderModuleClient.metadataGetValue(MetaDataValueParam.ofMerchant(MetadataModelTypeEnum.MOBILE,
                    "ifRefundApprove"));
            ifAllowRefund = "1".equals(refundApprove);
         }

         refundParam.setNeedCheckFlag(ifAllowRefund);
         this.orderCustomBusiness.refund().didCheckOrderRefund(orderInfo, detailList, refundParam, biz);
      }
   }

   protected void checkMobileRefundMealtime(OrderInfo orderInfo) {
      LocalDate nowDate = LocalDate.now();
      String errorMsg = OrderTips.refundOutOfTime(orderInfo.getOrderDate().toString());
      if (nowDate.isAfter(orderInfo.getOrderDate())) {
         log.info("[退单]订单日期{}不允许退单", orderInfo.getOrderDate());
         throw new ServiceException(errorMsg);
      } else {
         Long canteenId = orderInfo.getCanteenId() != null && orderInfo.getCanteenId() != -1L ? orderInfo.getCanteenId() : null;
         Long stallId = orderInfo.getStallId() != null && orderInfo.getStallId() != -1L ? orderInfo.getStallId() : null;
         Map<Integer, AllocMealtimeModel> mealtimeModelMap = this.orderModuleClient.mealtimelist(MealtimeQueryParam
                 .of(canteenId, stallId)).stream().collect(Collectors.toMap(AllocMealtimeModel::getMealtimeType, Function.identity()));
         AllocMealtimeModel mealtimeModel = (AllocMealtimeModel)mealtimeModelMap.get(orderInfo.getMealtimeType());
         LocalTime deadLineTime = null;
         boolean isOrderBeforeToday = orderInfo.getOrderTime().toLocalDate().isBefore(nowDate);
         if (OrderTypeEnum.CURR_MEAL.getKey().equals(orderInfo.getOrderType())) {
            log.info("[退单]当餐点餐退单规则检查，餐次配置：{}", mealtimeModel);
            deadLineTime = mealtimeModel.getCurrRefundDeadline();
            errorMsg = OrderTips.refundFailedOfTime(mealtimeModel.getMealtimeType(), deadLineTime);
         } else {
            AllocCanteenOrderDTO canteenOrderDTO;
            LocalDate tomorrow;
            if (OrderTypeEnum.RESERVE_MEAL.getKey().equals(orderInfo.getOrderType())) {
               canteenOrderDTO = this.allocOrderMetadataApi.queryAvailableOrder(canteenId, stallId);
               tomorrow = this.allocHolidayApi.getWeekdayDeadLine(nowDate, 1, "1".equals(canteenOrderDTO.getIfReserveSkipHoliday()));
               log.info("[退单]预订餐退单规则检查，订单日期：{}, 下单时间：{}，餐次配置：{}，点餐配置：{}", new Object[]{orderInfo.getOrderDate(),
                       orderInfo.getOrderTime(), mealtimeModel, canteenOrderDTO});
               if (nowDate.equals(orderInfo.getOrderDate())) {
                  if (isOrderBeforeToday && CharSequenceUtil.isNotBlank(canteenOrderDTO.getReserveRefundEndTime())) {
                     deadLineTime = LocalTime.MIN;
                     errorMsg = I18n.getMessage("order.refund.failed-by-yesterday-time", new Object[0]);
                  } else {
                     deadLineTime = mealtimeModel.getReserveRefundDeadline();
                     errorMsg = OrderTips.refundFailedOfTime(mealtimeModel.getMealtimeType(), deadLineTime);
                  }
               } else if (tomorrow.equals(orderInfo.getOrderDate()) && CharSequenceUtil.isNotBlank(canteenOrderDTO.getReserveRefundEndTime())) {
                  LocalDate deadLineDay = this.allocHolidayApi.getWeekdayDeadLine(tomorrow, -1, "1".equals(canteenOrderDTO
                          .getIfReserveSkipHoliday()));
                  if (nowDate.isAfter(deadLineDay)) {
                     deadLineTime = LocalTime.MIN;
                     errorMsg = I18n.getMessage("order.refund.failed-by-yesterday-time", new Object[0]);
                  } else {
                     deadLineTime = LocalTime.parse(canteenOrderDTO.getReserveRefundEndTime());
                     errorMsg = I18n.getMessage("order.refund.out-of-time", new Object[]{deadLineTime});
                  }
               }
            } else if (OrderTypeEnum.isBookMealCategory(orderInfo.getOrderType())) {
               canteenOrderDTO = this.allocOrderMetadataApi.queryAvailableOrder(canteenId, stallId);
               tomorrow = nowDate.plusDays(1L);
               log.info("[退单]报餐退单规则检查，订单日期：{}, 下单时间：{}，餐次配置：{}，点餐配置：{}", new Object[]{orderInfo.getOrderDate(), orderInfo.getOrderTime(), mealtimeModel, canteenOrderDTO});
               long hour;
               if (nowDate.equals(orderInfo.getOrderDate())) {
                  if (isOrderBeforeToday && CharSequenceUtil.isNotBlank(canteenOrderDTO.getNearDinnerCancelBookChargeHour())) {
                     hour = Long.parseLong(canteenOrderDTO.getNearDinnerCancelBookChargeHour());
                     deadLineTime = hour <= (long)mealtimeModel.getStartTime().getHour() ? mealtimeModel.getStartTime().minusHours(hour) : LocalTime.MIN;
                     errorMsg = I18n.getMessage("order.refund.failed-by-yesterday-time", new Object[0]);
                  } else {
                     deadLineTime = mealtimeModel.getBookRefundDeadline();
                     errorMsg = OrderTips.refundFailedOfTime(mealtimeModel.getMealtimeType(), deadLineTime);
                  }
               } else if (tomorrow.equals(orderInfo.getOrderDate()) && CharSequenceUtil.isNotBlank(canteenOrderDTO.getNearDinnerCancelBookChargeHour())) {
                  hour = Long.parseLong(canteenOrderDTO.getNearDinnerCancelBookChargeHour());
                  deadLineTime = hour > (long)mealtimeModel.getStartTime().getHour() ? mealtimeModel.getStartTime().minusHours(hour) : LocalTime.MAX;
                  errorMsg = OrderTips.refundOutOfTime(deadLineTime.toString());
               }
            }
         }

         if (deadLineTime != null && LocalTime.now().isAfter(deadLineTime)) {
            throw new ServiceException(errorMsg);
         }
      }
   }

   protected OrderRefund packageOrderRefund(OrderInfo orderInfo, String macRefundId, String applyReason, String resressPicurl, boolean needCheckFlag) {
      OrderRefund orderRefund = new OrderRefund();
      orderRefund.setOrderRefundId(Id.next());
      orderRefund.setOrderId(orderInfo.getOrderId());
      orderRefund.setMacOrderId(orderInfo.getMacOrderId());
      orderRefund.setMacRefundId(macRefundId);
      orderRefund.setApplyTime(LocalDateTime.now());
      orderRefund.setApplyReason(applyReason);
      orderRefund.setApplyType(ApplyTypeEnum.REFUND.getKey());
      orderRefund.setResressPicurl(resressPicurl);
      if (needCheckFlag) {
         orderRefund.setCheckState(CheckStateEnum.WAIT.getKey());
         orderRefund.setIfQuickFail(LeConstants.COMMON_NO);
      } else {
         orderRefund.setCheckTime(LocalDateTime.now());
         orderRefund.setCheckBy(SecurityUtils.getUsername());
         orderRefund.setCheckState(CheckStateEnum.REFUNDING.getKey());
         orderRefund.setIfQuickFail(LeConstants.COMMON_YES);
      }

      return orderRefund;
   }

   protected List<OrderRefundDetail> packageRefundDetailList(Long orderRefundId,
                                                             OrderRefundParam refundParam,
                                                             List<OrderDetail> orderDetailList) {
      List<OrderRefundDetail> refundDetailList;
      if (CollUtil.isEmpty(refundParam.getDetailRefundList())) {
         boolean restoreInventory = LeConstants.COMMON_YES.equals(refundParam.getRestoreInventory());
         refundDetailList = orderDetailList.stream().map((s) -> {
            OrderRefundDetail dto = OrderRefundDetail.newDefaultInstance();
            dto.setDetailId(s.getDetailId());
            dto.setQuantity(s.calcUnRefundGoodsNum());
            dto.setRestoreQuantity(restoreInventory ? s.calcUnRefundGoodsNum() : 0);
            return dto;
         }).collect(Collectors.toList());
      } else if (refundParam.ifCustomRefundAmount()) {
         Map<Long, OrderDetailRefundDTO> detailParamMap = refundParam.getDetailRefundList().stream()
                 .collect(Collectors.toMap(OrderDetailRefundDTO::getDetailId, Function.identity()));
         refundDetailList = orderDetailList.stream().map((s) -> {
            OrderDetailRefundDTO detailParam = (OrderDetailRefundDTO)detailParamMap.get(s.getDetailId());
            if (detailParam != null) {
               return detailParam.convertToOrderRefundDetail();
            } else {
               OrderRefundDetail dto = OrderRefundDetail.newDefaultInstance();
               dto.setDetailId(s.getDetailId());
               dto.setQuantity(0);
               dto.setRestoreQuantity(0);
               return dto;
            }
         }).collect(Collectors.toList());
      } else {
         refundDetailList = refundParam.getDetailRefundList().stream().map(OrderDetailRefundDTO::convertToOrderRefundDetail)
                 .collect(Collectors.toList());
      }

      refundDetailList.forEach((s) -> {
         s.setOrderRefundId(orderRefundId);
         s.setRealQuantity(Boolean.TRUE.equals(refundParam.getNeedCheckFlag()) ? 0 : s.getQuantity());
      });
      return refundDetailList;
   }

   protected void calcRefundDetailAmount(OrderInfo orderInfo, List<OrderDetail> orderDetailList, OrderRefund orderRefund, List<OrderRefundDetail> refundDetailList, BigDecimal customRefundAmount, boolean needCheckFlag, OrderRefundBizEnum biz) {
      LogUtil.infoFieldsX("退单明细计算-参数", orderDetailList, OrderDetail.logFieldsRefund(), refundDetailList, OrderRefundDetail.logFields());
      Map<Long, OrderRefundDetail> refundDetailMap = refundDetailList.stream().collect(Collectors.toMap(OrderRefundDetail::getDetailId, (orderRefundDetail) -> {
         return orderRefundDetail;
      }));
      BigDecimal totalRefundAmount = BigDecimal.ZERO;
      List<OrderDetail> orderDetailListSorted = orderDetailList.stream().sorted(Comparator.comparing(OrderDetail::getRealAmount)).collect(Collectors.toList());
      Iterator var11 = orderDetailListSorted.iterator();

      while(true) {
         OrderDetail orderDetail;
         OrderRefundDetail refundDetail;
         do {
            if (!var11.hasNext()) {
               if (customRefundAmount != null && !BigDecimal.ZERO.equals(customRefundAmount)) {
                  orderRefund.setRefundAmount(customRefundAmount);
               } else if (orderRefund.getRefundAmount() == null || BigDecimal.ZERO.equals(orderRefund.getRefundAmount())) {
                  orderRefund.setRefundAmount(LeNumUtil.sumField(refundDetailList, OrderRefundDetail::getRefundAmount));
               }

               if (!needCheckFlag) {
                  if (customRefundAmount != null && !BigDecimal.ZERO.equals(customRefundAmount)) {
                     orderRefund.setRealRefundAmount(customRefundAmount);
                  } else {
                     orderRefund.setRealRefundAmount(LeNumUtil.sumField(refundDetailList, OrderRefundDetail::getRealRefundAmount));
                  }
               }

               this.orderCustomBusiness.refund().didCalcRefundDetailAmountV2(orderInfo, orderDetailList, orderRefund, refundDetailList, customRefundAmount, needCheckFlag, biz);
               LogUtil.infoFieldsX("退单明细计算-结果", orderDetailList, OrderDetail.logFieldsRefund(), refundDetailList, OrderRefundDetail.logFields());
               return;
            }

            orderDetail = (OrderDetail)var11.next();
            refundDetail = (OrderRefundDetail)refundDetailMap.get(orderDetail.getDetailId());
         } while(refundDetail == null);

         Integer refundQuantity = needCheckFlag ? refundDetail.getQuantity() : refundDetail.getRealQuantity();
         BigDecimal refundAmount;
         if (customRefundAmount != null && !BigDecimal.ZERO.equals(customRefundAmount)) {
            if (((OrderDetail)CollUtil.getLast(orderDetailListSorted)).getDetailId().equals(orderDetail.getDetailId())) {
               refundAmount = NumberUtil.sub(customRefundAmount, totalRefundAmount);
            } else {
               refundAmount = NumberUtil.equals(orderInfo.calcUnRefundAmount(), BigDecimal.ZERO) ? BigDecimal.ZERO : orderDetail.calcUnRefundAmount().multiply(customRefundAmount).divide(orderInfo.calcUnRefundAmount(), 0, RoundingMode.DOWN);
            }
         } else if (orderDetail.calcUnRefundGoodsNum().equals(refundQuantity)) {
            refundAmount = orderDetail.calcUnRefundAmount();
         } else if (orderDetail.calcUnRefundGoodsNum() == 0) {
            refundAmount = BigDecimal.ZERO;
         } else {
            refundAmount = orderDetail.calcUnRefundAmount().multiply(BigDecimal.valueOf((long)refundQuantity)).divide(BigDecimal.valueOf((long)orderDetail.calcUnRefundGoodsNum()), 0, RoundingMode.DOWN);
         }

         if (refundAmount.compareTo(orderDetail.calcUnRefundAmount()) > 0) {
            refundAmount = orderDetail.calcUnRefundAmount();
         }

         if (refundDetail.getRefundAmount() == null || BigDecimal.ZERO.equals(refundDetail.getRefundAmount())) {
            refundDetail.setRefundAmount(refundAmount);
         }

         if (!needCheckFlag) {
            refundDetail.setRealQuantity(refundQuantity);
            refundDetail.setRealRefundAmount(refundAmount);
         }

         totalRefundAmount = totalRefundAmount.add(refundAmount);
      }
   }

   protected OrderRefundFeeConfigVO calcFeeRate(OrderInfo orderInfo, List<OrderDetail> detailList, OrderRefund orderRefund, List<OrderRefundDetail> refundDetailList, OrderRefundBizEnum biz) {
      OrderRefundFeeConfigVO feeVO = new OrderRefundFeeConfigVO();
      if (!biz.ifFromUser()) {
         return feeVO;
      } else if (!OrderTypeEnum.isBookMealCategory(orderInfo.getOrderType())) {
         return feeVO;
      } else {
         AllocCanteenOrderDTO canteenOrderDTO = this.allocOrderMetadataApi.queryAvailableOrder(orderInfo.getCanteenId(), orderInfo.getStallId());
         log.info("[退单手续费]报餐计算，订单日期：{}, 下单时间：{}，点餐配置：{}", new Object[]{orderInfo.getOrderDate(), orderInfo.getOrderTime(), canteenOrderDTO});
         feeVO.setNotAllowedCancelHour(canteenOrderDTO.getNearDinnerCancelBookChargeHour());
         feeVO.setFeeTimeOfDayBefore(canteenOrderDTO.getDayBeforeCancelBookChargeTime());
         feeVO.setFeeRate(canteenOrderDTO.getCancelBookFeeRatio());
         if (CharSequenceUtil.isEmpty(feeVO.getFeeTimeOfDayBefore())) {
            log.info("[退单手续费]未配置手续费时间");
            return feeVO;
         } else if (NumberUtil.isNumber(feeVO.getFeeRate()) && NumberUtil.parseInt(feeVO.getFeeRate()) > 0 && NumberUtil.parseInt(feeVO.getFeeRate()) <= 100) {
            LocalDate dateBeforeOrderDate = orderInfo.getOrderDate().minusDays(1L);
            LocalDateTime feeStartTime = dateBeforeOrderDate.atTime(LocalTime.parse(feeVO.getFeeTimeOfDayBefore()));
            if (LocalDateTime.now().isAfter(feeStartTime)) {
               orderRefund.fillFeeAmountByFeeRate(NumberUtil.mul(feeVO.getFeeRate(), "0.01"));
               log.info("[退单手续费]手续费 {} {}", orderRefund.getFeeRate(), orderRefund.getFeeAmount());
            }

            this.orderCustomBusiness.refund().didCalcRefundFeeAmountV2(orderInfo, detailList, orderRefund, refundDetailList, biz);
            return feeVO;
         } else {
            log.info("[退单手续费]未正确配置手续费 {}", feeVO.getFeeRate());
            return feeVO;
         }
      }
   }

   protected void calcRefundRealAmount(OrderInfo orderInfo, List<OrderDetail> detailList, OrderRefund orderRefund, List<OrderRefundDetail> refundDetailList, boolean ifCustomRefundAmount) {
      BigDecimal realRefundAmount = orderRefund.getRealRefundAmount();
      Map<Long, OrderRefundDetail> refundDetailMap = refundDetailList.stream().collect(Collectors.toMap(OrderRefundDetail::getDetailId, Function.identity()));
      boolean hasRefundAll = detailList.stream().allMatch((s) -> {
         OrderRefundDetail orderRefundDetail = (OrderRefundDetail)refundDetailMap.get(s.getDetailId());
         return orderRefundDetail != null ? s.getQuantity().equals(orderRefundDetail.getRealQuantity() + s.getGoodsRefundNum()) : s.getQuantity().equals(s.getGoodsRefundNum());
      });
      if (hasRefundAll && !ifCustomRefundAmount) {
         List<OrderAmountChange> additionalAmountList = this.orderAmountChangeService.listByOrderIds(CollUtil.toList(orderInfo.getOrderId()), CollUtil.toList(new LocalDate[]{orderInfo.getOrderDate()})).stream().filter((s) -> {
            return ChangeDetailTypeEnum.ifAdditionalFee(s.getChangeDetailType());
         }).collect(Collectors.toList());

         OrderAmountChange orderAmountChange;
         for(Iterator var10 = additionalAmountList.iterator(); var10.hasNext(); realRefundAmount = realRefundAmount.add(orderAmountChange.getChangeAmount().abs())) {
            orderAmountChange = (OrderAmountChange)var10.next();
         }

         orderRefund.setRealRefundAmount(realRefundAmount);
      }

      orderRefund.fillFeeAmountByFeeRate(orderRefund.getFeeRate());
      orderRefund.setRealRefundAmount(realRefundAmount.subtract(orderRefund.getFeeAmount()));
   }

   protected void checkRefundAmountLimit(OrderInfo orderInfo, OrderRefund orderRefund) {
      BigDecimal realRefundAmount = orderRefund.getRealRefundAmount();
      BigDecimal orderAlreadyRefundAmount = this.orderRefundService.getOrderRealRefundAmount(orderRefund.getOrderId());
      BigDecimal unRefundAmount = orderInfo.getRealAmount().subtract(orderAlreadyRefundAmount);
      log.info("退款金额检查：订单已退：{} 订单未退：{} 本次退款：{}", new Object[]{orderAlreadyRefundAmount, unRefundAmount, realRefundAmount});
      if (realRefundAmount.compareTo(unRefundAmount) > 0) {
         realRefundAmount = unRefundAmount;
      }

      orderRefund.setRealRefundAmount(realRefundAmount);
   }

   protected UnifyRefundDTO packagePayRefundDTO(OrderInfo orderInfo, OrderRefund orderRefund, List<OrderDetail> orderDetailList,
                                                List<OrderRefundDetail> refundDetailList) {
      LogUtil.printArgsIn("orderPayRefund", orderInfo, orderRefund);
      UnifyRefundDTO payRefundDTO = new UnifyRefundDTO();
      payRefundDTO.setRefundAmount(orderRefund.getRealRefundAmount());
      payRefundDTO.setOrderRechargeId(orderInfo.getOrderId());
      payRefundDTO.setRefundId(orderRefund.getOrderRefundId());
      Map<Long, OrderDetail> orderDetailMap = orderDetailList.stream().collect(Collectors.toMap(OrderDetail::getDetailId,
              Function.identity()));
      payRefundDTO.setDetailList(refundDetailList.stream().map((s) -> {
         return UnifyRefundDTO.Detail.of(s, (OrderDetail)orderDetailMap.get(s.getDetailId()));
      }).collect(Collectors.toList()));
      return payRefundDTO;
   }
//
//   protected OrderRefund getAndCheckOrderRefund(Long orderRefundId) {
//      OrderRefund orderRefund = this.orderRefundService.getOrderRefundById(orderRefundId);
//      if (ObjectUtil.isNull(orderRefund)) {
//         log.info("[退单审核]退单{}信息不存在", orderRefundId);
//         throw new LeException(I18n.getMessage("order.no-refund-order", new Object[0]));
//      } else if (!CheckStateEnum.WAIT.getKey().equals(orderRefund.getCheckState())) {
//         log.info("[退单审核]退单{}信息审核状态{}不正确", orderRefundId, orderRefund.getCheckState());
//         throw new LeException(I18n.getMessage("order.refund.repeated-check", new Object[0]));
//      } else {
//         return orderRefund;
//      }
//   }

   public OrderRefundResultVO payRefundResultHandler(UnifyRefundVO refundVO, OrderInfo orderInfo, OrderRefund orderRefund, List<OrderDetail> detailList, List<OrderRefundDetail> refundDetailList) {
      LogUtil.info("退款结果：", refundVO);
      OrderRefundResultVO customVO = this.orderCustomBusiness.refund().willHandleRefundResultV2(refundVO, orderInfo, detailList, orderRefund, refundDetailList);
      if (customVO != null) {
         return this.orderCustomBusiness.refund().didHandleRefundResult(refundVO, orderInfo, detailList, orderRefund, refundDetailList, customVO);
      } else {
         this.updateRecordAfterRefunded(refundVO, orderRefund, refundDetailList);
         List<OrderAmountDetail> orderAmountDetails = this.updateOrderAfterRefunded(refundVO, orderInfo, orderRefund, detailList, refundDetailList);
         if (PayStateEnum.isPaidState(refundVO.getCode())) {
            OrderMessageSend.orderV3Refunded(orderInfo, detailList, orderAmountDetails, orderRefund, refundDetailList, refundVO.getOutTradeNo());
         }

         OrderRefundResultVO resultVO = OrderRefundResultVO.of(orderInfo, orderRefund, (OrderRefundFeeConfigVO)null, refundVO);
         resultVO = this.orderCustomBusiness.refund().didHandleRefundResult(refundVO, orderInfo, detailList, orderRefund, refundDetailList, resultVO);
         return resultVO;
      }
   }

   protected List<OrderAmountDetail> updateOrderAfterRefunded(UnifyRefundVO refundVO, OrderInfo orderInfo, OrderRefund orderRefund, List<OrderDetail> detailList, List<OrderRefundDetail> refundDetailList) {
      if (!PayStateEnum.isPaidState(refundVO.getCode())) {
         return CollUtil.newArrayList(new OrderAmountDetail[0]);
      } else {
         Iterator var6 = refundDetailList.iterator();

         while(var6.hasNext()) {
            OrderRefundDetail orderRefundDetail = (OrderRefundDetail)var6.next();
            detailList.stream().filter((s) -> {
               return s.getDetailId().equals(orderRefundDetail.getDetailId());
            }).findFirst().ifPresent((s) -> {
               s.plusRefundAmount(orderRefundDetail.getRealRefundAmount());
               s.plusRefundQuantity(orderRefundDetail.getRealQuantity());
               s.setDetailState(s.calcUnRefundGoodsNum() == 0 ? DetailStateEnum.REFUNDED.getKey() : DetailStateEnum.PART_REFUND.getKey());
            });
         }

         this.orderDetailService.batchUpdateDetailRefundQuantity(detailList);
         this.updateOrderRefundStateAndAmount(orderInfo);
         List<OrderAmountDetail> orderAmountDetails = this.orderAmountDetailService.insertByRefund(refundVO.getRefundDetailList(), orderInfo.getOrderId(), orderInfo.getOrderDate(), orderRefund.getOrderRefundId());
         this.inventoryRestoreIfNeed(orderInfo, detailList, refundDetailList);
         return orderAmountDetails;
      }
   }

   protected void updateOrderRefundStateAndAmount(OrderInfo orderInfo) {
      LogUtil.printArgsIn("orderRefundStateHandler", orderInfo);
      List<OrderDetail> detailList = this.orderDetailService.getOrderDetailList(orderInfo.getOrderId(), orderInfo.getOrderDate());
      Integer orderRefundState = OrderRefundStateEnum.PART_SUCC.getKey();
      if (detailList.stream().allMatch((s) -> {
         return DetailStateEnum.NORMAL.getKey().equals(s.getDetailState());
      })) {
         orderRefundState = OrderRefundStateEnum.UN_APPLY.getKey();
      } else if (detailList.stream().allMatch((s) -> {
         return DetailStateEnum.REFUNDED.getKey().equals(s.getDetailState());
      })) {
         orderRefundState = OrderRefundStateEnum.FINISH.getKey();
      }

      orderInfo.setOrderRefundState(orderRefundState);
      orderInfo.setRefundAmount(this.orderRefundService.getOrderRealRefundAmount(orderInfo.getOrderId()));
      this.orderInfoService.updateOrderRefundState(orderInfo.getOrderId(), orderInfo.getOrderDate(), orderInfo.getOrderRefundState(),
              orderInfo.getRefundAmount());
      if (OrderRefundStateEnum.FINISH.getKey().equals(orderRefundState)) {
         this.orderDishesAndroidBusiness.didUpdateDishesState(orderInfo.getOrderId(), orderInfo.getDishesState());
      }

   }

   protected void inventoryRestoreIfNeed(OrderInfo orderInfo, List<OrderDetail> detailList, List<OrderRefundDetail> refundDetailList) {
      if (!CollUtil.isEmpty(refundDetailList)) {
         Map<Long, OrderDetail> orderDetailMap = detailList.stream().collect(Collectors.toMap(OrderDetail::getDetailId, Function.identity()));

         try {
            Iterator var6;
            OrderRefundDetail orderRefundDetail;
            OrderDetail orderDetail;
            if (OrderTypeEnum.SHOP.getKey().equals(orderInfo.getOrderType())) {
               RefundRepairInventoryDTO refundRepairInventoryDTO = new RefundRepairInventoryDTO();
               refundRepairInventoryDTO.setOrderId(orderInfo.getOrderId().toString());
               refundRepairInventoryDTO.setSupermarketId(orderInfo.getCanteenId());
               refundRepairInventoryDTO.setDetailList(CollUtil.newArrayList(new RefundRepairInventoryDetailDTO[0]));
               var6 = refundDetailList.iterator();

               while(var6.hasNext()) {
                  orderRefundDetail = (OrderRefundDetail)var6.next();
                  RefundRepairInventoryDetailDTO recover = new RefundRepairInventoryDetailDTO();
                  orderDetail = (OrderDetail)orderDetailMap.get(orderRefundDetail.getDetailId());
                  if (orderDetail != null && DetailTypeEnum.isProductType(orderDetail.getDetailType()) && orderRefundDetail.getRestoreQuantity() != null && orderRefundDetail.getRestoreQuantity() > 0) {
                     recover.setSupermarketDetailId(orderDetail.getMenuDetailId());
                     recover.setInventoryId(NumberUtil.isNumber(orderDetail.getInventoryId()) ? Long.valueOf(orderDetail.getInventoryId()) : null);
                     recover.setSalesMode(orderDetail.getSalesMode());
                     recover.setRefundNum(BigDecimal.valueOf((long)orderRefundDetail.getRestoreQuantity()));
                     refundRepairInventoryDTO.getDetailList().add(recover);
                  }
               }

               if (CollUtil.isNotEmpty(refundRepairInventoryDTO.getDetailList())) {
                  this.drpServiceApi.refundSuccPlusInventory(refundRepairInventoryDTO);
               }
            } else {
               List<MenuRecipeChangeSurplusNum> changeList = Lists.newArrayList();
               var6 = refundDetailList.iterator();

               while(var6.hasNext()) {
                  orderRefundDetail = (OrderRefundDetail)var6.next();
                  MenuRecipeChangeSurplusNum recover = new MenuRecipeChangeSurplusNum();
                  orderDetail = (OrderDetail)orderDetailMap.get(orderRefundDetail.getDetailId());
                  if (orderDetail != null && DetailTypeEnum.isDishesCategory(orderDetail.getDetailType()) && orderRefundDetail.getRestoreQuantity() != null && orderRefundDetail.getRestoreQuantity() > 0) {
                     recover.setDetailId(orderDetail.getMenuDetailId());
                     recover.setProductId(orderDetail.getGoodsDishesId());
                     recover.setSaleNum(-orderRefundDetail.getRestoreQuantity());
                     changeList.add(recover);
                  }
               }

               if (CollUtil.isNotEmpty(changeList)) {
                  this.menuDishesApi.changeSurplusNum(changeList, (Long)null, (Integer)null, (LocalDate)null);
               }
            }
         } catch (Exception var10) {
            log.info("[恢复库存]恢复库存失败", var10);
         }

      }
   }

   protected void updateRecordAfterRefunded(UnifyRefundVO refundVO, OrderRefund orderRefund, List<OrderRefundDetail> refundDetailList) {
      if (PayStateEnum.isPaidState(refundVO.getCode())) {
         orderRefund.setCheckState(CheckStateEnum.PASS.getKey());
         orderRefund.setCheckResult(CheckStateEnum.PASS.getDesc());
         if (orderRefund.getCheckTime() == null) {
            orderRefund.setCheckTime(LocalDateTime.now());
         }

         orderRefund.setRealRefundAmount(refundVO.getRefundAmount());
         if (refundVO.getRefundAmount().compareTo(LeNumUtil.sumField(refundDetailList, OrderRefundDetail::getRealRefundAmount)) < 0) {
            LeNumUtil.calcShareAmount(refundDetailList, refundVO.getRefundAmount(), OrderRefundDetail::getRealRefundAmount,
                    OrderRefundDetail::setRealRefundAmount);
         }
      } else if (PayStateEnum.isPayingState(refundVO.getCode())) {
         orderRefund.setCheckState(CheckStateEnum.REFUNDING.getKey());
         orderRefund.setCheckResult(CheckStateEnum.REFUNDING.getDesc());
      } else if (LeConstants.COMMON_NO.equals(orderRefund.getIfQuickFail())) {
         orderRefund.setCheckState(CheckStateEnum.WAIT.getKey());
         orderRefund.setCheckResult(CheckStateEnum.WAIT.getDesc());
      } else {
         orderRefund.setCheckState(CheckStateEnum.REFUND_FAIL.getKey());
         orderRefund.setCheckResult(CheckStateEnum.REFUND_FAIL.getDesc());
      }

      this.orderRefundService.updateOrderRefundById(orderRefund);
      this.orderRefundDetailService.updateRefundDetailQuantity(refundDetailList);
   }

   protected void saveOrderRefund(OrderRefund orderRefund, OrderInfo orderInfo, List<OrderRefundDetail> refundDetailList,
                                  List<OrderDetail> orderDetailList, OrderRefundBizEnum biz) {
      this.orderCustomBusiness.refund().willSaveRefund(orderInfo, orderDetailList, CollUtil.toList(orderRefund),
              refundDetailList, biz);
      this.orderRefundService.insertOrderRefundInfo(orderRefund);
      this.orderRefundDetailService.batchInsertOrderRefundDetail(refundDetailList);
   }

   protected void createFlowIfNecessary(OrderInfo orderInfo, OrderRefund orderRefund, List<OrderRefundDetail> refundDetailList,
                                        List<OrderDetail> detailList) {
      Long definitionId = this.flowApi.getByMappingIdAndDefinitionType((Long)null, FlowDefinitionEum.ORDER_REFUND);
      return;
      // 2025-02-20 注释掉 暂不走工作流
//      if (LeNumUtil.isValidId(definitionId)) {
//         CreatInstanceDto creatInstanceDto = new CreatInstanceDto();
//         creatInstanceDto.setDefinitionId(definitionId);
//         HashMap<String, String> contextMap = MapUtil.newHashMap();
//         contextMap.put("orderRefundId", String.valueOf(orderRefund.getOrderRefundId()));
//         contextMap.put("orderType", String.valueOf(orderInfo.getOrderType()));
//         contextMap.put("orderId", String.valueOf(orderInfo.getOrderId()));
//         contextMap.put("orderDate", orderInfo.getOrderDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
//         contextMap.put("applyTime", orderRefund.getApplyTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
//         contextMap.put("refundAmount", orderRefund.getRefundAmount() != null ? orderRefund.getRefundAmount().toString() : "");
//         if (LeNumUtil.isValidId(orderInfo.getCustId())) {
//            Optional.of(this.orderModuleClient.custPayInfoQuery(CustPayInfoQueryParam.ofCustId(orderInfo.getCustId()))).ifPresent((s) -> {
//               contextMap.put("custName", CharSequenceUtil.nullToEmpty(s.getCustName()));
//               contextMap.put("mobile", CharSequenceUtil.nullToEmpty(s.getMobile()));
//               contextMap.put("orgFullName", CharSequenceUtil.nullToEmpty(s.getOrgFullName()));
//               creatInstanceDto.setCreatId(s.getCustId());
//               creatInstanceDto.setCreatName(s.getCustName());
//            });
//         }
//
//         if (creatInstanceDto.getCreatId() == null) {
//            creatInstanceDto.setCreatId((Long)SecureManager.getSubjectId().orElse(LeConstants.DATA_DEFAULT_LONG));
//            creatInstanceDto.setCreatName((String)SecureManager.getSubjectName().orElse(""));
//         }
//
//         Map<Long, OrderDetail> detailMap = (Map)detailList.stream().collect(Collectors.toMap(OrderDetail::getDetailId, Function.identity()));
//         String detailStr = (String)refundDetailList.stream().map((s) -> {
//            OrderDetail orderDetail = (OrderDetail)detailMap.get(s.getDetailId());
//            return orderDetail != null ? orderDetail.getGoodsDishesName() + "*" + s.getQuantity() + ";" : "";
//         }).collect(Collectors.joining());
//         contextMap.put("detailStr", detailStr);
//         creatInstanceDto.setContext(contextMap);
//         Long instanceId = this.flowApi.creat(creatInstanceDto);
//         orderRefund.setFlowInstanceId(instanceId);
//      }

   }
//
//   protected void rejectFlowIfNecessary(OrderRefund orderRefund, List<OrderRefundDetail> refundDetailList, OrderCheckDTO orderCheckDTO) {
//      if (LeNumUtil.isValidId(orderRefund.getFlowInstanceId())) {
//         NextInstanceDto nextInstanceDto = new NextInstanceDto();
//         nextInstanceDto.setInstanceIds(CollUtil.toList(new Long[]{orderRefund.getFlowInstanceId()}));
//         nextInstanceDto.setRemark(orderCheckDTO.getCheckResult());
//         this.flowApi.reject(nextInstanceDto);
//      }
//
//   }
//
//   protected boolean nextFlowIfNecessary(OrderRefund orderRefund, List<OrderRefundDetail> refundDetailList, OrderCheckDTO orderCheckDTO) {
//      if (LeNumUtil.isValidId(orderRefund.getFlowInstanceId())) {
//         NextInstanceDto nextInstanceDto = new NextInstanceDto();
//         nextInstanceDto.setInstanceIds(CollUtil.toList(new Long[]{orderRefund.getFlowInstanceId()}));
//         nextInstanceDto.setRemark(orderCheckDTO.getCheckResult());
//         this.orderRefundService.updateOrderRefundById(orderRefund);
//         this.orderRefundDetailService.updateRefundDetailQuantity(refundDetailList);
//         this.flowApi.next(nextInstanceDto);
//         return true;
//      } else {
//         return false;
//      }
//   }
//
//   protected OrderRefund packageCorrect(OrderPartRefundDTO orderPartRefundDTO, Long orderId) {
//      OrderRefund orderRefund = new OrderRefund();
//      orderRefund.setOrderRefundId(Id.next());
//      orderRefund.setOrderId(orderId);
//      orderRefund.setMacOrderId(orderPartRefundDTO.getMacOrderId());
//      orderRefund.setApplyTime(LocalDateTime.now());
//      orderRefund.setApplyReason(orderPartRefundDTO.getRemark());
//      orderRefund.setApplyType(ApplyTypeEnum.CORRECT.getKey());
//      orderRefund.setResressPicurl(orderPartRefundDTO.getResressPicurl());
//      return orderRefund;
//   }
//
//   protected OrderCheckDTO packOrderCheckDTOFromCorrect(OrderRefund refund, List<OrderRefundDetail> refundDetailList) {
//      OrderCheckDTO orderCheckDTO = new OrderCheckDTO();
//      orderCheckDTO.setOrderRefundId(refund.getOrderRefundId());
//      orderCheckDTO.setCheckState(CheckStateEnum.PASS.getKey());
//      orderCheckDTO.setCheckResult(CheckStateEnum.PASS.getDesc());
//      orderCheckDTO.setDetailRefundList(refundDetailList.stream().map((s) -> {
//         return OrderDetailRefundDTO.of(s.getDetailId(), s.getQuantity());
//      }).toList());
//      return orderCheckDTO;
//   }
//
//   protected void updateCorrectToRefund(OrderRefund orderRefund, List<OrderRefundDetail> refundDetailList, List<OrderDetail> detailList) {
//      orderRefund.setApplyType(ApplyTypeEnum.REFUND.getKey());
//      orderRefund.setIfQuickFail(LeConstants.COMMON_NO);
//      if (CollUtil.isNotEmpty(refundDetailList)) {
//         Iterator var4 = refundDetailList.iterator();
//
//         while(var4.hasNext()) {
//            OrderRefundDetail refundDetail = (OrderRefundDetail)var4.next();
//            refundDetail.setRealRefundAmount(BigDecimal.ZERO);
//            refundDetail.setRealQuantity(0);
//            detailList.stream().filter((d) -> {
//               return d.getDetailId().equals(refundDetail.getDetailId());
//            }).findFirst().ifPresent((orderDetail) -> {
//               refundDetail.setQuantity(orderDetail.getQuantity() - refundDetail.getQuantity());
//            });
//         }
//      }
//
//   }
}
