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

import cn.hutool.core.bean.BeanUtil;
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.supply.purchase.api.AllocStallApi;
import com.bonus.canteen.core.supply.purchase.api.DrpAuthorityPurchaseApi;
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.DrpOrderGoodsDetailSaveDTO;
import com.bonus.canteen.core.supply.purchase.domain.param.DrpOrderGoodsPageDTO;
import com.bonus.canteen.core.supply.purchase.domain.param.DrpOrderGoodsPayStyleAddDTO;
import com.bonus.canteen.core.supply.purchase.domain.param.DrpOrderGoodsSaveDTO;
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.DrpMaterialLatestPriceService;
import com.bonus.canteen.core.supply.purchase.service.DrpOrderGoodsDetailService;
import com.bonus.canteen.core.supply.purchase.service.DrpPuchaseOrderGoodsService;
import com.bonus.canteen.core.supply.purchase.service.DrpPurchasePurNoticeService;
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.constant.LeConstants;
import com.bonus.common.houqin.i18n.I18n;
import com.bonus.common.houqin.utils.id.Id;
import com.bonus.common.security.utils.SecurityUtils;
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.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class DrpPuchaseOrderGoodsServiceImpl extends ServiceImpl<DrpPurchaseOrderGoodsMapper, DrpOrderGoods> implements DrpPuchaseOrderGoodsService {
   private static final Logger log = LoggerFactory.getLogger(DrpPuchaseOrderGoodsServiceImpl.class);
   @Resource(
      name = "smartCanteenTaskExecutor"
   )
   @Lazy
   private AsyncTaskExecutor asyncTaskExecutor;
   @Autowired
   @Lazy
   private DrpOrderGoodsDetailService drpOrderGoodsDetailService;
   @Autowired
   @Lazy
   private DrpPurchaseSupplierDeliverMapper drpPurchaseSupplierDeliverMapper;
   @Autowired
   @Lazy
   private DrpPurchasePurNoticeService drpPurchasePurNoticeService;
   @Autowired
   @Lazy
   private DrpPurchaseOrderGoodsPayStyleMapper drpPurchaseOrderGoodsPayStyleMapper;
   @Autowired
   @Lazy
   private AllocStallApi allocStallApi;
   @Autowired
   @Lazy
   private DrpAuthorityPurchaseApi drpAuthorityPurchaseApi;
   @Autowired
   @Lazy
   private DrpProductionPurchaseOrderMapper drpProductionPurchaseOrderMapper;
   @Autowired
   @Lazy
   private DrpMaterialLatestPriceService drpMaterialLatestPriceService;
   @Autowired
   @Lazy
   private DrpOrderGoodsDetailMapper drpOrderGoodsDetailMapper;

   @Transactional(
      rollbackFor = {Exception.class}
   )
   public DrpOrderGoodsAddVO addSaveDrpOrderGoods(DrpOrderGoodsSaveDTO content) {
      return this.addDrpOrderGoods(content, DrpOrderGoodsStatusEnum.WAIT_COMMIT.getKey());
   }

   @Transactional(
      rollbackFor = {Exception.class}
   )
   public DrpOrderGoodsAddVO addCommitDrpOrderGoods(DrpOrderGoodsSaveDTO content) {
      List<DrpOrderGoodsDetailSaveDTO> detailList = content.getDetailList();
      detailList.forEach((detail) -> {
         if (ObjectUtil.isNull(detail.getSinglePrice())) {
            throw new ServiceException("请填写采购单价");
         }
      });
      return this.addDrpOrderGoods(content, DrpOrderGoodsStatusEnum.IS_COMMIT.getKey());
   }

   protected DrpOrderGoodsAddVO addDrpOrderGoods(DrpOrderGoodsSaveDTO content, Integer orderStatus) {
      DrpOrderGoods drpOrderGoods = new DrpOrderGoods();
      BeanUtil.copyProperties(content, drpOrderGoods, new String[0]);
      drpOrderGoods.setOrderStatus(orderStatus);
      drpOrderGoods.setOrderAmount(((BigDecimal)content.getDetailList().stream().map(DrpOrderGoodsDetailSaveDTO::getTotalPrice).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add)).longValue());
//      AllocDrpModel allocDrpModel = this.drpMetadataService.queryMetadataByCanteenId(content.getCanteenId());
//      String ifPurOrderNeedSupplierConfirm = allocDrpModel.getIfPurOrderNeedSupplierConfirm();
//      if ((ObjectUtil.equal(ifPurOrderNeedSupplierConfirm, "2") || CharSequenceUtil.isBlank(ifPurOrderNeedSupplierConfirm)) && ObjectUtil.equal(orderStatus, DrpOrderGoodsStatusEnum.IS_COMMIT.getKey())) {
         drpOrderGoods.setSupplierConfirmStatus(DrpSupplierConfirmStatusEnum.CONFIRM_PASS.getKey());
         drpOrderGoods.setConfirmTime(LocalDateTime.now());
//      } else {
//         drpOrderGoods.setSupplierConfirmStatus(DrpSupplierConfirmStatusEnum.WAIT_CONFIRM.getKey());
//      }

      DrpOrderGoodsPayStyleAddDTO drpOrderGoodsPayStyleAddDTO;
      DrpOrderGoodsPayStyle drpOrderGoodsPayStyle;
      if (ObjectUtil.isEmpty(drpOrderGoods.getOrderGoodsId())) {
         drpOrderGoods.setOrderGoodsId(CustomIdGenerateUtil.generateOrderGoodsId());
         ((DrpPurchaseOrderGoodsMapper)this.baseMapper).insert(drpOrderGoods);
         drpOrderGoodsPayStyleAddDTO = content.getDrpOrderGoodsPayStyleAddDTO();
         drpOrderGoodsPayStyle = new DrpOrderGoodsPayStyle();
         BeanUtil.copyProperties(drpOrderGoodsPayStyleAddDTO, drpOrderGoodsPayStyle, new String[0]);
         drpOrderGoodsPayStyle.setOrderGoodsId(drpOrderGoods.getOrderGoodsId());
         this.drpPurchaseOrderGoodsPayStyleMapper.insert(drpOrderGoodsPayStyle);
      } else {
         ((DrpPurchaseOrderGoodsMapper)this.baseMapper).update(drpOrderGoods, Wrappers.lambdaQuery(DrpOrderGoods.class).eq(DrpOrderGoods::getOrderGoodsId, drpOrderGoods.getOrderGoodsId()));
         this.drpOrderGoodsDetailService.deleteByOrderGoodsId(drpOrderGoods.getOrderGoodsId());
         this.drpPurchaseOrderGoodsPayStyleMapper.delete(Wrappers.lambdaQuery(DrpOrderGoodsPayStyle.class).eq(DrpOrderGoodsPayStyle::getOrderGoodsId, drpOrderGoods.getOrderGoodsId()));
         drpOrderGoodsPayStyleAddDTO = content.getDrpOrderGoodsPayStyleAddDTO();
         drpOrderGoodsPayStyle = new DrpOrderGoodsPayStyle();
         BeanUtil.copyProperties(drpOrderGoodsPayStyleAddDTO, drpOrderGoodsPayStyle, new String[0]);
         drpOrderGoodsPayStyle.setOrderGoodsId(drpOrderGoods.getOrderGoodsId());
         this.drpPurchaseOrderGoodsPayStyleMapper.insert(drpOrderGoodsPayStyle);
      }

      List<DrpOrderGoodsDetail> saveDetailList = BeanUtil.copyToList(content.getDetailList(), DrpOrderGoodsDetail.class);
      saveDetailList.forEach((item) -> {
         item.setOrderGoodsDetailId(Id.next());
         item.setOrderGoodsId(drpOrderGoods.getOrderGoodsId());
      });
      this.drpOrderGoodsDetailService.saveBatch(saveDetailList);
      DrpOrderGoodsAddVO result = new DrpOrderGoodsAddVO();
      result.setOrderGoodsId(drpOrderGoods.getOrderGoodsId());
      if (!ObjectUtil.equal(orderStatus, DrpOrderGoodsStatusEnum.IS_COMMIT.getKey())) {
         return result;
      } else {
//         String ifPurOrderGoodsNeedProcess = allocDrpModel.getIfPurOrderNeedProcess();
//         boolean isAdmin = SecureManager.hasRole(new String[]{RoleCodeV2Enum.ROLE_SUPER_ADMIN.key()});
//         if (!ObjectUtil.equal(ifPurOrderGoodsNeedProcess, "2") && !isAdmin) {
//            Long userId = (Long)SecureManager.getSubjectId().get();
//            MgrUser mgrUser = this.mgrUserApi.selectMgrUserByUserId(userId);
//            Long definitionId = this.flowApi.getByMappingIdAndDefinitionType(userId, FlowDefinitionEum.PUR_ORDER_GOODS, 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);
//            DrpOrderGoodsVO drpOrderGoodsInfo = this.getDrpOrderGoodsInfo(drpOrderGoods.getOrderGoodsId());
//            drpOrderGoodsInfo.setDetailList((List)null);
//            creatInstanceDto.setContext(FlowBeanUtil.parseObj2Map(drpOrderGoodsInfo));
//            Long instanceId = this.flowApi.creat(creatInstanceDto);
//            ((DrpOrderGoodsMapper)this.baseMapper).update((Object)null, (Wrapper)((LambdaUpdateWrapper)((LambdaUpdateWrapper)Wrappers.lambdaUpdate(DrpOrderGoods.class).eq(DrpOrderGoods::getOrderGoodsId, drpOrderGoods.getOrderGoodsId())).set(DrpOrderGoods::getApproveStatus, DrpApproveStatusEnum.WAIT_APPROVE.key())).set(DrpOrderGoods::getProcessInstanceId, instanceId));
//         } else {
            this.autoPassProcess(drpOrderGoods.getOrderGoodsId());
            if (ObjectUtil.equal(drpOrderGoods.getSupplierConfirmStatus(), DrpSupplierConfirmStatusEnum.CONFIRM_PASS.getKey())) {
               (this.drpOrderGoodsDetailMapper.selectList(Wrappers.lambdaQuery(DrpOrderGoodsDetail.class).eq(DrpOrderGoodsDetail::getOrderGoodsId, content.getOrderGoodsId())).stream().collect(Collectors.toMap(DrpOrderGoodsDetail::getMaterialId, Function.identity(), (k1, k2) -> {
                  return k1;
               }))).values().forEach((detail) -> {
                  this.drpMaterialLatestPriceService.addMaterialLatestPrice(DrpMaterialLatestPriceDTO.builder().materialId(detail.getMaterialId()).unitId(detail.getUnitId()).priceType(DrpMaterialPriceTypeEnum.MATERIAL_ORDER_GOODS.key()).latestPrice(detail.getSinglePrice()).relatedId(detail.getOrderGoodsId()).remark(DrpMaterialPriceTypeEnum.MATERIAL_ORDER_GOODS.value()).build());
               });
            }

            this.asyncTaskExecutor.execute(() -> {
               this.drpPurchasePurNoticeService.sendSmsNoticeGeneral(content.getSupplierId(), (String)null, drpOrderGoods.getOrderGoodsId(), NoticeTemplateKeyEnum.DRP_PUR_PLAN_SUPPLY.getKey());
            });
//         }

         return result;
      }
   }

   protected void autoPassProcess(String orderGoodsId) {
      ((DrpPurchaseOrderGoodsMapper)this.baseMapper).update(null, (Wrappers.lambdaUpdate(DrpOrderGoods.class).set(DrpOrderGoods::getApproveStatus, DrpApproveStatusEnum.AGREE_APPROVE.key())).eq(DrpOrderGoods::getOrderGoodsId, orderGoodsId));
   }

   public List<DrpOrderGoodsPageVO> getDrpOrderGoodsList(DrpOrderGoodsPageDTO 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.PUR_ORDER_GOODS));
