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.common.utils.RedisUtil;
import com.bonus.canteen.core.menu.vo.MenuCategoryTreeVO;
import com.bonus.canteen.core.supply.purchase.api.AllocStallApi;
import com.bonus.canteen.core.supply.purchase.api.DrpAuthorityPurchaseApi;
import com.bonus.canteen.core.supply.purchase.api.MenuDishesApi;
import com.bonus.canteen.core.supply.purchase.constants.*;
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.DrpGoodsAllocationBusinessService;
import com.bonus.canteen.core.supply.purchase.service.DrpPurchasePurNoticeService;
import com.bonus.canteen.core.supply.purchase.service.DrpPurchasePlanService;
import com.bonus.canteen.core.supply.purchase.utils.CustomIdGenerateUtil;
import com.bonus.canteen.core.utils.TreeNodeUtil;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.common.houqin.constant.DelFlagEnum;
import com.bonus.common.houqin.constant.GlobalConstants;
import com.bonus.common.houqin.constant.LeConstants;
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 com.bonus.canteen.core.menu.domain.BaseTreeNode;
import org.redisson.api.RLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class DrpPurchasePlanServiceImpl extends ServiceImpl<DrpPurchasePlanMapper, DrpPurchasePlan> implements DrpPurchasePlanService {
   private static final Logger log = LoggerFactory.getLogger(DrpPurchasePlanServiceImpl.class);
   @Resource(
      name = "smartCanteenTaskExecutor"
   )
   @Lazy
   private AsyncTaskExecutor asyncTaskExecutor;
   @Autowired
   @Lazy
   private StringRedisTemplate stringRedisTemplate;
   @Autowired
   @Lazy
   private DrpPurPlanDetailMapper drpPurPlanDetailMapper;
   @Autowired
   @Lazy
   private DrpPurchasePurNoticeMapper drpPurchasePurNoticeMapper;
//   @Autowired
//   @Lazy
//   private DrpPurPlanDetailService drpPurPlanDetailService;
   @Autowired
   @Lazy
   private DrpInventoryMapper drpInventoryMapper;
   @Autowired
   @Lazy
   private DrpPurchasePurNoticeService drpPurchasePurNoticeService;
   @Autowired
   @Lazy
   private DrpIntoDetailMapper drpIntoDetailMapper;
   @Autowired
   @Lazy
   private DrpPurchaseOrderGoodsMapper drpPurchaseOrderGoodsMapper;
   @Autowired
   @Lazy
   private DrpOrderGoodsDetailMapper drpOrderGoodsDetailMapper;
   @Autowired
   @Lazy
   private DrpPurchaseInquiryMapper drpPurchaseInquiryMapper;
   @Autowired
   @Lazy
   private DrpPurchaseInquiryDetailMapper drpPurchaseInquiryDetailMapper;
   @Autowired
   @Lazy
   private DrpPurchaseInquirySupplierMapper drpPurchaseInquirySupplierMapper;
   @Autowired
   @Lazy
   private DrpPurchaseQuoteMapper drpPurchaseQuoteMapper;
   @Autowired
   @Lazy
   private DrpWarehouseMapper drpWarehouseMapper;
//   @Autowired
//   @Lazy
//   private MenuMaterialMapper menuMaterialMapper;
//   @Autowired
//   @Lazy
//   private DrpImportFailMaterialService drpImportFailMaterialService;
//   @Autowired
//   @Lazy
//   private DrpImportRecordMapper drpImportRecordMapper;
   @Autowired
   @Lazy
   private DrpPurchasePlanService drpPurchasePlanService;
//   @Autowired
//   @Lazy
//   private AllocCanteenApi allocCanteenApi;
   @Autowired
   @Lazy
   private DrpPurchaseSupplierMapper drpPurchaseSupplierMapper;
   @Autowired
   @Lazy
   private DrpAuthorityPurchaseApi drpAuthorityPurchaseApi;
//   @Autowired
//   @Lazy
//   private DrpOutInventoryService drpOutInventoryService;
   @Autowired
   @Lazy
   private AllocStallApi allocStallApi;
   @Autowired
   @Lazy
   private DrpProductionPurchaseOrderMapper drpProductionPurchaseOrderMapper;
//   @Autowired
//   @Lazy
//   private DrpGoodsAllocationMapper drpGoodsAllocationMapper;
//   @Autowired
//   @Lazy
//   private DrpGoodsAllocationDetailMapper drpGoodsAllocationDetailMapper;
//   @Autowired
//   @Lazy
//   private DrpGoodsAllocationService drpGoodsAllocationService;
//   @Autowired
//   @Lazy
//   private DrpWarehouseFetchUserMapper drpWarehouseFetchUserMapper;
   @Autowired
   @Lazy
   private DrpGoodsAllocationBusinessService drpGoodsAllocationBusinessService;
//   @Autowired
//   @Lazy
//   private MgrUserApi mgrUserApi;
   @Autowired
   @Lazy
   private DrpMarketPriceMapper drpMarketPriceMapper;
   @Autowired
   @Lazy
   private MenuDishesApi menuDishesApi;

   @Transactional(
      rollbackFor = {Exception.class}
   )
   public DrpPurchasePlanAddVO addSaveDrpPurchasePlan(DrpPurchasePlanSaveDTO content) {
      DrpPurchasePlan purchasePlan = new DrpPurchasePlan();
      BeanUtil.copyProperties(content, purchasePlan, new String[0]);
      String planId = content.getPlanId();
      purchasePlan.setStatus(DrpPurchasePlanStatusEnum.SAVE.key());
      if (CharSequenceUtil.isBlank(planId)) {
         planId = CustomIdGenerateUtil.generatePurchaseOrdId();
         purchasePlan.setPlanId(planId);
         this.baseMapper.insert(purchasePlan);
      } else {
         this.baseMapper.update(purchasePlan, Wrappers.lambdaQuery(DrpPurchasePlan.class).eq(DrpPurchasePlan::getPlanId, planId));
         this.drpPurPlanDetailMapper.delete(Wrappers.lambdaQuery(DrpPurPlanDetail.class).eq(DrpPurPlanDetail::getPlanId, planId));
      }

      List<DrpPurPlanDetailSaveDTO> detailList = content.getDetailList();
      Iterator var5 = detailList.iterator();

      while(var5.hasNext()) {
         DrpPurPlanDetailSaveDTO detail = (DrpPurPlanDetailSaveDTO)var5.next();
         DrpPurPlanDetail purPlanDetail = new DrpPurPlanDetail();
         BeanUtil.copyProperties(detail, purPlanDetail);
         purPlanDetail.setPlanId(planId);
         purPlanDetail.setDetailId(Id.next());
         this.drpPurPlanDetailMapper.insert(purPlanDetail);
      }

      DrpPurchasePlanAddVO result = new DrpPurchasePlanAddVO();
      result.setPlanId(planId);
      return result;
   }

   @Transactional(
      rollbackFor = {Exception.class}
   )
   public DrpPurchasePlanAddVO addCommitDrpPurchasePlan(DrpPurchasePlanSaveDTO content) {
      DrpPurchasePlan purchasePlan = new DrpPurchasePlan();
      BeanUtil.copyProperties(content, purchasePlan, new String[0]);
      String planId = content.getPlanId();
      purchasePlan.setStatus(DrpPurchasePlanStatusEnum.COMMIT.key());
      if (CharSequenceUtil.isBlank(planId)) {
         planId = CustomIdGenerateUtil.generatePurchaseOrdId();
         purchasePlan.setPlanId(planId);
         this.baseMapper.insert(purchasePlan);
      } else {
         this.baseMapper.update(purchasePlan, Wrappers.lambdaQuery(DrpPurchasePlan.class).eq(DrpPurchasePlan::getPlanId, planId));
         this.drpPurPlanDetailMapper.delete(Wrappers.lambdaQuery(DrpPurPlanDetail.class).eq(DrpPurPlanDetail::getPlanId, planId));
      }

      List<DrpPurPlanDetailSaveDTO> detailList = content.getDetailList();
      Iterator var5 = detailList.iterator();

      while(var5.hasNext()) {
         DrpPurPlanDetailSaveDTO detail = (DrpPurPlanDetailSaveDTO)var5.next();
         if (detail.getPurNum().compareTo(BigDecimal.ZERO) != 0) {
            DrpPurPlanDetail purPlanDetail = new DrpPurPlanDetail();
            BeanUtil.copyProperties(detail, purPlanDetail, new String[0]);
            purPlanDetail.setPlanId(planId);
            purPlanDetail.setDetailId(Id.next());
            purPlanDetail.setOriginalQuantity(purPlanDetail.getPurNum());
            this.drpPurPlanDetailMapper.insert(purPlanDetail);
         }
      }

      DrpPurchasePlanAddVO result = new DrpPurchasePlanAddVO();
      result.setPlanId(planId);
      this.approve(planId, content.getCanteenId());
      BigDecimal purTotal = (BigDecimal)detailList.stream().map(DrpPurPlanDetailSaveDTO::getPurNum).reduce(BigDecimal.ZERO, BigDecimal::add);
      if (purTotal.compareTo(BigDecimal.ZERO) <= 0) {
         this.baseMapper.update(null, ((Wrappers.lambdaUpdate(DrpPurchasePlan.class).set(DrpPurchasePlan::getApproveStatus, DrpApproveStatusEnum.REJECT_APPROVE.key())).set(DrpPurchasePlan::getApproveRemark, "货品已有库存，无需采购!")).eq(DrpPurchasePlan::getPlanId, planId));
      }

      return result;
   }

   protected void approve(String planId, Long canteenId) {
         this.autoPassProcess(planId);
         this.drpGoodsAllocationBusinessService.reduceInventory(planId);
   }

   @Transactional(
      rollbackFor = {Exception.class}
   )
   public void reduceInventory(String planId) {
      DrpPurchasePlanSaveDTO content = new DrpPurchasePlanSaveDTO();
      DrpPurchasePlanPageVO drpPurchasePlanPageVO = this.baseMapper.selectByPlanId(planId, DelFlagEnum.DEL_FALSE.key());
      BeanUtil.copyProperties(drpPurchasePlanPageVO, content);
      String var10000 = GlobalConstants.TENANT_ID.toString();
      String redisKey = "yst:drp:purOut" + var10000 + drpPurchasePlanPageVO.getCanteenId();
      RLock lock = RedisUtil.getLock(redisKey);

      try {
         List<DrpPurPlanDetailPageVO> detailPageVOList = this.drpPurPlanDetailMapper.selectListByPlanId(planId);
         content.setDetailList(detailPageVOList.stream().map((detailx) -> {
            DrpPurPlanDetailSaveDTO detailSaveDTO = new DrpPurPlanDetailSaveDTO();
            BeanUtil.copyProperties(detailx, detailSaveDTO);
            return detailSaveDTO;
         }).collect(Collectors.toList()));
//         AllocDrpModel allocDrpModel = this.drpMetadataService.queryMetadataByCanteenId(drpPurchasePlanPageVO.getCanteenId());
//         String ifPurPlanAddOutInventory = allocDrpModel.getIfPurPlanAddOutInventory();
//         if (ObjectUtil.equal(ifPurPlanAddOutInventory, "1")) {
//            List<DrpOutInventoryModel> outInventoryList = this.packageInventoryNum(content);
//            String ifPurPlanOutInventoryDate = allocDrpModel.getIfPurPlanOutInventoryDate();
//            LocalDateTime outDate = LocalDateTime.now();
//            if (CharSequenceUtil.isNotBlank(ifPurPlanOutInventoryDate)) {
//               outDate = LocalDateTime.now().plusDays((long)Integer.parseInt(ifPurPlanOutInventoryDate));
//            }
//
//            this.outWarehouse(outInventoryList, planId, content.getDetailList(), outDate);
//         }

//         String ifPurPlanAddUnitRounding = allocDrpModel.getIfPurPlanAddUnitRounding();
         Iterator var17 = content.getDetailList().iterator();

         while(true) {
            if (!var17.hasNext()) {
               BigDecimal purTotal = content.getDetailList().stream().map(DrpPurPlanDetailSaveDTO::getPurNum).reduce(BigDecimal.ZERO, BigDecimal::add);
               if (purTotal.compareTo(BigDecimal.ZERO) <= 0) {
                  this.baseMapper.update(null, ((Wrappers.lambdaUpdate(DrpPurchasePlan.class).set(DrpPurchasePlan::getApproveStatus, DrpApproveStatusEnum.REJECT_APPROVE.key())).set(DrpPurchasePlan::getApproveRemark, "货品已有库存，无需采购!")).eq(DrpPurchasePlan::getPlanId, planId));
               }
               break;
            }

            DrpPurPlanDetailSaveDTO detail = (DrpPurPlanDetailSaveDTO)var17.next();
            if (detail.getPurNum().compareTo(BigDecimal.ZERO) == 0) {
               this.drpPurPlanDetailMapper.delete((Wrappers.lambdaQuery(DrpPurPlanDetail.class).eq(DrpPurPlanDetail::getPlanId, planId)).eq(DrpPurPlanDetail::getDetailId, detail.getDetailId()));
            } else {
               DrpPurPlanDetail purPlanDetail = this.drpPurPlanDetailMapper.selectOne((Wrappers.lambdaQuery(DrpPurPlanDetail.class).eq(DrpPurPlanDetail::getPlanId, planId)).eq(DrpPurPlanDetail::getDetailId, detail.getDetailId()));
               purPlanDetail.setOriginalQuantity(detail.getPurNum());
//               if (ObjectUtil.equal(ifPurPlanAddUnitRounding, "1")) {
//                  purPlanDetail.setPurNum(detail.getPurNum().setScale(0, RoundingMode.CEILING));
//               } else {
                  purPlanDetail.setPurNum(detail.getPurNum());
//               }

               if (purPlanDetail.getPurNum() != null && purPlanDetail.getUnitPrice() != null) {
                  purPlanDetail.setPurchasingBudgetPrice(purPlanDetail.getPurNum().multiply(new BigDecimal(purPlanDetail.getUnitPrice())).longValue());
               }

               this.drpPurPlanDetailMapper.update(null, ((((Wrappers.lambdaUpdate(DrpPurPlanDetail.class).eq(DrpPurPlanDetail::getPlanId, planId)).eq(DrpPurPlanDetail::getDetailId, detail.getDetailId())).set(DrpPurPlanDetail::getPurNum, purPlanDetail.getPurNum())).set(DrpPurPlanDetail::getPurchasingBudgetPrice, purPlanDetail.getPurchasingBudgetPrice())).set(DrpPurPlanDetail::getOriginalQuantity, purPlanDetail.getOriginalQuantity()));
            }
         }
      } finally {
         if (lock.isHeldByCurrentThread() && lock.isLocked()) {
            lock.unlock();
         }

      }

   }

   protected void autoPassProcess(String planId) {
      (this.baseMapper).update(null, (Wrappers.lambdaUpdate(DrpPurchasePlan.class).set(DrpPurchasePlan::getApproveStatus, DrpApproveStatusEnum.AGREE_APPROVE.key())).eq(DrpPurchasePlan::getPlanId, planId));
   }

   public List<DrpPurchasePlanPageVO> getDrpPurchasePlanPage(DrpPurchasePlanPageDTO 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 4:
               content.setOrderStatus(DrpCommitStatusEnum.COMMIT.key());
               content.setCreateBy(SecurityUtils.getUsername());
               break;
            default:
               throw new ServiceException("不支持的类型传参 type: " + content.getType());
         }
      }

      List<DrpPurchasePlanPageVO> drpPurchasePlanPageVOPage = this.baseMapper.selectAllList(content, DelFlagEnum.DEL_FALSE.key());
      if (CollUtil.isEmpty(drpPurchasePlanPageVOPage)) {
         return drpPurchasePlanPageVOPage;
      } else {
         List<DrpProductionPurchaseOrder> drpProductionPurchaseOrders = this.drpProductionPurchaseOrderMapper.selectList(((Wrappers.lambdaQuery(DrpProductionPurchaseOrder.class).in(DrpProductionPurchaseOrder::getPlanId, drpPurchasePlanPageVOPage.stream().map(DrpPurchasePlanPageVO::getPlanId).collect(Collectors.toList()))).eq(DrpProductionPurchaseOrder::getOrderType, 2)).select(DrpProductionPurchaseOrder::getPlanId));
         Map<String, List<DrpProductionPurchaseOrder>> collect = drpProductionPurchaseOrders.stream().collect(Collectors.groupingBy(DrpProductionPurchaseOrder::getPlanId));
         drpPurchasePlanPageVOPage.forEach((d) -> {
            if (CharSequenceUtil.isNotEmpty(d.getStallId())) {
               String[] split = d.getStallId().split(",");
               d.setStallName(this.allocStallApi.getStallNameByIdSet(Arrays.stream(split).map(Long::valueOf).collect(Collectors.toSet())));
            }

            d.setCurCreateOrder(CollUtil.isNotEmpty(collect.get(d.getPlanId())));
         });
         return drpPurchasePlanPageVOPage;
      }
   }

   @Transactional(
      rollbackFor = {Exception.class}
   )
   public void removeByPlanId(String planId) {
      if (CharSequenceUtil.isBlank(planId)) {
         throw new ServiceException("采购计划单号为空");
      } else {
         DrpPurchasePlan purchasePlan = this.baseMapper.selectOne(((Wrappers.lambdaQuery(DrpPurchasePlan.class).eq(DrpPurchasePlan::getPlanId, planId)).eq(DrpPurchasePlan::getDelFlag, DelFlagEnum.DEL_FALSE.key())).eq(DrpPurchasePlan::getStatus, DrpPurchasePlanStatusEnum.SAVE.key()));
         if (ObjectUtil.isEmpty(purchasePlan)) {
            log.info("***[库存中心_采购计划]_删除采购计划_未查询到需要删除的采购计划************");
            throw new ServiceException("删除的数据不存在");
         } else {
            ((DrpPurchasePlanMapper)this.baseMapper).update(null, (Wrappers.lambdaUpdate(DrpPurchasePlan.class).eq(DrpPurchasePlan::getPlanId, planId)).set(DrpPurchasePlan::getDelFlag, DelFlagEnum.DEL_TRUE.key()));
            this.drpProductionPurchaseOrderMapper.delete((Wrappers.lambdaQuery(DrpProductionPurchaseOrder.class).eq(DrpProductionPurchaseOrder::getPlanId, planId)).eq(DrpProductionPurchaseOrder::getOrderType, 1));
         }
      }
   }

