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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import com.bonus.canteen.core.account.v3.api.AccPayBusinessApi;
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.AllocStallApi;
import com.bonus.canteen.core.common.constant.NuclearModeEnum;
import com.bonus.canteen.core.common.enums.DeliveryTypeEnum;
import com.bonus.canteen.core.common.enums.SourceTypeEnum;
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.customer.vo.CustPayVO;
import com.bonus.canteen.core.device.api.DeviceApi;
import com.bonus.canteen.core.device.manage.vo.DeviceInfoVO;
import com.bonus.canteen.core.menu.model.AllocMealtimeModel;
import com.bonus.canteen.core.order.android.business.OrderDishesAndroidBusiness;
import com.bonus.canteen.core.order.android.business.OrderPlaceAndroidBusiness;
import com.bonus.canteen.core.order.android.dto.OrderPayAndroidDTO;
import com.bonus.canteen.core.order.android.dto.OrderPayAndroidTotalDTO;
import com.bonus.canteen.core.order.android.vo.OrderPayAndroidVO;
import com.bonus.canteen.core.order.client.OrderModuleClient;
import com.bonus.canteen.core.order.client.po.CustPayInfoQueryParam;
import com.bonus.canteen.core.order.common.business.OrderPlaceBusiness;
import com.bonus.canteen.core.order.common.business.OrderResultBusiness;
import com.bonus.canteen.core.order.common.constants.ChangeDetailTypeEnum;
import com.bonus.canteen.core.order.common.constants.OrderErrorTypeEnum;
import com.bonus.canteen.core.order.common.constants.OrderTips;
import com.bonus.canteen.core.order.common.constants.OrderTypeEnum;
import com.bonus.canteen.core.order.common.dto.OrderDetailPayDTO;
import com.bonus.canteen.core.order.common.dto.OrderDidPayInfoDTO;
import com.bonus.canteen.core.order.common.model.*;
import com.bonus.canteen.core.order.common.service.*;
import com.bonus.canteen.core.order.custom.OrderCustomBusiness;
import com.bonus.canteen.core.order.mobile.vo.OrderAmountChangeVO;
import com.bonus.canteen.core.order.mq.OrderMessageSend;
import com.bonus.canteen.core.order.mq.po.OrderSavePO;
import com.bonus.canteen.core.order.utils.LeNumUtil;
import com.bonus.canteen.core.order.weight.service.MacWeighBindService;
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.PayChannelSelectEnum;
import com.bonus.canteen.core.pay.common.constants.PayStateEnum;
import com.bonus.canteen.core.pay.common.constants.PayTypeEnum;
import com.bonus.canteen.core.pay.common.constants.TradeTypeEnum;
import com.bonus.canteen.core.pay.common.model.TradeRecord;
import com.bonus.canteen.core.pay.common.vo.PayChannelSelectDTO;
import com.bonus.canteen.core.pay.common.vo.PayChannelSelectResultVO;
import com.bonus.canteen.core.pay.common.vo.TradeChannelVO;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.common.houqin.constant.LeConstants;
import com.bonus.common.houqin.constant.RetCodeEnum;
import com.bonus.common.houqin.i18n.I18n;
import com.bonus.canteen.core.common.utils.*;
import com.bonus.common.houqin.utils.id.Id;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class OrderPlaceAndroidBusinessImpl implements OrderPlaceAndroidBusiness {
   private static final Logger log = LoggerFactory.getLogger(OrderPlaceAndroidBusinessImpl.class);
   @Autowired
   @Lazy
   protected OrderPlaceBusiness orderPlaceBusiness;
   @Autowired
   @Lazy
   protected OrderResultBusiness orderResultBusiness;
   @Autowired
   @Lazy
   protected OrderDishesAndroidBusiness orderDishesAndroidBusiness;
   @Autowired
   @Lazy
   protected OrderCustomBusiness orderCustomBusiness;
   @Autowired
   @Lazy
   protected OrderModuleClient orderModuleClient;
   @Autowired
   @Lazy
   protected OrderInfoService orderInfoService;
   @Autowired
   @Lazy
   protected OrderDetailService orderDetailService;
   @Autowired
   @Lazy
   protected OrderDeliveryService orderDeliveryService;
   @Autowired
   @Lazy
   protected OrderAmountChangeService orderAmountChangeService;
   @Autowired
   @Lazy
   protected MacWeighBindService macWeighBindService;
   @Autowired
   @Lazy
   protected OrderRefundService orderRefundService;
   @Autowired
   @Lazy
   protected OrderErrorLogService orderErrorLogService;
   @Autowired
   @Lazy
   protected PayApi payApi;
   @Autowired
   @Lazy
   protected TradeRecordApi tradeRecordApi;
   @Autowired
   @Lazy
   protected AccInfoServiceV3Api accInfoServiceV3Api;
   @Autowired
   @Lazy
   protected DeviceApi deviceApi;
   @Autowired
   @Lazy
   protected AllocStallApi allocStallApi;
   @Autowired
   @Lazy
   protected AccPayBusinessApi accPayBusinessApi;
   @Value("${pay.async-pay-enable}")
   protected Boolean asyncPayEnable;

   public OrderPayAndroidVO placeAndPay(OrderPayAndroidTotalDTO androidTotalDTO, DeviceInfoVO deviceInfoVO) {
      LogUtil.info("[设备下单]placeAndPay入参", androidTotalDTO);
      this.orderPlaceBusiness.checkOrderSubmitted(androidTotalDTO.getMacOrderId());
      JavaxValidateUtils.validate(androidTotalDTO);
      this.orderPlaceBusiness.orderHandlerLock(androidTotalDTO.getMacOrderId(), 600);
      OrderSavePO orderSavePO = OrderSavePO.byLockKey(androidTotalDTO.getMacOrderId());

      OrderPayAndroidVO var7;
      try {
         this.checkPlaceParam(androidTotalDTO);
         orderSavePO.setPayDTO(this.createPay(androidTotalDTO, deviceInfoVO));
         this.packageOrderInfo(androidTotalDTO, deviceInfoVO, orderSavePO);
         this.orderPlaceBusiness.checkOrderPermission(orderSavePO.getOrderInfoList(), orderSavePO.getOrderDetailList());
         List<OrderAmountChange> amountChangeList = this.orderPlaceBusiness.calcNeedPayAmount(orderSavePO.getOrderInfoList(), orderSavePO.getOrderDetailList());
         List amountChangeListRole;
         if (!OrderTypeEnum.isShopCategory(androidTotalDTO.getOrderType())) {
            amountChangeListRole = this.orderPlaceBusiness.customNeedPayAmount(orderSavePO.getOrderInfoList(), androidTotalDTO.getAmount());
            amountChangeList.addAll(amountChangeListRole);
         }

         orderSavePO.getPayDTO().setAmount(LeNumUtil.sumField(orderSavePO.getOrderInfoList(), OrderInfo::calcNeedPayAmount));
         amountChangeListRole = this.orderPlaceBusiness.calcRuleAmount(orderSavePO.getPayDTO(), orderSavePO.getOrderInfoList(), orderSavePO.getOrderDetailList(), LeConstants.COMMON_YES.equals(androidTotalDTO.getIfTrial()));
         amountChangeList.addAll(amountChangeListRole);
         this.orderPlaceBusiness.checkCoupon(orderSavePO.getPayDTO(), orderSavePO.getOrderInfoList());
         orderSavePO.setAmountChangeList(amountChangeList);
         OrderPayAndroidVO customVO;
         if (LeConstants.COMMON_YES.equals(androidTotalDTO.getIfTrial())) {
            customVO = this.trialPay(orderSavePO);
            return customVO;
         }

         if (androidTotalDTO.ifOnline() && SourceTypeEnum.BUFFET.getKey().equals(deviceInfoVO.getDeviceType()) || OrderTypeEnum.isShopType(((OrderInfo)orderSavePO.getOrderInfoList().get(0)).getOrderType())) {
            this.orderPlaceBusiness.inventoryDeduct(orderSavePO.getOrderInfoList(), orderSavePO.getOrderDetailList());
         }

         customVO = this.orderCustomBusiness.android().willOrderPay(orderSavePO);
         if (customVO == null) {
            orderSavePO.getPayDTO().setIfFastAsyncPay(androidTotalDTO.ifOnline() && Boolean.TRUE.equals(this.asyncPayEnable) ? LeConstants.COMMON_YES : LeConstants.COMMON_NO);
            orderSavePO.setPayVO(this.orderPlaceBusiness.pay(orderSavePO.getPayDTO(), orderSavePO.getOrderInfoList(), orderSavePO.getOrderDetailList()));
            var7 = this.payResultHandler(orderSavePO);
            return var7;
         }

         var7 = customVO;
      } catch (Exception var11) {
         OrderPayAndroidVO var5 = this.payExceptionHandler(androidTotalDTO, orderSavePO, var11);
         return var5;
      } finally {
         if (!LeConstants.COMMON_YES.equals(androidTotalDTO.getIfTrial())) {
            OrderMessageSend.orderV3AsyncSave(orderSavePO);
         }

      }

      return var7;
   }

   public OrderPayAndroidVO packagePayAndroidVOByOrderSavePo(OrderSavePO orderSavePO, boolean ifTrial) {
      OrderPayAndroidVO payAndroidVO;
      if (ifTrial) {
         if (orderSavePO.getPayVO() != null) {
            payAndroidVO = OrderPayAndroidVO.of(orderSavePO.getPayVO());
         } else {
            payAndroidVO = OrderPayAndroidVO.of(RetCodeEnum.SUCC.getKey(), RetCodeEnum.SUCC.getDesc());
            payAndroidVO.setPayAmount(orderSavePO.getPayDTO().getAmount() != null ? orderSavePO.getPayDTO().getAmount().intValue() : 0);
            payAndroidVO.fillCustInfo(orderSavePO.getPayDTO());
         }

         payAndroidVO.setOrderList(orderSavePO.getOrderInfoList().stream().map(OrderPayAndroidVO.Order::of).collect(Collectors.toList()));
         payAndroidVO.setMacOrderId(((OrderInfo)orderSavePO.getOrderInfoList().get(0)).getMacOrderId());
      } else {
         payAndroidVO = OrderPayAndroidVO.of(orderSavePO.getPayVO());
         if (orderSavePO.getPayVO().getCustId() != null && !ObjectUtil.equal(orderSavePO.getPayDTO().getCustId(), orderSavePO.getPayVO().getCustId())) {
            CustPayVO custPayVO = this.orderModuleClient.custPayInfoQuery(CustPayInfoQueryParam.ofCustId(orderSavePO.getPayVO().getCustId()));
            Iterator var5 = orderSavePO.getOrderInfoList().iterator();

            while(var5.hasNext()) {
               OrderInfo orderInfo = (OrderInfo)var5.next();
               orderInfo.fillCustInfo(custPayVO);
            }

            payAndroidVO.fillCustInfo(custPayVO);
         } else {
            payAndroidVO.fillCustInfo(orderSavePO.getPayDTO());
         }

         payAndroidVO.fillCustInfoIfNecessary(orderSavePO.getPayVO());
         if (CharSequenceUtil.isBlank(payAndroidVO.getCustName()) && CharSequenceUtil.isNotBlank(orderSavePO.getPayVO().getCustName())) {
            payAndroidVO.setCustName(orderSavePO.getPayVO().getCustName());
         }

         if (CollUtil.isNotEmpty(orderSavePO.getOrderInfoList())) {
            payAndroidVO.fillOrderInfoList(orderSavePO.getOrderInfoList());
            payAndroidVO.setMacOrderId(((OrderInfo)orderSavePO.getOrderInfoList().get(0)).getMacOrderId());
         }
      }

      payAndroidVO.setOrderAmountChangeList(orderSavePO.getAmountChangeList().stream().filter((s) -> {
         return ChangeDetailTypeEnum.DISHES_DISCOUNTS.getKey().equals(s.getChangeDetailType()) || ChangeDetailTypeEnum.RULE_DISCOUNT.getKey().equals(s.getChangeDetailType());
      }).map(OrderAmountChangeVO::of).collect(Collectors.toList()));
      return payAndroidVO;
   }

   public OrderPayAndroidVO queryPayResult(String macOrderId) {
      OrderPayAndroidVO customVO = this.orderCustomBusiness.android().willQueryPayResult(macOrderId);
      if (customVO != null) {
         return this.orderCustomBusiness.android().didQueryPayResult(macOrderId, customVO);
      } else {
         this.orderPlaceBusiness.orderHandlerLock(macOrderId, 30);

         OrderPayAndroidVO var5;
         try {
            List<OrderInfo> orderInfoList = this.orderInfoService.listOrderInfoByMacOrderId(macOrderId, LocalDate.now().minusDays(1L), LocalDate.now().plusDays(1L));
            LogUtil.infoFields("设备查询订单", orderInfoList, OrderInfo.logFields());
            if (CollUtil.isEmpty(orderInfoList)) {
               throw new ServiceException(OrderTips.noOrder(), RetCodeEnum.PAY_SELECT_ORD_NO_EXIT.getKey());
            }

            OrderPayAndroidVO resultVO = this.convertOrderPayResult(orderInfoList);
            var5 = this.orderCustomBusiness.android().didQueryPayResult(macOrderId, resultVO);
         } finally {
            this.orderPlaceBusiness.orderHandlerUnLock(macOrderId);
         }

         return var5;
      }
   }

   public DeviceInfoVO getDeviceInfoByHeader(Map<String, String> headers, boolean throwIfNotFound) {
      DeviceInfoVO deviceInfoVO = null;
      String machineSn = HeaderFetchUtil.getMachineSn(headers);
      String machineNum = HeaderFetchUtil.getMachineNum(headers);
      if (CharSequenceUtil.isNotBlank(machineSn)) {
         deviceInfoVO = this.deviceApi.getDeviceInfoVoBySnCacheable(machineSn);
      } else if (CharSequenceUtil.isNotBlank(machineNum)) {
         deviceInfoVO = this.deviceApi.getDeviceInfoVoByNumCacheable(machineNum);
      }

      if (deviceInfoVO == null && throwIfNotFound) {
         throw new ServiceException(I18n.getMessage("order.locker.no-device-info", new Object[0]));
      } else {
         return deviceInfoVO;
      }
   }

   protected void checkPlaceParam(OrderPayAndroidTotalDTO androidTotalDTO) {
      if (!this.orderCustomBusiness.android().willPlaceParamCheck(androidTotalDTO)) {
         this.orderCustomBusiness.android().didPlaceParamCheck(androidTotalDTO);
      } else if (!OrderTypeEnum.isAndroidType(androidTotalDTO.getOrderType()) && !OrderTypeEnum.isBuffetType(androidTotalDTO.getOrderType()) && !OrderTypeEnum.isShopType(androidTotalDTO.getOrderType()) && !OrderTypeEnum.isBusType(androidTotalDTO.getOrderType())) {
         throw new ServiceException(I18n.getMessage("order.un-support-order-type", new Object[0]));
      } else {
         if (!androidTotalDTO.ifOnline()) {
            this.orderPlaceBusiness.checkMacOrderId(androidTotalDTO.getMacOrderId(), true);
         }

         if (OrderTypeEnum.isCanteenCategory(androidTotalDTO.getOrderType()) && androidTotalDTO.ifOnline()) {
            Iterator var2 = androidTotalDTO.getOrderList().iterator();

            while(var2.hasNext()) {
               OrderPayAndroidDTO orderPayAndroidDTO = (OrderPayAndroidDTO)var2.next();
               AllocMealtimeModel mealtimeModel = this.orderPlaceBusiness.checkMealtime(orderPayAndroidDTO.getMealtimeType(),
                       orderPayAndroidDTO.getOrderTime(), orderPayAndroidDTO.getCanteenId(), orderPayAndroidDTO.getStallId());
               orderPayAndroidDTO.setMealtimeType(mealtimeModel.getMealtimeType());
               orderPayAndroidDTO.setMealtimeName(mealtimeModel.getMealtimeName());
            }
         }

         this.orderCustomBusiness.android().didPlaceParamCheck(androidTotalDTO);
      }
   }

   protected UnifyPayDTO createPay(OrderPayAndroidTotalDTO orderPayAndroidTotalDTO, DeviceInfoVO deviceInfoVO) {
      PayChannelSelectDTO payChannelSelectDTO = this.packagePayChannelSelectDTO(orderPayAndroidTotalDTO, deviceInfoVO);
      PayChannelSelectEnum scenario = orderPayAndroidTotalDTO.ifOnline() ? PayChannelSelectEnum.DEVICE_CONSUME : PayChannelSelectEnum.DEVICE_OFFLINE_CONSUME;
      PayChannelSelectResultVO payChannelSelectResultVO = this.payApi.payChannelSelect(scenario, payChannelSelectDTO);
      UnifyPayDTO unifyPayDTO = UnifyPayDTO.of(payChannelSelectResultVO);
      unifyPayDTO.setTradeId(Id.next());
      unifyPayDTO.setTradeType(TradeTypeEnum.CONSUME.getKey());
      unifyPayDTO.setAuthCode(orderPayAndroidTotalDTO.getQrCode());
      unifyPayDTO.setSerialNum(orderPayAndroidTotalDTO.getSerialNum());
      unifyPayDTO.setNuClearMode(orderPayAndroidTotalDTO.getNuClearMode());
      unifyPayDTO.setOrderTime(((OrderPayAndroidDTO)orderPayAndroidTotalDTO.getOrderList().get(0)).getOrderTime());
      unifyPayDTO.setTerminalParams(orderPayAndroidTotalDTO.getTerminalParams());
      unifyPayDTO.setAlipayFaceAsync(orderPayAndroidTotalDTO.getAlipayFaceAsync());
      unifyPayDTO.fillDeviceInfo(deviceInfoVO);
      if (LeConstants.COMMON_YES.equals(orderPayAndroidTotalDTO.getAlipayFaceAsync()) && payChannelSelectResultVO.getCustPayVO() != null) {
         unifyPayDTO.setScenario(PayChannelSelectEnum.DEVICE_CONSUME.getKey());
      } else {
         unifyPayDTO.setScenario(scenario.getKey());
      }

      this.orderCustomBusiness.android().didCreatePay(orderPayAndroidTotalDTO, unifyPayDTO);
      return unifyPayDTO;
   }

   protected OrderPayAndroidVO payResultHandler(OrderSavePO orderSavePO) {
      LogUtil.info("处理支付结果", orderSavePO.getPayVO());
      UnifyPayVO payVO = orderSavePO.getPayVO();
      List<OrderInfo> orderInfoList = orderSavePO.getOrderInfoList();
      if (PayStateEnum.isPaidState(payVO.getCode()) && !payVO.isAsyncPay()) {
         List<OrderAmountDetail> orderAmountDetails = this.orderPlaceBusiness.calcOrderRealAmount(orderSavePO.getOrderInfoList(),
                 orderSavePO.getOrderDetailList(), orderSavePO.getAmountChangeList(), orderSavePO.getPayVO().getRealAmount(), orderSavePO.getPayVO().getDetailList());
         orderSavePO.setAmountDetailList(orderAmountDetails);
         Iterator var9 = orderInfoList.iterator();

         while(var9.hasNext()) {
            OrderInfo orderInfo = (OrderInfo)var9.next();
            this.orderPlaceBusiness.updateOrderFieldAfterPay(orderInfo, OrderDidPayInfoDTO.of(payVO));
         }

         if (SourceTypeEnum.ANDROID_BINDING.getKey().equals(((OrderInfo)orderSavePO.getOrderInfoList().get(0)).getSourceType())
                 || CharSequenceUtil.isNotEmpty(((OrderInfo)orderSavePO.getOrderInfoList().get(0)).getPlateSerialNum())) {
            this.macWeighBindService.cleanAfterOrderPaid(((OrderInfo)orderSavePO.getOrderInfoList().get(0)).getMacOrderId(),
                    ((OrderInfo)orderSavePO.getOrderInfoList().get(0)).getPlateSerialNum());
         }
      } else {
         Iterator var4 = orderSavePO.getOrderInfoList().iterator();

         while(var4.hasNext()) {
            OrderInfo orderInfo = (OrderInfo)var4.next();
            orderInfo.setPayState(orderSavePO.getPayVO().getCode());
         }
      }

      OrderPayAndroidVO payAndroidVO = this.packagePayAndroidVOByOrderSavePo(orderSavePO, false);
      payAndroidVO = this.orderCustomBusiness.android().didPayResultHandler(orderSavePO.getPayDTO(), orderSavePO.getPayVO(), orderSavePO.getOrderInfoList(), orderSavePO.getOrderDetailList(), payAndroidVO);
      return payAndroidVO;
   }

   protected OrderPayAndroidVO trialPay(OrderSavePO orderSavePO) {
      orderSavePO.getPayDTO().setIfTrail(LeConstants.COMMON_YES);
      orderSavePO.setPayVO(this.orderPlaceBusiness.pay(orderSavePO.getPayDTO(), orderSavePO.getOrderInfoList(), orderSavePO.getOrderDetailList()));
      OrderPayAndroidVO payAndroidVO = this.packagePayAndroidVOByOrderSavePo(orderSavePO, true);
      payAndroidVO = this.orderCustomBusiness.android().didTrialResultHandler(orderSavePO, payAndroidVO);
      return payAndroidVO;
   }

   protected BigDecimal payFloatUpHandle(BigDecimal amount, Integer payType, Long custId, AllocPayModel allocPayModel) {
      String payFloatUpRateSetting = null;
      if (!LeNumUtil.isValidId(custId)) {
         if (PayTypeEnum.WECHAT_QRCODE.getKey().equals(payType) && CharSequenceUtil.isNotBlank(allocPayModel.getWechatPayFloatUpRate())) {
            payFloatUpRateSetting = allocPayModel.getWechatPayFloatUpRate();
         } else if (PayTypeEnum.ALI_QRCODE.getKey().equals(payType) && CharSequenceUtil.isNotBlank(allocPayModel.getAliPayFloatUpRate())) {
            payFloatUpRateSetting = allocPayModel.getAliPayFloatUpRate();
         }

         if (CharSequenceUtil.isNotBlank(payFloatUpRateSetting)) {
            BigDecimal upRateAmount = amount.multiply(new BigDecimal(allocPayModel.getWechatPayFloatUpRate())).divide(new BigDecimal("100"), 0, RoundingMode.HALF_UP);
            amount = amount.add(upRateAmount);
            LogUtil.info("设备下单", "上浮比例", payFloatUpRateSetting, "上浮后金额", amount);
         }
      }

      return amount;
   }

   protected OrderPayAndroidVO convertOrderPayResult(List<OrderInfo> orderInfoList) {
      TradeRecord tradeRecord = this.tradeRecordApi.getLastTradeRecordByOrderId(orderInfoList.get(0).getOrderId());
      if (tradeRecord == null) {
         return OrderPayAndroidVO.of(RetCodeEnum.PAY_QRCODE_ORD_ERROR.getKey(), I18n.getMessage("order.mac.pay-failed", new Object[0]));
      } else if (PayStateEnum.isPayingState(tradeRecord.getTradeState())) {
         return OrderPayAndroidVO.of(RetCodeEnum.PAY_QRCODE_ING.getKey(), tradeRecord.getTradeResult());
      } else {
         List<TradeChannelVO> channelVOList = this.tradeRecordApi.listChannelDetailByTradeId(tradeRecord.getId());
         OrderPayAndroidVO orderPayAndroidVO = OrderPayAndroidVO.of(tradeRecord, channelVOList);
         orderPayAndroidVO.setMacOrderId(((OrderInfo)orderInfoList.get(0)).getMacOrderId());
         if (PayStateEnum.isPaidState(tradeRecord.getTradeState())) {
            orderPayAndroidVO.fillOrderInfoList(orderInfoList);
         }

         Long custId = ((OrderInfo)orderInfoList.get(0)).getCustId();
         if (LeNumUtil.isValidId(custId)) {
            CustPayVO custPayVO = this.orderModuleClient.custPayInfoQuery(CustPayInfoQueryParam.ofCustId(custId));
            orderPayAndroidVO.fillCustInfo(custPayVO);
            AccInfoDetailVO accInfoDetail = this.accInfoServiceV3Api.getAccInfoDetail(custId);
            orderPayAndroidVO.setAccBal(accInfoDetail.getAccAllBal().intValue());
            orderPayAndroidVO.setWalletBal(accInfoDetail.getWalletBal().intValue());
            orderPayAndroidVO.setSubsidyBal(accInfoDetail.getSubsidyBal().intValue());
            orderPayAndroidVO.setRedEnvelope(accInfoDetail.getRedEnvelope().intValue());
         }

         return orderPayAndroidVO;
      }
   }

   protected OrderPayAndroidVO payExceptionHandler(OrderPayAndroidTotalDTO androidTotalDTO, OrderSavePO orderSavePO, Exception e) {
      log.error("设备下单异常 {}, {}", new Object[]{androidTotalDTO, orderSavePO, e});
      if (!androidTotalDTO.ifOnline()) {
         ObjectNode jsonNodes = JacksonUtil.objectNode();
         jsonNodes.set("androidTotalDTO", JacksonUtil.valueToTree(androidTotalDTO));
         jsonNodes.set("orderSavePO", JacksonUtil.valueToTree(orderSavePO));
         this.orderErrorLogService.saveError((Long)null, LogUtil.getCurrentTraceId(), OrderErrorTypeEnum.OFFLINE_ORDER, e.getMessage(), JacksonUtil.writeValueAsString(jsonNodes));
      }

      OrderPayAndroidVO vo = new OrderPayAndroidVO();
      if (e instanceof ServiceException) {
         vo.setCode(((ServiceException)e).getCode());
         vo.setMsg(e.getMessage());
      } else {
         vo.setCode(RetCodeEnum.FAIL.getKey());
         vo.setMsg(RetCodeEnum.FAIL.getDesc());
      }

      vo.setMacOrderId(orderSavePO.getMacOrderId());
      return vo;
   }

   protected void packageOrderInfo(OrderPayAndroidTotalDTO androidTotalDTO, DeviceInfoVO deviceInfoVO, OrderSavePO orderSavePO) {
      Iterator var4 = androidTotalDTO.getOrderList().iterator();

      while(var4.hasNext()) {
         OrderPayAndroidDTO orderPayAndroidDTO = (OrderPayAndroidDTO)var4.next();
         OrderInfo orderInfo = orderPayAndroidDTO.convertToOrderInfo();
         orderInfo.setOrderId(Id.next());
         orderInfo.setMacOrderId(androidTotalDTO.getMacOrderId());
         orderInfo.setOrderType(androidTotalDTO.getOrderType());
         orderInfo.setIfOnline(androidTotalDTO.getIfOnline());
         orderInfo.setConsumMode(androidTotalDTO.getConsumMode());
         orderInfo.setMachineSn(deviceInfoVO.getDeviceSn());
         orderInfo.setMachineNum(deviceInfoVO.getDeviceNum());
         orderInfo.setSourceType(deviceInfoVO.getDeviceType());
         orderInfo.setNuClearMode(orderSavePO.getPayDTO().getNuClearMode());
         orderInfo.setPayType(orderSavePO.getPayDTO().getPayType());
         orderInfo.setPayChannel(orderSavePO.getPayDTO().getPayChannel());
         orderInfo.fillCustInfo(orderSavePO.getPayDTO());
         if (NuclearModeEnum.isCard(androidTotalDTO.getNuClearMode())) {
            orderInfo.setPayParam(androidTotalDTO.getSerialNum());
         } else if (NuclearModeEnum.isQrCode(androidTotalDTO.getNuClearMode())) {
            orderInfo.setPayParam(androidTotalDTO.getQrCode());
         }

         orderSavePO.getOrderInfoList().add(orderInfo);
         OrderDelivery orderDelivery = orderPayAndroidDTO.convertToOrderDelivery();
         if (DeliveryTypeEnum.isValidType(orderDelivery.getDeliveryType())) {
            orderDelivery.setDeliveryId(Id.next());
            orderDelivery.setOrderId(orderInfo.getOrderId());
            orderDelivery.setOrderDate(orderInfo.getOrderDate());
            if (CharSequenceUtil.isBlank(orderDelivery.getConsigneeName())) {
               orderDelivery.setConsigneeName(orderSavePO.getPayDTO().getCustName());
            }

            if (CharSequenceUtil.isBlank(orderDelivery.getDeliveryMobile())) {
               orderDelivery.setConsigneeMobile(orderSavePO.getPayDTO().getMobile());
            }

            orderSavePO.getOrderDeliveryList().add(orderDelivery);
         }

         orderInfo.setOperatorId(androidTotalDTO.getOperatorId());
         orderInfo.setOperatorName(androidTotalDTO.getOperatorName());
         orderInfo.setCashierId(androidTotalDTO.getOperatorId());
         orderInfo.setCashierName(androidTotalDTO.getOperatorName());
         Iterator var8 = orderPayAndroidDTO.getOrderDetailList().iterator();

         while(var8.hasNext()) {
            OrderDetailPayDTO detailPayDTO = (OrderDetailPayDTO)var8.next();
            OrderDetail orderDetail = detailPayDTO.convertToOrderDetail();
            orderDetail.setDetailId(Id.next());
            orderDetail.setOrderId(orderInfo.getOrderId());
            orderDetail.setMachineSn(orderInfo.getMachineSn());
            orderDetail.setOrderDate(orderInfo.getOrderDate());
            orderSavePO.getOrderDetailList().add(orderDetail);
         }
      }

      this.orderCustomBusiness.android().didPackageOrderInfo(androidTotalDTO, deviceInfoVO, orderSavePO.getPayDTO(), orderSavePO.getOrderInfoList(), orderSavePO.getOrderDetailList(), orderSavePO.getOrderDeliveryList());
   }

   protected PayChannelSelectDTO packagePayChannelSelectDTO(OrderPayAndroidTotalDTO orderPayAndroidTotalDTO, DeviceInfoVO deviceInfoVO) {
      PayChannelSelectDTO payChannelSelectDTO = new PayChannelSelectDTO();
      payChannelSelectDTO.setNuClearMode(orderPayAndroidTotalDTO.getNuClearMode());
      payChannelSelectDTO.setPayType(orderPayAndroidTotalDTO.getPayType());
      payChannelSelectDTO.setCouponNum(orderPayAndroidTotalDTO.getCouponNum());
      payChannelSelectDTO.setOpenId(orderPayAndroidTotalDTO.getOpenid());
      payChannelSelectDTO.setSerialNum(orderPayAndroidTotalDTO.getSerialNum());
      payChannelSelectDTO.setAuthCode(orderPayAndroidTotalDTO.getQrCode());
      payChannelSelectDTO.setCustId(orderPayAndroidTotalDTO.getCustId());
      payChannelSelectDTO.setCanteenId((Long)LeNumUtil.reduceField(orderPayAndroidTotalDTO.getOrderList(), OrderPayAndroidDTO::getCanteenId, (Object)null));
      payChannelSelectDTO.setStallId((Long)LeNumUtil.reduceField(orderPayAndroidTotalDTO.getOrderList(), OrderPayAndroidDTO::getStallId, (Object)null));
      payChannelSelectDTO.setOnlineState(LeConstants.COMMON_YES);
      payChannelSelectDTO.setSourceType(deviceInfoVO.getDeviceType());
      payChannelSelectDTO.setCustId(orderPayAndroidTotalDTO.getCustId());
      payChannelSelectDTO.setMachineSn(deviceInfoVO.getDeviceSn());
      return payChannelSelectDTO;
   }
}