//               if (instanceIdsByState.isEmpty()) {
//                  return new ArrayList();
//               }
//
//               content.setInstanceIds(instanceIdsByState);
//               break;
//            case 3:
//               content.setOrderStatus(DrpCommitStatusEnum.COMMIT.key());
//               instanceIdsByState = this.flowApi.getInstanceIdsByState(FlowDefinitionEum.getStagingDefinitionsByEnum(FlowDefinitionEum.PUR_ORDER_GOODS));
//               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());
         }
      }
      List<DrpOrderGoodsPageVO> resultList = this.baseMapper.getDrpOrderGoodsList(content, DelFlagEnum.DEL_FALSE.key());
//      Map<Long, Boolean> limitMap = this.flowApi.getLimitMap(resultList.stream().map(DrpOrderGoodsPageVO::getProcessInstanceId).toList());
      resultList.forEach((i) -> {
//         i.setCurUserApprove((Boolean)limitMap.get(i.getProcessInstanceId()));
         if (CharSequenceUtil.isNotEmpty(i.getStallId())) {
            String[] split = i.getStallId().split(",");
            i.setStallName(this.allocStallApi.getStallNameByIdSet(Arrays.stream(split).map(Long::valueOf).collect(Collectors.toSet())));
         }

      });
      return resultList;
   }

   public DrpOrderGoodsVO getDrpOrderGoodsInfo(String orderGoodsId) {
      if (ObjectUtil.isEmpty(orderGoodsId)) {
         throw new ServiceException("采购订单号为空");
      } else {
         DrpOrderGoodsVO drpOrderGoodsVO = this.baseMapper.getDrpOrderGoodsInfo(orderGoodsId);
         if (ObjectUtil.isNull(drpOrderGoodsVO)) {
            throw new ServiceException("采购订单不存在");
         } else {
            List<DrpOrderGoodsDetailVO> detailList = this.drpOrderGoodsDetailService.getDrpOrderGoodsDetailVOListByOrderGoodsId(orderGoodsId);
            drpOrderGoodsVO.setDetailList(detailList);
            if (drpOrderGoodsVO.getSupplierId() != null) {
               List<DrpSupplierDeliver> drpSupplierDeliverList = this.drpPurchaseSupplierDeliverMapper.selectList(Wrappers.lambdaQuery(DrpSupplierDeliver.class).eq(DrpSupplierDeliver::getSupplierId, drpOrderGoodsVO.getSupplierId()));
               drpOrderGoodsVO.setDrpSupplierDeliverList(drpSupplierDeliverList);
            }

            DrpOrderGoodsPayStyle drpOrderGoodsPayStyle = this.drpPurchaseOrderGoodsPayStyleMapper.selectOne(Wrappers.lambdaQuery(DrpOrderGoodsPayStyle.class).eq(DrpOrderGoodsPayStyle::getOrderGoodsId, orderGoodsId));
            DrpOrderGoodsPayStyleVO drpOrderGoodsPayStyleVO = new DrpOrderGoodsPayStyleVO();
            BeanUtil.copyProperties(drpOrderGoodsPayStyle, drpOrderGoodsPayStyleVO, new String[0]);
            drpOrderGoodsVO.setDrpOrderGoodsPayStyleVO(drpOrderGoodsPayStyleVO);
            return drpOrderGoodsVO;
         }
      }
   }

   public void deleteDrpOrderGoods(String orderGoodsId) {
      if (ObjectUtil.isEmpty(orderGoodsId)) {
         throw new ServiceException("采购订单号为空");
      } else {
         DrpOrderGoods drpOrderGoods = this.getDrpOrderGoodsStatusById(orderGoodsId);
         if (drpOrderGoods.isDeleteStatus()) {
            throw new ServiceException("采购订单状态错误，不能删除");
         } else {
            ((DrpPurchaseOrderGoodsMapper)this.baseMapper).update(null, (Wrappers.lambdaUpdate(DrpOrderGoods.class).set(DrpOrderGoods::getDelFlag, DelFlagEnum.DEL_TRUE.key())).eq(DrpOrderGoods::getOrderGoodsId, orderGoodsId));
            this.drpProductionPurchaseOrderMapper.delete((Wrappers.lambdaQuery(DrpProductionPurchaseOrder.class).eq(DrpProductionPurchaseOrder::getOrderGoodsId, orderGoodsId)).eq(DrpProductionPurchaseOrder::getOrderType, 2));
         }
      }
   }