//   public List<String> sendEmail(DrpPurSendEmailDTO content) {
//      Long checkCount = this.drpPurNoticeMapper.selectCount((Wrapper)Wrappers.lambdaQuery(DrpPurNotice.class).eq(DrpPurNotice::getPlanId, content.getPlanId()));
//      if (checkCount > 0L) {
//         return LeResponse.fail(I18n.getMessage("drp.pur-have-notice", new Object[0]));
//      } else {
//         List<List<DrpPurDetailSupplierVO>> detailSupplierList = this.drpPurPlanDetailService.listPurDetailGroupBySupplier(content.getPlanId());
//         if (CollUtil.isEmpty(detailSupplierList)) {
//            return LeResponse.fail(I18n.getMessage("drp.pur-no-detail", new Object[0]));
//         } else {
//            String tempUsername = "";
//            PigxUser user = SecurityUtils.getUser();
//            if (ObjectUtil.isNotEmpty(user)) {
//               tempUsername = user.getUsername();
//            }
//
//            this.asyncTaskExecutor.execute(() -> {
//               this.drpPurNoticeService.sendAllEmail(detailSupplierList, content, tempUsername);
//            });
//            return LeResponse.succ(RetCodeEnum.SUCC.getKey(), "邮件开始发送，请稍后在通知记录中查看发送结果!");
//         }
//      }
//   }

   public List<DrpPurMaterialPageVO> pageMaterial(DrpPurMaterialPageDTO content) {
      String materialName = content.getMaterialName();
      List<Long> categoryIdList = content.getCategoryIdList();
      List records;
      if (CollUtil.isNotEmpty(categoryIdList)) {
         records = this.drpInventoryMapper.selectCategoryTree(DelFlagEnum.DEL_FALSE.key());
         List<MenuCategoryTreeVO> childList = TreeNodeUtil.getChildList(records, categoryIdList);
         if (CollUtil.isNotEmpty(childList)) {
            assert childList != null;

            categoryIdList = childList.stream().map(BaseTreeNode::getId).collect(Collectors.toList());
         }
      }

      List<DrpPurMaterialPageVO> recordsNew = this.baseMapper.pageMaterialInfo(content, materialName.toUpperCase(), materialName.toLowerCase(), DelFlagEnum.DEL_FALSE.key(), categoryIdList, content.getWarehouseId());
      Iterator var9 = recordsNew.iterator();

      while(var9.hasNext()) {
         DrpPurMaterialPageVO item = (DrpPurMaterialPageVO)var9.next();
         MaterialIntoDetailModel materialIntoDetailModel = this.drpIntoDetailMapper.selectLastIntoDetail(item.getMaterialId(), content.getWarehouseId(), DrpIntoInventoryStatusEnum.COMMIT.key());
         if (!ObjectUtil.isEmpty(materialIntoDetailModel)) {
            if (Objects.equals(MaterialTypeEnum.MATERIAL.key(), item.getMaterialType())) {
               item.setUnitId(materialIntoDetailModel.getUnitId());
               item.setUnitName(materialIntoDetailModel.getUnitName());
            }

            item.setSupplierId(materialIntoDetailModel.getSupplierId()).setSupplierName(materialIntoDetailModel.getSupplierName()).setPurPrice(materialIntoDetailModel.getUnitPrice()).setPurNum(materialIntoDetailModel.getPurNum());
         }
      }

      return recordsNew;
   }

   public List<DrpPurMaterialInfoPageVO> pageMaterialInfo(DrpPurMaterialInfoPageDTO content) {
      log.info("[电子秤-货品检索]进入接口:{}", LocalDateTime.now());
      String materialName = ObjectUtil.isNull(content.getMaterialName()) ? "" : content.getMaterialName();
      content.setMaterialName(materialName);
      DrpWarehouse drpWarehouse;
      if (content.getCanteenId() != null && content.getWarehouseId() == null) {
         drpWarehouse = this.drpWarehouseMapper.selectOne(Wrappers.lambdaQuery(DrpWarehouse.class).eq(DrpWarehouse::getCanteenId, content.getCanteenId()));
         content.setWarehouseId(drpWarehouse != null ? drpWarehouse.getWarehouseId() : null);
      }

      if (CharSequenceUtil.isNotEmpty(content.getMaterialCode())) {
         content.setMaterialCode(LeBeanUtil.fieldLikeHandle(content.getMaterialCode()));
      }

      if (CharSequenceUtil.isNotBlank(content.getBarCode())) {
         content.setBarCode(LeBeanUtil.fieldLikeHandle(content.getBarCode()));
      }

      if (ObjectUtil.isNotEmpty(content.getWarehouseId())) {
         drpWarehouse = this.drpWarehouseMapper.selectOne(Wrappers.lambdaQuery(DrpWarehouse.class).eq(DrpWarehouse::getWarehouseId, content.getWarehouseId()));
         if (ObjectUtil.isNotEmpty(drpWarehouse)) {
            content.setWarehouseType(drpWarehouse.getWarehouseType());
         }
      }

      List resultList;
      if (Objects.equals(content.getInterfaceType(), DrpInterfaceType.DEVICE)) {
         resultList = this.menuDishesApi.listAllCategoryIdById(content.getCategoryIdList());
         content.setCategoryIdList(resultList);
      }

      List<DrpPurMaterialInfoPageVO> resultListNew = this.baseMapper.pagePurMaterialInfo(content, materialName.toUpperCase(), materialName.toLowerCase(), DelFlagEnum.DEL_FALSE.key(), DrpUseStatusEnum.ENABLE.key());
      resultListNew.forEach((s) -> {
         s.setIfCollect(LeConstants.COMMON_NO);
//         Long picNum = this.menuMaterialRegisterPicMapper.selectCount(Wrappers.lambdaQuery(MenuMaterialRegisterPic.class).eq(MenuMaterialRegisterPic::getMaterialId, s.getMaterialId()));
//         if (picNum > 0L) {
//            s.setIfCollect(LeConstants.COMMON_YES);
//         }

         s.setIfRegister(LeConstants.COMMON_NO);
//         MenuMaterialRegister menuMaterialRegister = this.menuMaterialRegisterMapper.selectOne(Wrappers.lambdaQuery(MenuMaterialRegister.class).eq(MenuMaterialRegister::getMaterialId, s.getMaterialId()).select(MenuMaterialRegister::getMaterialId, MenuMaterialRegister::getIfSuccess));
//         if (ObjectUtil.isNotEmpty(menuMaterialRegister) && ObjectUtil.equal(menuMaterialRegister.getIfSuccess(), LeConstants.COMMON_YES)) {
//            s.setIfRegister(LeConstants.COMMON_YES);
//         }

      });
      return resultListNew;
   }

   @Transactional(
      rollbackFor = {Exception.class}
   )
   public String generateOrderGoods(DrpPurGenerateOrderGoodsDTO content) {
      DrpOrderGoods drpOrderGoods = new DrpOrderGoods();
      String orderGoodsId = CustomIdGenerateUtil.generateOrderGoodsId();
      drpOrderGoods.setOrderGoodsId(orderGoodsId);
      drpOrderGoods.setOrderStatus(DrpOrderGoodsStatusEnum.WAIT_COMMIT.getKey());
      this.drpPurchaseOrderGoodsMapper.insert(drpOrderGoods);
      Iterator var4 = content.getDetailList().iterator();

      while(var4.hasNext()) {
         DrpPurGenerateOrderGoodsDetailDTO drpPurGenerateOrderGoodsDetailDTO = (DrpPurGenerateOrderGoodsDetailDTO)var4.next();
         DrpOrderGoodsDetail drpOrderGoodsDetail = new DrpOrderGoodsDetail();
         BeanUtil.copyProperties(drpPurGenerateOrderGoodsDetailDTO, drpOrderGoodsDetail, new String[0]);
         drpOrderGoodsDetail.setOrderGoodsDetailId(Id.next());
         drpOrderGoodsDetail.setOrderGoodsId(orderGoodsId);
         drpOrderGoodsDetail.setOrderNum(drpPurGenerateOrderGoodsDetailDTO.getPurNum());
         this.drpOrderGoodsDetailMapper.insert(drpOrderGoodsDetail);
      }

      return orderGoodsId;
   }

   @Transactional(
      rollbackFor = {Exception.class}
   )
   public String generateInquiry(DrpPurGenerateInquiryDTO content) {
      DrpInquiry drpInquiry = new DrpInquiry();
      String inquiryId = CustomIdGenerateUtil.generateInquiryId();
      drpInquiry.setInquiryId(inquiryId);
      drpInquiry.setStatus(DrpInquiryStatusEnum.NO_COMMIT.key());
      this.drpPurchaseInquiryMapper.insert(drpInquiry);
      Iterator var4 = content.getDetailList().iterator();

      while(var4.hasNext()) {
         DrpPurGenerateInquiryDetailDTO drpPurGenerateInquiryDetailDTO = (DrpPurGenerateInquiryDetailDTO)var4.next();
         DrpInquiryDetail drpInquiryDetail = new DrpInquiryDetail();
         BeanUtil.copyProperties(drpPurGenerateInquiryDetailDTO, drpInquiryDetail);
         drpInquiryDetail.setInquiryDetailId(Id.next());
         drpInquiryDetail.setInquiryId(inquiryId);
         this.drpPurchaseInquiryDetailMapper.insert(drpInquiryDetail);
      }

      return inquiryId;
   }

