package com.bonus.canteen.core.nutrition.common.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bonus.canteen.core.common.enums.AllocMealtimeTypeEnum;
import com.bonus.canteen.core.common.page.QueryParseHelper;
import com.bonus.canteen.core.menu.api.MenuDishesApi;
import com.bonus.canteen.core.menu.constant.MenuSalesTypeEnum;
import com.bonus.canteen.core.menu.entity.MenuDishes;
import com.bonus.canteen.core.menu.vo.MenuMaterialBasVO;
import com.bonus.canteen.core.nutrition.common.dto.HealthDietReportDTO;
import com.bonus.canteen.core.nutrition.common.dto.HealthDishesDTO;
import com.bonus.canteen.core.nutrition.common.dto.HealthDishesNutritionDto;
import com.bonus.canteen.core.nutrition.common.enums.HealthDishSourceEnum;
import com.bonus.canteen.core.nutrition.common.mapper.HealthDishesNutritionMapper;
import com.bonus.canteen.core.nutrition.common.model.HealthDishesNutrition;
import com.bonus.canteen.core.nutrition.common.service.HealthDishesNutritionService;
import com.bonus.canteen.core.nutrition.common.vo.*;
import com.bonus.canteen.core.nutrition.utils.NuConvertUtil;
import com.bonus.canteen.core.order.api.OrderNutritionApi;
import com.bonus.canteen.core.order.api.vo.OrdDetailApiVO;
import com.bonus.canteen.core.order.common.constants.OrderStateEnum;
import com.bonus.canteen.core.order.common.dto.OrderSearchParamDTO;
import com.bonus.canteen.core.order.common.vo.OrderDetailVO;
import com.bonus.canteen.core.order.common.vo.OrderInfoVO;
import com.bonus.common.houqin.i18n.I18n;
import com.bonus.common.houqin.utils.LeBeanUtil;
import com.bonus.common.houqin.utils.id.Id;
import com.bonus.canteen.core.nutrition.constant.NutritionConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.invoke.SerializedLambda;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class HealthDishesNutritionServiceImpl extends ServiceImpl<HealthDishesNutritionMapper, HealthDishesNutrition> implements HealthDishesNutritionService {
   private static final Logger log = LoggerFactory.getLogger(HealthDishesNutritionServiceImpl.class);
//   @Lazy
//   @Autowired
//   private HealthCateringService healthCateringService;
   @Lazy
   @Autowired
   private OrderNutritionApi orderNutritionApi;
   @Lazy
   @Autowired
   private MenuDishesApi menuDishesApi;

   private static BigDecimal getActualContent(BigDecimal contant, BigDecimal actualWeight, BigDecimal standardWeight) {
      return !ObjectUtil.isNull(contant) && !NumberUtil.equals(contant, BigDecimal.ZERO) ? actualWeight.divide(standardWeight,
              NutritionConstants.NEW_SCALE, RoundingMode.HALF_UP).multiply(contant) : BigDecimal.ZERO;
   }
//
//   @Transactional(
//      rollbackFor = {Exception.class}
//   )
//   public void addCustomDishes(List<HealthDishesNutritionDto> dishesNutritionDtoList) {
//      this.checkDishesNutritionDto(dishesNutritionDtoList);
//      Long custId = ((HealthDishesNutritionDto)dishesNutritionDtoList.get(0)).getCustId();
//      LocalDate eatDate = ((HealthDishesNutritionDto)dishesNutritionDtoList.get(0)).getEatDate();
//      LambdaQueryWrapper<HealthDishesNutrition> queryWrapper = (LambdaQueryWrapper)((LambdaQueryWrapper)Wrappers.lambdaQuery(HealthDishesNutrition.class).eq(HealthDishesNutrition::getCustId, custId)).eq(HealthDishesNutrition::getEatDate, eatDate);
//      this.remove(queryWrapper);
//      List<HealthDishesNutrition> healthDishesNutritions = dishesNutritionDtoList.stream().map((healthDishesNutritionDto) -> {
//         HealthDishesNutrition healthDishesNutrition = BeanUtil.copyProperties(healthDishesNutritionDto, HealthDishesNutrition.class, new String[0]);
//         healthDishesNutrition.setId(Id.next());
//         Integer dishesSource = healthDishesNutrition.getDishesSource();
//         if (NumberUtil.equals(dishesSource, HealthDishSourceEnum.CUSTOM.key())) {
//            healthDishesNutrition.setDishesId(Id.next());
//         }
//
//         return healthDishesNutrition;
//      }).collect(Collectors.toList());
//      this.saveBatch(healthDishesNutritions);
//   }

   public List<HealthDishesNutritionVo> getCustomizeDishes(HealthDishesDTO healthDishesDTO, Boolean ifCustomize) {
      Long custId = healthDishesDTO.getCustId();
      LocalDate eatDate = healthDishesDTO.getEatDate();
      List<HealthDishesNutritionVo> healthDishesNutritionVos = CollUtil.newArrayList(new HealthDishesNutritionVo[0]);
      if (this.ifCustomize(custId, eatDate) && ifCustomize) {
         LambdaQueryWrapper<HealthDishesNutrition> queryWrapper = (Wrappers.lambdaQuery(HealthDishesNutrition.class)
                 .eq(HealthDishesNutrition::getCustId, custId)).eq(HealthDishesNutrition::getEatDate, eatDate);
         List<HealthDishesNutrition> list = this.list(queryWrapper);
         return LeBeanUtil.copyCreateList(list, HealthDishesNutritionVo.class);
      } else {
         healthDishesNutritionVos = this.buildOrderNutrition(custId, eatDate);
         return healthDishesNutritionVos;
      }
   }

   public List<HealthDishesNutritionVo> buildOrderNutrition(Long custId, LocalDate eatDate) {
      List<HealthDishesNutritionVo> healthDishesNutritionVos = CollUtil.newArrayList(new HealthDishesNutritionVo[0]);
      List<OrderDetailMiniVo> ordDetailS = this.getPeriodOrdDetailS((new HealthDietReportDTO()).setCustId(custId).setStartDate(eatDate).setEndDate(eatDate));
      Iterator var5 = ordDetailS.iterator();

      while(var5.hasNext()) {
         OrderDetailMiniVo ordDetail = (OrderDetailMiniVo)var5.next();
         Long dishesId = ordDetail.getGoodsDishesId();
         MenuDishes menuDish = this.menuDishesApi.getOneMenuDishes(dishesId);
         if (!ObjectUtil.isNull(menuDish)) {
            HealthDishesNutritionVo healthDishesNutritionVo = this.buildDishesNutritionVo(ordDetail, dishesId, menuDish);
            healthDishesNutritionVo.setHealthDishTraceElementsVo((HealthDishTraceElementsVo)BeanUtil.copyProperties(menuDish, HealthDishTraceElementsVo.class, new String[0]));
            healthDishesNutritionVos.add(healthDishesNutritionVo);
         }
      }

      return healthDishesNutritionVos;
   }

   public Boolean ifCustomize(Long custId, LocalDate eatDate) {
      LambdaQueryWrapper<HealthDishesNutrition> queryWrapper = (Wrappers.lambdaQuery(HealthDishesNutrition.class)
              .eq(HealthDishesNutrition::getCustId, custId)).eq(HealthDishesNutrition::getEatDate, eatDate);
      return this.count(queryWrapper) > 0L;
   }
//
//   public HealthDietReportVO queryDietReport(HealthDietReportDTO queryDTO, Boolean ifCustomize) {
//      Long custId = queryDTO.getCustId();
//      LocalDate startDate = queryDTO.getStartDate();
//      LocalDate endData = queryDTO.getEndDate();
//      long days = LocalDateTimeUtil.between(startDate.atStartOfDay(), endData.atStartOfDay(), ChronoUnit.DAYS) + 1L;
//      List<HealthDishesNutritionVo> healthDishesNutritionVos = CollUtil.newArrayList(new HealthDishesNutritionVo[0]);
//
//      for(int i = 0; (long)i < days; ++i) {
//         LocalDate date = startDate.plusDays((long)i);
//         if (this.ifCustomize(custId, date) && ifCustomize) {
//            HealthDishesDTO dishesDTO = HealthDishesDTO.builder().custId(custId).eatDate(date).build();
//            healthDishesNutritionVos.addAll(this.getCustomizeDishes(dishesDTO, ifCustomize));
//         } else {
//            healthDishesNutritionVos.addAll(this.buildOrderNutrition(custId, date));
//         }
//      }
//
//      BigDecimal caloriesAll = NuConvertUtil.toTwo((Number)null);
//      BigDecimal caloriesBreakFast = NuConvertUtil.toTwo((Number)null);
//      BigDecimal caloriesLunch = NuConvertUtil.toTwo((Number)null);
//      BigDecimal caloriesDinner = NuConvertUtil.toTwo((Number)null);
//      BigDecimal proteinAll = NuConvertUtil.toTwo((Number)null);
//      BigDecimal proteinBreakFast = NuConvertUtil.toTwo((Number)null);
//      BigDecimal proteinLunch = NuConvertUtil.toTwo((Number)null);
//      BigDecimal proteinDinner = NuConvertUtil.toTwo((Number)null);
//      BigDecimal carbohydrateAll = NuConvertUtil.toTwo((Number)null);
//      BigDecimal carbohydrateBreakFast = NuConvertUtil.toTwo((Number)null);
//      BigDecimal carbohydrateLunch = NuConvertUtil.toTwo((Number)null);
//      BigDecimal carbohydrateDinner = NuConvertUtil.toTwo((Number)null);
//      BigDecimal fatAll = NuConvertUtil.toTwo((Number)null);
//      BigDecimal fatBreakFast = NuConvertUtil.toTwo((Number)null);
//      BigDecimal fatLunch = NuConvertUtil.toTwo((Number)null);
//      BigDecimal fatDinner = NuConvertUtil.toTwo((Number)null);
//      BigDecimal dietaryFiberAll = NuConvertUtil.toTwo((Number)null);
//      BigDecimal sodiumAll = NuConvertUtil.toTwo((Number)null);
//
//      HealthDishesNutritionVo healthDishesNutritionVo;
//      BigDecimal actualWeight;
//      BigDecimal standardWeight;
//      BigDecimal actualProtein;
//      BigDecimal actualFat;
//      for(Iterator var27 = healthDishesNutritionVos.iterator(); var27.hasNext(); sodiumAll = sodiumAll.add(getActualContent(healthDishesNutritionVo.getSodium(), actualWeight, standardWeight))) {
//         healthDishesNutritionVo = (HealthDishesNutritionVo)var27.next();
//         actualWeight = healthDishesNutritionVo.getActualWeight();
//         standardWeight = healthDishesNutritionVo.getStandardWeight();
//         BigDecimal actualCaloriesNutrition = getActualContent(healthDishesNutritionVo.getCalories(), actualWeight, standardWeight);
//         actualProtein = getActualContent(healthDishesNutritionVo.getProtein(), actualWeight, standardWeight);
//         BigDecimal actualCarbohydrate = getActualContent(healthDishesNutritionVo.getCarbohydrate(), actualWeight, standardWeight);
//         actualFat = getActualContent(healthDishesNutritionVo.getFat(), actualWeight, standardWeight);
//         if (NumberUtil.equals(AllocMealtimeTypeEnum.MEALTIME_BREAKFAST.getKey(), healthDishesNutritionVo.getMealtimeType())) {
//            caloriesBreakFast = caloriesBreakFast.add(actualCaloriesNutrition);
//            proteinBreakFast = proteinBreakFast.add(actualProtein);
//            carbohydrateBreakFast = carbohydrateBreakFast.add(actualCarbohydrate);
//            fatBreakFast = fatBreakFast.add(actualFat);
//         }
//
//         if (NumberUtil.equals(AllocMealtimeTypeEnum.MEALTIME_LUNCH.getKey(), healthDishesNutritionVo.getMealtimeType())) {
//            caloriesLunch = caloriesLunch.add(actualCaloriesNutrition);
//            proteinLunch = proteinLunch.add(actualProtein);
//            carbohydrateLunch = carbohydrateLunch.add(actualCarbohydrate);
//            fatLunch = fatLunch.add(actualFat);
//         }
//
//         if (NumberUtil.equals(AllocMealtimeTypeEnum.MEALTIME_DINNER.getKey(), healthDishesNutritionVo.getMealtimeType())) {
//            caloriesDinner = caloriesDinner.add(actualCaloriesNutrition);
//            proteinDinner = proteinDinner.add(actualProtein);
//            carbohydrateDinner = carbohydrateDinner.add(actualCarbohydrate);
//            fatDinner = fatDinner.add(actualFat);
//         }
//
//         caloriesAll = caloriesAll.add(actualCaloriesNutrition);
//         proteinAll = proteinAll.add(actualProtein);
//         carbohydrateAll = carbohydrateAll.add(actualCarbohydrate);
//         fatAll = fatAll.add(actualFat);
//         dietaryFiberAll = dietaryFiberAll.add(getActualContent(healthDishesNutritionVo.getDietaryFiber(), actualWeight, standardWeight));
//      }
//
//      NutrReferenceIntakeVO nutrientReferenceIntake = (NutrReferenceIntakeVO)Optional.ofNullable(this.healthCateringService.getCustIntake(queryDTO.getCustId())).orElse(new NutrReferenceIntakeVO());
//      List<HealthNutritionVO> healthNutritionVOS = CollUtil.newArrayList(new HealthNutritionVO[0]);
//      healthNutritionVOS.add(HealthNutritionVO.builder().name(HealthNutritionNameEnum.CALORIES.value()).actual(this.getAverage(caloriesAll, days)).advise(NuConvertUtil.toTwo(nutrientReferenceIntake.getCalories())).build());
//      healthNutritionVOS.add(HealthNutritionVO.builder().name(HealthNutritionNameEnum.PROTEIN.value()).actual(this.getAverage(proteinAll, days)).advise(NuConvertUtil.toTwo(nutrientReferenceIntake.getProtein())).build());
//      healthNutritionVOS.add(HealthNutritionVO.builder().name(HealthNutritionNameEnum.CARBOHYDRATE.value()).actual(this.getAverage(carbohydrateAll, days)).advise(NuConvertUtil.toTwo(nutrientReferenceIntake.getCarbohydrate())).build());
//      healthNutritionVOS.add(HealthNutritionVO.builder().name(HealthNutritionNameEnum.FAT.value()).actual(this.getAverage(fatAll, days)).advise(NuConvertUtil.toTwo(nutrientReferenceIntake.getFat())).build());
//      healthNutritionVOS.add(HealthNutritionVO.builder().name(HealthNutritionNameEnum.DIETARYFIBER.value()).actual(this.getAverage(dietaryFiberAll, days)).advise(NuConvertUtil.toTwo(nutrientReferenceIntake.getDietaryFiber())).build());
//      healthNutritionVOS.add(HealthNutritionVO.builder().name(HealthNutritionNameEnum.SODIUM.value()).actual(this.getAverage(sodiumAll, days)).advise(NuConvertUtil.toTwo(nutrientReferenceIntake.getSodium())).build());
//      Map<String, BigDecimal> nutritionPercent = new LinkedHashMap();
//      standardWeight = NumberUtil.add(new BigDecimal[]{this.getAverage(proteinAll, days), this.getAverage(carbohydrateAll, days), this.getAverage(fatAll, days)});
//      nutritionPercent.put(HealthNutritionNameEnum.PROTEIN.value(), NuConvertUtil.per(this.getAverage(proteinAll, days), standardWeight));
//      nutritionPercent.put(HealthNutritionNameEnum.CARBOHYDRATE.value(), NuConvertUtil.per(this.getAverage(carbohydrateAll, days), standardWeight));
//      nutritionPercent.put(HealthNutritionNameEnum.FAT.value(), NuConvertUtil.per(this.getAverage(fatAll, days), standardWeight));
//      Map<String, BigDecimal> nutritionBreakfastPercent = new LinkedHashMap();
//      actualProtein = NumberUtil.add(new BigDecimal[]{this.getAverage(proteinBreakFast, days), this.getAverage(carbohydrateBreakFast, days), this.getAverage(fatBreakFast, days)});
//      nutritionBreakfastPercent.put(HealthNutritionNameEnum.PROTEIN.value(), NuConvertUtil.per(this.getAverage(proteinBreakFast, days), actualProtein));
//      nutritionBreakfastPercent.put(HealthNutritionNameEnum.CARBOHYDRATE.value(), NuConvertUtil.per(this.getAverage(carbohydrateBreakFast, days), actualProtein));
//      nutritionBreakfastPercent.put(HealthNutritionNameEnum.FAT.value(), NuConvertUtil.per(this.getAverage(fatBreakFast, days), actualProtein));
//      Map<String, BigDecimal> nutritionLunchPercent = new LinkedHashMap();
//      actualFat = NumberUtil.add(new BigDecimal[]{this.getAverage(proteinLunch, days), this.getAverage(carbohydrateLunch, days), this.getAverage(fatLunch, days)});
//      nutritionLunchPercent.put(HealthNutritionNameEnum.PROTEIN.value(), NuConvertUtil.per(this.getAverage(proteinLunch, days), actualFat));
//      nutritionLunchPercent.put(HealthNutritionNameEnum.CARBOHYDRATE.value(), NuConvertUtil.per(this.getAverage(carbohydrateLunch, days), actualFat));
//      nutritionLunchPercent.put(HealthNutritionNameEnum.FAT.value(), NuConvertUtil.per(this.getAverage(fatLunch, days), actualFat));
//      Map<String, BigDecimal> nutritionDinnerPercent = new LinkedHashMap();
//      BigDecimal dinnerTotal = NumberUtil.add(new BigDecimal[]{this.getAverage(proteinDinner, days), this.getAverage(carbohydrateDinner, days), this.getAverage(fatDinner, days)});
//      nutritionDinnerPercent.put(HealthNutritionNameEnum.PROTEIN.value(), NuConvertUtil.per(this.getAverage(proteinDinner, days), dinnerTotal));
//      nutritionDinnerPercent.put(HealthNutritionNameEnum.CARBOHYDRATE.value(), NuConvertUtil.per(this.getAverage(carbohydrateDinner, days), dinnerTotal));
//      nutritionDinnerPercent.put(HealthNutritionNameEnum.FAT.value(), NuConvertUtil.per(this.getAverage(fatDinner, days), dinnerTotal));
//      Map<String, BigDecimal> caloriesPercent = new LinkedHashMap();
//      standardWeight = NumberUtil.add(new BigDecimal[]{this.getAverage(caloriesBreakFast, days), this.getAverage(caloriesLunch, days), this.getAverage(caloriesDinner, days)});
//      caloriesPercent.put(AllocMealtimeTypeEnum.MEALTIME_BREAKFAST.getDesc(), NuConvertUtil.per(this.getAverage(caloriesBreakFast, days), standardWeight));
//      caloriesPercent.put(AllocMealtimeTypeEnum.MEALTIME_LUNCH.getDesc(), NuConvertUtil.per(this.getAverage(caloriesLunch, days), standardWeight));
//      caloriesPercent.put(AllocMealtimeTypeEnum.MEALTIME_DINNER.getDesc(), NuConvertUtil.per(this.getAverage(caloriesDinner, days), standardWeight));
//      return HealthDietReportVO.builder().healthNutritionVOS(healthNutritionVOS).nutritionPercent(nutritionPercent).nutritionBreakfastPercent(nutritionBreakfastPercent).nutritionLunchPercent(nutritionLunchPercent).nutritionDinnerPercent(nutritionDinnerPercent).caloriesPercent(caloriesPercent).build();
//   }

   public HealthNormalElementsVo getNormalElements(Long custId, LocalDate startDate, LocalDate endData, Boolean ifCustomize) {
      long days = LocalDateTimeUtil.between(startDate.atStartOfDay(), endData.atStartOfDay(), ChronoUnit.DAYS) + 1L;
      List<HealthDishesNutritionVo> healthDishesNutritionVos = CollUtil.newArrayList(new HealthDishesNutritionVo[0]);

      for(int i = 0; (long)i < days; ++i) {
         LocalDate date = startDate.plusDays((long)i);
         if (this.ifCustomize(custId, date) && !ObjectUtil.isNull(ifCustomize) && ifCustomize) {
            HealthDishesDTO dishesDTO = HealthDishesDTO.builder().custId(custId).eatDate(date).build();
            healthDishesNutritionVos.addAll(this.getCustomizeDishes(dishesDTO, ifCustomize));
         } else {
            healthDishesNutritionVos.addAll(this.buildOrderNutrition(custId, date));
         }
      }

      BigDecimal caloriesAll = NuConvertUtil.toTwo((Number)null);
      BigDecimal proteinAll = NuConvertUtil.toTwo((Number)null);
      BigDecimal carbohydrateAll = NuConvertUtil.toTwo((Number)null);
      BigDecimal fatAll = NuConvertUtil.toTwo((Number)null);
      BigDecimal dietaryFiberAll = NuConvertUtil.toTwo((Number)null);
      BigDecimal sodiumAll = NuConvertUtil.toTwo((Number)null);
      BigDecimal cholesterolAll = NuConvertUtil.toTwo((Number)null);

      BigDecimal actualWeight;
      BigDecimal standardWeight;
      HealthDishTraceElementsVo healthDishTraceElementsVo;
      for(Iterator var15 = healthDishesNutritionVos.iterator(); var15.hasNext(); cholesterolAll = cholesterolAll.add(getActualContent(NuConvertUtil.toTwo(healthDishTraceElementsVo.getCholesterol()), actualWeight, standardWeight))) {
         HealthDishesNutritionVo healthDishesNutritionVo = (HealthDishesNutritionVo)var15.next();
         actualWeight = healthDishesNutritionVo.getActualWeight();
         standardWeight = healthDishesNutritionVo.getStandardWeight();
         caloriesAll = caloriesAll.add(getActualContent(healthDishesNutritionVo.getCalories(), actualWeight, standardWeight));
         proteinAll = proteinAll.add(getActualContent(healthDishesNutritionVo.getProtein(), actualWeight, standardWeight));
         carbohydrateAll = carbohydrateAll.add(getActualContent(healthDishesNutritionVo.getCarbohydrate(), actualWeight, standardWeight));
         fatAll = fatAll.add(getActualContent(healthDishesNutritionVo.getFat(), actualWeight, standardWeight));
         dietaryFiberAll = dietaryFiberAll.add(getActualContent(healthDishesNutritionVo.getDietaryFiber(), actualWeight, standardWeight));
         sodiumAll = sodiumAll.add(getActualContent(healthDishesNutritionVo.getSodium(), actualWeight, standardWeight));
         healthDishTraceElementsVo = ObjectUtil.isNotNull(healthDishesNutritionVo.getHealthDishTraceElementsVo()) ? healthDishesNutritionVo.getHealthDishTraceElementsVo() : new HealthDishTraceElementsVo();
      }

      return HealthNormalElementsVo.builder().calories(this.getAverage(caloriesAll, days)).protein(this.getAverage(proteinAll, days)).carbohydrate(this.getAverage(carbohydrateAll, days)).fat(this.getAverage(fatAll, days)).dietaryFiber(this.getAverage(dietaryFiberAll, days)).cholesterol(this.getAverage(cholesterolAll, days)).sodium(this.getAverage(sodiumAll, days)).build();
   }

//   public List<HealthNutritionVO> getTraceElements(HealthDietReportDTO queryDTO) {
//      LocalDate startDate = queryDTO.getStartDate();
//      LocalDate endData = queryDTO.getEndDate();
//      long days = LocalDateTimeUtil.between(startDate.atStartOfDay(), endData.atStartOfDay(), ChronoUnit.DAYS) + 1L;
//      List<OrderDetailMiniVo> ordDetailS = this.getPeriodOrdDetailS(queryDTO);
//      List<HealthDishTraceElementsVo> traceElementsVos = CollUtil.newArrayList(new HealthDishTraceElementsVo[0]);
//      Iterator var8 = ordDetailS.iterator();
//
//      while(var8.hasNext()) {
//         OrderDetailMiniVo ordDetail = (OrderDetailMiniVo)var8.next();
//         BigDecimal quantity = NuConvertUtil.toTwo(ordDetail.getQuantity());
//         BigDecimal weightUnit = NuConvertUtil.toTwo(ordDetail.getWeightUnit());
//         BigDecimal actualWeight = NuConvertUtil.toTwo((Number)null);
//         BigDecimal standardWeight = NuConvertUtil.toTwo((Number)null);
//         if (MenuSalesTypeEnum.PORTION_ON.key().equals(ordDetail.getSalesMode())) {
//            actualWeight = NumberUtil.mul(quantity, weightUnit);
//            standardWeight = weightUnit;
//         } else if (MenuSalesTypeEnum.WEIGHT_ON.key().equals(ordDetail.getSalesMode())) {
//            actualWeight = quantity;
//            standardWeight = weightUnit;
//         }
//
//         if (!NumberUtil.equals(actualWeight, BigDecimal.ZERO)) {
//            Long dishesId = ordDetail.getGoodsDishesId();
//            MenuDishes menuDish = this.menuDishesApi.getOneMenuDishes(dishesId);
//            if (!ObjectUtil.isNull(menuDish)) {
//               HealthDishTraceElementsVo traceElementsVo = (HealthDishTraceElementsVo)BeanUtil.copyProperties(menuDish, HealthDishTraceElementsVo.class, new String[0]);
//               traceElementsVo = (HealthDishTraceElementsVo)NuConvertUtil.getActualContent(traceElementsVo, actualWeight, standardWeight);
//               traceElementsVos.add(traceElementsVo);
//            }
//         }
//      }
//
//      HealthDishTraceElementsVo healthDishTraceElementsVo = new HealthDishTraceElementsVo();
//      if (CollUtil.isNotEmpty(traceElementsVos)) {
//         HealthDishTraceElementsVo sumDoubleValues = (HealthDishTraceElementsVo)NuConvertUtil.sumDoubleValues(traceElementsVos);
//         healthDishTraceElementsVo = ObjectUtil.isNull(sumDoubleValues) ? new HealthDishTraceElementsVo() : sumDoubleValues;
//         healthDishTraceElementsVo = (HealthDishTraceElementsVo)NuConvertUtil.getDailyAverageData(healthDishTraceElementsVo, days);
//      }
//
//      NutrReferenceIntakeVO nutrientReferenceIntake = (NutrReferenceIntakeVO)Optional.ofNullable(this.healthCateringService.getCustIntake(queryDTO.getCustId())).orElse(new NutrReferenceIntakeVO());
//      List<HealthNutritionVO> healthNutritionVOS = CollUtil.newArrayList(new HealthNutritionVO[0]);
//      healthNutritionVOS.add(HealthNutritionVO.builder().name("钙(mg/d)").actual(NuConvertUtil.toTwo(healthDishTraceElementsVo.getCalcium())).advise(NuConvertUtil.toTwo(nutrientReferenceIntake.getCalcium())).build());
//      healthNutritionVOS.add(HealthNutritionVO.builder().name("铁(mg/d)").actual(NuConvertUtil.toTwo(healthDishTraceElementsVo.getIron())).advise(NuConvertUtil.toTwo(nutrientReferenceIntake.getIron())).build());
//      healthNutritionVOS.add(HealthNutritionVO.builder().name("碘(μg/d)").actual(NuConvertUtil.toTwo(healthDishTraceElementsVo.getIodine())).advise(NuConvertUtil.toTwo(nutrientReferenceIntake.getIodine())).build());
//      healthNutritionVOS.add(HealthNutritionVO.builder().name("钾(mg/d)").actual(NuConvertUtil.toTwo(healthDishTraceElementsVo.getKalium())).advise(NuConvertUtil.toTwo(nutrientReferenceIntake.getKalium())).build());
//      healthNutritionVOS.add(HealthNutritionVO.builder().name("维生素A(μg/d)").actual(NuConvertUtil.toTwo(healthDishTraceElementsVo.getVitaminA())).advise(NuConvertUtil.toTwo(nutrientReferenceIntake.getVitaminA())).build());
//      healthNutritionVOS.add(HealthNutritionVO.builder().name("维生素C(mg/d)").actual(NuConvertUtil.toTwo(healthDishTraceElementsVo.getVitaminC())).advise(NuConvertUtil.toTwo(nutrientReferenceIntake.getVitaminC())).build());
//      healthNutritionVOS.add(HealthNutritionVO.builder().name("维生素E(mg/d)").actual(NuConvertUtil.toTwo(healthDishTraceElementsVo.getVitaminE())).advise(NuConvertUtil.toTwo(nutrientReferenceIntake.getVitaminE())).build());
//      healthNutritionVOS.add(HealthNutritionVO.builder().name("镁(mg/d)").actual(NuConvertUtil.toTwo(healthDishTraceElementsVo.getMagnesium())).advise(NuConvertUtil.toTwo(nutrientReferenceIntake.getMagnesium())).build());
//      healthNutritionVOS.add(HealthNutritionVO.builder().name("锌(mg/d)").actual(NuConvertUtil.toTwo(healthDishTraceElementsVo.getZinc())).advise(NuConvertUtil.toTwo(nutrientReferenceIntake.getZinc())).build());
//      return healthNutritionVOS;
//   }
//
//   public HealthDietPagodaVO getDietPagoda(HealthDietReportDTO healthDietReportDTO) {
//      List<OrderDetailMiniVo> ordDetailS = this.getPeriodOrdDetailS(healthDietReportDTO);
//      List<HealthDietPagodaVO> dietPagodaSum = CollUtil.newArrayList(new HealthDietPagodaVO[0]);
//      Iterator var4 = ordDetailS.iterator();
//
//      while(var4.hasNext()) {
//         OrderDetailMiniVo ordDetail = (OrderDetailMiniVo)var4.next();
//         BigDecimal quantity = NuConvertUtil.toTwo(ordDetail.getQuantity());
//         BigDecimal weightUnit = NuConvertUtil.toTwo(ordDetail.getWeightUnit());
//         BigDecimal actualWeight = NuConvertUtil.toTwo((Number)null);
//         BigDecimal standardWeight = NuConvertUtil.toTwo((Number)null);
//         if (MenuSalesTypeEnum.PORTION_ON.key().equals(ordDetail.getSalesMode())) {
//            actualWeight = NumberUtil.mul(quantity, weightUnit);
//            standardWeight = weightUnit;
//         } else if (MenuSalesTypeEnum.WEIGHT_ON.key().equals(ordDetail.getSalesMode())) {
//            actualWeight = quantity;
//            standardWeight = weightUnit;
//         }
//
//         if (!NumberUtil.equals(actualWeight, BigDecimal.ZERO)) {
//            HealthDietPagodaVO healthDietPagodaVO = this.queryMaterialDetail(ordDetail.getGoodsDishesId());
//            healthDietPagodaVO = (HealthDietPagodaVO)NuConvertUtil.getActualContent(healthDietPagodaVO, actualWeight, standardWeight);
//            dietPagodaSum.add(healthDietPagodaVO);
//         }
//      }
//
//      if (CollUtil.isEmpty(dietPagodaSum)) {
//         return new HealthDietPagodaVO();
//      } else {
//         HealthDietPagodaVO dietPagodaVO = ObjectUtil.isEmpty(dietPagodaSum) ? new HealthDietPagodaVO() : (HealthDietPagodaVO)NuConvertUtil.sumDoubleValues(dietPagodaSum);
//         long days = LocalDateTimeUtil.between(healthDietReportDTO.getStartDate().atStartOfDay(), healthDietReportDTO.getEndDate().atStartOfDay(), ChronoUnit.DAYS) + 1L;
//         return (HealthDietPagodaVO)NuConvertUtil.getDailyAverageData(dietPagodaVO, days);
//      }
//   }
//
////   public HealthDietReportDTO checkRequest(LeRequest<String> request) {
////      String content = (String)request.getContent();
////      HealthDietReportDTO healthDietReportDTO = (HealthDietReportDTO) QueryParseHelper.getParamFromContent(content, HealthDietReportDTO.class);
////      if (!ObjectUtil.isEmpty(healthDietReportDTO.getCustId()) && !ObjectUtil.isEmpty(healthDietReportDTO.getStartDate()) && !ObjectUtil.isEmpty(healthDietReportDTO.getEndDate())) {
////         return healthDietReportDTO;
////      } else {
////         throw new LeException(I18n.getMessage("nutrition.analysis.custIdAndDate.nonNull", new Object[0]));
////      }
////   }
//
//   public HealthDietPagodaVO queryMaterialDetail(Long dishesId) {
//      List<MenuMaterialBasVO> menuMaterialBasVOList = this.menuDishesApi.getMenuMaterialByDishesId(dishesId);
//      HealthDietPagodaVO dietPagodaVO = new HealthDietPagodaVO();
//      Iterator var4 = menuMaterialBasVOList.iterator();
//
//      while(var4.hasNext()) {
//         MenuMaterialBasVO menuMaterialBasVO = (MenuMaterialBasVO)var4.next();
//         String bigType = menuMaterialBasVO.getBigType();
//         Double weight = menuMaterialBasVO.getWeight();
//         if (!StrUtil.isBlank(bigType) && !NumberUtil.equals(weight, 0.0)) {
//            Double oldWeight = 0.0;
//            switch (bigType) {
//               case "蔬菜类及制品":
//                  oldWeight = dietPagodaVO.getVegetables() != null ? dietPagodaVO.getVegetables() : 0.0;
//                  dietPagodaVO.setVegetables(NumberUtil.add(weight, oldWeight));
//                  break;
//               case "植物油":
//                  oldWeight = dietPagodaVO.getOil() != null ? dietPagodaVO.getOil() : 0.0;
//                  dietPagodaVO.setOil(NumberUtil.add(weight, oldWeight));
//                  break;
//               case "薯类、淀粉及制品":
//                  oldWeight = dietPagodaVO.getOil() != null ? dietPagodaVO.getOil() : 0.0;
//                  dietPagodaVO.setTubers(NumberUtil.add(weight, oldWeight));
//                  break;
//               case "坚果、种子类":
//                  oldWeight = dietPagodaVO.getSoybeans_nuts() != null ? dietPagodaVO.getSoybeans_nuts() : 0.0;
//                  dietPagodaVO.setSoybeans_nuts(NumberUtil.add(weight, oldWeight));
//                  break;
//               case "水果类及制品":
//                  oldWeight = dietPagodaVO.getFruits() != null ? dietPagodaVO.getFruits() : 0.0;
//                  dietPagodaVO.setFruits(NumberUtil.add(weight, oldWeight));
//                  break;
//               case "干豆类及制品":
//               case "谷类及制品":
//                  oldWeight = dietPagodaVO.getWhole_grains_beans() != null ? dietPagodaVO.getWhole_grains_beans() : 0.0;
//                  dietPagodaVO.setWhole_grains_beans(NumberUtil.add(weight, oldWeight));
//                  break;
//               case "乳制品":
//               case "乳类及制品":
//                  oldWeight = dietPagodaVO.getDairy() != null ? dietPagodaVO.getDairy() : 0.0;
//                  dietPagodaVO.setDairy(NumberUtil.add(weight, oldWeight));
//                  break;
//               case "水产品":
//               case "鱼虾蟹贝类":
//               case "畜肉类及制品":
//               case "禽肉类及制品":
//               case "蛋类及制品":
//                  oldWeight = dietPagodaVO.getAnimal_meat() != null ? dietPagodaVO.getAnimal_meat() : 0.0;
//                  dietPagodaVO.setAnimal_meat(NumberUtil.add(weight, oldWeight));
//            }
//         }
//      }
//
//      return dietPagodaVO;
//   }
//
//   public List<HealthDishesNutritionVo> mergDish(List<HealthDishesNutritionVo> list) {
//      return new ArrayList(((Map)list.stream().collect(Collectors.groupingBy((vo) -> {
//         return Arrays.asList(vo.getDishesId(), vo.getMealtimeType());
//      }))).values().stream().map((vos) -> {
//         return (HealthDishesNutritionVo)vos.stream().reduce((vo1, vo2) -> {
//            HealthDishesNutritionVo newVo = new HealthDishesNutritionVo();
//            BeanUtils.copyProperties(vo1, newVo);
//            newVo.setActualWeight(vo1.getActualWeight().add(vo2.getActualWeight()));
//            return newVo;
//         }).get();
//      }).toList());
//   }
//
//   public Map<String, Long> countMenuAndMaterial(HealthDietReportDTO content) {
//      Map<String, Long> map = new HashMap();
//      Long menuCount = 0L;
//      Long materialCount = 0L;
//
//      try {
//         List<OrderDetailMiniVo> ordDetailS = this.getPeriodOrdDetailS(content);
//         if (CollUtil.isNotEmpty(ordDetailS)) {
//            menuCount = (long)(Integer)ordDetailS.stream().map((x) -> {
//               return NumberUtil.equals(x.getSalesMode(), MenuSalesTypeEnum.WEIGHT_ON.key()) ? 1 : x.getQuantity();
//            }).reduce(0, Integer::sum);
//            List<Long> dishIds = (List)ordDetailS.stream().map(OrderDetailMiniVo::getGoodsDishesId).distinct().collect(Collectors.toList());
//            Set<Long> materialIds = new HashSet();
//            Iterator var8 = dishIds.iterator();
//
//            while(var8.hasNext()) {
//               Long dishId = (Long)var8.next();
//               List<MenuMaterialBasVO> menuMaterialByDishesId = this.menuDishesApi.getMenuMaterialByDishesId(dishId);
//               materialIds.addAll((Collection)menuMaterialByDishesId.stream().map(MenuMaterialBasVO::getMaterialId).collect(Collectors.toSet()));
//            }
//
//            materialCount = (long)materialIds.size();
//         }
//      } catch (NullPointerException var14) {
//         log.info("菜品计算出现异常");
//      } finally {
//         map.put("menuCount", menuCount);
//         map.put("materialCount", materialCount);
//      }
//
//      return map;
//   }

   public List<OrderDetailMiniVo> getPeriodOrdDetailS(HealthDietReportDTO healthDietReportDTO) {
      OrderSearchParamDTO orderSearchParamDTO = new OrderSearchParamDTO();
      orderSearchParamDTO.setCustId(healthDietReportDTO.getCustId());
      orderSearchParamDTO.setStartDate(healthDietReportDTO.getStartDate());
      orderSearchParamDTO.setEndDate(healthDietReportDTO.getEndDate());
      orderSearchParamDTO.setMealtimeTypeList(healthDietReportDTO.getMealtimeTypeList());
      orderSearchParamDTO.setOrderStateList(CollUtil.toList(new Integer[]{OrderStateEnum.FINISH.getKey()}));
      List<OrderDetailMiniVo> ordDetailApiVOS = CollUtil.newArrayList(new OrderDetailMiniVo[0]);
      Iterator var4 = this.orderNutritionApi.listOrderInfoVO(orderSearchParamDTO, false).iterator();

      while(var4.hasNext()) {
         OrderInfoVO orderInfoVO = (OrderInfoVO)var4.next();
         Iterator var6 = orderInfoVO.getOrderDetailList().iterator();

         while(var6.hasNext()) {
            OrderDetailVO orderDetailVO = (OrderDetailVO)var6.next();
            ordDetailApiVOS.add(OrderDetailMiniVo.builder().goodsDishesId(orderDetailVO.getGoodsDishesId()).quantity(orderDetailVO.getQuantity()).weightUnit(orderDetailVO.getWeightUnit()).salesMode(orderDetailVO.getSalesMode()).mealtimeType(orderInfoVO.getMealtimeType()).build());
         }
      }

      return ordDetailApiVOS;
   }
//
//   public List<OrdDetailApiVO> getPeriodOrdDetailFull(HealthDietReportDTO healthDietReportDTO) {
//      OrderSearchParamDTO orderSearchParamDTO = new OrderSearchParamDTO();
//      orderSearchParamDTO.setCustId(healthDietReportDTO.getCustId());
//      orderSearchParamDTO.setStartDate(healthDietReportDTO.getStartDate());
//      orderSearchParamDTO.setEndDate(healthDietReportDTO.getEndDate());
//      orderSearchParamDTO.setMealtimeTypeList(healthDietReportDTO.getMealtimeTypeList());
//      orderSearchParamDTO.setOrderStateList(CollUtil.toList(new Integer[]{OrderStateEnum.FINISH.getKey()}));
//      List<OrdDetailApiVO> ordDetailApiVOS = CollUtil.newArrayList(new OrdDetailApiVO[0]);
//      Iterator var4 = this.orderNutritionApi.listOrderInfoVO(orderSearchParamDTO, false).iterator();
//
//      while(var4.hasNext()) {
//         OrderInfoVO orderInfoVO = (OrderInfoVO)var4.next();
//         Iterator var6 = orderInfoVO.getOrderDetailList().iterator();
//
//         while(var6.hasNext()) {
//            OrderDetailVO orderDetailVO = (OrderDetailVO)var6.next();
//            OrdDetailApiVO ordDetailApiVO = new OrdDetailApiVO();
//            ordDetailApiVO.setOrderId(orderDetailVO.getOrderId());
//            ordDetailApiVO.setGoodsDishesId(orderDetailVO.getGoodsDishesId());
//            ordDetailApiVO.setGoodsDishesName(orderDetailVO.getGoodsDishesName());
//            ordDetailApiVO.setGoodsDishesImgUrl(orderDetailVO.getGoodsDishesImgUrl());
//            ordDetailApiVO.setMenuDetailId(orderDetailVO.getMenuDetailId());
//            ordDetailApiVO.setSalePrice(orderDetailVO.getSalePrice());
//            ordDetailApiVO.setPrefPrice(orderDetailVO.getPrefPrice());
//            ordDetailApiVO.setPrice(orderDetailVO.getPrice());
//            ordDetailApiVO.setWeightUnit(orderDetailVO.getWeightUnit());
//            ordDetailApiVO.setQuantity(orderDetailVO.getQuantity());
//            ordDetailApiVO.setUnitName(orderDetailVO.getUnitName());
//            ordDetailApiVO.setTotalAmount(orderDetailVO.getTotalAmount());
//            ordDetailApiVO.setCalcTotalAmount(orderDetailVO.getCalcTotalAmount());
//            ordDetailApiVO.setRealAmount(orderDetailVO.getRealAmount());
//            ordDetailApiVO.setSalesMode(orderDetailVO.getSalesMode());
//            ordDetailApiVO.setDetailType(orderDetailVO.getDetailType());
//            ordDetailApiVO.setMealtimeName(orderInfoVO.getMealtimeName());
//            ordDetailApiVO.setMealtimeType(orderInfoVO.getMealtimeType());
//            ordDetailApiVOS.add(ordDetailApiVO);
//         }
//      }
//
//      return ordDetailApiVOS;
//   }

   private BigDecimal getAverage(BigDecimal total, Long days) {
      total = total == null ? BigDecimal.ZERO : total;
      return total.divide(BigDecimal.valueOf(days), NutritionConstants.NEW_SCALE, RoundingMode.HALF_UP);
   }

   private HealthDishesNutritionVo buildDishesNutritionVo(OrderDetailMiniVo ordDetail, Long dishesId, MenuDishes menuDish) {
      BigDecimal quantity = NuConvertUtil.toTwo(ordDetail.getQuantity());
      BigDecimal weightUnit = NuConvertUtil.toTwo(ordDetail.getWeightUnit());
      BigDecimal actualWeight = NuConvertUtil.toTwo((Number)null);
      BigDecimal standardWeight = NuConvertUtil.toTwo((Number)null);
      if (MenuSalesTypeEnum.PORTION_ON.key().equals(ordDetail.getSalesMode())) {
         actualWeight = NumberUtil.mul(quantity, weightUnit);
         standardWeight = weightUnit;
      } else if (MenuSalesTypeEnum.WEIGHT_ON.key().equals(ordDetail.getSalesMode())) {
         actualWeight = quantity;
         standardWeight = weightUnit;
      }

      HealthDishesNutritionVo healthDishesNutritionVo = HealthDishesNutritionVo.builder().dishesId(dishesId)
              .dishesName(menuDish.getDishesName()).actualWeight(actualWeight).standardWeight(standardWeight)
              .mealtimeType(ordDetail.getMealtimeType()).dishesSource(HealthDishSourceEnum.MENU.key())
              .calories(NuConvertUtil.toTwo(menuDish.getCalories())).protein(NuConvertUtil.toTwo(menuDish.getProtein()))
              .carbohydrate(NuConvertUtil.toTwo(menuDish.getCarbohydrate())).fat(NuConvertUtil.toTwo(menuDish.getFat()))
              .dietaryFiber(NuConvertUtil.toTwo(menuDish.getDietaryFiber())).sodium(NuConvertUtil.toTwo(menuDish.getSodium())).build();
      return healthDishesNutritionVo;
   }
//
//   private void checkDishesNutritionDto(List<HealthDishesNutritionDto> dishesNutritionDtoList) {
//      Iterator var2 = dishesNutritionDtoList.iterator();
//
//      while(var2.hasNext()) {
//         HealthDishesNutritionDto healthDishesNutritionDto = (HealthDishesNutritionDto)var2.next();
//         Assert.notNull(healthDishesNutritionDto.getCustId(), () -> {
//            return new LeException(I18n.getMessage("nutrition.dish.custId.nonNull", new Object[0]));
//         });
//         Assert.notBlank(healthDishesNutritionDto.getDishesName(), () -> {
//            return new LeException(I18n.getMessage("nutrition.dish.dishName.nonNull", new Object[0]));
//         });
//         Assert.notNull(healthDishesNutritionDto.getActualWeight(), () -> {
//            return new LeException(I18n.getMessage("nutrition.dish.weight.nonNull", new Object[0]));
//         });
//         Assert.notNull(healthDishesNutritionDto.getEatDate(), () -> {
//            return new LeException(I18n.getMessage("nutrition.dish.eatDate.nonNull", new Object[0]));
//         });
//         Assert.notNull(healthDishesNutritionDto.getMealtimeType(), () -> {
//            return new LeException(I18n.getMessage("nutrition.dish.mealtimeType.nonNull", new Object[0]));
//         });
//         Integer dishesSource = healthDishesNutritionDto.getDishesSource();
//         Assert.notNull(dishesSource, () -> {
//            return new LeException(I18n.getMessage("nutrition.dish.dishesSource.nonNull", new Object[0]));
//         });
//         if (HealthDishSourceEnum.MENU.key().equals(dishesSource)) {
//            Assert.notNull(healthDishesNutritionDto.getDishesId(), () -> {
//               return new LeException(I18n.getMessage("nutrition.dish.dishId.nonNull", new Object[0]));
//            });
//         }
//      }
//
//   }
}