//   public List<DrpOrderGoodsPageVO> getDrpOrderGoodsSupplierList(DrpOrderGoodsPageDTO content) {
//      Long userId = (Long)SecureManager.getSubjectId().get();
//      return ((DrpOrderGoodsMapper)this.baseMapper).getDrpOrderGoodsSupplierList(content, DelFlagEnum.DEL_FALSE.key(), userId, DrpApproveStatusEnum.AGREE_APPROVE.key());
//   }
//
//   @Transactional(
//      rollbackFor = {Exception.class}
//   )
//   public DrpOrderGoodsAddVO updateSupplierConfirm(DrpOrderGoodsSupplierConfirmDTO content) {
//      ((DrpOrderGoodsMapper)this.baseMapper).update((Object)null, (Wrapper)((LambdaUpdateWrapper)((LambdaUpdateWrapper)((LambdaUpdateWrapper)Wrappers.lambdaUpdate(DrpOrderGoods.class).eq(DrpOrderGoods::getOrderGoodsId, content.getOrderGoodsId())).set(DrpOrderGoods::getSupplierConfirmStatus, content.getSupplierConfirmStatus())).set(DrpOrderGoods::getConfirmRemark, content.getConfirmRemark())).set(DrpOrderGoods::getConfirmTime, LocalDateTime.now()));
//      if (ObjectUtil.equal(content.getSupplierConfirmStatus(), DrpSupplierConfirmStatusEnum.IS_REJECT.getKey())) {
//         ((DrpOrderGoodsMapper)this.baseMapper).update((Object)null, (Wrapper)((LambdaUpdateWrapper)((LambdaUpdateWrapper)((LambdaUpdateWrapper)((LambdaUpdateWrapper)Wrappers.lambdaUpdate(DrpOrderGoods.class).eq(DrpOrderGoods::getOrderGoodsId, content.getOrderGoodsId())).set(DrpOrderGoods::getOrderStatus, DrpOrderGoodsStatusEnum.WAIT_COMMIT.getKey())).set(DrpOrderGoods::getApproveStatus, DrpApproveStatusEnum.WAIT_APPROVE.key())).set(DrpOrderGoods::getConfirmRemark, content.getConfirmRemark())).set(DrpOrderGoods::getConfirmTime, LocalDateTime.now()));
//      }
//
//      if (ObjectUtil.equal(content.getSupplierConfirmStatus(), DrpSupplierConfirmStatusEnum.CONFIRM_PASS.getKey())) {
//         ((Map)this.drpOrderGoodsDetailMapper.selectList((Wrapper)Wrappers.lambdaQuery(DrpOrderGoodsDetail.class).eq(DrpOrderGoodsDetail::getOrderGoodsId, content.getOrderGoodsId())).stream().collect(Collectors.toMap(DrpOrderGoodsDetail::getMaterialId, Function.identity(), (k1, k2) -> {
//            return k1;
//         }))).values().forEach((detail) -> {
//            this.drpMaterialLatestPriceService.addMaterialLatestPrice(DrpMaterialLatestPriceDTO.builder().materialId(detail.getMaterialId()).unitId(detail.getUnitId()).priceType(DrpMaterialPriceTypeEnum.MATERIAL_ORDER_GOODS.key()).latestPrice(detail.getSinglePrice()).relatedId(detail.getOrderGoodsId()).remark(DrpMaterialPriceTypeEnum.MATERIAL_ORDER_GOODS.value()).build());
//         });
//      }
//
//      DrpOrderGoodsAddVO result = new DrpOrderGoodsAddVO();
//      result.setOrderGoodsId(content.getOrderGoodsId());
//      return result;
//   }

   public void cancelPurOrder(String orderGoodsId) {
      if (ObjectUtil.isEmpty(orderGoodsId)) {
         throw new ServiceException("采购订单号为空");
      } else {
         Long checkIfOperate = this.baseMapper.selectCount((Wrappers.lambdaQuery(DrpOrderGoods.class).eq(DrpOrderGoods::getOrderGoodsId, orderGoodsId)).and((wrapper) -> {
            ((wrapper.eq(DrpOrderGoods::getIfDismantle, LeConstants.COMMON_YES)).or()).gt(DrpOrderGoods::getTotalIntoNum, BigDecimal.ZERO);
         }));
         if (checkIfOperate > 0L) {
            throw new ServiceException("订单已被拆解或入库，无法撤销");
         } else {
            this.baseMapper.update(null, (((Wrappers.lambdaUpdate(DrpOrderGoods.class).eq(DrpOrderGoods::getOrderGoodsId, orderGoodsId)).set(DrpOrderGoods::getOrderStatus, DrpOrderGoodsStatusEnum.WAIT_COMMIT.getKey())).set(DrpOrderGoods::getSupplierConfirmStatus, DrpSupplierConfirmStatusEnum.WAIT_CONFIRM.getKey())).set(DrpOrderGoods::getApproveStatus, DrpApproveStatusEnum.WAIT_APPROVE.key()));
         }
      }
   }