//   public void applyApproval(String planId) {
//      if (CharSequenceUtil.isBlank(planId)) {
//         throw new LeException(I18n.getMessage("drp.pur-plan-id-is-null", new Object[0]));
//      } else {
//         DrpPurchasePlanPageDTO content = new DrpPurchasePlanPageDTO();
//         content.setPlanId(planId);
//         content.setOrderStatus(DrpPurchasePlanStatusEnum.COMMIT.key());
//         Page<DrpPurchasePlanPageVO> resultPage = new Page(0L, -1L);
//         MgrUserAuthPO authPO = this.drpAuthorityApi.getUserAuthPO();
//         resultPage = ((DrpPurchasePlanMapper)this.baseMapper).selectAllList(resultPage, content, DelFlagEnum.DEL_FALSE.key(), authPO);
//         List<DrpPurchasePlanPageVO> records = resultPage.getRecords();
//         if (CollUtil.isEmpty(records)) {
//            throw new LeException(I18n.getMessage("drp.pur-plan-not-exit", new Object[0]));
//         } else {
//            DrpPurchasePlanPageVO drpPurchasePlanPageVO = (DrpPurchasePlanPageVO)records.get(0);
//            List<DrpPurPlanDetailPageVO> detailList = this.drpPurPlanDetailMapper.selectListByPlanId(planId);
//            drpPurchasePlanPageVO.setDetailList(detailList);
//            if (!ObjectUtil.equal(drpPurchasePlanPageVO.getApproveStatus(), DrpApproveStatusEnum.WAIT_APPROVE.key()) && !ObjectUtil.equal(drpPurchasePlanPageVO.getApproveStatus(), DrpApproveStatusEnum.REJECT_APPROVE.key())) {
//               throw new LeException(I18n.getMessage("drp.check-inventory-can-not-create-process", new Object[0]));
//            } else {
//               Long userId = (Long)SecureManager.getSubjectId().get();
//               Long definitionId = this.flowApi.getByMappingIdAndDefinitionType(userId, FlowDefinitionEum.DRP_PUR_PLAN);
//               if (ObjectUtil.isNull(definitionId)) {
//                  ((DrpPurchasePlanMapper)this.baseMapper).update((Object)null, (Wrapper)((LambdaUpdateWrapper)Wrappers.lambdaUpdate(DrpPurchasePlan.class).eq(DrpPurchasePlan::getPlanId, planId)).set(DrpPurchasePlan::getApproveStatus, DrpApproveStatusEnum.AGREE_APPROVE.key()));
//               } else {
//                  CreatInstanceDto creatInstanceDto = new CreatInstanceDto();
//                  creatInstanceDto.setDefinitionId(definitionId);
//                  DrpPurchasePlanPageVO detail = this.detail(planId);
//                  detail.setDetailList((List)null);
//                  creatInstanceDto.setContext(FlowBeanUtil.parseObj2Map(detail));
//                  Long instanceId = this.flowApi.creat(creatInstanceDto);
//                  ((DrpPurchasePlanMapper)this.baseMapper).update((Object)null, (Wrapper)((LambdaUpdateWrapper)((LambdaUpdateWrapper)Wrappers.lambdaUpdate(DrpPurchasePlan.class).eq(DrpPurchasePlan::getPlanId, planId)).set(DrpPurchasePlan::getApproveStatus, DrpApproveStatusEnum.IN_APPROVE.key())).set(DrpPurchasePlan::getProcessInstanceId, instanceId));
//               }
//
//            }
//         }
//      }
//   }

   public List<MaterialInventoryVO> listPurDetailInventory(MaterialInventoryDTO content) {
      List<Long> materialIdList = content.getDetailList().stream().map(MaterialInventoryDetailDTO::getMaterialId).collect(Collectors.toList());
      return this.drpInventoryMapper.selectInventoryByMaterialIdList(materialIdList, content.getWarehouseId());
   }

   public List<DrpPurPlanDetailListVO> listPurDetail(String planId) {
      return this.drpPurPlanDetailMapper.listDetailById(planId);
   }

   @Transactional(
      rollbackFor = {Exception.class}
   )
   public void purGenerateOrder(List<DrpPurGenerateOrderDTO> content) {
      if (CollUtil.isEmpty(content)) {
         throw new ServiceException("拆解明细不能为空");
      } else {
         Iterator var2 = content.iterator();

         while(var2.hasNext()) {
            DrpPurGenerateOrderDTO drpPurGenerateOrderDTO = (DrpPurGenerateOrderDTO)var2.next();
            DrpOrderGoods drpOrderGoods = new DrpOrderGoods();
            String orderGoodsId = CustomIdGenerateUtil.generateOrderGoodsId();
            drpOrderGoods.setOrderGoodsId(orderGoodsId);
            drpOrderGoods.setSupplierId(drpPurGenerateOrderDTO.getSupplierId());
            drpOrderGoods.setOrderStatus(DrpOrderGoodsStatusEnum.WAIT_COMMIT.getKey());
            this.drpPurchaseOrderGoodsMapper.insert(drpOrderGoods);
            Iterator var6 = drpPurGenerateOrderDTO.getMaterialList().iterator();

            while(var6.hasNext()) {
               DrpPurGenerateOrderMaterialDTO drpPurGenerateOrderMaterialDTO = (DrpPurGenerateOrderMaterialDTO)var6.next();
               DrpOrderGoodsDetail drpOrderGoodsDetail = new DrpOrderGoodsDetail();
               BeanUtil.copyProperties(drpPurGenerateOrderMaterialDTO, drpOrderGoodsDetail);
               drpOrderGoodsDetail.setOrderGoodsDetailId(Id.next());
               drpOrderGoodsDetail.setOrderGoodsId(orderGoodsId);
               this.drpOrderGoodsDetailMapper.insert(drpOrderGoodsDetail);
            }
         }

      }
   }

   @Transactional(
      rollbackFor = {Exception.class}
   )
   public void purGenerateInquiry(List<DrpPurDismantleGenerateInquiryDTO> content) {
      if (CollUtil.isEmpty(content)) {
         throw new ServiceException("拆解明细不能为空");
      } else {
         Iterator var2 = content.iterator();

         while(var2.hasNext()) {
            DrpPurDismantleGenerateInquiryDTO drpPurDismantleGenerateInquiryDTO = (DrpPurDismantleGenerateInquiryDTO)var2.next();
            String inquiryId = CustomIdGenerateUtil.generateInquiryId();
            this.packageInquiry(inquiryId, LocalDateTime.now());
            Iterator var5 = drpPurDismantleGenerateInquiryDTO.getMaterialList().iterator();

            while(var5.hasNext()) {
               DrpPurDismantleGenerateInquiryMaterialDTO drpPurDismantleGenerateInquiryMaterialDTO = (DrpPurDismantleGenerateInquiryMaterialDTO)var5.next();
               DrpInquiryDetail drpInquiryDetail = new DrpInquiryDetail();
               BeanUtil.copyProperties(drpPurDismantleGenerateInquiryMaterialDTO, drpInquiryDetail, new String[0]);
               drpInquiryDetail.setInquiryDetailId(Id.next());
               drpInquiryDetail.setInquiryId(inquiryId);
               drpInquiryDetail.setPurNum(drpPurDismantleGenerateInquiryMaterialDTO.getOrderNum());
               this.drpPurchaseInquiryDetailMapper.insert(drpInquiryDetail);
            }
         }

      }
   }

