package com.bonus.canteen.core.supply.purchase.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bonus.canteen.core.menu.domain.MenuDishes;
import com.bonus.canteen.core.menu.domain.MenuMaterial;
import com.bonus.canteen.core.menu.enums.AllocMealtimeTypeEnum;
import com.bonus.canteen.core.menu.mapper.MenuDishesMapper;
import com.bonus.canteen.core.menu.mapper.MenuMaterialMapper;
import com.bonus.canteen.core.supply.purchase.api.MenuDishesApi;
import com.bonus.canteen.core.supply.purchase.constants.DrpApproveStatusEnum;
import com.bonus.canteen.core.supply.purchase.constants.DrpCommitStatusEnum;
import com.bonus.canteen.core.supply.purchase.constants.DrpInterfaceType;
import com.bonus.canteen.core.supply.purchase.domain.bo.*;
import com.bonus.canteen.core.supply.purchase.domain.param.*;
import com.bonus.canteen.core.supply.purchase.domain.vo.*;
import com.bonus.canteen.core.supply.purchase.mapper.*;
import com.bonus.canteen.core.supply.purchase.service.DrpOtherService;
import com.bonus.canteen.core.supply.purchase.service.DrpProductionPlanService;
import com.bonus.canteen.core.supply.purchase.utils.CustomIdGenerateUtil;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.common.houqin.constant.DelFlagEnum;
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.common.security.utils.SecurityUtils;
import org.apache.commons.compress.utils.Lists;
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 org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class DrpProductionPlanServiceImpl extends ServiceImpl<DrpProductionPlanMapper, DrpProductionPlan> implements DrpProductionPlanService {
   private static final Logger log = LoggerFactory.getLogger(DrpProductionPlanServiceImpl.class);
   @Autowired
   @Lazy
   private DrpProductionPlanMapper drpProductionPlanMapper;
   @Autowired
   @Lazy
   private DrpProductionPlanDetailMapper drpProductionPlanDetailMapper;
   @Autowired
   @Lazy
   private DrpPurchasePlanMapper drpPurchasePlanMapper;
   @Autowired
   @Lazy
   private DrpPurPlanDetailMapper drpPurPlanDetailMapper;
   @Autowired
   @Lazy
   private MenuMaterialMapper menuMaterialMapper;
   @Autowired
   @Lazy
   private MenuDishesApi menuDishesApi;
   @Autowired
   @Lazy
   private MenuDishesMapper menuDishesMapper;
   @Autowired
   @Lazy
   private DrpProductionPurchaseOrderMapper drpProductionPurchaseOrderMapper;
   @Autowired
   @Lazy
   private DrpOtherService drpOtherService;

   public List<DrpProductionPlanPageVO> pageProductionPlan(DrpProductionPlanPageDTO content) {
      if (content.getInterfaceType().equals(DrpInterfaceType.APP) && ObjectUtil.isNotEmpty(content.getType())) {
         List instanceIdsByState;
         switch (content.getType()) {
            case 1:
               content.setOrderStatus(DrpCommitStatusEnum.SAVE.key());
               content.setCreateBy(SecurityUtils.getUsername());
               break;
//            case 2:
//               content.setOrderStatus(DrpCommitStatusEnum.COMMIT.key());
//               instanceIdsByState = this.flowApi.getInstanceIdsByState(State.WAITING, FlowDefinitionEum.getStagingDefinitionsByEnum(FlowDefinitionEum.DRP_PRODUCTION_PLAN_PLAN));
//               if (instanceIdsByState.isEmpty()) {
//                  return new ArrayList();
//               }
//
//               content.setInstanceIds(instanceIdsByState);
//               break;
//            case 3:
//               content.setOrderStatus(DrpCommitStatusEnum.COMMIT.key());
//               instanceIdsByState = this.flowApi.getInstanceIdsByState(FlowDefinitionEum.getStagingDefinitionsByEnum(FlowDefinitionEum.DRP_PRODUCTION_PLAN_PLAN));
//               if (instanceIdsByState.isEmpty()) {
//                  return new ArrayList();
//               }
//
//               content.setInstanceIds(instanceIdsByState);
//               break;
            case 4:
               content.setOrderStatus(DrpCommitStatusEnum.COMMIT.key());
               content.setCreateBy(SecurityUtils.getUsername());
               break;
            default:
               throw new ServiceException("不支持的类型传参 type: " + content.getType());
         }
      }

      if (CharSequenceUtil.isNotEmpty(content.getProductionPlanName())) {
         content.setProductionPlanName(LeBeanUtil.fieldLikeHandle(content.getProductionPlanName()));
      }

      List<DrpProductionPlanPageVO> resultList = this.drpProductionPlanMapper.pageProductionPlan(content, DelFlagEnum.DEL_FALSE.key());
//      Map<Long, Boolean> limitMap = this.flowApi.getLimitMap((List)resultList.stream().map(DrpProductionPlanPageVO::getProcessInstanceId).collect(Collectors.toList()));
      List<String> planIds = resultList.stream().map(DrpProductionPlanPageVO::getProductionPlanId).collect(Collectors.toList());
      List<ProductionPlanDateVO> productionPlanDateVOS = this.drpProductionPlanDetailMapper.listDetailPlanDateByIdList(planIds);
      Map<String, List<ProductionPlanDateVO>> map = productionPlanDateVOS.stream().collect(Collectors.groupingBy(ProductionPlanDateVO::getProductionPlanId));
      Iterator var10 = resultList.iterator();

      while(var10.hasNext()) {
         DrpProductionPlanPageVO drpProductionPlanPageVO = (DrpProductionPlanPageVO)var10.next();
//         drpProductionPlanPageVO.setCurUserApprove((Boolean)limitMap.get(drpProductionPlanPageVO.getProcessInstanceId()));
         if (map.get(drpProductionPlanPageVO.getProductionPlanId()) != null) {
            drpProductionPlanPageVO.setDetailPlanDate((map.get(drpProductionPlanPageVO.getProductionPlanId())).stream().map(ProductionPlanDateVO::getDetailDate).filter(Objects::nonNull).collect(Collectors.toList()));
         }

         Long count = this.drpProductionPurchaseOrderMapper.selectCount((Wrappers.lambdaQuery(DrpProductionPurchaseOrder.class).eq(DrpProductionPurchaseOrder::getProductionPlanId, drpProductionPlanPageVO.getProductionPlanId())).eq(DrpProductionPurchaseOrder::getOrderType, 1));
         drpProductionPlanPageVO.setCurUCreatePurchasePlan(count > 0L);
      }

      return resultList;
   }

   @Transactional(
      rollbackFor = {Exception.class}
   )
   public String addProductionPlan(DrpProductionPlanAddDTO content) {
      DrpProductionPlan drpProductionPlan;
      if (CharSequenceUtil.isBlank(content.getProductionPlanId())) {
         drpProductionPlan = new DrpProductionPlan();
         BeanUtil.copyProperties(content, drpProductionPlan);
         String productionId = CustomIdGenerateUtil.generateProductionId();
         drpProductionPlan.setProductionPlanId(productionId);
         this.drpProductionPlanMapper.insert(drpProductionPlan);
         content.setProductionPlanId(productionId);
      } else {
         drpProductionPlan = (DrpProductionPlan)this.drpProductionPlanMapper.selectById(content.getProductionPlanId());
         BeanUtil.copyProperties(content, drpProductionPlan, new String[0]);
         this.drpProductionPlanMapper.updateById(drpProductionPlan);
         this.drpProductionPlanDetailMapper.delete(Wrappers.lambdaQuery(DrpProductionPlanDetail.class).eq(DrpProductionPlanDetail::getProductionPlanId, content.getProductionPlanId()));
      }

      this.insertDrpProductionPlanDetailData(content, drpProductionPlan);
      return content.getProductionPlanId();
   }

   protected void insertDrpProductionPlanDetailData(DrpProductionPlanAddDTO content, DrpProductionPlan drpProductionPlan) {
      List<MenuDishesSizeModel> menuDishesSizeModels = this.menuDishesApi.listDishesSizeModel();
      HashMap<String, Long> dishesIdMap = new HashMap();
      Iterator var5 = menuDishesSizeModels.iterator();

      String ifProductionPlanNeedProcess;
      while(var5.hasNext()) {
         MenuDishesSizeModel menuDishesSizeModel = (MenuDishesSizeModel)var5.next();
         Long var10000 = menuDishesSizeModel.getBaseDishesId();
         ifProductionPlanNeedProcess = "" + var10000 + "_" + menuDishesSizeModel.getSizeType();
         dishesIdMap.put(ifProductionPlanNeedProcess, menuDishesSizeModel.getDishesId());
      }

      var5 = content.getProductionDetailList().iterator();

      while(var5.hasNext()) {
         DrpProductionPlanDetailAddDTO drpProductionPlanDetailAddDTO = (DrpProductionPlanDetailAddDTO)var5.next();
         log.info("生产计划新增，明细:{}", drpProductionPlanDetailAddDTO);
         if (ObjectUtil.isEmpty(drpProductionPlanDetailAddDTO.getSizeType())) {
            log.info("赋值sizeType");
            MenuDishes sizeTypeModel = (MenuDishes)this.menuDishesMapper.selectOne((Wrappers.lambdaQuery(MenuDishes.class).eq(MenuDishes::getBaseDishesId, drpProductionPlanDetailAddDTO.getDishesId())).select(MenuDishes::getSizeType));
            drpProductionPlanDetailAddDTO.setSizeType(sizeTypeModel.getSizeType());
         }

         DrpProductionPlanDetail drpProductionPlanDetail = new DrpProductionPlanDetail();
         BeanUtil.copyProperties(drpProductionPlanDetailAddDTO, drpProductionPlanDetail);
         drpProductionPlanDetail.setProductionDetailId(Id.next());
         drpProductionPlanDetail.setProductionPlanId(content.getProductionPlanId());
         Long var10002 = drpProductionPlanDetailAddDTO.getDishesId();
         drpProductionPlanDetail.setDishesId((Long)dishesIdMap.get("" + var10002 + "_" + drpProductionPlanDetailAddDTO.getSizeType()));
         this.drpProductionPlanDetailMapper.insert(drpProductionPlanDetail);
      }

      if (content.getStatus() != null && content.getStatus() == 2) {
//         boolean isAdmin = SecureManager.hasRole(new String[]{RoleCodeV2Enum.ROLE_SUPER_ADMIN.key()});
//         AllocDrpModel allocDrpModel = this.drpMetadataService.queryMetadataByCanteenId(content.getCanteenId());
//         ifProductionPlanNeedProcess = allocDrpModel.getIfProductionPlanNeedProcess();
//         if (!isAdmin && !ObjectUtil.equal(ifProductionPlanNeedProcess, "2")) {
//            Long userId = (Long)SecureManager.getSubjectId().get();
//            MgrUser mgrUser = this.mgrUserApi.selectMgrUserByUserId(userId);
//            Long definitionId = this.flowApi.getByMappingIdAndDefinitionType(userId, FlowDefinitionEum.DRP_PRODUCTION_PLAN_PLAN, mgrUser != null ? mgrUser.getAreaId() : null);
//            if (ObjectUtil.isNull(definitionId)) {
//               throw new LeException(I18n.getMessage("drp.process-definition-is-null", new Object[0]));
//            }
//
//            CreatInstanceDto creatInstanceDto = new CreatInstanceDto();
//            creatInstanceDto.setDefinitionId(definitionId);
//            DrpProductionPlanDetailVO detail = this.detail(content.getProductionPlanId());
//            detail.setMenuDishesVOList((List)null);
//            detail.setProductionPlanType(drpProductionPlan.getProductionPlanType());
//            creatInstanceDto.setContext(FlowBeanUtil.parseObj2Map(detail));
//            Long instanceId = this.flowApi.creat(creatInstanceDto);
//            this.drpProductionPlanMapper.update((Object)null, (Wrapper)((LambdaUpdateWrapper)((LambdaUpdateWrapper)Wrappers.lambdaUpdate(DrpProductionPlan.class).set(DrpProductionPlan::getProcessInstanceId, instanceId)).set(DrpProductionPlan::getApproveStatus, DrpApproveStatusEnum.WAIT_APPROVE.key())).eq(DrpProductionPlan::getProductionPlanId, content.getProductionPlanId()));
//         } else {
            this.drpProductionPlanMapper.update(null, (Wrappers.lambdaUpdate(DrpProductionPlan.class).set(DrpProductionPlan::getApproveStatus, DrpApproveStatusEnum.AGREE_APPROVE.key())).eq(DrpProductionPlan::getProductionPlanId, content.getProductionPlanId()));
//         }
      }

   }

   public void deleteProductionPlan(String productionId) {
      if (CharSequenceUtil.isBlank(productionId)) {
         throw new ServiceException("生产计划单号为空");
      } else {
         this.drpProductionPlanMapper.update(null, (Wrappers.lambdaUpdate(DrpProductionPlan.class).eq(DrpProductionPlan::getProductionPlanId, productionId)).set(DrpProductionPlan::getDelFlag, DelFlagEnum.DEL_TRUE.key()));
      }
   }

   @Transactional(
      rollbackFor = {Exception.class}
   )
   public String generatePurPlan(List<DrpGeneratePurPlanDetailDTO> content) {
      DrpPurchasePlan drpPurchasePlan = new DrpPurchasePlan();
      String planId = CustomIdGenerateUtil.generatePurchaseOrdId();
      drpPurchasePlan.setPlanId(planId);
      drpPurchasePlan.setPurDate(LocalDateTime.now());
      this.drpPurchasePlanMapper.insert(drpPurchasePlan);
      Iterator var4 = content.iterator();

      while(var4.hasNext()) {
         DrpGeneratePurPlanDetailDTO drpGeneratePurPlanDetailDTO = (DrpGeneratePurPlanDetailDTO)var4.next();
         DrpPurPlanDetail drpPurPlanDetail = new DrpPurPlanDetail();
         BeanUtil.copyProperties(drpGeneratePurPlanDetailDTO, drpPurPlanDetail, new String[0]);
         drpPurPlanDetail.setDetailId(Id.next());
         drpPurPlanDetail.setPlanId(planId);
         this.drpPurPlanDetailMapper.insert(drpPurPlanDetail);
      }

      return planId;
   }

   public List<DrpProductionDetailDirectListVO> listDetailDirect(String productionPlanId) {
      return this.drpProductionPlanDetailMapper.listDetailDirect(productionPlanId);
   }

   public List<DrpProductionDetailRecipeOrderListVO> listDetailRecipeOrder(String productionPlanId) {
      List<DrpProductionDetailRecipeOrderListVO> resultList = this.drpProductionPlanDetailMapper.listDetailRecipeOrder(productionPlanId);
      List<MenuDishesSizeModel> menuDishesSizeModels = this.menuDishesApi.listDishesSizeModel();
      HashMap<Long, DishesSizeModel> baseDishesMap = new HashMap();
      Iterator var5 = menuDishesSizeModels.iterator();

      DishesSizeModel dishesSizeModel;
      while(var5.hasNext()) {
         MenuDishesSizeModel menuDishesSizeModel = (MenuDishesSizeModel)var5.next();
         dishesSizeModel = new DishesSizeModel();
         dishesSizeModel.setBaseDishesId(menuDishesSizeModel.getBaseDishesId());
         dishesSizeModel.setSizeType(menuDishesSizeModel.getSizeType());
         baseDishesMap.put(menuDishesSizeModel.getDishesId(), dishesSizeModel);
      }

      var5 = resultList.iterator();

      while(var5.hasNext()) {
         DrpProductionDetailRecipeOrderListVO result = (DrpProductionDetailRecipeOrderListVO)var5.next();
         dishesSizeModel = baseDishesMap.get(result.getDishesId());
         if (dishesSizeModel != null) {
            result.setDishesId(dishesSizeModel.getBaseDishesId());
            result.setSizeType(dishesSizeModel.getSizeType());
         }
      }

      return resultList;
   }

   public List<DrpProductionDishesNumVO> listProductionDishesSum(String productionPlanId) {
      List<DrpProductionDishesNumVO> drpProductionDishesNumVOList = this.drpProductionPlanDetailMapper.listProductionDishesSum(productionPlanId);
      if (CollUtil.isEmpty(drpProductionDishesNumVOList)) {
         throw new ServiceException("生产计划没有菜品明细!");
      } else {
         Map<String, DrpProductionDishesNumVO> map = new HashMap();
         drpProductionDishesNumVOList.forEach((dishes) -> {
            Long var10001 = dishes.getDishesId();
            DrpProductionDishesNumVO last = map.get("" + var10001 + "_" + dishes.getSizeType());
            if (ObjectUtil.isNotEmpty(last)) {
               dishes.setDishesNum(dishes.getDishesNum() + last.getDishesNum());
               map.put(dishes.getDishesId() + "_" + dishes.getSizeType(), dishes);
            } else {
               map.put(dishes.getDishesId() + "_" + dishes.getSizeType(), dishes);
            }

         });
         return new ArrayList(map.values());
      }
   }

   public void saveReserveRate(List<DrpReserveRateSaveDTO> content) {
      Iterator var2 = content.iterator();

      while(var2.hasNext()) {
         DrpReserveRateSaveDTO drpReserveRateSaveDTO = (DrpReserveRateSaveDTO)var2.next();
         this.menuMaterialMapper.update(null, (Wrappers.lambdaUpdate(MenuMaterial.class).eq(MenuMaterial::getMaterialId, drpReserveRateSaveDTO.getMaterialId())).set(MenuMaterial::getReserveRate, drpReserveRateSaveDTO.getReserveRate()));
      }

   }

   public String batchGeneratePurPlan(DrpGeneratePurPlanDTO content) {
      String productionPlanIds = String.join(",", content.getProductionPlanId());
      List<DrpGeneratePurPlanDetailDTO> list = content.getDetailDTOList();
      DrpPurchasePlan drpPurchasePlan = new DrpPurchasePlan();
      String planId = CustomIdGenerateUtil.generatePurchaseOrdId();
      drpPurchasePlan.setPlanId(planId);
      drpPurchasePlan.setProductionPlanId(productionPlanIds);
      drpPurchasePlan.setPurDate(LocalDateTime.now());
      this.drpPurchasePlanMapper.insert(drpPurchasePlan);
      list.forEach((d) -> {
         DrpPurPlanDetail drpPurPlanDetail = new DrpPurPlanDetail();
         BeanUtil.copyProperties(d, drpPurPlanDetail, new String[0]);
         drpPurPlanDetail.setDetailId(Id.next());
         drpPurPlanDetail.setPlanId(planId);
         this.drpPurPlanDetailMapper.insert(drpPurPlanDetail);
      });
      return planId;
   }

   public List<DrpProductionDishesNumVO> listProductionDishesSumByPlanIds(List<String> content) {
      List<DrpProductionDishesNumVO> drpProductionDishesNumVOList = this.drpProductionPlanDetailMapper.listProductionDishesSumByPlanIds(content);
      if (CollUtil.isEmpty(drpProductionDishesNumVOList)) {
         throw new ServiceException("生产计划没有菜品明细!");
      } else {
         Map<Long, DrpProductionDishesNumVO> map = new HashMap();
         drpProductionDishesNumVOList.forEach((dishes) -> {
            DrpProductionDishesNumVO last = map.get(dishes.getDishesId());
            if (ObjectUtil.isNotEmpty(last)) {
               dishes.setDishesNum(dishes.getDishesNum() + last.getDishesNum());
               map.put(dishes.getDishesId(), dishes);
            } else {
               map.put(dishes.getDishesId(), dishes);
            }

         });
         return new ArrayList(map.values());
      }
   }

   public AmountBaseByPageHelperVO materialCount(DrpProductionPlanPageDTO content) {
      List<DrpProductionPlanMaterialCountVO> list = this.drpProductionPlanMapper.materialCount(content);
      DrpProductionPlanMaterialCountVO drpProductionPlanMaterialCountVO = new DrpProductionPlanMaterialCountVO();
      drpProductionPlanMaterialCountVO.setMaterialName("合计");
      drpProductionPlanMaterialCountVO.setCategoryName(String.valueOf(list.stream().map(DrpProductionPlanMaterialCountVO::getCategoryId).distinct().count()));
      drpProductionPlanMaterialCountVO.setMaterialCount(list.stream().map(DrpProductionPlanMaterialCountVO::getMaterialCount).reduce(BigDecimal.ZERO, BigDecimal::add).setScale(3, RoundingMode.HALF_UP));
      return (new AmountBaseByPageHelperVO<DrpProductionPlanMaterialCountVO>()).setList(list).setTotalLine(drpProductionPlanMaterialCountVO);
   }

   public DrpProductionPlanDetailVO detail(String productionPlanId) {
      DrpProductionPlanDetailVO drpProductionPlanDetailVO = this.drpProductionPlanMapper.queryByPlanId(productionPlanId);
      List<LocalDate> detailPlanDate = this.drpProductionPlanDetailMapper.listDetailPlanDate(productionPlanId);
      drpProductionPlanDetailVO.setDetailPlanDate(detailPlanDate);
      List<DrpProductionDetailRecipeOrderListVO> resultList = this.drpProductionPlanDetailMapper.listDetailRecipeOrder(productionPlanId);
      List<MenuDishesSizeModel> menuDishesSizeModels = this.menuDishesApi.listDishesSizeModel();
      Map<Long, MenuDishesSizeModel> baseDishesMap = menuDishesSizeModels.stream().collect(Collectors.toMap(MenuDishesSizeModel::getDishesId, (e) -> {
         return e;
      }, (k1, k2) -> {
         return k1;
      }));
      Iterator var7 = resultList.iterator();

      while(var7.hasNext()) {
         DrpProductionDetailRecipeOrderListVO result = (DrpProductionDetailRecipeOrderListVO)var7.next();
         MenuDishesSizeModel dishesSizeModel = (MenuDishesSizeModel)baseDishesMap.get(result.getDishesId());
         if (dishesSizeModel != null) {
            result.setDishesId(dishesSizeModel.getBaseDishesId());
            result.setSizeType(dishesSizeModel.getSizeType());
         }
      }

      Map<LocalDate, List<DrpProductionDetailRecipeOrderListVO>> dishesMap = resultList.stream().filter((d) -> {
         return d.getDetailDate() != null;
      }).collect(Collectors.groupingBy(DrpProductionDetailRecipeOrderListVO::getDetailDate));
      List<DrpProductionPlanDetailMenuDishesVO> menuDishesVOList = new ArrayList();
      dishesMap.forEach((key, value) -> {
         DrpProductionPlanDetailMenuDishesVO drpProductionPlanDetailMenuDishesVO = new DrpProductionPlanDetailMenuDishesVO();
         drpProductionPlanDetailMenuDishesVO.setDetailDate(key);
         Map<Integer, List<DrpProductionDetailRecipeOrderListVO>> mealtimeTypeMap = value.stream().collect(Collectors.groupingBy(DrpProductionDetailRecipeOrderListVO::getMealtimeType));
         List<DrpProductionPlanDetailMenuDishesVO.DrpMealtimeTypeVO> mealtimeTypeVOList = new ArrayList();
         mealtimeTypeMap.forEach((key1, value1) -> {
            DrpProductionPlanDetailMenuDishesVO.DrpMealtimeTypeVO drpMealtimeTypeVO = new DrpProductionPlanDetailMenuDishesVO.DrpMealtimeTypeVO();
            drpMealtimeTypeVO.setMealtimeType(key1);
            drpMealtimeTypeVO.setMealtimeName(AllocMealtimeTypeEnum.getDescByKey(key1));
            List<DrpProductionPlanDetailMenuDishesVO.DrpPlanDetailMenuDishesVO> drpPlanDetailMenuDishesVOList = new ArrayList();
            value1.forEach((d) -> {
               DrpProductionPlanDetailMenuDishesVO.DrpPlanDetailMenuDishesVO drpPlanDetailMenuDishesVO = new DrpProductionPlanDetailMenuDishesVO.DrpPlanDetailMenuDishesVO();
               drpPlanDetailMenuDishesVO.setDishesId(d.getDishesId());
               drpPlanDetailMenuDishesVO.setDishesName(d.getDishesName());
               drpPlanDetailMenuDishesVO.setDishesNum(d.getDishesNum());
               drpPlanDetailMenuDishesVO.setSizeType(d.getSizeType());
               drpPlanDetailMenuDishesVOList.add(drpPlanDetailMenuDishesVO);
            });
            drpMealtimeTypeVO.setDrpPlanDetailMenuDishesVOList(drpPlanDetailMenuDishesVOList);
            mealtimeTypeVOList.add(drpMealtimeTypeVO);
         });
         drpProductionPlanDetailMenuDishesVO.setMealtimeTypeVOList(mealtimeTypeVOList);
         menuDishesVOList.add(drpProductionPlanDetailMenuDishesVO);
      });
      List<DrpProductionPlanDetailMenuDishesVO> menuDishesVOListNew = menuDishesVOList.stream().sorted(Comparator.comparing(DrpProductionPlanDetailMenuDishesVO::getDetailDate)).collect(Collectors.toList());
      drpProductionPlanDetailVO.setMenuDishesVOList(menuDishesVOListNew);
      return drpProductionPlanDetailVO;
   }

//   public DrpProductionPlanDetailVO preOrderInfo(OrderDrpDishesSumDTO content) {
//      DrpProductionPlanDetailVO drpProductionPlanDetailVO = new DrpProductionPlanDetailVO();
//      List<OrderDrpDishesSumVO> orderDrpDishesSumVOS = this.orderDrpApi.dishesSum(content);
//      orderDrpDishesSumVOS = (List)orderDrpDishesSumVOS.stream().sorted(Comparator.comparing(OrderDrpDishesSumVO::getOrderDate)).collect(Collectors.toList());
//      orderDrpDishesSumVOS = (List)orderDrpDishesSumVOS.stream().filter((d) -> {
//         return d.getSalesMode() != null && d.getSalesMode() != 2;
//      }).collect(Collectors.toList());
//      if (CollUtil.isEmpty(orderDrpDishesSumVOS)) {
//         throw new LeException(I18n.getMessage("drp.production-advance-order-has-no-detail", new Object[0]));
//      } else {
//         List<MenuDishesSizeModel> menuDishesSizeModels = this.menuDishesApi.listDishesSizeModel();
//         Map<Long, MenuDishesSizeModel> baseDishesMap = (Map)menuDishesSizeModels.stream().collect(Collectors.toMap(MenuDishesSizeModel::getDishesId, (e) -> {
//            return e;
//         }, (k1, k2) -> {
//            return k1;
//         }));
//         Iterator var6 = orderDrpDishesSumVOS.iterator();
//
//         while(var6.hasNext()) {
//            OrderDrpDishesSumVO result = (OrderDrpDishesSumVO)var6.next();
//            MenuDishesSizeModel dishesSizeModel = (MenuDishesSizeModel)baseDishesMap.get(result.getGoodsDishesId());
//            if (dishesSizeModel != null) {
//               result.setSizeType(dishesSizeModel.getSizeType());
//               result.setGoodsDishesId(dishesSizeModel.getBaseDishesId());
//            }
//         }
//
//         Map<LocalDate, List<OrderDrpDishesSumVO>> dishesMap = (Map)orderDrpDishesSumVOS.stream().collect(Collectors.groupingBy(OrderDrpDishesSumVO::getOrderDate, LinkedHashMap::new, Collectors.toList()));
//         List<DrpProductionPlanDetailMenuDishesVO> menuDishesVOList = new ArrayList();
//         dishesMap.forEach((key, value) -> {
//            DrpProductionPlanDetailMenuDishesVO drpProductionPlanDetailMenuDishesVO = new DrpProductionPlanDetailMenuDishesVO();
//            drpProductionPlanDetailMenuDishesVO.setDetailDate(key);
//            Map<Integer, List<OrderDrpDishesSumVO>> mealtimeTypeMap = (Map)value.stream().collect(Collectors.groupingBy(OrderDrpDishesSumVO::getMealtimeType));
//            List<DrpProductionPlanDetailMenuDishesVO.DrpMealtimeTypeVO> mealtimeTypeVOList = new ArrayList();
//            mealtimeTypeMap.forEach((key1, value1) -> {
//               DrpProductionPlanDetailMenuDishesVO.DrpMealtimeTypeVO drpMealtimeTypeVO = new DrpProductionPlanDetailMenuDishesVO.DrpMealtimeTypeVO();
//               drpMealtimeTypeVO.setMealtimeType(key1);
//               drpMealtimeTypeVO.setMealtimeName(AllocMealtimeTypeEnum.getDescByKey(key1));
//               List<DrpProductionPlanDetailMenuDishesVO.DrpPlanDetailMenuDishesVO> drpPlanDetailMenuDishesVOList = new ArrayList();
//               value1.forEach((d) -> {
//                  DrpProductionPlanDetailMenuDishesVO.DrpPlanDetailMenuDishesVO drpPlanDetailMenuDishesVO = new DrpProductionPlanDetailMenuDishesVO.DrpPlanDetailMenuDishesVO();
//                  drpPlanDetailMenuDishesVO.setDishesId(d.getGoodsDishesId());
//                  drpPlanDetailMenuDishesVO.setDishesName(d.getGoodsDishesName());
//                  drpPlanDetailMenuDishesVO.setDishesNum(d.getQuantity());
//                  drpPlanDetailMenuDishesVO.setSizeType(d.getSizeType());
//                  drpPlanDetailMenuDishesVOList.add(drpPlanDetailMenuDishesVO);
//               });
//               drpMealtimeTypeVO.setDrpPlanDetailMenuDishesVOList(drpPlanDetailMenuDishesVOList);
//               mealtimeTypeVOList.add(drpMealtimeTypeVO);
//            });
//            drpProductionPlanDetailMenuDishesVO.setMealtimeTypeVOList(mealtimeTypeVOList);
//            menuDishesVOList.add(drpProductionPlanDetailMenuDishesVO);
//         });
//         drpProductionPlanDetailVO.setMenuDishesVOList(menuDishesVOList);
//         return drpProductionPlanDetailVO;
//      }
//   }

//   public DrpProductionPlanTotalVO getTotal() {
//      boolean isAdmin = SecureManager.hasRole(new String[]{RoleCodeV2Enum.ROLE_SUPER_ADMIN.key()});
//      if (!isAdmin) {
//         String crby = SecurityUtils.getUser().getUsername();
//         return this.drpProductionPlanMapper.queryTotal(crby);
//      } else {
//         return this.drpProductionPlanMapper.queryTotal((String)null);
//      }
//   }

//   public String mergeGeneratePurPlan(List<String> content) {
//      List<DrpProductionPlan> drpProductionPlans = this.drpProductionPlanMapper.selectList(((LambdaQueryWrapper)((LambdaQueryWrapper)Wrappers.lambdaQuery(DrpProductionPlan.class).in(DrpProductionPlan::getProductionPlanId, content)).eq(DrpProductionPlan::getDelFlag, DelFlagEnum.DEL_FALSE.key())).select(new SFunction[]{DrpProductionPlan::getProductionPlanId, DrpProductionPlan::getStallId, DrpProductionPlan::getCanteenId}));
//      if (drpProductionPlans.isEmpty()) {
//         throw new LeException("生产计划不存在！");
//      } else {
//         Map<Long, List<DrpProductionPlan>> canteenMap = (Map)drpProductionPlans.stream().collect(Collectors.groupingBy(DrpProductionPlan::getCanteenId));
//         if (canteenMap.size() > 1) {
//            throw new LeException("只能合并同食堂生产计划！");
//         } else {
//            Map<Long, List<DrpProductionPlan>> stallMap = (Map)drpProductionPlans.stream().collect(Collectors.groupingBy(DrpProductionPlan::getStallId));
//            List<DrpDishesConvertVO> lastList = Lists.newArrayList();
//            stallMap.forEach((stallId, planList) -> {
//               List<DrpProductionDishesNumVO> stallAllList = Lists.newArrayList();
//               planList.forEach((drpProductionPlan) -> {
//                  List<DrpProductionDishesNumVO> drpProductionDishesNumVOS = this.drpProductionPlanService.listProductionDishesSum(drpProductionPlan.getProductionPlanId());
//                  if (CollUtil.isEmpty(drpProductionDishesNumVOS)) {
//                     throw new LeException("生产计划" + drpProductionPlan.getProductionPlanId() + "没有菜品明细!");
//                  } else {
//                     stallAllList.addAll(drpProductionDishesNumVOS);
//                  }
//               });
//               Map<String, DrpProductionDishesNumVO> mergeMap = (Map)stallAllList.stream().collect(Collectors.toMap((d) -> {
//                  Long var10000 = d.getDishesId();
//                  return "" + var10000 + "_" + d.getSizeType();
//               }, (d) -> {
//                  return d;
//               }, (k1, k2) -> {
//                  k1.setDishesNum(k1.getDishesNum() + k2.getDishesNum());
//                  return k1;
//               }));
//               List<DrpDishesConvertDTO> drpDishesConvertDTOList = Lists.newArrayList();
//               mergeMap.values().forEach((drpProductionDishesNumVO) -> {
//                  DrpDishesConvertDTO drpDishesConvertDTO = new DrpDishesConvertDTO();
//                  drpDishesConvertDTO.setDishesId(drpProductionDishesNumVO.getDishesId());
//                  drpDishesConvertDTO.setDishesNum(drpProductionDishesNumVO.getDishesNum());
//                  drpDishesConvertDTO.setSizeType((long)drpProductionDishesNumVO.getSizeType());
//                  drpDishesConvertDTOList.add(drpDishesConvertDTO);
//               });
//               List<DrpDishesConvertVO> drpDishesConvertVOS = this.drpOtherService.dishesConvert(drpDishesConvertDTOList);
//               if (CollUtil.isEmpty(drpDishesConvertVOS)) {
//                  throw new LeException("菜品未绑定原料,转换失败!");
//               } else {
//                  drpDishesConvertVOS.forEach((d) -> {
//                     d.setStallId(stallId);
//                  });
//                  lastList.addAll(drpDishesConvertVOS);
//               }
//            });
//            if (!lastList.isEmpty()) {
//               DrpPurchasePlan drpPurchasePlan = new DrpPurchasePlan();
//               drpPurchasePlan.setStatus(DrpMaterialTenderEnum.WAIT_COMMIT.key());
//               drpPurchasePlan.setRemark("生产计划合并生成采购计划");
//               drpPurchasePlan.setApproveStatus(DrpApproveStatusEnum.WAIT_APPROVE.key());
//               drpPurchasePlan.setDelFlag(LeConstants.COMMON_NO);
//               drpPurchasePlan.setProductionPlanId(String.join(",", content));
//               drpPurchasePlan.setCanteenId(((DrpProductionPlan)drpProductionPlans.get(0)).getCanteenId());
//               drpPurchasePlan.setStallId((String)stallMap.keySet().stream().map(String::valueOf).collect(Collectors.joining(",")));
//               String planId = CustomIdGenerateUtil.generatePurchaseOrdId();
//               drpPurchasePlan.setPlanId(planId);
//               drpPurchasePlan.setPurDate(LocalDateTime.now());
//               this.drpPurchasePlanMapper.insert(drpPurchasePlan);
//               List<MenuMaterialUnitVO> menuMaterialList = this.menuMaterialMapper.getMenuMaterialAndUnitByMaterialIdList((List)lastList.stream().map(DrpDishesConvertVO::getMaterialId).collect(Collectors.toList()));
//               Map<Long, MenuMaterialUnitVO> menuMaterialUnitVOMap = (Map)menuMaterialList.stream().collect(Collectors.toMap(MenuMaterialUnitVO::getMaterialId, (e) -> {
//                  return e;
//               }, (k1, k2) -> {
//                  return k1;
//               }));
//               lastList.forEach((d) -> {
//                  MenuMaterialUnitVO menuMaterialUnitVO = (MenuMaterialUnitVO)menuMaterialUnitVOMap.get(d.getMaterialId());
//                  DrpPurPlanDetail drpPurPlanDetail = new DrpPurPlanDetail();
//                  List<DrpWarehouseInventoryNum> inventoryNumList = this.getInventoryNum(drpPurchasePlan.getCanteenId(), d.getMaterialId(), menuMaterialUnitVO.getUnitId());
//                  if (CollUtil.isNotEmpty(inventoryNumList)) {
//                     drpPurPlanDetail.setInventoryNum((BigDecimal)inventoryNumList.stream().map(DrpWarehouseInventoryNum::getInventoryNum).reduce(BigDecimal.ZERO, BigDecimal::add));
//                  }
//
//                  BeanUtil.copyProperties(d, drpPurPlanDetail, new String[0]);
//                  drpPurPlanDetail.setDetailId(Id.next());
//                  drpPurPlanDetail.setPlanId(planId);
//                  drpPurPlanDetail.setUnitId(menuMaterialUnitVO.getUnitId());
//                  drpPurPlanDetail.setStallId(d.getStallId());
//                  if (menuMaterialUnitVO.getRate().compareTo(BigDecimal.ZERO) > 0) {
//                     BigDecimal purNumByg = d.getTotalConvertWeight().multiply(new BigDecimal(1000));
//                     drpPurPlanDetail.setPurNum(purNumByg.divide(menuMaterialUnitVO.getRate(), 3, RoundingMode.HALF_UP));
//                  } else {
//                     drpPurPlanDetail.setPurNum(BigDecimal.ZERO);
//                  }
//
//                  drpPurPlanDetail.setProPlanNum(drpPurPlanDetail.getPurNum());
//                  this.drpPurPlanDetailMapper.insert(drpPurPlanDetail);
//               });
//               content.forEach((id) -> {
//                  DrpProductionPurchaseOrder drpProductionPurchaseOrder = new DrpProductionPurchaseOrder();
//                  drpProductionPurchaseOrder.setProductionPlanId(id);
//                  drpProductionPurchaseOrder.setPlanId(planId);
//                  drpProductionPurchaseOrder.setOrderType(1);
//                  this.drpProductionPurchaseOrderMapper.insert(drpProductionPurchaseOrder);
//               });
//               return planId;
//            } else {
//               return null;
//            }
//         }
//      }
//   }

   public List<DrpDishesConvertVO> getMenuMaterialByPlanIdList(List<String> content) {
      if (CollUtil.isEmpty(content)) {
         throw new ServiceException("生产计划ID不能为空！");
      } else {
         List<DrpProductionDishesNumVO> drpProductionDishesNumVOList = Lists.newArrayList();
         content.forEach((d) -> {
            drpProductionDishesNumVOList.addAll(this.listProductionDishesSum(d));
         });
         Map<String, DrpProductionDishesNumVO> mergeMap = drpProductionDishesNumVOList.stream().collect(Collectors.toMap((d) -> {
            Long var10000 = d.getDishesId();
            return "" + var10000 + "_" + d.getSizeType();
         }, (d) -> {
            return d;
         }, (k1, k2) -> {
            k1.setDishesNum(k1.getDishesNum() + k2.getDishesNum());
            return k1;
         }));
         List<DrpDishesConvertDTO> drpDishesConvertDTOList = Lists.newArrayList();
         mergeMap.values().forEach((drpProductionDishesNumVO) -> {
            DrpDishesConvertDTO drpDishesConvertDTO = new DrpDishesConvertDTO();
            drpDishesConvertDTO.setDishesId(drpProductionDishesNumVO.getDishesId());
            drpDishesConvertDTO.setDishesNum(drpProductionDishesNumVO.getDishesNum());
            drpDishesConvertDTO.setSizeType((long)drpProductionDishesNumVO.getSizeType());
            drpDishesConvertDTOList.add(drpDishesConvertDTO);
         });
         return this.drpOtherService.dishesConvert(drpDishesConvertDTOList);
      }
   }

//   protected List<DrpWarehouseInventoryNum> getInventoryNum(Long canteenId, Long materialId, Long unitId) {
//      DrpWarehouse fc = (DrpWarehouse)this.drpWarehouseMapper.selectOne((Wrapper)((LambdaQueryWrapper)Wrappers.lambdaQuery(DrpWarehouse.class).eq(DrpWarehouse::getCanteenId, canteenId)).eq(DrpWarehouse::getDelFlag, DelFlagEnum.DEL_FALSE.key()));
//      if (fc == null) {
//         return Collections.emptyList();
//      } else {
//         DrpWarehouse zc = (DrpWarehouse)this.drpWarehouseMapper.selectOne(((LambdaQueryWrapper)((LambdaQueryWrapper)Wrappers.lambdaQuery(DrpWarehouse.class).eq(DrpWarehouse::getWarehouseId, fc.getParentId())).eq(DrpWarehouse::getDelFlag, DelFlagEnum.DEL_FALSE.key())).select(new SFunction[]{DrpWarehouse::getWarehouseId}));
//         List<Long> warehouseIds = Arrays.asList(fc.getWarehouseId(), zc != null ? zc.getWarehouseId() : null);
//         return this.drpWarehouseMapper.getInventoryNumByWarehouseIds(warehouseIds, materialId, unitId);
//      }
//   }

}