//   public void importOrderGoodsExcel(MultipartFile excel) {
//      String redisKey = "yst:merchant-id:order:goods: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 ImportOrderGoodsExcelDTO(), 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<ImportOrderGoodsExcelDTO> finalImportOrderExcelList = new ArrayList();
//         Iterator var6 = importOrderGoodsExcelDTOList.iterator();
//
//         while(var6.hasNext()) {
//            ImportOrderGoodsExcelDTO i = (ImportOrderGoodsExcelDTO)var6.next();
//            if (CharSequenceUtil.isBlank(i.getMaterialCode()) && CharSequenceUtil.isBlank(i.getMaterialName()) && CharSequenceUtil.isBlank(i.getSupplierName()) && ObjectUtil.isEmpty(i.getUnitPrice()) && ObjectUtil.isEmpty(i.getPurNum()) && ObjectUtil.isEmpty(i.getWarehouseName()) && ObjectUtil.isEmpty(i.getRequestArrivalTime())) {
//               throw new LeException("Excel中包含空白行，请检查并删除空白行！");
//            }
//
//            if (CharSequenceUtil.isBlank(i.getMaterialCode()) || CharSequenceUtil.isBlank(i.getMaterialName()) || CharSequenceUtil.isBlank(i.getSupplierName()) || ObjectUtil.isEmpty(i.getUnitPrice()) || ObjectUtil.isEmpty(i.getPurNum()) || ObjectUtil.isEmpty(i.getWarehouseName()) || ObjectUtil.isEmpty(i.getRequestArrivalTime()) || ObjectUtil.isEmpty(i.getCanteenName()) || ObjectUtil.isEmpty(i.getStallName())) {
//               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.importOrderGoodsBuss(finalImportOrderExcelList, redisKey);
//         });
//      }
//   }

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