//   public void purPlanApproveAgree(PurPlanApproveDTO content) {
//      ArrayList<Long> instanceIds = Lists.newArrayList(new Long[]{content.getInstanceId()});
//      NextInstanceDto nextInstanceDto = new NextInstanceDto();
//      nextInstanceDto.setInstanceIds(instanceIds);
//      nextInstanceDto.setRemark(content.getRemark());
//      this.flowApi.next(nextInstanceDto);
//   }

//   public void purPlanApproveReject(PurPlanApproveDTO content) {
//      ArrayList<Long> instanceIds = Lists.newArrayList(new Long[]{content.getInstanceId()});
//      NextInstanceDto nextInstanceDto = new NextInstanceDto();
//      nextInstanceDto.setInstanceIds(instanceIds);
//      nextInstanceDto.setRemark(content.getRemark());
//      this.flowApi.reject(nextInstanceDto);
//   }

//   @Transactional(
//      rollbackFor = {Exception.class}
//   )
//   public DrpPurchasePlanAddVO morePurPlanMergeOne(DrpMorePurPlanMergeOneDTO content) {
//      Long checkStatus = ((DrpPurchasePlanMapper)this.baseMapper).selectCount((Wrapper)((LambdaQueryWrapper)Wrappers.lambdaQuery(DrpPurchasePlan.class).in(DrpPurchasePlan::getPlanId, content.getPlanIdList())).eq(DrpPurchasePlan::getStatus, DrpPurchasePlanStatusEnum.SAVE.key()));
//      if (checkStatus > 0L) {
//         throw new LeException("存在未提交采购计划，无法合并!");
//      } else {
//         Long checkMerge = ((DrpPurchasePlanMapper)this.baseMapper).selectCount((Wrapper)((LambdaQueryWrapper)Wrappers.lambdaQuery(DrpPurchasePlan.class).in(DrpPurchasePlan::getPlanId, content.getPlanIdList())).eq(DrpPurchasePlan::getIfMerge, LeConstants.COMMON_YES));
//         if (checkMerge > 0L) {
//            throw new LeException("存在已合并采购计划，无法再次合并!");
//         } else {
//            DrpPurchasePlan drpPurchasePlan = new DrpPurchasePlan();
//            BeanUtil.copyProperties(content, drpPurchasePlan, new String[0]);
//            String mainPanId = "M_" + CustomIdGenerateUtil.generatePurchaseOrdId();
//            drpPurchasePlan.setPlanId(mainPanId);
//            drpPurchasePlan.setStatus(content.getCommitType());
//            String relatePlanIds = CollUtil.join(content.getPlanIdList(), ",");
//            drpPurchasePlan.setRelatePlanIds(relatePlanIds);
//            drpPurchasePlan.setIfMerge(LeConstants.COMMON_YES);
//            ((DrpPurchasePlanMapper)this.baseMapper).insert(drpPurchasePlan);
//            ((DrpPurchasePlanMapper)this.baseMapper).update((Object)null, (Wrapper)((LambdaUpdateWrapper)Wrappers.lambdaUpdate(DrpPurchasePlan.class).in(DrpPurchasePlan::getPlanId, content.getPlanIdList())).set(DrpPurchasePlan::getIfMerge, LeConstants.COMMON_YES));
//            List<PurPlanDetailModel> purPlanDetailModelList = this.drpPurPlanDetailMapper.listDetailByIdList(content.getPlanIdList());
//            Map<String, DrpPurPlanDetail> map = new HashMap();
//            Iterator var9 = purPlanDetailModelList.iterator();
//
//            DrpPurPlanDetail drpPurPlanDetail;
//            while(var9.hasNext()) {
//               PurPlanDetailModel purPlanDetailModel = (PurPlanDetailModel)var9.next();
//               Long var10000 = purPlanDetailModel.getMaterialId();
//               String key = "" + var10000 + "_" + purPlanDetailModel.getUnitId() + "_" + purPlanDetailModel.getStallId();
//               drpPurPlanDetail = (DrpPurPlanDetail)map.get(key);
//               if (ObjectUtil.isEmpty(drpPurPlanDetail)) {
//                  drpPurPlanDetail = new DrpPurPlanDetail();
//                  BeanUtil.copyProperties(purPlanDetailModel, drpPurPlanDetail, new String[0]);
//                  drpPurPlanDetail.setDetailId(Id.next());
//                  drpPurPlanDetail.setPlanId(mainPanId);
//                  map.put(key, drpPurPlanDetail);
//               } else {
//                  drpPurPlanDetail.setPurNum(drpPurPlanDetail.getPurNum().add(purPlanDetailModel.getPurNum()));
//                  if (ObjectUtil.isNotEmpty(purPlanDetailModel.getProPlanNum()) && ObjectUtil.isNotEmpty(drpPurPlanDetail.getProPlanNum())) {
//                     drpPurPlanDetail.setProPlanNum(drpPurPlanDetail.getProPlanNum().add(purPlanDetailModel.getProPlanNum()));
//                  }
//
//                  drpPurPlanDetail.setUnitPrice((Long)Optional.ofNullable(purPlanDetailModel.getUnitPrice()).orElse(0L));
//                  drpPurPlanDetail.setInventoryNum(((BigDecimal)Optional.ofNullable(drpPurPlanDetail.getInventoryNum()).orElse(BigDecimal.ZERO)).add((BigDecimal)Optional.ofNullable(purPlanDetailModel.getInventoryNum()).orElse(BigDecimal.ZERO)));
//                  drpPurPlanDetail.setOriginalQuantity(((BigDecimal)Optional.ofNullable(drpPurPlanDetail.getOriginalQuantity()).orElse(BigDecimal.ZERO)).add((BigDecimal)Optional.ofNullable(purPlanDetailModel.getOriginalQuantity()).orElse(BigDecimal.ZERO)));
//                  drpPurPlanDetail.setPurchasingBudgetPrice((new BigDecimal(purPlanDetailModel.getUnitPrice())).multiply(drpPurPlanDetail.getPurNum()).longValue());
//                  map.put(key, drpPurPlanDetail);
//               }
//            }
//
//            List<DrpPurPlanDetail> purPlanDetailList = new ArrayList();
//            Iterator var14 = map.entrySet().iterator();
//
//            while(var14.hasNext()) {
//               Map.Entry<String, DrpPurPlanDetail> entry = (Map.Entry)var14.next();
//               drpPurPlanDetail = (DrpPurPlanDetail)entry.getValue();
//               purPlanDetailList.add(drpPurPlanDetail);
//            }
//
//            this.drpPurPlanDetailService.saveBatch(purPlanDetailList);
//            if (content.getCommitType() == 2) {
//               this.applyApproval(mainPanId);
//            }
//
//            DrpPurchasePlanAddVO drpPurchasePlanAddVO = new DrpPurchasePlanAddVO();
//            drpPurchasePlanAddVO.setPlanId(mainPanId);
//            return drpPurchasePlanAddVO;
//         }
//      }
//   }

   @Transactional(
      rollbackFor = {Exception.class}
   )
   public void purGenerateInquiryByGoods(DrpPurDismantleGenerateInquiryDTO dto) {
      DrpPurchasePlan purchasePlan = this.baseMapper.selectOne(((Wrappers.lambdaQuery(DrpPurchasePlan.class).eq(DrpPurchasePlan::getPlanId, dto.getPlanId())).eq(DrpPurchasePlan::getDelFlag, DelFlagEnum.DEL_FALSE.key())).eq(DrpPurchasePlan::getStatus, DrpPurchasePlanStatusEnum.COMMIT.key()));
      List<DrpPurDismantleGenerateInquiryMaterialDTO> materialList = dto.getMaterialList();
      Map<List<Long>, List<DrpPurDismantleGenerateInquiryMaterialDTO>> supplierIdsByMaterialId = materialList.stream().collect(Collectors.groupingBy(DrpPurDismantleGenerateInquiryMaterialDTO::getSupplierIds));
      if (CollUtil.isNotEmpty(supplierIdsByMaterialId)) {
         supplierIdsByMaterialId.forEach((key, value) -> {
            String inquiryId = CustomIdGenerateUtil.generateInquiryId();
            this.packageInquiry(inquiryId, purchasePlan.getPurDate());
            List<DrpInquiryDetail> inquiryDetails = new ArrayList();
            Iterator var6 = value.iterator();

            while(var6.hasNext()) {
               DrpPurDismantleGenerateInquiryMaterialDTO drpPurDismantleGenerateInquiryMaterialDTO = (DrpPurDismantleGenerateInquiryMaterialDTO)var6.next();
               DrpInquiryDetail drpInquiryDetail = new DrpInquiryDetail();
               BeanUtil.copyProperties(drpPurDismantleGenerateInquiryMaterialDTO, drpInquiryDetail);
               drpInquiryDetail.setInquiryDetailId(Id.next());
               drpInquiryDetail.setInquiryId(inquiryId);
               drpInquiryDetail.setPurNum(drpPurDismantleGenerateInquiryMaterialDTO.getOrderNum());
               this.drpPurchaseInquiryDetailMapper.insert(drpInquiryDetail);
               inquiryDetails.add(drpInquiryDetail);
            }

            this.saveInquiryAndSendMsgToSupplier(key, inquiryId, inquiryDetails);
         });
      }

   }

   public AmountBaseByPageHelperVO<DrpProductionPlanMaterialCountVO> materialCount(DrpPurchasePlanPageDTO content) {
      List<DrpProductionPlanMaterialCountVO> list = this.baseMapper.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 DrpPurchasePlanPageVO detail(String content) {
      DrpPurchasePlanPageVO drpPurchasePlanPageVO = this.baseMapper.selectByPlanId(content, DelFlagEnum.DEL_FALSE.key());
      drpPurchasePlanPageVO.setStallName(this.allocStallApi.getStallNameByIdSet(Arrays.stream(drpPurchasePlanPageVO.getStallId().split(",")).map(Long::valueOf).collect(Collectors.toSet())));
      List<DrpPurPlanDetailPageVO> detailList = this.drpPurPlanDetailMapper.selectListByPlanId(content);
      detailList.forEach((d) -> {
         List<DrpWarehouseInventoryNum> inventoryNumList = this.getInventoryNum(drpPurchasePlanPageVO.getCanteenId(), d.getMaterialId(), d.getUnitId());
         d.setInventoryNumList(inventoryNumList);
      });
      drpPurchasePlanPageVO.setDetailList(detailList);
      return drpPurchasePlanPageVO;
   }

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

//   public DrpPurchasePlanMergeVO mergeDetail(List<String> content) {
//      List<DrpPurchasePlanPageVO> mergeList = new ArrayList();
//      if (CollUtil.isNotEmpty(content)) {
//         content.forEach((d) -> {
//            DrpPurchasePlanPageVO drpPurchasePlanPageVO = ((DrpPurchasePlanMapper)this.baseMapper).selectByPlanId(d, DelFlagEnum.DEL_FALSE.key());
//            String[] split = drpPurchasePlanPageVO.getStallId().split(",");
//            drpPurchasePlanPageVO.setStallName(this.allocStallApi.getStallNameByIdSet((Set)Arrays.stream(split).map(Long::valueOf).collect(Collectors.toSet())));
//            List<DrpPurPlanDetailPageVO> detailList = this.drpPurPlanDetailMapper.selectListByPlanId(d);
//            detailList.forEach((drpPurPlanDetailPageVO) -> {
//               drpPurPlanDetailPageVO.setCrtime(drpPurchasePlanPageVO.getCrtime());
//            });
//            drpPurchasePlanPageVO.setDetailList(detailList);
//            mergeList.add(drpPurchasePlanPageVO);
//         });
//      }
//
//      Map<Long, List<DrpPurchasePlanPageVO>> canteenMap = (Map)mergeList.stream().collect(Collectors.groupingBy(DrpPurchasePlanPageVO::getCanteenId));
//      if (canteenMap.size() > 1) {
//         throw new LeException(I18n.getMessage("不同食堂采购计划无法合并!", new Object[0]));
//      } else {
//         List<Map<String, DrpPurPlanDetailPageVO>> detailList = new ArrayList();
//         mergeList.forEach((d) -> {
//            Map<String, DrpPurPlanDetailPageVO> detailPageVOMap = (Map)d.getDetailList().stream().collect(Collectors.toMap((detailPageVO) -> {
//               Long var10000 = detailPageVO.getMaterialId();
//               return "" + var10000 + "-" + detailPageVO.getStallId();
//            }, (e) -> {
//               return e;
//            }, (key1, key2) -> {
//               key1.setPurNum(key1.getPurNum().add(key2.getPurNum()));
//               key1.setPurchasingBudgetPrice(key1.getPurchasingBudgetPrice().add(key2.getPurchasingBudgetPrice()));
//               if (key1.getCrtime().isBefore(key2.getCrtime())) {
//                  key1.setUnitPrice(key2.getUnitPrice());
//                  key1.setLastPurMaterialPrice(key2.getLastPurMaterialPrice());
//               }
//
//               return key1;
//            }));
//            detailList.add(detailPageVOMap);
//         });
//         Map<String, DrpPurPlanDetailPageVO> mergedMap = (Map)detailList.stream().flatMap((map) -> {
//            return map.entrySet().stream();
//         }).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (detailPageVO, detailPageVO1) -> {
//            DrpPurPlanDetailPageVO drpPurPlanDetailPageVO = new DrpPurPlanDetailPageVO();
//            BeanUtil.copyProperties(detailPageVO, drpPurPlanDetailPageVO, new String[0]);
//            drpPurPlanDetailPageVO.setPurNum(detailPageVO.getPurNum().add(detailPageVO1.getPurNum()));
//            if (detailPageVO.getProPlanNum() != null) {
//               drpPurPlanDetailPageVO.setProPlanNum(detailPageVO.getProPlanNum().add(detailPageVO1.getProPlanNum()));
//            }
//
//            if (detailPageVO.getPurchasingBudgetPrice() != null) {
//               drpPurPlanDetailPageVO.setPurchasingBudgetPrice(detailPageVO.getPurchasingBudgetPrice().add(detailPageVO1.getPurchasingBudgetPrice()));
//            }
//
//            return drpPurPlanDetailPageVO;
//         }));
//         return (new DrpPurchasePlanMergeVO()).setMergeList(mergeList).setDetailList(new ArrayList(mergedMap.values()));
//      }
//   }

   public Map<Long, BigDecimal> syncPurchasePrice(List<Long> content, Long canteenId) {
         List<DrpMaterialLatestPriceVO> materialLatestPriceList = this.drpPurchaseOrderGoodsMapper.getDrpOrderGoodsLastPriceList(content, canteenId);
         return materialLatestPriceList.stream().collect(Collectors.toMap(DrpMaterialLatestPriceVO::getMaterialId, (e) -> {
            return BigDecimal.valueOf((long)e.getLatestPrice());
         }, (k1, k2) -> {
            return k1;
         }));
//      else {
//         AllocCanteen allocCanteen = this.allocCanteenApi.getAllocCanteen(canteenId);
//         List<DrpMaterialLatestPriceVO> materialLatestPriceList = this.drpMarketPriceMapper.getLastPriceList(content, allocCanteen.getAreaId());
//         return (Map)materialLatestPriceList.stream().collect(Collectors.toMap(DrpMaterialLatestPriceVO::getMaterialId, (e) -> {
//            return BigDecimal.valueOf((long)e.getLatestPrice());
//         }, (k1, k2) -> {
//            return k1;
//         }));
//      }
   }

//   public void importExcel(MultipartFile excel) {
//      String redisKey = "yst:merchant-id:pur:plan:lock".replace("merchant-id", TenantContextHolder.getTenantId().toString());
//      String asyncState = (String)this.stringRedisTemplate.opsForValue().get(redisKey);
//      if (CharSequenceUtil.isNotBlank(asyncState)) {
//         throw new LeException(I18n.getMessage("drp.importing-into", new Object[0]));
//      } else {
//         List importOrderGoodsExcelDTOList;
//         try {
//            importOrderGoodsExcelDTOList = EasyExcelUtil.readSingleExcel(excel, new ImportPurPlanExcelDTO(), 2);
//         } catch (Exception var8) {
//            log.error("导入采购计划解析数据错误", var8);
//            throw new LeException(I18n.getMessage("acc_batch_import_data_exception", new Object[0]));
//         }
//
//         log.info("读取到的excel信息集合:{}", importOrderGoodsExcelDTOList);
//         List<ImportPurPlanExcelDTO> finalImportOrderExcelList = new ArrayList();
//         Iterator var6 = importOrderGoodsExcelDTOList.iterator();
//
//         while(var6.hasNext()) {
//            ImportPurPlanExcelDTO i = (ImportPurPlanExcelDTO)var6.next();
//            if (CharSequenceUtil.isBlank(i.getMaterialCode()) && CharSequenceUtil.isBlank(i.getMaterialName()) && ObjectUtil.isEmpty(i.getPurNum()) && ObjectUtil.isEmpty(i.getPlanDate())) {
//               throw new LeException("Excel中包含空白行，请检查并删除空白行！");
//            }
//
//            if (CharSequenceUtil.isBlank(i.getMaterialCode()) || CharSequenceUtil.isBlank(i.getMaterialName()) || ObjectUtil.isEmpty(i.getPurNum()) || ObjectUtil.isEmpty(i.getPlanDate())) {
//               log.info("[导入采购计划]_存在属性为空!");
//               throw new LeException(I18n.getMessage("drp.into-import-file-value-is-empty", new Object[]{i.getMaterialName()}));
//            }
//
//            finalImportOrderExcelList.add(i);
//         }
//
//         this.asyncTaskExecutor.execute(() -> {
//            this.importBuss(finalImportOrderExcelList, redisKey);
//         });
//      }
//   }

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

//   public List<DrpFetchMaterialImportPurPlanPageVO> pageFetchMaterialImportPurPlan(DrpFetchMaterialImportPurPlanPageDTO content) {
//      if (CharSequenceUtil.isNotBlank(content.getPlanId())) {
//         content.setPlanId(LeBeanUtil.fieldLikeHandle(content.getPlanId()));
//      }
//
//      PageMethod.startPage(content);
//      List<DrpFetchMaterialImportPurPlanPageVO> drpFetchMaterialImportPurPlanPageVOS = ((DrpPurchasePlanMapper)this.baseMapper).pageFetchMaterialImportPurPlan(content, DrpCommitStatusEnum.COMMIT.key(), DrpApproveStatusEnum.AGREE_APPROVE.key());
//      drpFetchMaterialImportPurPlanPageVOS.forEach((d) -> {
//         if (CharSequenceUtil.isNotEmpty(d.getStallId())) {
//            String[] split = d.getStallId().split(",");
//            d.setStallName(this.allocStallApi.getStallNameByIdSet((Set)Arrays.stream(split).map(Long::valueOf).collect(Collectors.toSet())));
//         }
//
//      });
//      return drpFetchMaterialImportPurPlanPageVOS;
//   }

//   public List<DrpFetchMaterialImportPurPlanDetailPageVO> pageFetchMaterialImportPurPlanDetail(DrpFetchMaterialImportPurPlanDetailPageDTO content) {
//      PageMethod.startPage(content);
//      return this.drpPurPlanDetailMapper.pageFetchMaterialImportPurPlanDetail(content);
//   }

   public boolean deductionInventory(Long areaId) {
//      AllocDrpModel allocDrpModel = this.drpMetadataService.queryMetadata(content);
//      String ifPurPlanAddOutInventory = allocDrpModel.getIfPurPlanAddOutInventory();
      return ObjectUtil.equal("0", "1");
   }

//   protected void importBuss(List<ImportPurPlanExcelDTO> finalImportOrderExcelList, String redisKey) {
//      List<DrpImportFailMaterial> failMaterialList = new ArrayList();
//      DrpImportRecord drpImportRecord = new DrpImportRecord();
//      Long importRecordId = Id.next();
//      drpImportRecord.setImportRecordId(importRecordId);
//      drpImportRecord.setImportType(DrpImportTypeEnum.PLAN.key());
//      drpImportRecord.setImportTime(LocalDateTime.now());
//      drpImportRecord.setImportResult(DrpImportResultEnum.SUCCESS.key());
//      DrpPurchasePlanSaveDTO drpPurchasePlanSaveDTO = new DrpPurchasePlanSaveDTO();
//      List<DrpPurPlanDetailSaveDTO> detailList = new ArrayList();
//
//      try {
//         finalImportOrderExcelList.forEach((d) -> {
//            DeductCanteenStallVO deductCanteenStallVO = this.allocCanteenApi.queryCanteenStallByName(d.getCanteenName(), d.getStallName());
//            if (deductCanteenStallVO == null) {
//               String var10002 = d.getCanteenName();
//               throw new LeException(var10002 + "-" + d.getStallName() + ":查询不到食堂档口信息！");
//            } else {
//               AllocCanteen allocCanteen = this.allocCanteenApi.getAllocCanteen(deductCanteenStallVO.getCanteenId());
//               if (CharSequenceUtil.isNotEmpty(d.getSupplierNames())) {
//                  String[] supplierNames = d.getSupplierNames().split(",");
//                  List<DrpSupplier> drpSuppliers = this.drpSupplierMapper.selectList((Wrapper)((LambdaQueryWrapper)Wrappers.lambdaQuery(DrpSupplier.class).in(DrpSupplier::getSupplierName, Arrays.asList(supplierNames))).eq(DrpSupplier::getAreaId, allocCanteen.getAreaId()));
//                  if (CollUtil.isNotEmpty(drpSuppliers)) {
//                     drpPurchasePlanSaveDTO.setSupplierIds((String)drpSuppliers.stream().map((drpSupplier) -> {
//                        return drpSupplier.getSupplierId().toString();
//                     }).collect(Collectors.joining(",")));
//                  }
//               }
//
//               drpPurchasePlanSaveDTO.setPurDate(DrpDateUtil.stringToLocalDateTimeByPatt(d.getPlanDate(), "yyyyMMddHHmmss"));
//               drpPurchasePlanSaveDTO.setRemark(d.getRemark());
//               drpPurchasePlanSaveDTO.setCanteenId(deductCanteenStallVO.getCanteenId());
//               drpPurchasePlanSaveDTO.setStallId("" + deductCanteenStallVO.getStallId());
//               drpPurchasePlanSaveDTO.setPurchasingBudgetTotal(d.getPurchasingBudgetPrice().multiply(new BigDecimal("100")).longValue());
//               MenuMaterial menuMaterial = (MenuMaterial)this.menuMaterialMapper.selectOne((Wrapper)((LambdaQueryWrapper)Wrappers.lambdaQuery(MenuMaterial.class).eq(MenuMaterial::getMaterialCode, d.getMaterialCode())).eq(MenuMaterial::getDelFlag, LeConstants.COMMON_NO));
//               if (null == menuMaterial) {
//                  throw new LeException(d.getMaterialName() + "货品不存在！");
//               } else if (!Objects.equals(menuMaterial.getMaterialName(), d.getMaterialName())) {
//                  throw new LeException(d.getMaterialName() + "货品名称与编码不对应！");
//               } else {
//                  DrpPurPlanDetailSaveDTO dto = new DrpPurPlanDetailSaveDTO();
//                  dto.setMaterialId(menuMaterial.getMaterialId());
//                  dto.setUnitId(menuMaterial.getUnitId());
//                  dto.setPurNum(d.getPurNum());
//                  dto.setProPlanNum(BigDecimal.ZERO);
//                  InventoryModel inventoryModel = this.drpInventoryMapper.getInventoryNumByMaterialId(menuMaterial.getMaterialId(), (Long)null, menuMaterial.getUnitId());
//                  dto.setInventoryNum(inventoryModel != null ? inventoryModel.getInventoryNum() : BigDecimal.ZERO);
//                  Map<Long, BigDecimal> longBigDecimalMap = this.syncPurchasePrice(Collections.singletonList(menuMaterial.getMaterialId()), deductCanteenStallVO.getCanteenId());
//                  dto.setUnitPrice(longBigDecimalMap == null ? BigDecimal.ZERO : (BigDecimal)longBigDecimalMap.get(menuMaterial.getMaterialId()));
//                  dto.setPurchasingBudgetPrice(dto.getUnitPrice() != null ? d.getPurNum().multiply(dto.getUnitPrice()) : BigDecimal.ZERO);
//                  detailList.add(dto);
//               }
//            }
//         });
//         drpPurchasePlanSaveDTO.setDetailList(detailList);
//         if (CollUtil.isNotEmpty(drpPurchasePlanSaveDTO.getDetailList())) {
//            this.drpPurchasePlanService.addSaveDrpPurchasePlan(drpPurchasePlanSaveDTO);
//         }
//      } catch (Exception var13) {
//         DrpImportFailMaterial drpImportFailMaterial = new DrpImportFailMaterial();
//         drpImportFailMaterial.setImportRecordId(Id.next());
//         drpImportFailMaterial.setFailReason(var13.getMessage());
//         failMaterialList.add(drpImportFailMaterial);
//         drpImportRecord.setImportRecordId(drpImportFailMaterial.getImportRecordId());
//         drpImportRecord.setImportResult(DrpImportResultEnum.FAIL.key());
//         drpPurchasePlanSaveDTO.setDetailList((List)null);
//         drpImportRecord.setErrorReason(var13.getMessage());
//         throw new LeException("系统异常:" + var13.getMessage());
//      } finally {
//         this.stringRedisTemplate.delete(redisKey);
//         this.drpImportRecordMapper.insert(drpImportRecord);
//         this.drpImportFailMaterialService.saveBatch(failMaterialList);
//      }
//
//   }

   protected void packageInquiry(String inquiryId, LocalDateTime purDate) {
      DrpInquiry drpInquiry = new DrpInquiry();
      drpInquiry.setInquiryId(inquiryId);
      drpInquiry.setTitle("采购询价");
      drpInquiry.setStartTime(LocalDateTime.now());
      drpInquiry.setEndTime(LocalDateTime.of(LocalDate.from(purDate), LocalTime.MAX));
      drpInquiry.setRequestArrivalTime(LocalDate.now());
      drpInquiry.setSupplierId(0L);
      drpInquiry.setStatus(DrpInquiryStatusEnum.NO_COMMIT.key());
      this.drpPurchaseInquiryMapper.insert(drpInquiry);
   }

   protected void saveInquiryAndSendMsgToSupplier(List<Long> key, String inquiryId, List<DrpInquiryDetail> inquiryDetails) {
      Iterator var4 = key.iterator();

      while(var4.hasNext()) {
         Long supplierId = (Long)var4.next();
         DrpInquirySupplier drpInquirySupplier = new DrpInquirySupplier();
         drpInquirySupplier.setInquirySupplierId(Id.next());
         drpInquirySupplier.setInquiryId(inquiryId);
         drpInquirySupplier.setSupplierId(supplierId);
         this.drpPurchaseInquirySupplierMapper.insert(drpInquirySupplier);
         Long inquirySupplierId = drpInquirySupplier.getInquirySupplierId();
         Iterator var8 = inquiryDetails.iterator();

         while(var8.hasNext()) {
            DrpInquiryDetail detail = (DrpInquiryDetail)var8.next();
            DrpQuote quote = new DrpQuote();
            BeanUtil.copyProperties(detail, quote, new String[0]);
            quote.setId((Long)null);
            quote.setQuoteId(Id.next());
            quote.setInquirySupplierId(inquirySupplierId);
            quote.setQuoteNum(detail.getPurNum());
            this.drpPurchaseQuoteMapper.insert(quote);
         }
      }

   }

//   protected List<DrpOutInventoryModel> packageInventoryNum(DrpPurchasePlanSaveDTO content) {
//      List<DrpOutInventoryModel> outInventoryList = Lists.newArrayList();
//      DrpWarehouse fc = (DrpWarehouse)this.drpWarehouseMapper.selectOne((Wrapper)((LambdaQueryWrapper)Wrappers.lambdaQuery(DrpWarehouse.class).eq(DrpWarehouse::getCanteenId, content.getCanteenId())).eq(DrpWarehouse::getDelFlag, DelFlagEnum.DEL_FALSE.key()));
//      if (fc == null) {
//         log.info("食堂未绑定仓库！");
//         return outInventoryList;
//      } 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}));
//         if (zc == null) {
//            log.info("食堂未绑定总仓仓库！！");
//            return outInventoryList;
//         } else {
//            List<DrpPurPlanDetailSaveDTO> detailList = content.getDetailList();
//            Map<String, InventoryModel> fcKcMap = (Map)detailList.stream().collect(Collectors.toMap((detail) -> {
//               Long var10000 = detail.getMaterialId();
//               return "" + var10000 + "-" + detail.getUnitId();
//            }, (detail) -> {
//               return new InventoryModel();
//            }, (k1, k2) -> {
//               return k1;
//            }));
//            Map<String, InventoryModel> zcKcMap = (Map)detailList.stream().collect(Collectors.toMap((detail) -> {
//               Long var10000 = detail.getMaterialId();
//               return "" + var10000 + "-" + detail.getUnitId();
//            }, (detail) -> {
//               return new InventoryModel();
//            }, (k1, k2) -> {
//               return k1;
//            }));
//            this.getInventoryByWarehouse(fc, fcKcMap);
//            this.getInventoryByWarehouse(zc, zcKcMap);
//            content.getDetailList().forEach((d) -> {
//               if (d.getUnitPrice() == null) {
//                  d.setUnitPrice(BigDecimal.ZERO);
//               }
//
//               BigDecimal purNum = d.getPurNum();
//               Long var10001 = d.getMaterialId();
//               InventoryModel inventoryModel = (InventoryModel)fcKcMap.get("" + var10001 + "-" + d.getUnitId());
//               InventoryModel inventoryModelZc;
//               BigDecimal outCount;
//               if (inventoryModel != null) {
//                  if (inventoryModel.getInventoryNum() == null) {
//                     inventoryModel.setInventoryNum(BigDecimal.ZERO);
//                  }
//
//                  if (d.getPurNum().compareTo(inventoryModel.getInventoryNum()) > 0) {
//                     purNum = d.getPurNum().subtract(inventoryModel.getInventoryNum());
//                     if (inventoryModel.getInventoryNum().compareTo(BigDecimal.ZERO) != 0) {
//                        outInventoryList.add((new DrpOutInventoryModel()).setInventoryId(inventoryModel.getInventoryId()).setOutCount(inventoryModel.getInventoryNum()).setWarehouseId(fc.getWarehouseId()).setStallId(d.getStallId()));
//                        inventoryModel.setInventoryNum(BigDecimal.ZERO);
//                        fcKcMap.put(d.getMaterialId() + "-" + d.getUnitId(), inventoryModel);
//                     }
//
//                     d.setPurNum(purNum);
//                     d.setPurchasingBudgetPrice(d.getPurNum().multiply(d.getUnitPrice()));
//                     var10001 = d.getMaterialId();
//                     inventoryModelZc = (InventoryModel)zcKcMap.get("" + var10001 + "-" + d.getUnitId());
//                     if (inventoryModelZc != null) {
//                        if (inventoryModelZc.getInventoryNum() == null) {
//                           inventoryModelZc.setInventoryNum(BigDecimal.ZERO);
//                        }
//
//                        if (purNum.compareTo(inventoryModelZc.getInventoryNum()) > 0) {
//                           purNum = d.getPurNum().subtract(inventoryModelZc.getInventoryNum());
//                           d.setPurNum(purNum);
//                           d.setPurchasingBudgetPrice(d.getPurNum().multiply(d.getUnitPrice()));
//                           if (inventoryModelZc.getInventoryNum().compareTo(BigDecimal.ZERO) != 0) {
//                              outCount = inventoryModelZc.getInventoryNum();
//                              outInventoryList.add((new DrpOutInventoryModel()).setInventoryId(inventoryModelZc.getInventoryId()).setOutCount(outCount).setWarehouseId(zc.getWarehouseId()).setWarehouseType(1).setChildWarehouseId(fc.getWarehouseId()).setOriginalQuantity(inventoryModelZc.getInventoryNum()).setStallId(d.getStallId()).setMaterialId(d.getMaterialId()).setUnitId(d.getUnitId()));
//                              inventoryModelZc.setInventoryNum(BigDecimal.ZERO);
//                              zcKcMap.put(d.getMaterialId() + "-" + d.getUnitId(), inventoryModelZc);
//                           }
//                        } else {
//                           outCount = purNum;
//                           if (inventoryModelZc.getInventoryNum().compareTo(purNum) < 0) {
//                              outCount = purNum;
//                           }
//
//                           outInventoryList.add((new DrpOutInventoryModel()).setInventoryId(inventoryModelZc.getInventoryId()).setOutCount(outCount).setWarehouseId(zc.getWarehouseId()).setWarehouseType(1).setChildWarehouseId(fc.getWarehouseId()).setOriginalQuantity(purNum).setStallId(d.getStallId()).setMaterialId(d.getMaterialId()).setUnitId(d.getUnitId()));
//                           d.setPurNum(BigDecimal.ZERO);
//                           d.setPurchasingBudgetPrice(d.getPurNum().multiply(d.getUnitPrice()));
//                           inventoryModelZc.setInventoryNum(inventoryModelZc.getInventoryNum().subtract(purNum));
//                           zcKcMap.put(d.getMaterialId() + "-" + d.getUnitId(), inventoryModelZc);
//                        }
//                     }
//                  } else {
//                     outInventoryList.add((new DrpOutInventoryModel()).setInventoryId(inventoryModel.getInventoryId()).setOutCount(purNum).setWarehouseId(fc.getWarehouseId()).setStallId(d.getStallId()));
//                     d.setPurNum(BigDecimal.ZERO);
//                     d.setPurchasingBudgetPrice(d.getPurNum().multiply(d.getUnitPrice()));
//                     inventoryModel.setInventoryNum(inventoryModel.getInventoryNum().subtract(purNum));
//                     fcKcMap.put(d.getMaterialId() + "-" + d.getUnitId(), inventoryModel);
//                  }
//               } else {
//                  var10001 = d.getMaterialId();
//                  inventoryModelZc = (InventoryModel)zcKcMap.get("" + var10001 + "-" + d.getUnitId());
//                  if (inventoryModelZc != null) {
//                     if (inventoryModelZc.getInventoryNum() == null) {
//                        inventoryModelZc.setInventoryNum(BigDecimal.ZERO);
//                     }
//
//                     if (purNum.compareTo(inventoryModelZc.getInventoryNum()) > 0) {
//                        purNum = d.getPurNum().subtract(inventoryModelZc.getInventoryNum());
//                        d.setPurNum(purNum);
//                        d.setPurchasingBudgetPrice(d.getPurNum().multiply(d.getUnitPrice()));
//                        if (inventoryModelZc.getInventoryNum().compareTo(BigDecimal.ZERO) != 0) {
//                           outCount = inventoryModelZc.getInventoryNum();
//                           outInventoryList.add((new DrpOutInventoryModel()).setInventoryId(inventoryModelZc.getInventoryId()).setOutCount(outCount).setWarehouseId(zc.getWarehouseId()).setWarehouseType(1).setChildWarehouseId(fc.getWarehouseId()).setOriginalQuantity(inventoryModelZc.getInventoryNum()).setStallId(d.getStallId()).setMaterialId(d.getMaterialId()).setUnitId(d.getUnitId()));
//                           inventoryModelZc.setInventoryNum(BigDecimal.ZERO);
//                           zcKcMap.put(d.getMaterialId() + "-" + d.getUnitId(), inventoryModelZc);
//                        }
//                     } else {
//                        outCount = purNum;
//                        if (inventoryModelZc.getInventoryNum().compareTo(purNum) < 0) {
//                           outCount = purNum;
//                        }
//
//                        outInventoryList.add((new DrpOutInventoryModel()).setInventoryId(inventoryModelZc.getInventoryId()).setOutCount(outCount).setWarehouseId(zc.getWarehouseId()).setWarehouseType(1).setChildWarehouseId(fc.getWarehouseId()).setOriginalQuantity(purNum).setStallId(d.getStallId()).setMaterialId(d.getMaterialId()).setUnitId(d.getUnitId()));
//                        d.setPurNum(BigDecimal.ZERO);
//                        d.setPurchasingBudgetPrice(d.getPurNum().multiply(d.getUnitPrice()));
//                        inventoryModelZc.setInventoryNum(inventoryModelZc.getInventoryNum().subtract(purNum));
//                        zcKcMap.put(d.getMaterialId() + "-" + d.getUnitId(), inventoryModelZc);
//                     }
//                  }
//               }
//
//            });
//            return outInventoryList;
//         }
//      }
//   }

//   protected void getInventoryByWarehouse(DrpWarehouse ck, Map<String, InventoryModel> zcKcMap) {
//      zcKcMap.forEach((key, value) -> {
//         String[] split = key.split("-");
//         InventoryModel inventoryModel = this.drpInventoryMapper.getInventoryNumByMaterialId(Long.valueOf(split[0]), ck.getWarehouseId(), Long.valueOf(split[1]));
//         if (inventoryModel != null) {
//            zcKcMap.put(key, inventoryModel);
//         }
//
//      });
//   }

//   protected void outWarehouse(List<DrpOutInventoryModel> outInventoryList, String planId, List<DrpPurPlanDetailSaveDTO> detailList, LocalDateTime outDate) {
//      if (!CollUtil.isEmpty(outInventoryList)) {
//         log.info("分仓出库开始:{}", outInventoryList);
//         this.fcOutWarehouse(outInventoryList, planId, 1, outDate);
//         Map<Long, List<DrpOutInventoryModel>> zcOutMap = (Map)outInventoryList.stream().filter((drpOutInventoryModel) -> {
//            return drpOutInventoryModel.getWarehouseId() != null && drpOutInventoryModel.getWarehouseType() != null && drpOutInventoryModel.getWarehouseType() == 1;
//         }).collect(Collectors.groupingBy(DrpOutInventoryModel::getWarehouseId));
//         if (!zcOutMap.isEmpty()) {
//            log.info("总仓调拨出库开始:{}", zcOutMap);
//            zcOutMap.forEach((zcWarehouseId, zcList) -> {
//               String goodsAllocationId = this.addGoodsAllocation(zcWarehouseId, zcList, outDate);
//
//               try {
//                  this.drpGoodsAllocationService.allocationHira(goodsAllocationId, outDate);
//                  zcList.forEach((drpOutInventoryModel) -> {
//                     drpOutInventoryModel.setOutCount(drpOutInventoryModel.getOriginalQuantity());
//                     drpOutInventoryModel.setInventoryId((Long)null);
//                  });
//                  log.info("总仓调拨出库成功，分仓出库开始:{}", zcList);
//                  this.fcOutWarehouse(zcList, planId, 2, outDate);
//               } catch (Exception var9) {
//                  log.error("调拨失败:{}", var9.getMessage());
//                  Map<String, List<DrpOutInventoryModel>> kcDcMap = (Map)zcList.stream().collect(Collectors.groupingBy((d) -> {
//                     Long var10000 = d.getMaterialId();
//                     return "" + var10000 + "-" + d.getStallId();
//                  }));
//                  detailList.forEach((d) -> {
//                     Long var10001 = d.getMaterialId();
//                     List<DrpOutInventoryModel> drpOutInventoryModels = (List)kcDcMap.get("" + var10001 + "-" + d.getStallId());
//                     if (drpOutInventoryModels != null) {
//                        BigDecimal outCount = (BigDecimal)drpOutInventoryModels.stream().map(DrpOutInventoryModel::getOriginalQuantity).reduce(BigDecimal.ZERO, BigDecimal::add);
//                        d.setPurNum(d.getPurNum().add(outCount));
//                        d.setPurchasingBudgetPrice(d.getUnitPrice() != null ? d.getPurNum().multiply(d.getUnitPrice()) : BigDecimal.ZERO);
//                     }
//
//                  });
//               }
//
//            });
//         }
//      }
//   }

//   protected String addGoodsAllocation(Long zcWarehouseId, List<DrpOutInventoryModel> zcList, LocalDateTime outDate) {
//      DrpGoodsAllocation drpGoodsAllocation = new DrpGoodsAllocation();
//      drpGoodsAllocation.setGoodsAllocationId(CustomIdGenerateUtil.generateGoodsAllocationId());
//      drpGoodsAllocation.setOutWarehouseId(zcWarehouseId);
//      drpGoodsAllocation.setIntoWarehouseId(((DrpOutInventoryModel)zcList.get(0)).getChildWarehouseId());
//      drpGoodsAllocation.setRequestArrivalTime(outDate);
//      drpGoodsAllocation.setRemark("采购计划出库分仓库存不足总仓自动调拨");
//      drpGoodsAllocation.setAllocationStatus(DrpGoodsAllocationStatusEnum.WAIT_ALLOCATION.key());
//      drpGoodsAllocation.setDelFlag(DelFlagEnum.DEL_FALSE.key());
//      DrpFetchUserVO drpFetchUserVO = this.drpWarehouseMapper.getFetchUserByWarehouseId(drpGoodsAllocation.getIntoWarehouseId());
//      Optional<Long> subject = SecureManager.getSubjectId();
//      Long subjectId = null;
//      if (subject.isPresent()) {
//         subjectId = (Long)subject.get();
//      }
//
//      drpGoodsAllocation.setCrbyId(drpFetchUserVO != null ? drpFetchUserVO.getFetchUserId() : subjectId);
//      this.drpGoodsAllocationMapper.insert(drpGoodsAllocation);
//      Map<Long, DrpOutInventoryModel> zcMap = (Map)zcList.stream().collect(Collectors.toMap(DrpOutInventoryModel::getInventoryId, Function.identity(), (key1, key2) -> {
//         key1.setOutCount(key1.getOutCount().add(key2.getOutCount()));
//         return key1;
//      }));
//      zcMap.forEach((inventoryId, drpOutInventoryModel) -> {
//         DrpGoodsAllocationDetail drpGoodsAllocationDetail = new DrpGoodsAllocationDetail();
//         drpGoodsAllocationDetail.setGoodsAllocationDetailId(Id.next());
//         drpGoodsAllocationDetail.setGoodsAllocationId(drpGoodsAllocation.getGoodsAllocationId());
//         drpGoodsAllocationDetail.setInventoryId(drpOutInventoryModel.getInventoryId());
//         DrpInventory drpInventory = (DrpInventory)this.drpInventoryMapper.selectOne((Wrapper)Wrappers.lambdaQuery(DrpInventory.class).eq(DrpInventory::getInventoryId, drpOutInventoryModel.getInventoryId()));
//         if (drpInventory == null) {
//            throw new LeException(drpOutInventoryModel.getInventoryId() + "库存不存在");
//         } else {
//            drpGoodsAllocationDetail.setMaterialId(drpInventory.getMaterialId());
//            drpGoodsAllocationDetail.setUnitId(drpInventory.getUnitId());
//            if (drpInventory.getMaterialNum().compareTo(drpOutInventoryModel.getOutCount().setScale(0, RoundingMode.CEILING)) >= 0) {
//               drpGoodsAllocationDetail.setOrderNum(drpOutInventoryModel.getOutCount().setScale(0, RoundingMode.CEILING));
//            } else {
//               drpGoodsAllocationDetail.setOrderNum(drpOutInventoryModel.getOutCount());
//            }
//
//            drpGoodsAllocationDetail.setRemark("采购计划出库分仓库存不足总仓自动调拨");
//            drpGoodsAllocationDetail.setFetchNum(drpInventory.getMaterialNum());
//            this.drpGoodsAllocationDetailMapper.insert(drpGoodsAllocationDetail);
//         }
//      });
//      return drpGoodsAllocation.getGoodsAllocationId();
//   }

//   protected void fcOutWarehouse(List<DrpOutInventoryModel> outInventoryList, String planId, Integer type, LocalDateTime outDate) {
//      Long userId = (Long)SecureManager.getSubjectId().get();
//      Map<Long, List<DrpOutInventoryModel>> fcOutMap = (Map)outInventoryList.stream().filter((drpOutInventoryModel) -> {
//         return drpOutInventoryModel.getWarehouseId() != null && drpOutInventoryModel.getWarehouseType() == null;
//      }).collect(Collectors.groupingBy(DrpOutInventoryModel::getWarehouseId));
//      if (type == 2) {
//         fcOutMap = (Map)outInventoryList.stream().collect(Collectors.groupingBy(DrpOutInventoryModel::getChildWarehouseId));
//      }
//
//      fcOutMap.forEach((key, value) -> {
//         Map<Long, List<DrpOutInventoryModel>> stallMap = (Map)value.stream().collect(Collectors.groupingBy(DrpOutInventoryModel::getStallId));
//         stallMap.forEach((stallId, stallList) -> {
//            DrpWarehouseFetchUser drpWarehouseFetchUser = (DrpWarehouseFetchUser)this.drpWarehouseFetchUserMapper.selectOne((Wrapper)((LambdaQueryWrapper)Wrappers.lambdaQuery(DrpWarehouseFetchUser.class).eq(DrpWarehouseFetchUser::getWarehouseId, key)).eq(DrpWarehouseFetchUser::getStallId, stallId));
//            DrpFetchUserVO drpFetchUserVO = this.drpWarehouseMapper.getFetchUserByWarehouseId(key);
//            DrpOutInventoryAddDTO dto = new DrpOutInventoryAddDTO();
//            dto.setWarehouseId(key);
//            dto.setFetchUserId(drpWarehouseFetchUser != null ? drpWarehouseFetchUser.getFetchUserId() : (drpFetchUserVO != null ? drpFetchUserVO.getFetchUserId() : userId));
//            dto.setOutDate(outDate);
//            BigDecimal totalCount = (BigDecimal)stallList.stream().map(DrpOutInventoryModel::getOutCount).reduce(BigDecimal.ZERO, BigDecimal::add);
//            dto.setTotalAmount(0L);
//            dto.setTotalNum(totalCount);
//            dto.setOutType(DrpOutInventoryTypeEnum.FETCH.key());
//            dto.setRemark("采购自动出库");
//            dto.setStatus(DrpOutInventoryStatusEnum.COMMIT.key());
//            List<DrpOutDetailAddDTO> detailList = new ArrayList();
//
//            DrpOutDetailAddDTO drpOutDetailAddDTO;
//            for(Iterator var12 = stallList.iterator(); var12.hasNext(); detailList.add(drpOutDetailAddDTO)) {
//               DrpOutInventoryModel drpOutInventoryModel = (DrpOutInventoryModel)var12.next();
//               drpOutDetailAddDTO = new DrpOutDetailAddDTO();
//               drpOutDetailAddDTO.setFetchNum(drpOutInventoryModel.getOutCount());
//               drpOutDetailAddDTO.setTotalPrice(0);
//               if (drpOutInventoryModel.getInventoryId() == null) {
//                  drpOutDetailAddDTO.setInventoryId(this.drpInventoryMapper.getInventoryNumByMaterialId(drpOutInventoryModel.getMaterialId(), key, drpOutInventoryModel.getUnitId()).getInventoryId());
//               } else {
//                  drpOutDetailAddDTO.setInventoryId(drpOutInventoryModel.getInventoryId());
//               }
//            }
//
//            dto.setDetailList(detailList);
//            dto.setPlanId(planId);
//            this.drpOutInventoryService.addCommitOutWarehouse(dto);
//         });
//      });
//   }
}
