package com.bonus.canteen.core.order.weight.business.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import com.bonus.canteen.core.account.v3.api.vo.AccInfoDetailVO;
import com.bonus.canteen.core.account.v3.api.vo.AccInfoServiceV3Api;
import com.bonus.canteen.core.allocation.alloc.model.AllocPayModel;
import com.bonus.canteen.core.allocation.api.AllocCanteenApi;
import com.bonus.canteen.core.allocation.api.AllocStallApi;
import com.bonus.canteen.core.allocation.canteen.model.AllocCanteen;
import com.bonus.canteen.core.allocation.canteen.model.AllocStall;
import com.bonus.canteen.core.common.redis.RedisUtil;
import com.bonus.canteen.core.common.utils.JacksonUtil;
import com.bonus.canteen.core.common.utils.JavaxValidateUtils;
import com.bonus.canteen.core.common.utils.LogUtil;
import com.bonus.canteen.core.device.api.DeviceApi;
import com.bonus.canteen.core.menu.model.AllocMealtimeModel;
import com.bonus.canteen.core.order.client.OrderModuleClient;
import com.bonus.canteen.core.order.client.po.MealtimeQueryParam;
import com.bonus.canteen.core.order.client.po.OrderConfigQueryParam;
import com.bonus.canteen.core.order.common.business.OrderPlaceBusiness;
import com.bonus.canteen.core.order.common.business.OrderRefundBusiness;
import com.bonus.canteen.core.order.common.constants.OrderCacheConstants;
import com.bonus.canteen.core.order.common.constants.OrderErrorTypeEnum;
import com.bonus.canteen.core.order.common.constants.OrderRefundBizEnum;
import com.bonus.canteen.core.order.common.constants.OrderStateEnum;
import com.bonus.canteen.core.order.common.dto.OrderDidPayInfoDTO;
import com.bonus.canteen.core.order.common.model.OrderAmountChange;
import com.bonus.canteen.core.order.common.model.OrderAmountDetail;
import com.bonus.canteen.core.order.common.model.OrderDetail;
import com.bonus.canteen.core.order.common.model.OrderInfo;
import com.bonus.canteen.core.order.common.service.*;
import com.bonus.canteen.core.order.custom.OrderCustomBusiness;
import com.bonus.canteen.core.order.mobile.service.OrderInfoMobileBusiness;
import com.bonus.canteen.core.order.mobile.vo.OrderNutrientInfoVO;
import com.bonus.canteen.core.order.mq.po.OrderSavePO;
import com.bonus.canteen.core.order.utils.LeNumUtil;
import com.bonus.canteen.core.order.weight.business.OrderWeightBusiness;
import com.bonus.canteen.core.order.weight.dto.OrderWeightPlaceDetailDTO;
import com.bonus.canteen.core.pay.api.PayApi;
import com.bonus.canteen.core.pay.api.TradeRecordApi;
import com.bonus.canteen.core.pay.api.dto.UnifyPayDTO;
import com.bonus.canteen.core.pay.api.vo.UnifyPayVO;
import com.bonus.canteen.core.pay.common.constants.*;
import com.bonus.canteen.core.pay.common.vo.PayChannelSelectDTO;
import com.bonus.canteen.core.pay.common.vo.PayChannelSelectResultVO;
import com.bonus.common.houqin.constant.LeConstants;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.redisson.api.RLock;
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.time.LocalDate;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class OrderWeightBusinessImpl implements OrderWeightBusiness {
   private static final Logger log = LoggerFactory.getLogger(OrderWeightBusinessImpl.class);
   @Autowired
   @Lazy
   protected OrderPlaceBusiness orderPlaceBusiness;
   @Autowired
   @Lazy
   protected OrderRefundBusiness orderRefundBusiness;
   @Autowired
   @Lazy
   protected OrderCustomBusiness orderCustomBusiness;
   @Autowired
   @Lazy
   protected OrderInfoMobileBusiness orderInfoMobileBusiness;
   @Autowired
   @Lazy
   protected OrderInfoService orderInfoService;
   @Autowired
   @Lazy
   protected OrderDetailService orderDetailService;
   @Autowired
   @Lazy
   protected OrderRefundService orderRefundService;
   @Autowired
   @Lazy
   protected OrderRefundDetailService orderRefundDetailService;
   @Autowired
   @Lazy
   protected OrderErrorLogService orderErrorLogService;
   @Autowired
   @Lazy
   protected OrderModuleClient orderModuleClient;
   @Autowired
   @Lazy
   protected DeviceApi deviceApi;
   @Autowired
   @Lazy
   protected PayApi payApi;
   @Autowired
   @Lazy
   protected AllocCanteenApi allocCanteenApi;
   @Autowired
   @Lazy
   protected AllocStallApi allocStallApi;
   @Autowired
   @Lazy
   private AccInfoServiceV3Api accInfoServiceV3Api;
   @Autowired
   @Lazy
   private TradeRecordApi tradeRecordApi;

//   public List<OrderWeightInfoVO> placeOrder(OrderWeightPlaceOrderDTO placeOrderDTO) {
//      LogUtil.info("自助餐下单参数", placeOrderDTO);
//      JavaxValidateUtils.validate(placeOrderDTO);
//      RLock lock = RedisUtil.getLock(OrderCacheConstants.weightOrderHandleLockKey(placeOrderDTO.getMacOrderId()));
//      lock.lock();
//      OrderSavePO orderSavePO = null;
//
//      try {
//         orderSavePO = this.retrieveByMacOrderId(placeOrderDTO.getMacOrderId());
//         if (orderSavePO == null) {
//            orderSavePO = this.createOrderSavePO(placeOrderDTO.getMacOrderId(), placeOrderDTO.getWeightBindType(), placeOrderDTO.getOpenid());
//         }
//
//         if (this.checkIfRepeatSubmit(orderSavePO, placeOrderDTO)) {
//            List var16 = this.convertToOrderWeightInfoVO(orderSavePO);
//            return var16;
//         }
//
//         log.info("自助餐下单-设备信息查询");
//         DeviceInfoVO deviceInfoVO = CharSequenceUtil.isNotEmpty(placeOrderDTO.getMachineSn()) ? this.deviceApi.getDeviceInfoVoBySnCacheable(placeOrderDTO.getMachineSn()) : null;
//         this.createOrders(orderSavePO, placeOrderDTO, deviceInfoVO);
//         if (orderSavePO.getOrderInfoList().stream().anyMatch((s) -> {
//            return PayStateEnum.isFinishedState(s.getPayState()) || OrderStateEnum.isCancelState(s.getOrderState());
//         })) {
//            this.payOrder(orderSavePO, placeOrderDTO.convertToOrderWeightPayDTO());
//         } else {
//            this.orderPlaceBusiness.calcNeedPayAmount(orderSavePO.getOrderInfoList(), orderSavePO.getOrderDetailList());
//            this.orderPlaceBusiness.saveCache(orderSavePO, !MacWeightBindTypeEnum.BIND_UN_BIND.key().equals(placeOrderDTO.getWeightBindType()));
//         }
//      } catch (Exception var14) {
//         this.placeExceptionHandler(placeOrderDTO, orderSavePO, var14);
//         throw var14;
//      } finally {
//         try {
//            if (lock.isHeldByCurrentThread() && lock.isLocked()) {
//               lock.unlock();
//            }
//         } catch (Exception var13) {
//            log.error("解锁异常", var13);
//         }
//
//      }
//
//      return this.convertToOrderWeightInfoVO(orderSavePO);
//   }
//
//   public OrderWeightPayVO pay(OrderWeightPayDTO weightPayDTO) {
//      LogUtil.info("自助餐结算-请求参数", weightPayDTO);
//      JavaxValidateUtils.validate(weightPayDTO);
//      RLock lock = RedisUtil.getLock(OrderCacheConstants.weightOrderHandleLockKey(weightPayDTO.getMacOrderId()));
//      lock.lock();
//
//      OrderWeightPayVO var5;
//      try {
//         OrderSavePO orderSavePO = this.retrieveByMacOrderId(weightPayDTO.getMacOrderId());
//         OrderWeightPayVO payVO = this.payOrder(orderSavePO, weightPayDTO);
//         LogUtil.info("自助餐结算|结果", payVO);
//         var5 = payVO;
//      } finally {
//         try {
//            if (lock.isHeldByCurrentThread() && lock.isLocked()) {
//               lock.unlock();
//            }
//         } catch (Exception var12) {
//            log.error("解锁异常", var12);
//         }
//
//      }
//
//      return var5;
//   }
//
//   public List<OrderWeightInfoVO> queryByMacOrderIds(List<String> macOrderIds) {
//      log.info("查询自助餐订单信息: {}", macOrderIds);
//      List<OrderWeightInfoVO> result = CollUtil.newArrayList(new OrderWeightInfoVO[0]);
//      if (CollUtil.isEmpty(macOrderIds)) {
//         return result;
//      } else {
//         Iterator var3 = macOrderIds.iterator();
//
//         while(var3.hasNext()) {
//            String macOrderId = (String)var3.next();
//            OrderSavePO orderSavePO = this.retrieveByMacOrderId(macOrderId);
//            if (orderSavePO != null) {
//               result.addAll(this.convertToOrderWeightInfoVO(orderSavePO));
//            } else {
//               log.warn("未查询自助餐订单信息");
//            }
//         }
//
//         return result;
//      }
//   }
//
//   public void applyCorrect(OrderPartRefundDTO orderPartRefundDTO) {
//      this.orderRefundBusiness.orderCorrect(orderPartRefundDTO, OrderRefundBizEnum.MOBILE_CORRECT);
//   }

   public void didUpdateCorrect(String macOrderId) {
      this.orderPlaceBusiness.cleanCache(macOrderId);
   }

//   protected OrderSavePO retrieveByMacOrderId(String macOrderId) {
//      OrderSavePO orderSavePO = null;
//      String cacheStr = RedisUtil.getString(OrderCacheConstants.orderCacheKey(macOrderId));
//      if (CharSequenceUtil.isNotBlank(cacheStr)) {
//         log.info("自助餐缓存查询");
//         orderSavePO = (OrderSavePO) JacksonUtil.readValue(cacheStr, OrderSavePO.class);
//      } else {
//         log.info("自助餐数据库查询");
//         List<OrderInfo> orderInfoList = this.orderInfoService.listOrderInfoByMacOrderId(macOrderId, LocalDate.now().minusDays(7L), LocalDate.now().plusDays(0L));
//         if (CollUtil.isNotEmpty(orderInfoList)) {
//            List<Long> orderIds = (List)orderInfoList.stream().map(OrderInfo::getOrderId).collect(Collectors.toList());
//            List<LocalDate> dateList = (List)orderInfoList.stream().map(OrderInfo::getOrderDate).collect(Collectors.toList());
//            List<OrderDetail> orderDetailList = this.orderDetailService.getOrderDetailList((List)orderIds, (Collection)dateList);
//            orderSavePO = OrderSavePO.byLockKey(macOrderId);
//            orderSavePO.getOrderInfoList().addAll(orderInfoList);
//            orderSavePO.getOrderDetailList().addAll(orderDetailList);
//         }
//      }
//
//      orderSavePO = this.orderCustomBusiness.weight().didRetrieveByMacOrderId(macOrderId, orderSavePO);
//      LogUtil.info("自助餐-查询订单结果", orderSavePO);
//      return orderSavePO;
//   }
//
//   protected OrderSavePO createOrderSavePO(String macOrderId, Integer weightBindType, String openid) {
//      LogUtil.info("自助餐-创建订单", macOrderId, weightBindType, openid);
//      return OrderSavePO.byLockKey(macOrderId);
//   }
//
//   protected boolean checkIfRepeatSubmit(OrderSavePO orderSavePO, OrderWeightPlaceOrderDTO placeOrderDTO) {
//      boolean ifRepeat = false;
//      List<Long> paidOrderIds = (List)orderSavePO.getOrderInfoList().stream().filter((s) -> {
//         return PayStateEnum.isPaidState(s.getPayState());
//      }).map(OrderInfo::getOrderId).collect(Collectors.toList());
//      List<String> currentSubmitKeys = (List)orderSavePO.getOrderDetailList().stream().filter((s) -> {
//         return paidOrderIds.contains(s.getOrderId());
//      }).map(OrderDetail::getSubmitKey).collect(Collectors.toList());
//      List<OrderWeightPlaceDetailDTO> filteredDetailList = (List)placeOrderDTO.getOrderDetailList().stream().filter((s) -> {
//         return !currentSubmitKeys.contains(s.getSubmitKey());
//      }).collect(Collectors.toList());
//      if (CollUtil.isNotEmpty(placeOrderDTO.getOrderDetailList()) && CollUtil.isEmpty(filteredDetailList)) {
//         log.warn("本次提交菜品全部为重复提交");
//         ifRepeat = true;
//      }
//
//      placeOrderDTO.setOrderDetailList(filteredDetailList);
//      return this.orderCustomBusiness.weight().didCheckRepeatSubmitDishes(orderSavePO, placeOrderDTO, ifRepeat);
//   }
//
//   protected List<OrderInfo> filterBeforeOrderPay(OrderSavePO orderSavePO) {
//      if (orderSavePO != null && !CollUtil.isEmpty(orderSavePO.getOrderInfoList())) {
//         orderSavePO.setPayDTO((UnifyPayDTO)null);
//         orderSavePO.setPayVO((UnifyPayVO)null);
//         Map<Long, List<OrderDetail>> orderDetailGroup = (Map)orderSavePO.getOrderDetailList().stream().collect(Collectors.groupingBy(OrderDetail::getOrderId));
//         List<Long> notNeedPayOrderIds = (List)orderSavePO.getOrderInfoList().stream().filter((s) -> {
//            return !PayStateEnum.isUnPayState(s.getPayState()) || OrderStateEnum.isCancelState(s.getOrderState()) || !orderDetailGroup.containsKey(s.getOrderId());
//         }).map(OrderInfo::getOrderId).collect(Collectors.toList());
//         List<OrderInfo> notNeedPayOrders = (List)orderSavePO.getOrderInfoList().stream().filter((s) -> {
//            return notNeedPayOrderIds.contains(s.getOrderId());
//         }).collect(Collectors.toList());
//         List<OrderDetail> notNeedPayDetails = (List)orderSavePO.getOrderDetailList().stream().filter((s) -> {
//            return notNeedPayOrderIds.contains(s.getOrderId());
//         }).collect(Collectors.toList());
//         List<OrderInfo> needPayOrders = (List)orderSavePO.getOrderInfoList().stream().filter((s) -> {
//            return !notNeedPayOrderIds.contains(s.getOrderId());
//         }).collect(Collectors.toList());
//         List<OrderDetail> needPayDetails = (List)orderSavePO.getOrderDetailList().stream().filter((s) -> {
//            return !notNeedPayOrderIds.contains(s.getOrderId());
//         }).collect(Collectors.toList());
//         boolean isOfflineOrder = notNeedPayOrders.stream().anyMatch((s) -> {
//            return PayStateEnum.isFinishedState(s.getPayState());
//         });
//         if (isOfflineOrder) {
//            needPayOrders.forEach((s) -> {
//               s.setIfOnline(LeConstants.COMMON_NO);
//            });
//         }
//
//         this.orderCustomBusiness.weight().didFilterBeforePay(orderSavePO, notNeedPayOrders, notNeedPayDetails, needPayOrders, needPayDetails);
//         orderSavePO.setOrderInfoList(needPayOrders);
//         orderSavePO.setOrderDetailList(needPayDetails);
//         if (CollUtil.isNotEmpty(needPayOrders)) {
//            LogUtil.infoFieldsX("不需要支付订单过滤", notNeedPayOrders, OrderInfo.logFieldsRelated(), notNeedPayDetails, OrderDetail.logFieldsAmount(), needPayOrders, OrderInfo.logFieldsRelated(), needPayDetails, OrderDetail.logFieldsAmount());
//         }
//
//         return notNeedPayOrders;
//      } else {
//         return CollUtil.newArrayList(new OrderInfo[0]);
//      }
//   }
//
//   protected UnifyPayDTO createPay(OrderSavePO orderSavePO, OrderWeightPayDTO weightPayDTO, DeviceInfoVO deviceInfoVO, List<OrderInfo> notNeedPayOrders) {
//      Long canteenId = (Long) LeNumUtil.reduceField(orderSavePO.getOrderInfoList(), OrderInfo::getCanteenId, (Object)null);
//      Long stallId = (Long)LeNumUtil.reduceField(orderSavePO.getOrderInfoList(), OrderInfo::getStallId, (Object)null);
//      AllocPayModel merchantPayModel = this.orderModuleClient.metadataQueryPayConfig(OrderConfigQueryParam.ofMerchant());
//      Integer payType = PayTypeEnum.MEAL_CARD.getKey();
//      Long custId = ((OrderInfo)orderSavePO.getOrderInfoList().get(0)).getCustId();
//      boolean containsPayScorePaidOrder = notNeedPayOrders.stream().anyMatch((s) -> {
//         return PayStateEnum.isPaidState(s.getPayState()) && PayTypeEnum.WECHAT_WITHHOLD.getKey().equals(s.getPayType());
//      });
//      if (merchantPayModel.supportPayChannel(PayChannelEnum.ALI.getKey()) && "1".equals(merchantPayModel.getIfOpenAlipayWithhold()) && MacWeightBindTypeEnum.BIND_ALI_APPLET.key().equals(weightPayDTO.getWeightBindType())) {
//         log.info("[自助餐]支付宝代扣");
//         payType = PayTypeEnum.ALI_PAY_WITHHOLD.getKey();
//      } else if (merchantPayModel.supportPayChannel(PayChannelEnum.WECHAT.getKey()) && "1".equals(merchantPayModel.getIfOpenWechatPayment()) && MacWeightBindTypeEnum.BIND_WXPAY.key().equals(weightPayDTO.getWeightBindType()) && !containsPayScorePaidOrder) {
//         log.info("[自助餐]微信支付分");
//         payType = PayTypeEnum.WECHAT_WITHHOLD.getKey();
//      }
//
//      PayChannelSelectDTO payChannelSelectDTO = new PayChannelSelectDTO();
//      payChannelSelectDTO.setPayType(payType);
//      payChannelSelectDTO.setOpenId(weightPayDTO.getOpenid());
//      payChannelSelectDTO.setCustId(custId);
//      payChannelSelectDTO.setCanteenId(canteenId);
//      payChannelSelectDTO.setStallId(stallId);
//      payChannelSelectDTO.setOnlineState(LeConstants.COMMON_YES);
//      payChannelSelectDTO.setSourceType(((OrderInfo)orderSavePO.getOrderInfoList().get(0)).getSourceType());
//      PayChannelSelectEnum scenario = PayChannelSelectEnum.DEVICE_OFFLINE_CONSUME;
//      PayChannelSelectResultVO payChannelSelectResultVO = this.payApi.payChannelSelect(scenario, payChannelSelectDTO);
//      UnifyPayDTO unifyPayDTO = UnifyPayDTO.of(payChannelSelectResultVO);
//      unifyPayDTO.setTradeId(Id.next());
//      unifyPayDTO.setScenario(scenario.getKey());
//      unifyPayDTO.setTradeType(TradeTypeEnum.CONSUME.getKey());
//      unifyPayDTO.setOrderTime(((OrderInfo)orderSavePO.getOrderInfoList().get(0)).getOrderTime());
//      if (CharSequenceUtil.isNotBlank(weightPayDTO.getOpenid())) {
//         unifyPayDTO.setOpenid(weightPayDTO.getOpenid());
//      }
//
//      unifyPayDTO.setNuClearMode(((OrderInfo)orderSavePO.getOrderInfoList().get(0)).getNuClearMode());
//      unifyPayDTO.setAuthCode(weightPayDTO.getAlifToken());
//      unifyPayDTO.setTerminalParams(weightPayDTO.getAliSign());
//      unifyPayDTO.fillDeviceInfo(deviceInfoVO);
//      this.orderCustomBusiness.weight().didCreatePay(orderSavePO, weightPayDTO, deviceInfoVO, unifyPayDTO);
//      return unifyPayDTO;
//   }
//
//   protected OrderWeightPayVO payOrder(OrderSavePO orderSavePO, OrderWeightPayDTO weightPayDTO) {
//      try {
//         List<OrderInfo> notNeedPayOrders = this.filterBeforeOrderPay(orderSavePO);
//         if (orderSavePO != null && !CollUtil.isEmpty(orderSavePO.getOrderDetailList())) {
//            String machineSn = (String)LeNumUtil.reduceField(orderSavePO.getOrderInfoList(), OrderInfo::getMachineSn, (Object)null);
//            DeviceInfoVO deviceInfoVO = CharSequenceUtil.isNotEmpty(machineSn) ? this.deviceApi.getDeviceInfoVoBySnCacheable(machineSn) : null;
//            UnifyPayDTO unifyPayDTO = this.createPay(orderSavePO, weightPayDTO, deviceInfoVO, notNeedPayOrders);
//            orderSavePO.setPayDTO(unifyPayDTO);
//            this.updateOrderField(orderSavePO.getOrderInfoList(), unifyPayDTO);
//            List<OrderAmountChange> amountChangeList = this.orderPlaceBusiness.calcNeedPayAmount(orderSavePO.getOrderInfoList(), orderSavePO.getOrderDetailList());
//            unifyPayDTO.setAmount((BigDecimal)orderSavePO.getOrderInfoList().stream().map(OrderInfo::calcNeedPayAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
//            List<OrderAmountChange> amountChangeListRole = this.orderPlaceBusiness.calcRuleAmount(unifyPayDTO, orderSavePO.getOrderInfoList(), orderSavePO.getOrderDetailList(), false);
//            amountChangeList.addAll(amountChangeListRole);
//            this.orderPlaceBusiness.checkCoupon(unifyPayDTO, orderSavePO.getOrderInfoList());
//            orderSavePO.setAmountChangeList(amountChangeList);
//            UnifyPayVO unifyPayVO = this.orderPlaceBusiness.pay(unifyPayDTO, orderSavePO.getOrderInfoList(), orderSavePO.getOrderDetailList());
//            orderSavePO.setPayVO(unifyPayVO);
//            return this.payResultHandler(orderSavePO, weightPayDTO, notNeedPayOrders);
//         } else {
//            Long custId = CollUtil.isNotEmpty(notNeedPayOrders) ? ((OrderInfo)notNeedPayOrders.get(0)).getCustId() : null;
//            return this.noNeedPayHandler(weightPayDTO.getMacOrderId(), notNeedPayOrders, weightPayDTO.getWeightBindType(), custId, weightPayDTO.getOpenid());
//         }
//      } catch (Exception var10) {
//         return this.payExceptionHandler(weightPayDTO, orderSavePO, var10);
//      }
//   }
//
//   protected void updateOrderField(List<OrderInfo> orderInfoList, UnifyPayDTO payDTO) {
//      Iterator var3 = orderInfoList.iterator();
//
//      while(var3.hasNext()) {
//         OrderInfo orderInfo = (OrderInfo)var3.next();
//         orderInfo.setCustId(payDTO.getCustId());
//         orderInfo.setPayType(payDTO.getPayType());
//         orderInfo.setPayChannel(payDTO.getPayChannel());
//      }
//
//   }
//
//   protected OrderWeightPayVO payResultHandler(OrderSavePO orderSavePO, OrderWeightPayDTO weightPayDTO, List<OrderInfo> notNeedPayOrders) {
//      OrderWeightPayVO weightPayVO = OrderWeightPayVO.of(orderSavePO.getPayVO());
//      Long custId = orderSavePO.getPayDTO().getCustId();
//      Iterator var6;
//      OrderInfo orderInfo;
//      if (orderSavePO.getPayVO().getCustId() != null && !ObjectUtil.equal(orderSavePO.getPayDTO().getCustId(), orderSavePO.getPayVO().getCustId())) {
//         var6 = orderSavePO.getOrderInfoList().iterator();
//
//         while(var6.hasNext()) {
//            orderInfo = (OrderInfo)var6.next();
//            orderInfo.setCustId(orderSavePO.getPayVO().getCustId());
//         }
//      }
//
//      this.fillAccInfoInNeed(custId, weightPayVO);
//      if (PayStateEnum.isPaidState(orderSavePO.getPayVO().getCode())) {
//         List<OrderAmountDetail> orderAmountDetails = this.orderPlaceBusiness.calcOrderRealAmount(orderSavePO.getOrderInfoList(), orderSavePO.getOrderDetailList(), orderSavePO.getAmountChangeList(), orderSavePO.getPayVO().getRealAmount(), orderSavePO.getPayVO().getDetailList());
//         orderSavePO.setAmountDetailList(orderAmountDetails);
//         Iterator var10 = orderSavePO.getOrderInfoList().iterator();
//
//         while(var10.hasNext()) {
//            OrderInfo orderInfo = (OrderInfo)var10.next();
//            this.orderPlaceBusiness.updateOrderFieldAfterPay(orderInfo, OrderDidPayInfoDTO.of(orderSavePO.getPayVO()));
//         }
//      } else {
//         var6 = orderSavePO.getOrderInfoList().iterator();
//
//         while(var6.hasNext()) {
//            orderInfo = (OrderInfo)var6.next();
//            orderInfo.setPayState(orderSavePO.getPayVO().getCode());
//         }
//      }
//
//      this.cancelOrdersIfNeed(notNeedPayOrders);
//      this.orderPlaceBusiness.saveCache(orderSavePO, true);
//      return this.orderCustomBusiness.weight().didHandlePayResult(orderSavePO, weightPayDTO, notNeedPayOrders, weightPayVO);
//   }
//
//   protected void createOrders(OrderSavePO orderSavePO, OrderWeightPlaceOrderDTO placeOrderDTO, DeviceInfoVO deviceInfoVO) {
//      log.info("自助餐下单-组装订单信息");
//      orderSavePO.getWeightDetailList().addAll(placeOrderDTO.getOrderDetailList());
//      OrderInfo increasedOrderInfo = placeOrderDTO.convertToOrderInfo(deviceInfoVO);
//      increasedOrderInfo.setOrderId(Id.next());
//      this.orderInfoService.initOrderCustInfo(CollUtil.toList(new OrderInfo[]{increasedOrderInfo}), placeOrderDTO.getCustId());
//      List<OrderDetail> increasedOrderDetails = placeOrderDTO.convertToDetailList();
//      increasedOrderDetails.forEach((orderDetail) -> {
//         orderDetail.setOrderId(increasedOrderInfo.getOrderId());
//         orderDetail.setOrderDate(increasedOrderInfo.getOrderDate());
//      });
//      if (CollUtil.isNotEmpty(placeOrderDTO.getOrderDetailList())) {
//         placeOrderDTO.getOrderDetailList().stream().filter((s) -> {
//            return s.getSubmitTime() != null;
//         }).findFirst().ifPresent((s) -> {
//            increasedOrderInfo.setOrderTime(s.getSubmitTime());
//         });
//      }
//
//      OrderInfo targetOrderInfo = (OrderInfo)orderSavePO.getOrderInfoList().stream().filter((s) -> {
//         return PayStateEnum.isUnPayState(s.getPayState()) && !OrderStateEnum.isCancelState(s.getOrderState());
//      }).filter((s) -> {
//         return ObjectUtil.equal(s.getCanteenId(), increasedOrderInfo.getCanteenId()) && ObjectUtil.equal(s.getStallId(), increasedOrderInfo.getStallId());
//      }).findFirst().orElse((Object)null);
//      if (targetOrderInfo == null) {
//         targetOrderInfo = (OrderInfo)orderSavePO.getOrderInfoList().stream().filter((s) -> {
//            return PayStateEnum.isUnPayState(s.getPayState()) && !OrderStateEnum.isCancelState(s.getOrderState());
//         }).filter((s) -> {
//            return CharSequenceUtil.isEmpty(s.getMachineSn());
//         }).filter((s) -> {
//            return CharSequenceUtil.equals(s.getPlateSerialNum(), placeOrderDTO.getPlateSerialNum());
//         }).findFirst().orElse((Object)null);
//         if (targetOrderInfo != null) {
//            targetOrderInfo.setMachineSn(increasedOrderInfo.getMachineSn());
//            targetOrderInfo.setMachineNum(increasedOrderInfo.getMachineNum());
//            targetOrderInfo.setSourceType(increasedOrderInfo.getSourceType());
//            targetOrderInfo.setCanteenId(increasedOrderInfo.getCanteenId());
//            targetOrderInfo.setStallId(increasedOrderInfo.getStallId());
//         }
//      }
//
//      if (targetOrderInfo == null) {
//         targetOrderInfo = increasedOrderInfo;
//         OrderInfo bindOrderInfo = (OrderInfo)orderSavePO.getOrderInfoList().stream().filter((s) -> {
//            return CharSequenceUtil.equals(s.getPlateSerialNum(), placeOrderDTO.getPlateSerialNum());
//         }).filter((s) -> {
//            return CharSequenceUtil.isNotEmpty(s.getMachineSn());
//         }).findFirst().orElse((Object)null);
//         if (bindOrderInfo != null) {
//            increasedOrderInfo.setMachineSn(bindOrderInfo.getMachineSn());
//            increasedOrderInfo.setMachineNum(bindOrderInfo.getMachineNum());
//            increasedOrderInfo.setSourceType(bindOrderInfo.getSourceType());
//            increasedOrderInfo.setNuClearMode(bindOrderInfo.getNuClearMode());
//         }
//
//         orderSavePO.getOrderInfoList().add(increasedOrderInfo);
//      } else {
//         Long orderId = targetOrderInfo.getOrderId();
//         increasedOrderInfo.setOrderId(orderId);
//         increasedOrderDetails.forEach((s) -> {
//            s.setOrderId(orderId);
//         });
//      }
//
//      Map<String, OrderDetail> orderDetailMapBySubmitKey = (Map)orderSavePO.getOrderDetailList().stream().collect(Collectors.toMap(OrderDetail::getSubmitKey, Function.identity(), (s1, s2) -> {
//         return s2;
//      }));
//      Iterator var8 = increasedOrderDetails.iterator();
//
//      while(var8.hasNext()) {
//         OrderDetail increasedOrderDetail = (OrderDetail)var8.next();
//         OrderDetail existsOrderDetail = (OrderDetail)orderDetailMapBySubmitKey.get(increasedOrderDetail.getSubmitKey());
//         if (existsOrderDetail != null) {
//            if (increasedOrderDetail.getQuantity() > 0) {
//               existsOrderDetail.setQuantity(increasedOrderDetail.getQuantity());
//               existsOrderDetail.setTotalWeight(increasedOrderDetail.getTotalWeight());
//            } else {
//               orderSavePO.getOrderDetailList().removeIf((s) -> {
//                  return s.getDetailId().equals(existsOrderDetail.getDetailId());
//               });
//               this.orderDetailService.removeByDetailId(existsOrderDetail.getDetailId(), existsOrderDetail.getOrderDate());
//            }
//         } else if (increasedOrderDetail.getQuantity() > 0) {
//            orderSavePO.getOrderDetailList().add(increasedOrderDetail);
//         }
//      }
//
//      if (LeNumUtil.isValidId(targetOrderInfo.getCanteenId()) && CharSequenceUtil.isEmpty(targetOrderInfo.getCanteenName())) {
//         AllocCanteen allocCanteen = this.allocCanteenApi.getAllocCanteen(targetOrderInfo.getCanteenId());
//         if (allocCanteen != null) {
//            targetOrderInfo.setCanteenName(allocCanteen.getCanteenName());
//         }
//      }
//
//      if (LeNumUtil.isValidId(targetOrderInfo.getStallId()) && CharSequenceUtil.isEmpty(targetOrderInfo.getStallName())) {
//         AllocStall allocStall = this.allocStallApi.getAllocStall(targetOrderInfo.getStallId());
//         if (allocStall != null) {
//            targetOrderInfo.setStallName(allocStall.getStallName());
//         }
//      }
//
//      if (!LeNumUtil.isValidId(targetOrderInfo.getMealtimeType()) && LeNumUtil.isValidId(targetOrderInfo.getCanteenId())) {
//         OrderInfo firstOrder = (OrderInfo)CollUtil.getFirst(orderSavePO.getOrderInfoList());
//         if (firstOrder != null && LeNumUtil.isValidId(firstOrder.getMealtimeType())) {
//            targetOrderInfo.setMealtimeType(firstOrder.getMealtimeType());
//            targetOrderInfo.setMealtimeName(firstOrder.getMealtimeName());
//         } else {
//            AllocMealtimeModel mealtime = this.orderModuleClient.mealtimeQuery(MealtimeQueryParam.ofAssignTime(targetOrderInfo.getOrderTime().toLocalTime(), targetOrderInfo.getCanteenId(), targetOrderInfo.getStallId()));
//            if (mealtime != null) {
//               targetOrderInfo.setMealtimeType(mealtime.getMealtimeType());
//               targetOrderInfo.setMealtimeName(mealtime.getMealtimeName());
//            }
//         }
//      }
//
//      this.orderCustomBusiness.weight().didPackageOrderInfo(orderSavePO, placeOrderDTO, deviceInfoVO);
//      LogUtil.infoFieldsX("自助餐下单-订单创建信息", orderSavePO.getOrderInfoList(), OrderInfo.logFieldsRelated(), orderSavePO.getOrderDetailList(), OrderDetail.logFieldsGoods());
//   }
//
//   protected List<OrderWeightInfoVO> convertToOrderWeightInfoVO(OrderSavePO orderSavePO) {
//      if (orderSavePO != null && !CollUtil.isEmpty(orderSavePO.getOrderInfoList())) {
//         Map<Long, OrderWeightPlaceDetailDTO> submitDetailMap = (Map)orderSavePO.getWeightDetailList().stream().collect(Collectors.toMap(OrderWeightPlaceDetailDTO::getDetailId, Function.identity()));
//         List<OrderWeightInfoVO> result = CollUtil.newArrayList(new OrderWeightInfoVO[0]);
//         Iterator var4 = orderSavePO.getOrderInfoList().iterator();
//
//         while(var4.hasNext()) {
//            OrderInfo orderInfo = (OrderInfo)var4.next();
//            if (PayStateEnum.isUnPayState(orderInfo.getPayState()) && !OrderStateEnum.isCancelState(orderInfo.getOrderState())) {
//               OrderWeightInfoVO orderWeightInfoVO = OrderWeightInfoVO.of(orderInfo);
//               List<OrderWeightDetailVO> weightDetailVOs = (List)orderSavePO.getOrderDetailList().stream().filter((s) -> {
//                  return s.getOrderId().equals(orderInfo.getOrderId());
//               }).map((s) -> {
//                  return OrderWeightDetailVO.of(s, (OrderWeightPlaceDetailDTO)submitDetailMap.get(s.getDetailId()));
//               }).collect(Collectors.toList());
//               orderWeightInfoVO.setOrderDetailList(weightDetailVOs);
//               result.add(orderWeightInfoVO);
//               if (CollUtil.isNotEmpty(weightDetailVOs)) {
//                  Map<Long, Double> dishesQuantityMap = (Map)weightDetailVOs.stream().filter((s) -> {
//                     return LeNumUtil.isValidId(s.getGoodsDishesId()) && s.totalGram() > 0.0;
//                  }).collect(Collectors.toMap(OrderWeightDetailVO::getGoodsDishesId, OrderWeightDetailVO::totalGram, Double::sum));
//                  OrderNutrientInfoVO nutrientInfo = this.orderInfoMobileBusiness.getNutrientInfo(dishesQuantityMap);
//                  orderWeightInfoVO.setNutrientInfo(nutrientInfo);
//               }
//            }
//         }
//
//         return this.orderCustomBusiness.weight().didConvertOrderList(orderSavePO, result);
//      } else {
//         return ListUtil.empty();
//      }
//   }
//
//   protected OrderWeightPayVO noNeedPayHandler(String macOrderId, List<OrderInfo> notNeedPayOrders, Integer weightBindType, Long custId, String openid) {
//      LogUtil.infoFieldsX("不需要支付", notNeedPayOrders, OrderInfo.logFieldsRelated());
//      this.cancelOrdersIfNeed(notNeedPayOrders);
//      OrderWeightPayVO vo = new OrderWeightPayVO();
//      vo.setCode(LeRetCodeEnum.SUCC.getKey());
//      vo.setMsg(LeRetCodeEnum.SUCC.getDesc());
//      vo.setMacOrderId(macOrderId);
//      vo.setPayType(PayTypeEnum.MEAL_CARD.getKey());
//      vo.setPayAmount(0);
//      vo.setAccPayAmount(0);
//      vo.setOutPayAmount(0);
//      vo.setRealAmount(0);
//      this.fillAccInfoInNeed(custId, vo);
//      if (CollUtil.isNotEmpty(notNeedPayOrders) && notNeedPayOrders.stream().noneMatch((s) -> {
//         return PayStateEnum.isPaidState(s.getPayState());
//      })) {
//         this.orderPlaceBusiness.cleanCache(macOrderId);
//      }
//
//      OrderCustomWeightNoNeedPayPO customDTO = OrderCustomWeightNoNeedPayPO.of(macOrderId, notNeedPayOrders, weightBindType, custId, openid);
//      return this.orderCustomBusiness.weight().didHandleNoNeedPay(customDTO, vo);
//   }
//
//   protected void placeExceptionHandler(OrderWeightPlaceOrderDTO placeOrderDTO, OrderSavePO orderSavePO, Exception e) {
//      log.error("自助餐下单异常 {} {}", new Object[]{placeOrderDTO, orderSavePO, e});
//   }
//
//   protected OrderWeightPayVO payExceptionHandler(OrderWeightPayDTO weightPayDTO, OrderSavePO orderSavePO, Exception e) {
//      log.error("自助餐结算异常 {}, {}", new Object[]{weightPayDTO, orderSavePO, e});
//      ObjectNode jsonNodes = JacksonUtil.objectNode();
//      jsonNodes.set("weightPayDTO", JacksonUtil.valueToTree(weightPayDTO));
//      jsonNodes.set("orderSavePO", JacksonUtil.valueToTree(orderSavePO));
//      this.orderErrorLogService.saveError((Long)null, LogUtil.getCurrentTraceId(), OrderErrorTypeEnum.WEIGHT_ORDER_PAY, e.getMessage(), JacksonUtil.writeValueAsString(jsonNodes));
//      OrderWeightPayVO vo = new OrderWeightPayVO();
//      if (e instanceof LeException) {
//         vo.setCode(((LeException)e).getCode());
//         vo.setMsg(e.getMessage());
//      } else {
//         vo.setCode(LeRetCodeEnum.FAIL.getKey());
//         vo.setMsg(LeRetCodeEnum.FAIL.getDesc());
//      }
//
//      return vo;
//   }
//
//   protected void cancelOrdersIfNeed(List<OrderInfo> notNeedPayOrders) {
//      if (CollUtil.isNotEmpty(notNeedPayOrders)) {
//         List<Long> cancelOrderIds = (List)notNeedPayOrders.stream().filter((s) -> {
//            return PayStateEnum.isUnPayState(s.getPayState()) && !OrderStateEnum.isCancelState(s.getOrderState());
//         }).map(OrderInfo::getOrderId).collect(Collectors.toList());
//         List<LocalDate> dates = (List)notNeedPayOrders.stream().filter((s) -> {
//            return cancelOrderIds.contains(s.getOrderId());
//         }).map(OrderInfo::getOrderDate).collect(Collectors.toList());
//         this.orderInfoService.updateCancelByOrderIds(cancelOrderIds, dates);
//         notNeedPayOrders.stream().filter((s) -> {
//            return cancelOrderIds.contains(s.getOrderId());
//         }).forEach((s) -> {
//            s.setOrderState(OrderStateEnum.CANCEL.getKey());
//         });
//      }
//
//   }
//
//   protected void fillAccInfoInNeed(Long custId, OrderWeightPayVO vo) {
//      if (LeNumUtil.isValidId(custId) && vo.getAccBal() == null) {
//         AccInfoDetailVO accInfoDetail = this.accInfoServiceV3Api.getAccInfoDetail(custId);
//         vo.setAccBal(accInfoDetail.getAccAllBal().intValue());
//         vo.setWalletBal(accInfoDetail.getWalletBal().intValue());
//         vo.setSubsidyBal(accInfoDetail.getSubsidyBal().intValue());
//         vo.setRedEnvelope(accInfoDetail.getRedEnvelope().intValue());
//      }
//
//   }
}