//   public List<DrpOrderGoodsManagePageVO> getOrderGoodsManagers(DrpOrderGoodsManagePageDTO page) {
//      if (CharSequenceUtil.isNotBlank(page.getOrderGoodsId())) {
//         page.setOrderGoodsId(LeBeanUtil.fieldLikeHandle(page.getOrderGoodsId()));
//      }
//
//      PageMethod.startPage(page);
//      return Objects.equals(LeConstants.COMMON_YES, page.getIfPay()) ? this.drpOrderGoodsPayMapper.getOrderGoodsPayList(page, DrpOrderGoodsPayAndRefundTypeEnum.PAY_OR_REFUND.key()) : this.drpOrderGoodsRefundMapper.getOrderGoodsRefundList(page, DrpOrderGoodsPayAndRefundTypeEnum.PAY_OR_REFUND.key());
//   }

//   public DrpOrderGoodsManageDetailVO getOrderGoodsDetail(DrpOrderGoodsDetailDTO content) {
//      return Objects.equals(LeConstants.COMMON_YES, content.getIfPay()) ? this.drpOrderGoodsPayMapper.getOrderGoodsPayDetail(content.getId()) : this.drpOrderGoodsRefundMapper.getOrderGoodsRefundDetail(content.getId());
//   }

//   public DrpOrderGoodsManageTotalVO getTotal(DrpOrderGoodsManagePageDTO content) {
//      if (CharSequenceUtil.isNotBlank(content.getOrderGoodsId())) {
//         content.setOrderGoodsId(LeBeanUtil.fieldLikeHandle(content.getOrderGoodsId()));
//      }
//
//      return Objects.equals(LeConstants.COMMON_YES, content.getIfPay()) ? this.drpOrderGoodsPayMapper.getOrderGoodsPayTotal(content, DrpOrderGoodsPayAndRefundTypeEnum.PAY_OR_REFUND.key()) : this.drpOrderGoodsRefundMapper.getOrderGoodsRefundTotal(content, DrpOrderGoodsPayAndRefundTypeEnum.PAY_OR_REFUND.key());
//   }

