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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.bonus.canteen.core.allocation.api.FlowApi;
import com.bonus.canteen.core.allocation.flow.enums.FlowDefinitionEum;
import com.bonus.canteen.core.auth.api.MgrAuthApi;
import com.bonus.canteen.core.common.page.PageDTO;
import com.bonus.canteen.core.common.page.PageVO;
import com.bonus.canteen.core.common.utils.JavaxValidateUtils;
import com.bonus.canteen.core.common.utils.LogUtil;
import com.bonus.canteen.core.customer.dto.CustOrgTreeDTO;
import com.bonus.canteen.core.device.api.DeviceApi;
import com.bonus.canteen.core.menu.model.AllocMealtimeModel;
import com.bonus.canteen.core.order.android.business.OrderDishesAndroidBusiness;
import com.bonus.canteen.core.order.client.OrderModuleClient;
import com.bonus.canteen.core.order.client.po.CustPlaceListQueryParam;
import com.bonus.canteen.core.order.client.po.MealtimeQueryParam;
import com.bonus.canteen.core.order.common.business.OrderResultBusiness;
import com.bonus.canteen.core.order.common.constants.*;
import com.bonus.canteen.core.order.common.dto.OrderPreBookQueryDTO;
import com.bonus.canteen.core.order.common.dto.OrderSearchParam;
import com.bonus.canteen.core.order.common.model.OrderAmountDetail;
import com.bonus.canteen.core.order.common.model.OrderInfo;
import com.bonus.canteen.core.order.common.model.OrderRefund;
import com.bonus.canteen.core.order.common.query.OrderIndexType;
import com.bonus.canteen.core.order.common.query.OrderQueryHelper;
import com.bonus.canteen.core.order.common.service.*;
import com.bonus.canteen.core.order.common.vo.OrderDetailVO;
import com.bonus.canteen.core.order.common.vo.OrderIdDateVO;
import com.bonus.canteen.core.order.common.vo.OrderPreBookVO;
import com.bonus.canteen.core.order.custom.OrderCustomBusiness;
import com.bonus.canteen.core.order.deprecated.dto.OrderDetailSumGetDTO;
import com.bonus.canteen.core.order.deprecated.vo.OrderDetailSumGetVO;
import com.bonus.canteen.core.order.mobile.vo.OrderAmountChangeVO;
import com.bonus.canteen.core.order.utils.LeNumUtil;
import com.bonus.canteen.core.order.utils.LeOrderUtil;
import com.bonus.canteen.core.order.web.business.OrderWebBusiness;
import com.bonus.canteen.core.order.web.dto.OrderDeliveryDetailDTO;
import com.bonus.canteen.core.order.web.dto.OrderDetailWebDTO;
import com.bonus.canteen.core.order.web.dto.OrderRefundWebDTO;
import com.bonus.canteen.core.order.web.dto.OrderUserPermissionDTO;
import com.bonus.canteen.core.order.web.vo.*;
import com.bonus.canteen.core.pay.api.TradeRecordApi;
import com.bonus.canteen.core.pay.api.dto.OrderTradeQueryDTO;
import com.bonus.canteen.core.pay.api.vo.OrderTradeInfoVO;
import com.bonus.canteen.core.pay.api.vo.UnifyPaySelectVO;
import com.bonus.canteen.core.pay.common.constants.PayStateEnum;
import com.bonus.canteen.core.pay.common.vo.TradeChannelVO;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.common.houqin.constant.DelFlagEnum;
import com.bonus.common.houqin.constant.LeConstants;
import com.bonus.common.houqin.i18n.I18n;
import com.github.pagehelper.Page;
import com.github.pagehelper.page.PageMethod;
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 javax.sql.rowset.serial.SerialException;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class OrderWebBusinessImpl implements OrderWebBusiness {
   private static final Logger log = LoggerFactory.getLogger(OrderWebBusinessImpl.class);
   @Lazy
   @Autowired
   protected OrderInfoService orderInfoService;
   @Lazy
   @Autowired
   protected OrderDetailService orderDetailService;
   @Lazy
   @Autowired
   protected OrderDeliveryService orderDeliveryService;
   @Lazy
   @Autowired
   protected OrderAmountChangeService orderAmountChangeService;
   @Lazy
   @Autowired
   protected OrderAmountDetailService orderAmountDetailService;
   @Lazy
   @Autowired
   protected OrderRefundService orderRefundService;
   @Lazy
   @Autowired
   protected OrderRefundDetailService orderRefundDetailService;
   @Lazy
   @Autowired
   protected OrderPreBookService orderPreBookService;
   @Lazy
   @Autowired
   private OrderResultBusiness orderResultBusiness;
   @Lazy
   @Autowired
   private OrderDishesAndroidBusiness orderDishesAndroidBusiness;
   @Lazy
   @Autowired
   private OrderCustomBusiness orderCustomBusiness;
   @Lazy
   @Autowired
   private OrderModuleClient orderModuleClient;
   @Autowired
   @Lazy
   protected DeviceApi deviceApi;
   @Autowired
   @Lazy
   protected MgrAuthApi mgrAuthApi;
   @Autowired
   @Lazy
   protected TradeRecordApi tradeRecordApi;
   @Autowired
   @Lazy
   protected FlowApi flowApi;

   public OrderInfoWebVO getOrderInfo(Long orderId) {
      if (!LeNumUtil.isValidId(orderId)) {
         return null;
      } else {
         List<OrderListWebVO> voList = this.orderInfoService.queryOrderInfoWeb(CollUtil.toList(orderId), null);
         if (CollUtil.isEmpty(voList)) {
            return null;
         } else {
            OrderInfoWebVO infoVO = OrderInfoWebVO.of(voList.get(0));
            this.fillOrderInfoDetail(infoVO);
            return infoVO;
         }
      }
   }

   public PageVO<OrderListWebVO> queryOrderInfoWebByPage(PageDTO page, OrderDetailWebDTO param) {
      OrderUserPermissionDTO permissionDTO = this.currentUserPermissions();
      OrderQueryHelper.initQueryParam(param, OrderIndexType.CANTEEN_ID_STALL_ID_MEALTIME_ORDER_TYPE_ORDER_DATE);
      PageMethod.startPage(page);
      OrderSearchParam searchParam = this.orderCustomBusiness.web().beforeQueryOrderId(param, param.convertToOrderSearchParam());
      List<OrderIdDateVO> orderIdPage = this.orderInfoService.queryOrderId(searchParam, permissionDTO);
      if (CollUtil.isEmpty(orderIdPage)) {
         return PageVO.of(orderIdPage, CollUtil.newArrayList(new OrderListWebVO[0]));
      } else {
         PageVO<OrderListWebVO> pageOrderInfo = PageVO.of(orderIdPage, this.orderInfoService.queryOrderInfoWeb(orderIdPage.stream()
                 .map(OrderIdDateVO::getId).collect(Collectors.toList()), orderIdPage.stream().map(OrderIdDateVO::getOrderDate)
                 .collect(Collectors.toList())));
         List<OrderListWebVO> orderInfoWebList = pageOrderInfo.getRecords();
         this.fillOrderListDetail(orderInfoWebList);
         this.orderCustomBusiness.web().didQueryOrderInfoWebByPage(param, pageOrderInfo);
         return pageOrderInfo;
      }
   }

   public PageVO<OrderDeliveryDetailVO> queryOrderDeliveryDetailByPage(PageDTO page, OrderDeliveryDetailDTO deliveryDTO) {
      OrderUserPermissionDTO permissionDTO = this.currentUserPermissions();
      OrderQueryHelper.initQueryParam(deliveryDTO, OrderIndexType.CANTEEN_ID_STALL_ID_MEALTIME_ORDER_TYPE_ORDER_DATE);
      PageDTO.startPage(page);
      List<OrderIdDateVO> orderIdDatePage = this.orderInfoService.queryDeliveryId(deliveryDTO.convertToOrderSearchParam(), permissionDTO);
      List<OrderDeliveryDetailVO> records = this.orderInfoService.queryOrderDeliveryDetailList(orderIdDatePage.stream().map(OrderIdDateVO::getId).collect(Collectors.toList()),
              orderIdDatePage.stream().map(OrderIdDateVO::getOrderDate).collect(Collectors.toList()));
      if (CollUtil.isNotEmpty(records)) {
         List<Long> ordIdList = records.stream().map(OrderDeliveryDetailVO::getOrderId).collect(Collectors.toList());
         List<LocalDate> orderDateList = records.stream().map(OrderDeliveryDetailVO::getOrderDate).collect(Collectors.toList());
         Map<Long, List<OrderDetailVO>> detailMap = this.orderDetailService.getDetailVOGroupByOrderIdList(ordIdList, orderDateList);
         Iterator var9 = records.iterator();

         while(var9.hasNext()) {
            OrderDeliveryDetailVO orderDetailVO = (OrderDeliveryDetailVO)var9.next();
            List<OrderDetailVO> detailList = detailMap.get(orderDetailVO.getOrderId());
            orderDetailVO.setDishDetailStr(LeOrderUtil.getDetailDescStr(detailList, orderDetailVO.getOrderType(), true));
         }
      }

      PageVO<OrderDeliveryDetailVO> deliveryPage = PageVO.of(orderIdDatePage, records);
      this.orderCustomBusiness.web().didQueryOrderDeliveryDetailByPage(deliveryDTO, deliveryPage);
      return deliveryPage;
   }

   public void orderWriteOffWeb(Long orderId) {
      OrderInfo orderInfo = this.getAndCheckOrderInfo(orderId);
      Integer originalDishesState = orderInfo.getDishesState();
      if (!this.orderCustomBusiness.web().willWriteOff(orderInfo)) {
         this.orderCustomBusiness.web().didWriteOff(orderInfo, originalDishesState);
      }

      if (OrderStateEnum.isPlaceState(orderInfo.getOrderState())) {
         this.orderInfoService.updateOrderFinishByOrderIds(CollUtil.toList(orderId), CollUtil.toList(orderInfo.getOrderDate()));
         this.orderDishesAndroidBusiness.didUpdateDishesState(orderInfo.getOrderId(), originalDishesState);
         this.orderCustomBusiness.web().didWriteOff(orderInfo, originalDishesState);
      } else {
         throw new ServiceException(I18n.getMessage("order.web.not-allow-write-un-pay"));
      }
   }

   public PageVO<OrderRefundWebVO> pageOrderRefundList(PageDTO page, OrderRefundWebDTO refundWebDTO) {
      OrderUserPermissionDTO permissionDTO = this.currentUserPermissions();
      OrderQueryHelper.initQueryParam(refundWebDTO);
      PageMethod.startPage(page);
      List<OrderIdDateVO> orderIdDatePage = this.orderInfoService.queryRefundId(refundWebDTO.convertToOrderRefundSearchParam(), permissionDTO);
      List<OrderRefundWebVO> orderRefundWebVOS = this.orderInfoService.pageOrderRefundList(orderIdDatePage.stream().map(OrderIdDateVO::getId).collect(Collectors.toList()), (List)orderIdDatePage.stream().map(OrderIdDateVO::getOrderDate).collect(Collectors.toList()));
      if (CollUtil.isNotEmpty(orderRefundWebVOS)) {
         List<Long> orderRefundIds = orderRefundWebVOS.stream().map(OrderRefundWebVO::getOrderRefundId).collect(Collectors.toList());
         List<LocalDate> orderDates = orderRefundWebVOS.stream().map(OrderRefundWebVO::getOrderDate).collect(Collectors.toList());
         Map<Long, List<OrderRefundDetailVO>> refundDetailGroup = this.orderRefundDetailService.listOrderRefundDetailVO(orderRefundIds, orderDates).stream().collect(Collectors.groupingBy(OrderRefundDetailVO::getOrderRefundId));
         List<Long> flowInstancesIds = orderRefundWebVOS.stream().map(OrderRefundWebVO::getFlowInstanceId).filter(LeNumUtil::isValidId).collect(Collectors.toList());
         Map<Long, Boolean> flowLimitMap = this.flowApi.getLimitMap(flowInstancesIds);
         orderRefundWebVOS.forEach((s) -> {
            boolean enableToAudit = !LeNumUtil.isValidId(s.getFlowInstanceId()) || (Boolean)flowLimitMap.getOrDefault(s.getFlowInstanceId(), false);
            enableToAudit = enableToAudit && CheckStateEnum.WAIT.getKey().equals(s.getCheckState());
            s.setRefundDetailList(refundDetailGroup.get(s.getOrderRefundId()));
            s.setAuditable(enableToAudit ? LeConstants.COMMON_YES : LeConstants.COMMON_NO);
         });
      }

      PageVO<OrderRefundWebVO> pageVO = PageVO.of(orderIdDatePage, orderRefundWebVOS);
      this.orderCustomBusiness.web().didQueryRefundPage(refundWebDTO, pageVO);
      return pageVO;
   }

   public PageVO<OrderPreBookVO> queryPreBookPage(PageDTO page, OrderPreBookQueryDTO queryDTO) {
      JavaxValidateUtils.validate(queryDTO);
      PageMethod.startPage(page);
      return PageVO.of(this.orderPreBookService.listByParam(queryDTO));
   }
//
//   public void goodsUpdateStatusById(OrdPartWriteOffDTO ordDTO) {
//      LogUtil.printArgsIn("goodsUpdateStatusById", ordDTO);
//      OrderInfo ordAppInfo = this.orderInfoService.checkAndGetOrderInfo(ordDTO.getOrderId());
//      Integer dishesStateBeforeUpdated = ordAppInfo.getDishesState();
//      if (ObjectUtil.isNull(ordAppInfo)) {
//         throw new LeException(OrderTips.noOrder());
//      } else if (!OrderTypeEnum.RESERVE_SHOP.getKey().equals(ordAppInfo.getOrderType())) {
//         throw new LeException(I18n.getMessage("order.web.not-allow-update-not-shop", new Object[0]));
//      } else if (!OrderStateEnum.isPlaceState(ordAppInfo.getOrderState())) {
//         throw new LeException(I18n.getMessage("order.web.not-allow-update-placed", new Object[0]));
//      } else if (!DishesStateEnum.WAIT_TAKE.getKey().equals(dishesStateBeforeUpdated) && !DishesStateEnum.ALREADY_TAKE.getKey().equals(dishesStateBeforeUpdated)) {
//         this.orderInfoService.updateOrderState(ordAppInfo.getOrderId(), ordAppInfo.getOrderDate(), (Integer)null, (Integer)null, DishesStateEnum.WAIT_TAKE.getKey(), (String)null);
//         this.orderDishesAndroidBusiness.didUpdateDishesState(ordAppInfo.getOrderId(), dishesStateBeforeUpdated);
//      } else {
//         throw new LeException(I18n.getMessage("order.web.repeat-confirm", new Object[0]));
//      }
//   }

   public UnifyPaySelectVO orderSyncPayState(Long orderId) {
      UnifyPaySelectVO unifyPaySelectVO = this.orderCustomBusiness.web().willReSyncOrderPayResult(orderId);
      if (unifyPaySelectVO != null) {
         return unifyPaySelectVO;
      } else {
         OrderInfo orderInfo = this.orderInfoService.checkAndGetOrderInfo(orderId);
         return PayStateEnum.isPaidState(orderInfo.getPayState()) ? (new UnifyPaySelectVO())
                 .setCode(orderInfo.getPayState()).setPayType(orderInfo.getPayType())
                 .setPayChannel(orderInfo.getPayChannel()).setCustId(orderInfo.getCustId())
                 .setAmount(orderInfo.calcNeedPayAmount()).setRealAmount(orderInfo.getRealAmount())
                 : this.orderResultBusiness.reSyncOrderPayResult(orderId);
      }
   }

   public OrderRefund orderSyncRefundState(Long orderRefundId) {
      OrderRefund orderRefund = this.orderCustomBusiness.web().willReSyncOrderRefundResult(orderRefundId);
      if (orderRefund != null) {
         return orderRefund;
      } else {
         orderRefund = this.orderRefundService.getOrderRefundById(orderRefundId);
         if (orderRefund == null) {
            throw new ServiceException(I18n.getMessage("order.no-refund-order", new Object[0]));
         } else if (CheckStateEnum.REFUNDING.getKey().equals(orderRefund.getCheckState())) {
            this.orderResultBusiness.reSyncOrderRefundResult(orderRefundId);
            return this.orderRefundService.getOrderRefundById(orderRefundId);
         } else {
            return orderRefund;
         }
      }
   }

   public PageVO<OrderDetailSumGetVO> queryOrderDetailSumGet(PageDTO page, OrderDetailSumGetDTO deliveryDTO) {
      OrderUserPermissionDTO permissionDTO = this.currentUserPermissions();
      List<Long> userPlaceIds = LeNumUtil.isValidId(deliveryDTO.getReserveUserId()) ?
              this.orderModuleClient.custPlaceIdListByUserIds(CustPlaceListQueryParam.ofUserId(deliveryDTO.getReserveUserId()))
              : ListUtil.empty();
      OrderQueryHelper.initQueryParam(deliveryDTO, OrderIndexType.CANTEEN_ID_STALL_ID_MEALTIME_ORDER_TYPE_ORDER_DATE);
      PageMethod.startPage(page);
      List<OrderIdDateVO> deliveryIdDatePage = this.orderInfoService.queryDeliveryId(deliveryDTO
              .convertToOrderDeliverySearchParam(userPlaceIds), permissionDTO);
      List<OrderDetailSumGetVO> records = this.orderInfoService.queryOrderDetailSumGet((List)deliveryIdDatePage.stream()
              .map(OrderIdDateVO::getId).collect(Collectors.toList()), (List)deliveryIdDatePage.stream()
              .map(OrderIdDateVO::getOrderDate).collect(Collectors.toList()));
      PageVO<OrderDetailSumGetVO> pageVO = PageVO.of(deliveryIdDatePage, records);
      this.orderCustomBusiness.web().didQueryOrderDetailSumGet(deliveryDTO, pageVO);
      return pageVO;
   }
//
//   public PageVO<OrderInfoBackfieldVO> queryOrderByGoodsId(PageDTO pageDTO, Long goodsDishesId, Long menuDetailId) {
//      PageMethod.startPage(pageDTO);
//      Page<Long> orderIds = (Page)this.orderInfoService.queryOrderIdsByGoodsId(goodsDishesId, menuDetailId);
//      if (CollUtil.isEmpty(orderIds)) {
//         CollUtil.newArrayList(new Object[0]);
//      }
//
//      List<OrderInfoBackfieldVO> infoBackfieldVOList = this.orderInfoService.listOrderForBackfield(orderIds, (List)null);
//      List<LocalDate> orderDates = (List)infoBackfieldVOList.stream().map(OrderInfoBackfieldVO::getOrderDate).collect(Collectors.toList());
//      Map<Long, List<OrderDetailVO>> orderDetailMap = (Map)this.orderDetailService.listDetailVOByOrderIds(orderIds, orderDates).stream().collect(Collectors.groupingBy(OrderDetailVO::getOrderId, Collectors.toList()));
//      Iterator var8 = infoBackfieldVOList.iterator();
//
//      while(var8.hasNext()) {
//         OrderInfoBackfieldVO backfieldVO = (OrderInfoBackfieldVO)var8.next();
//         backfieldVO.setOrderDetailList((List)orderDetailMap.getOrDefault(backfieldVO.getOrderId(), CollUtil.newArrayList(new OrderDetailVO[0])));
//      }
//
//      return PageVO.of((List)orderIds, infoBackfieldVOList);
//   }
//
//   public PageVO<OrderInfoBackfieldVO> queryOrderBackfieldPage(PageDTO pageDTO, OrderBackfieldSearchDTO orderBackfieldSearchDTO) {
//      OrderUserPermissionDTO permissionDTO = this.currentUserPermissions();
//      PageMethod.startPage(pageDTO);
//      List<OrderIdDateVO> orderIdDatePage = this.orderInfoService.queryOrderId(orderBackfieldSearchDTO.convertToOrderSearchParam(), permissionDTO);
//      List<OrderInfoBackfieldVO> infoBackfieldVOList = this.orderInfoService.listOrderForBackfield((List)orderIdDatePage.stream().map(OrderIdDateVO::getId).collect(Collectors.toList()), (List)orderIdDatePage.stream().map(OrderIdDateVO::getOrderDate).collect(Collectors.toList()));
//      if (CollUtil.isNotEmpty(infoBackfieldVOList)) {
//         List<Long> orderIds = (List)infoBackfieldVOList.stream().map(OrderInfoBackfieldVO::getOrderId).collect(Collectors.toList());
//         List<LocalDate> orderDates = (List)infoBackfieldVOList.stream().map(OrderInfoBackfieldVO::getOrderDate).collect(Collectors.toList());
//         Map<Long, List<OrderDetailVO>> orderDetailMap = (Map)this.orderDetailService.listDetailVOByOrderIds(orderIds, orderDates).stream().collect(Collectors.groupingBy(OrderDetailVO::getOrderId, Collectors.toList()));
//         Iterator var9 = infoBackfieldVOList.iterator();
//
//         while(var9.hasNext()) {
//            OrderInfoBackfieldVO backfieldVO = (OrderInfoBackfieldVO)var9.next();
//            backfieldVO.setOrderDetailList((List)orderDetailMap.getOrDefault(backfieldVO.getOrderId(), CollUtil.newArrayList(new OrderDetailVO[0])));
//         }
//      }
//
//      return PageVO.of(orderIdDatePage, infoBackfieldVOList);
//   }

   public OrderRefundWaitNumVO getRefundWaitNum() {
//      Long definitionId = this.flowApi.getByMappingIdAndDefinitionType((Long)null, FlowDefinitionEum.ORDER_REFUND);
//      if (LeNumUtil.isValidId(definitionId)) {
//         Map<String, Long> homePageFlowNotice = this.flowApi.getHomePageFlowNotice();
//         Long num = (Long)homePageFlowNotice.getOrDefault(FlowDefinitionEum.ORDER_REFUND.getType(), 0L);
//         return OrderRefundWaitNumVO.of(num);
//         throw new ServiceException("不支持工作流!");
//      } else {
         OrderRefundWebDTO orderRefundWebDTO = new OrderRefundWebDTO();
         orderRefundWebDTO.setCheckState(CheckStateEnum.WAIT.getKey());
         PageVO<OrderRefundWebVO> orderRefundWebVOPageVO = this.pageOrderRefundList(PageDTO.of(1L, 1L), orderRefundWebDTO);
         return OrderRefundWaitNumVO.of(orderRefundWebVOPageVO.getTotal());
//      }
   }

   protected OrderInfo getAndCheckOrderInfo(Long orderId) {
      OrderInfo orderInfo = this.orderInfoService.checkAndGetOrderInfo(orderId);
      if (OrderStateEnum.isFinishState(orderInfo.getOrderState())) {
         throw new ServiceException(I18n.getMessage("order.web.already-write-off", new Object[0]));
      } else {
         LocalDate nowDate = LocalDate.now();
         if (!OrderTypeEnum.SHOP.getKey().equals(orderInfo.getOrderType()) && !OrderTypeEnum.RESERVE_SHOP.getKey().equals(orderInfo.getOrderType())) {
            if (nowDate.isBefore(orderInfo.getOrderDate())) {
               log.info("[订单核销]当前日期{}早于订单日期{}，不允许核销", nowDate, orderInfo.getOrderDate());
               throw new ServiceException(I18n.getMessage("order.web.not-allow-write-off-date", new Object[]{orderInfo.getOrderDate()}));
            }

            if (nowDate.equals(orderInfo.getOrderDate())) {
               AllocMealtimeModel mealtime = this.orderModuleClient.mealtimeQuery(MealtimeQueryParam.ofMealtimeType(orderInfo.getMealtimeType(), orderInfo.getCanteenId(), orderInfo.getStallId()));
               LocalTime nowTime = LocalTime.now();
               if (nowTime.isBefore(mealtime.getStartTime())) {
                  log.info("[订单核销]当前时间{}早于餐次开餐时间{},不允许核销", nowTime, mealtime.getStartTime());
                  throw new ServiceException(I18n.getMessage("order.web.not-allow-write-off-time", new Object[]{mealtime.getStartTime()}));
               }
            }
         }

         return orderInfo;
      }
   }

   public OrderUserPermissionDTO currentUserPermissions() {
      OrderUserPermissionDTO orderUserPermissionDTO = new OrderUserPermissionDTO();
      orderUserPermissionDTO.setCodes(this.mgrAuthApi.getTenantCanteenStallIdList(true));
      List<CustOrgTreeDTO> tenantOrg = this.mgrAuthApi.getTenantOrg(LeConstants.COMMON_NO, DelFlagEnum.DEL_FALSE.key(), true);
      orderUserPermissionDTO.setOrgIds(tenantOrg.stream().map(CustOrgTreeDTO::getOrgId).collect(Collectors.toList()));
      return orderUserPermissionDTO;
   }

   public void fillOrderListDetail(List<OrderListWebVO> orderInfoWebList) {
      if (CollUtil.isNotEmpty(orderInfoWebList)) {
         List<Long> ordIdList = orderInfoWebList.stream().map(OrderListWebVO::getOrderId).collect(Collectors.toList());
         List<LocalDate> orderDateList = orderInfoWebList.stream().map(OrderListWebVO::getOrderDate).collect(Collectors.toList());
         Map<Long, List<OrderDetailVO>> detailMap = this.orderDetailService.getDetailVOGroupByOrderIdList(ordIdList, orderDateList);
         Map<Long, List<OrderAmountDetail>> amountGroup = this.orderAmountDetailService.listByOrderIds(ordIdList, orderDateList,
                 OrderAmountDetailTypeEnum.PAY.getKey()).stream().collect(Collectors.groupingBy(OrderAmountDetail::getOrderId));
         List<Long> waitingPayOrderIds = orderInfoWebList.stream().filter((s) -> {
            return PayStateEnum.isPartPayState(s.getPayState()) || PayStateEnum.isPayingState(s.getPayState());
         }).map(OrderListWebVO::getOrderId).collect(Collectors.toList());
         Map<Long, OrderTradeInfoVO> orderTradeMap = this.orderTradeMap(waitingPayOrderIds);
         this.orderDetailService.fillOrderDetailMachine(orderInfoWebList);
         Iterator var8 = orderInfoWebList.iterator();

         while(var8.hasNext()) {
            OrderListWebVO orderDetailVO = (OrderListWebVO)var8.next();
            orderDetailVO.setOrderDetailList(detailMap.get(orderDetailVO.getOrderId()));
            orderDetailVO.setDishDetailStr(LeOrderUtil.getDetailDescStr(orderDetailVO.getOrderDetailList(),
                    orderDetailVO.getOrderType()));
            orderDetailVO.setRefundDishDetailStr(LeOrderUtil.getDetailRefundDescStr(orderDetailVO.getOrderDetailList(),
                    orderDetailVO.getOrderType()));
            orderDetailVO.setPayTypesStr(LeOrderUtil.getPayTypesDescStr(amountGroup.get(orderDetailVO.getOrderId()),
                    orderDetailVO.getPayType(), PayStateEnum.isPartPayState(orderDetailVO.getPayState())));
            orderDetailVO.fillOrderTradeInfo((OrderTradeInfoVO)orderTradeMap.get(orderDetailVO.getOrderId()));
         }
      }

   }

   public void fillOrderInfoDetail(OrderInfoWebVO orderInfoWebVO) {
      List<Long> ordIdList = CollUtil.toList(orderInfoWebVO.getOrderId());
      List<LocalDate> orderDateList = CollUtil.toList(orderInfoWebVO.getOrderDate());
      Map<Long, List<OrderDetailVO>> detailMap = this.orderDetailService.getDetailVOGroupByOrderIdList(ordIdList, orderDateList);
      List<OrderAmountChangeVO> amountChangeVOList = this.orderAmountChangeService.listByOrderIds(ordIdList, CollUtil.toList(new LocalDate[]{orderInfoWebVO.getOrderDate()})).stream().map(OrderAmountChangeVO::of).collect(Collectors.toList());
      List<OrderAmountDetail> amountDetailList = this.orderAmountDetailService.listByOrderIds(ordIdList, orderDateList, OrderAmountDetailTypeEnum.PAY.getKey());
      Map<Long, List<OrderAmountDetail>> amountGroup = amountDetailList.stream().collect(Collectors.groupingBy(OrderAmountDetail::getOrderId));
      Map<Long, List<OrderAmountDetailWebVO>> amountVOGroup = this.amountVOGroup(amountDetailList);
      this.orderDetailService.fillOrderDetailMachine(CollUtil.toList(orderInfoWebVO));
      orderInfoWebVO.setOrderDetailList(detailMap.get(orderInfoWebVO.getOrderId()));
      orderInfoWebVO.setDishDetailStr(LeOrderUtil.getDetailDescStr(orderInfoWebVO.getOrderDetailList(), orderInfoWebVO.getOrderType()));
      orderInfoWebVO.setRefundDishDetailStr(LeOrderUtil.getDetailRefundDescStr(orderInfoWebVO.getOrderDetailList(), orderInfoWebVO.getOrderType()));
      orderInfoWebVO.setAmountChangeList(amountChangeVOList);
      orderInfoWebVO.setPayTypesStr(LeOrderUtil.getPayTypesDescStr(amountGroup.get(orderInfoWebVO.getOrderId()), orderInfoWebVO.getPayType(), PayStateEnum.isPartPayState(orderInfoWebVO.getPayState())));
      orderInfoWebVO.setAmountDetailList(amountVOGroup.get(orderInfoWebVO.getOrderId()));
      if (PayStateEnum.isPartPayState(orderInfoWebVO.getPayState()) || PayStateEnum.isPayingState(orderInfoWebVO.getPayState())) {
         OrderTradeInfoVO tradeInfoVO = (OrderTradeInfoVO)this.orderTradeMap(CollUtil.toList(orderInfoWebVO.getOrderId())).get(orderInfoWebVO.getOrderId());
         orderInfoWebVO.fillOrderTradeInfo(tradeInfoVO);
      }

   }

   protected Map<Long, List<OrderAmountDetailWebVO>> amountVOGroup(List<OrderAmountDetail> amountDetailList) {
      if (CollUtil.isEmpty(amountDetailList)) {
         return MapUtil.newHashMap();
      } else {
         Set<Long> tradeChannelIds = amountDetailList.stream().map(OrderAmountDetail::getTradeChannelId).collect(Collectors.toSet());
         Map<Long, TradeChannelVO> tradeChannelMap = this.tradeRecordApi.listChannelDetailByTradeChannelIds(tradeChannelIds).stream().collect(Collectors.toMap(TradeChannelVO::getTradeChannelId, Function.identity()));
         List<OrderAmountDetailWebVO> voList = amountDetailList.stream().flatMap((s) -> {
            return OrderAmountDetailWebVO.listOf(s).stream();
         }).collect(Collectors.toList());
         Iterator var5 = voList.iterator();

         while(var5.hasNext()) {
            OrderAmountDetailWebVO vo = (OrderAmountDetailWebVO)var5.next();
            vo.fillTradeChannelVO(tradeChannelMap.get(vo.getTradeChannelId()));
         }

         return voList.stream().collect(Collectors.groupingBy(OrderAmountDetailWebVO::getOrderId));
      }
   }

   protected Map<Long, OrderTradeInfoVO> orderTradeMap(List<Long> orderIds) {
      OrderTradeQueryDTO queryDTO = OrderTradeQueryDTO.builder().orderRechargeIds(orderIds).queryAccExceptionInfo(true)
              .lastTradeRecord(false).build();
      return this.tradeRecordApi.listOrderTradeInfo(queryDTO).stream().collect(Collectors.toMap(OrderTradeInfoVO::getOrderRechargeId,
              Function.identity(), (o, n) -> {
         return o;
      }));
   }
}