//   public void mergeExport(List<String> content, HttpServletResponse response) {
//      if (CollUtil.isEmpty(content)) {
//         throw new LeException("请选择采购订单！");
//      } else {
//         List<DrpOrderGoodsExportVO> drpOrderGoodsExportVOList = this.drpOrderGoodsMapper.getOrderGoodsMaterialListByOrderIdList(content);
//         List<DrpOrderGoodsExportVO> exportVOList = Lists.newArrayList();
//         if (CollUtil.isNotEmpty(drpOrderGoodsExportVOList)) {
//            Map<String, DrpOrderGoodsExportVO> exportVOMap = (Map)drpOrderGoodsExportVOList.stream().collect(Collectors.toMap((excelVO) -> {
//               Long var10000 = excelVO.getMaterialId();
//               return "" + var10000 + "-" + excelVO.getStallId();
//            }, Function.identity(), (key1, key2) -> {
//               key1.setOrderNum(key1.getOrderNum().add(key2.getOrderNum()));
//               key1.setTotalPrice(key1.getTotalPrice() + key2.getTotalPrice());
//               return key1;
//            }));
//            exportVOMap.forEach((key, drpOrderGoodsExportVOx) -> {
//               exportVOList.add(drpOrderGoodsExportVOx);
//            });
//            DrpOrderGoodsExportVO drpOrderGoodsExportVO = new DrpOrderGoodsExportVO();
//            exportVOList.add(new DrpOrderGoodsExportVO());
//            drpOrderGoodsExportVO.setMaterialName("合计");
//            drpOrderGoodsExportVO.setOrderNum((BigDecimal)exportVOList.stream().map(DrpOrderGoodsExportVO::getOrderNum).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add));
//            drpOrderGoodsExportVO.setTotalPrice(exportVOList.stream().filter((d) -> {
//               return d.getTotalPrice() != null;
//            }).mapToInt(DrpOrderGoodsExportVO::getTotalPrice).sum());
//            exportVOList.add(drpOrderGoodsExportVO);
//         }
//
//         try {
//            File tempFile = File.createTempFile("采购订单明细", ".xlsx");
//            net.xnzn.core.common.utils.EasyExcelUtil.writeExcelMerge(response, "采购订单明细", DrpOrderGoodsExportVO.class, exportVOList, "采购订单明细", (List)null, tempFile);
//            this.exportApi.createRecord("采购订单明细", ExportFileTypeEnum.EXCEL, false, (LocalDateTime)null, tempFile);
//         } catch (Exception var7) {
//            throw new LeException("导出错误:" + var7.getMessage());
//         }
//      }
//   }

//   public void importOrderGoodsBuss(List<ImportOrderGoodsExcelDTO> finalImportOrderExcelList, String redisKey) {
//      List<DrpImportFailMaterial> failMaterialList = new ArrayList();
//      Map<String, List<ImportOrderGoodsExcelDTO>> supplierMap = (Map)finalImportOrderExcelList.stream().collect(Collectors.groupingBy(ImportOrderGoodsExcelDTO::getSupplierName));
//      DrpImportRecord drpImportRecord = new DrpImportRecord();
//      Long importRecordId = Id.next();
//      drpImportRecord.setImportRecordId(importRecordId);
//      drpImportRecord.setImportType(DrpImportTypeEnum.PUR.key());
//      drpImportRecord.setImportTime(LocalDateTime.now());
//      drpImportRecord.setImportResult(DrpImportResultEnum.SUCCESS.key());
//      supplierMap.forEach((key, value) -> {
//         DrpOrderGoodsSaveDTO dto = new DrpOrderGoodsSaveDTO();
//
//         try {
//            ImportOrderGoodsExcelDTO importOrderGoodsExcelDTO = (ImportOrderGoodsExcelDTO)value.get(0);
//            DeductCanteenStallVO deductCanteenStallVO = this.allocCanteenApi.queryCanteenStallByName(importOrderGoodsExcelDTO.getCanteenName(), importOrderGoodsExcelDTO.getStallName());
//            if (ObjectUtil.isNull(deductCanteenStallVO)) {
//               throw new LeException("食堂档口不存在！");
//            }
//
//            AllocCanteen allocCanteen = this.allocCanteenApi.getAllocCanteen(deductCanteenStallVO.getCanteenId());
//            DrpSupplier drpSupplier = (DrpSupplier)this.drpSupplierMapper.selectOne(((LambdaQueryWrapper)((LambdaQueryWrapper)((LambdaQueryWrapper)Wrappers.lambdaQuery(DrpSupplier.class).eq(DrpSupplier::getSupplierName, key)).eq(allocCanteen.getAreaId() != null, DrpSupplier::getAreaId, allocCanteen.getAreaId())).eq(DrpSupplier::getDelFlag, DelFlagEnum.DEL_FALSE.key())).select(new SFunction[]{DrpSupplier::getSupplierId}));
//            if (null == drpSupplier) {
//               throw new LeException("供应商不存在");
//            }
//
//            long count = value.stream().map(ImportOrderGoodsExcelDTO::getCanteenName).filter(Objects::nonNull).distinct().count();
//            long count1 = value.stream().map(ImportOrderGoodsExcelDTO::getStallName).filter(Objects::nonNull).distinct().count();
//            if (count > 1L || count1 > 1L) {
//               throw new LeException("只支持一个食堂和一个档口的采购订单导入！");
//            }
//
//            dto.setSupplierId(drpSupplier.getSupplierId());
//            dto.setRequestArrivalTime(DrpDateUtil.stringToLocalDateByPatt(importOrderGoodsExcelDTO.getRequestArrivalTime(), "yyyyMMdd"));
//            dto.setSupplyAddress(importOrderGoodsExcelDTO.getSupplyAddress());
//            DrpWarehouse drpWarehouse = (DrpWarehouse)this.drpWarehouseMapper.selectOne(((LambdaQueryWrapper)((LambdaQueryWrapper)((LambdaQueryWrapper)((LambdaQueryWrapper)Wrappers.lambdaQuery(DrpWarehouse.class).eq(DrpWarehouse::getWarehouseName, importOrderGoodsExcelDTO.getWarehouseName())).eq(DrpWarehouse::getDelFlag, DelFlagEnum.DEL_FALSE.key())).eq(DrpWarehouse::getAreaId, allocCanteen.getAreaId())).eq(DrpWarehouse::getStatus, DelFlagEnum.DEL_FALSE.key())).select(new SFunction[]{DrpWarehouse::getWarehouseId}));
//            if (ObjectUtil.isEmpty(drpWarehouse)) {
//               throw new LeException(I18n.getMessage("drp.no-warehouse", new Object[0]));
//            }
//
//            dto.setWarehouseId(drpWarehouse.getWarehouseId());
//            List<DrpOrderGoodsDetailSaveDTO> detailList = new ArrayList();
//            Iterator var17 = value.iterator();
//
//            while(var17.hasNext()) {
//               ImportOrderGoodsExcelDTO orderGoodsExcelDTO = (ImportOrderGoodsExcelDTO)var17.next();
//               MenuMaterial menuMaterial = (MenuMaterial)this.menuMaterialMapper.selectOne((Wrapper)((LambdaQueryWrapper)Wrappers.lambdaQuery(MenuMaterial.class).eq(MenuMaterial::getMaterialCode, orderGoodsExcelDTO.getMaterialCode())).eq(MenuMaterial::getDelFlag, LeConstants.COMMON_NO));
//               if (null == menuMaterial) {
//                  throw new LeException(orderGoodsExcelDTO.getMaterialName() + "货品不存在！");
//               }
//
//               if (!Objects.equals(menuMaterial.getMaterialName(), orderGoodsExcelDTO.getMaterialName())) {
//                  throw new LeException(orderGoodsExcelDTO.getMaterialName() + "货品名称与编码不对应！");
//               }
//
//               dto.setCanteenId(deductCanteenStallVO.getCanteenId());
//               DrpOrderGoodsDetailSaveDTO detailSaveDTO = new DrpOrderGoodsDetailSaveDTO();
//               detailSaveDTO.setMaterialId(menuMaterial.getMaterialId());
//               detailSaveDTO.setUnitId(menuMaterial.getUnitId());
//               detailSaveDTO.setOrderNum(orderGoodsExcelDTO.getPurNum());
//               detailSaveDTO.setSinglePrice(orderGoodsExcelDTO.getUnitPrice().multiply(new BigDecimal(100)));
//               detailSaveDTO.setTotalPrice(orderGoodsExcelDTO.getUnitPrice().multiply(orderGoodsExcelDTO.getPurNum()).multiply(new BigDecimal(100)));
//               detailSaveDTO.setStallId(deductCanteenStallVO.getStallId());
//               detailList.add(detailSaveDTO);
//            }
//
//            dto.setStallId((String)detailList.stream().map((d) -> {
//               return String.valueOf(d.getStallId());
//            }).distinct().collect(Collectors.joining(",")));
//            dto.setDetailList(detailList);
//            if (CollUtil.isNotEmpty(dto.getDetailList())) {
//               this.drpOrderGoodsService.addSaveDrpOrderGoods(dto);
//            }
//         } catch (Exception var24) {
//            log.error("导入采购订单失败:{}", var24.getMessage());
//            DrpImportFailMaterial drpImportFailMaterial = new DrpImportFailMaterial();
//            drpImportFailMaterial.setImportRecordId(Id.next());
//            drpImportFailMaterial.setFailReason(var24.getMessage());
//            failMaterialList.add(drpImportFailMaterial);
//            drpImportRecord.setImportRecordId(drpImportFailMaterial.getImportRecordId());
//            drpImportRecord.setImportResult(DrpImportResultEnum.FAIL.key());
//            dto.setDetailList((List)null);
//            drpImportRecord.setErrorReason(var24.getMessage());
//            throw new LeException("系统异常:" + var24.getMessage());
//         } finally {
//            this.stringRedisTemplate.delete(redisKey);
//            this.drpImportRecordMapper.insert(drpImportRecord);
//            this.drpImportFailMaterialService.saveBatch(failMaterialList);
//         }
//
//      });
//   }

   protected DrpOrderGoods getDrpOrderGoodsStatusById(String orderGoodsId) {
      DrpOrderGoods drpOrderGoods = this.baseMapper.selectOne((Wrappers.lambdaQuery(DrpOrderGoods.class).select(DrpOrderGoods::getOrderGoodsId, DrpOrderGoods::getOrderStatus).eq(DrpOrderGoods::getOrderGoodsId, orderGoodsId)).eq(DrpOrderGoods::getDelFlag, DelFlagEnum.DEL_FALSE.key()));
      if (ObjectUtil.isNull(drpOrderGoods)) {
         throw new ServiceException("采购订单不存在");
      } else {
         return drpOrderGoods;
      }
   }
}
