From 781c5f73033ad1ae8c350210c46b4e24925d427b Mon Sep 17 00:00:00 2001
From: liding <756868258@qq.com>
Date: 星期四, 17 九月 2026 17:29:16 +0800
Subject: [PATCH] fix:委托编号更改

---
 inspect-server/src/main/java/com/ruoyi/inspect/service/impl/InsOrderServiceImpl.java |  884 ++++++++++++++++++++++++++++++++++++++++++++++++----------
 1 files changed, 733 insertions(+), 151 deletions(-)

diff --git a/inspect-server/src/main/java/com/ruoyi/inspect/service/impl/InsOrderServiceImpl.java b/inspect-server/src/main/java/com/ruoyi/inspect/service/impl/InsOrderServiceImpl.java
index dba348e..d7c0021 100644
--- a/inspect-server/src/main/java/com/ruoyi/inspect/service/impl/InsOrderServiceImpl.java
+++ b/inspect-server/src/main/java/com/ruoyi/inspect/service/impl/InsOrderServiceImpl.java
@@ -13,18 +13,33 @@
 import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
 import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
 import com.baomidou.mybatisplus.core.metadata.IPage;
-import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
+import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
 import com.baomidou.mybatisplus.core.toolkit.Wrappers;
 import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.ruoyi.basic.dto.InventoryDetailDTO;
+import com.ruoyi.basic.dto.StandardTreeTemplateBindingVo;
+import com.ruoyi.basic.dto.TemplateInspectionItemDto;
 import com.ruoyi.basic.mapper.IfsInventoryQuantityMapper;
 import com.ruoyi.basic.mapper.StandardProductListMapper;
+import com.ruoyi.basic.mapper.StructureItemParameterMapper;
 import com.ruoyi.basic.pojo.IfsInventoryQuantity;
 import com.ruoyi.basic.pojo.StandardProductList;
+import com.ruoyi.basic.pojo.StandardMethod;
+import com.ruoyi.basic.pojo.StructureItemParameter;
 import com.ruoyi.basic.pojo.StructureTestObject;
+import com.ruoyi.basic.pojo.StandardTree;
+import com.ruoyi.basic.pojo.StandardTemplate;
+import com.ruoyi.basic.service.StandardTemplateService;
+import com.ruoyi.basic.service.StandardMethodService;
+import com.ruoyi.basic.service.StandardTreeService;
+import com.ruoyi.basic.utils.StandardTreePathParser;
 import com.ruoyi.common.constant.InsOrderTypeConstants;
+import com.ruoyi.common.core.domain.Result;
 import com.ruoyi.common.core.domain.entity.User;
+import com.ruoyi.common.enums.OrderType;
 import com.ruoyi.common.numgen.NumberGenerator;
-import com.ruoyi.common.utils.*;
+import com.ruoyi.common.utils.QueryWrappers;
+import com.ruoyi.common.utils.SecurityUtils;
 import com.ruoyi.common.utils.api.IfsApiUtils;
 import com.ruoyi.framework.exception.ErrorException;
 import com.ruoyi.inspect.dto.*;
@@ -34,14 +49,16 @@
 import com.ruoyi.inspect.service.InsOrderStateService;
 import com.ruoyi.inspect.service.InsProductService;
 import com.ruoyi.inspect.service.InsSampleService;
+import com.ruoyi.inspect.vo.IfsOrderVO;
 import com.ruoyi.inspect.vo.InsOrderPrintingVo;
-import com.ruoyi.performance.pojo.AuxiliaryOutputWorkingHoursTemporary;
-import com.ruoyi.performance.service.AuxiliaryOutputWorkingHoursTemporaryService;
+import com.ruoyi.inspect.vo.OrderTemplateSummaryVo;
+import com.ruoyi.inspect.vo.TemplateConditionVo;
 import com.ruoyi.system.mapper.UserMapper;
 import lombok.AllArgsConstructor;
 import org.apache.commons.lang3.StringUtils;
 import org.springframework.beans.BeanUtils;
 import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Isolation;
 import org.springframework.transaction.annotation.Transactional;
 
 import javax.servlet.http.HttpServletResponse;
@@ -67,6 +84,8 @@
 public class InsOrderServiceImpl extends ServiceImpl<InsOrderMapper, InsOrder>
         implements InsOrderService {
 
+    private static final String DIRECT_TEMPLATE_LABORATORY = "鏂拌仛";
+
     private InsOrderMapper insOrderMapper;
     private InsSampleService insSampleService;
     private InsSampleMapper insSampleMapper;
@@ -82,14 +101,18 @@
     private IfsApiUtils ifsApiUtils;
     private SpotCheckQuarterItemMapper spotCheckQuarterItemMapper;
     private StandardProductListMapper standardProductListMapper;
-    private AuxiliaryOutputWorkingHoursTemporaryService auxiliaryOutputWorkingHoursTemporaryService;
+    private StructureItemParameterMapper structureItemParameterMapper;
+    private StandardTreeService standardTreeService;
+    private StandardMethodService standardMethodService;
+    private StandardTemplateService standardTemplateService;
+    private InsOrderStandardTemplateMapper insOrderStandardTemplateMapper;
+    private InsOrderTemplateDeviceMapper insOrderTemplateDeviceMapper;
 
 
 
     //鑾峰彇妫�楠屼笅鍗曟暟鎹�
     @Override
     public IPage<SampleOrderDto> selectInsOrderParameter(IPage<InsOrder> page, SampleOrderDto sampleOrderDto) {
-        //todo: 鍙湅鎴戝垽鏂叏閮�,涓汉,缁勭粐鐨勬潈闄�
         String laboratory = null;
         // 鍒ゆ柇鏄惁鏄叏閮�
         String isOrderAll = null;
@@ -116,36 +139,52 @@
         insOrderMapper.updateById(insOrder);
         List<InsSample> insSamples = insSampleMapper.selectList(Wrappers.<InsSample>lambdaQuery().eq(InsSample::getInsOrderId, orderId));
         List<Integer> ids = insSamples.stream().map(InsSample::getId).collect(Collectors.toList());
-        List<InsProduct> insProducts = insProductMapper.selectList(Wrappers.<InsProduct>lambdaQuery()
-                .in(InsProduct::getInsSampleId, ids)
-                .eq(InsProduct::getState, 1)
-                .select(InsProduct::getSonLaboratory).groupBy(InsProduct::getSonLaboratory));
+        List<InsProduct> insProducts = ids.isEmpty()
+                ? Collections.emptyList()
+                : insProductMapper.selectList(Wrappers.<InsProduct>lambdaQuery()
+                        .in(InsProduct::getInsSampleId, ids)
+                        .eq(InsProduct::getState, 1)
+                        .select(InsProduct::getSonLaboratory).groupBy(InsProduct::getSonLaboratory));
+
+        InsOrder order = insOrderMapper.selectById(orderId);
+        boolean directTemplateOrder = isDirectTemplateOrder(order, insSamples);
+        Set<String> taskLaboratories = directTemplateOrder
+                ? Collections.singleton(DIRECT_TEMPLATE_LABORATORY)
+                : insProducts.stream()
+                        .map(InsProduct::getSonLaboratory)
+                        .filter(StringUtils::isNotBlank)
+                        .collect(Collectors.toCollection(LinkedHashSet::new));
+        if (!directTemplateOrder && taskLaboratories.size() != insProducts.size()) {
+            throw new ErrorException("璇ユ楠屽崟鏈夋湭缁存姢瀹為獙瀹ょ殑妫�楠岄」鐩�");
+        }
 
         // 鎵归噺娣诲姞妫�楠屼换鍔$姸鎬佽〃
-        List<InsOrderState> insOrderStateList = insProducts.stream().map(insProduct -> {
+        List<InsOrderState> insOrderStateList = taskLaboratories.stream()
+                .filter(laboratory -> insOrderStateService.count(Wrappers.<InsOrderState>lambdaQuery()
+                        .eq(InsOrderState::getInsOrderId, orderId)
+                        .eq(InsOrderState::getLaboratory, laboratory)) == 0)
+                .map(laboratory -> {
             InsOrderState insOrderState = new InsOrderState();
             insOrderState.setInsOrderId(orderId);
-            try {
-                insOrderState.setLaboratory(insProduct.getSonLaboratory());
-            } catch (NullPointerException e) {
-                throw new ErrorException("璇ユ楠屽崟鏈夋湭缁存姢瀹為獙瀹ょ殑妫�楠岄」鐩�");
-            }
+            insOrderState.setLaboratory(laboratory);
             insOrderState.setInsState(0);
             return insOrderState;
         }).collect(Collectors.toList());
-        insOrderStateService.saveBatch(insOrderStateList);
+        if (!insOrderStateList.isEmpty()) {
+            insOrderStateService.saveBatch(insOrderStateList);
+        }
 
         if (userId != null) {
             InsSampleUser insSampleUser = new InsSampleUser();
             insSampleUser.setState(0);
             insSampleUser.setUserId(userId);
             insSampleUser.setInsSampleId(orderId);
-            insSampleUser.setSonLaboratory(sonLaboratory);
+            insSampleUser.setSonLaboratory(directTemplateOrder
+                    ? DIRECT_TEMPLATE_LABORATORY : sonLaboratory);
             insSampleUserMapper.insert(insSampleUser);
         }
 
         // 鍒ゆ柇璁㈠崟鏈夋病鏈夌粦瀹氭娊鏍疯鍒�
-        InsOrder order = insOrderMapper.selectById(orderId);
         if (order.getQuarterItemId() != null) {
            // 闇�瑕佹坊鍔犱笅鍙戞椂闂村埌鎶芥牱鏃堕棿, 鍙栨牱浜哄憳灏辨槸妫�娴嬩汉
             SpotCheckQuarterItem spotCheckQuarterItem = spotCheckQuarterItemMapper.selectById(order.getQuarterItemId());
@@ -155,53 +194,25 @@
             spotCheckQuarterItemMapper.updateById(spotCheckQuarterItem);
         }
 
-        // 鍒涘缓宸ユ椂鏆傚瓨
-        // 缂撳瓨鏍峰搧id, 缂栧彿map
-//        addWorkingHoursTemporary(userId, insSamples, ids, order);
-
         return 1;
     }
 
-    /**
-     * 鍒涘缓宸ユ椂鏆傚瓨
-     * @param userId
-     * @param insSamples
-     * @param ids
-     * @param order
-     */
-    private void addWorkingHoursTemporary(Integer userId, List<InsSample> insSamples, List<Integer> ids, InsOrder order) {
-        Map<Integer, String> sampleMap = insSamples.stream().collect(Collectors.toMap(InsSample::getId, InsSample::getSampleCode));
-        List<InsProduct> insProductList = insProductMapper.selectList(Wrappers.<InsProduct>lambdaQuery()
-                .in(InsProduct::getInsSampleId, ids)
-                .eq(InsProduct::getState, 1));
-        List<AuxiliaryOutputWorkingHoursTemporary> outputWorkingHours = insProductList.stream().map(insProduct -> {
-            AuxiliaryOutputWorkingHoursTemporary auxiliaryOutputWorkingHours = new AuxiliaryOutputWorkingHoursTemporary();
-            auxiliaryOutputWorkingHours.setInspectionItemClass(insProduct.getInspectionItemClass());//妫�娴嬮」鍒嗙被
-            auxiliaryOutputWorkingHours.setInspectionItem(insProduct.getInspectionItem());//妫�娴嬬埗椤�
-            auxiliaryOutputWorkingHours.setInspectionItemSubclass(insProduct.getInspectionItemSubclass());//妫�娴嬪瓙椤�
-            auxiliaryOutputWorkingHours.setSample(sampleMap.get(insProduct.getInsSampleId()));//鏍峰搧缂栧彿
-            auxiliaryOutputWorkingHours.setOrderId(order.getId());//璁㈠崟id
-            auxiliaryOutputWorkingHours.setOrderNo(order.getEntrustCode());//闈炲姞鐝鎵樺崟鍙�
-            auxiliaryOutputWorkingHours.setWorkTime(insProduct.getManHour());//闈炲姞鐝伐鏃�
-            auxiliaryOutputWorkingHours.setAmount(1);//闈炲姞鐝暟閲�
-            auxiliaryOutputWorkingHours.setOutputWorkTime((ObjectUtils.isNotEmpty(auxiliaryOutputWorkingHours.getOvertimeWorkTime()) ? auxiliaryOutputWorkingHours.getOvertimeWorkTime() : BigDecimal.ZERO).add(ObjectUtils.isNotEmpty(auxiliaryOutputWorkingHours.getWorkTime()) ? auxiliaryOutputWorkingHours.getWorkTime() : BigDecimal.ZERO));//浜ч噺宸ユ椂
-            auxiliaryOutputWorkingHours.setManHourGroup(insProduct.getManHourGroup());//宸ユ椂鍒嗙粍
-            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
-            DateTimeFormatter formatters = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
-            auxiliaryOutputWorkingHours.setDateTime(LocalDateTime.now().toLocalDate().atStartOfDay().format(formatters));//鏃ユ湡
-            LocalDateTime localDateTime = LocalDateTime.now();
-            DateTime parse = DateUtil.parse(localDateTime.format(formatter));
-            auxiliaryOutputWorkingHours.setWeekDay(getWeek(localDateTime.format(formatters)));//鏄熸湡
-            auxiliaryOutputWorkingHours.setWeek(String.valueOf(DateUtil.weekOfYear(DateUtil.offsetDay(parse, 1))));//鍛ㄦ
-            auxiliaryOutputWorkingHours.setCheck(userId);//妫�娴嬩汉
-            auxiliaryOutputWorkingHours.setPrice(insProduct.getPrice());//鍗曚环
-            auxiliaryOutputWorkingHours.setSampleId(insProduct.getInsSampleId());//鏍峰搧id
-            auxiliaryOutputWorkingHours.setInsProductId(insProduct.getId());//妫�楠岄」id
-
-            return auxiliaryOutputWorkingHours;
-        }).collect(Collectors.toList());
-        auxiliaryOutputWorkingHoursTemporaryService.saveBatch(outputWorkingHours);
+    private boolean isDirectTemplateOrder(InsOrder order, List<InsSample> samples) {
+        if (order == null || CollectionUtils.isEmpty(samples)) {
+            return false;
+        }
+        Long snapshotCount = insOrderStandardTemplateMapper.selectCount(
+                Wrappers.<InsOrderStandardTemplate>lambdaQuery()
+                        .eq(InsOrderStandardTemplate::getInsOrderId, order.getId()));
+        return snapshotCount > 0 && samples.stream().anyMatch(sample ->
+                sample.getStandardMethodListId() == null
+                        && StringUtils.isBlank(sample.getFactory())
+                        && StringUtils.isBlank(sample.getSampleType())
+                        && StringUtils.isBlank(sample.getModel())
+                        && StringUtils.isBlank(order.getFactory())
+                        && StringUtils.isBlank(order.getSampleType()));
     }
+
 
     public static String getWeek(String dayStr) {
         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@@ -237,6 +248,19 @@
             default:
                 return "鏈煡";
         }
+    }
+
+
+    // 濡傛灉浣犱娇鐢� Java 8+锛屼篃鍙互鐢� Stream API 绠�鍖栦唬鐮侊細
+    public List<StandardProductList> findMissingItemsWithStream(List<StandardProductList> standardList,
+                                                                List<InsProduct> insList) {
+        Set<Integer> insIds = insList.stream()
+                .map(InsProduct::getStructureItemParameterId)
+                .collect(Collectors.toSet());
+
+        return standardList.stream()
+                .filter(product -> !insIds.contains(product.getStructureItemParameterId()))
+                .collect(Collectors.toList());
     }
 
     @Override
@@ -340,9 +364,9 @@
                 }
             }
         });
-        //鏄惁涓哄師鏉愭枡涓嬪崟
-        if (insOrder.getTypeSource() != null && insOrder.getTypeSource().equals(1)) {
-            // 鍘熸潗鏂欎笅鍗�: 濮旀墭浜哄氨鏄姤妫�浜�, 鐢熶骇鍗曚綅灏辨槸渚涘簲鍟嗗崟浣�
+        //鍘熸潗鏂欎笅鍗曟垨澶栬喘鎴愬搧涓嬪崟
+        if (Objects.nonNull(insOrder.getTypeSource())&&Objects.nonNull(insOrder.getIfsInventoryId())) {
+            // 濮旀墭浜哄氨鏄姤妫�浜�, 鐢熶骇鍗曚綅灏辨槸渚涘簲鍟嗗崟浣�
             IfsInventoryQuantity ifsInventoryQuantity = ifsInventoryQuantityMapper.selectById(insOrder.getIfsInventoryId());
             Integer declareUserId = ifsInventoryQuantity.getDeclareUserId();
             User user = userMapper.selectById(declareUserId);
@@ -380,51 +404,195 @@
             upInsOrderOfState(insOrder);
 
             // 鍒嗛厤妫�楠屼汉
-            upInsOrder(insOrder.getId(), null, appointed != null ? appointed.toString() : null, SecurityUtils.getUserId().intValue(), "鍘熸潗鏂�");
+            String sonLaboratory = insOrder.getTypeSource().equals(1)?"鍘熸潗鏂�":"鎴愬搧瀹為獙瀹�";
+            upInsOrder(insOrder.getId(), null, appointed != null ? appointed.toString() : null, SecurityUtils.getUserId().intValue(), sonLaboratory);
 
-            // 鏍规嵁闆朵欢鍙峰垽鏂槸鍚︽槸杈呮潗
-            boolean isRaw = false;
-            StructureTestObject productObject = insOrderMapper.selectProductByPartNo(ifsInventoryQuantity.getPartNo());
-            // 鏌ヨ浜у搧
-            if (productObject != null && StrUtil.isNotBlank(productObject.getObjectType()) && productObject.getObjectType().equals("1")) {
-                isRaw = true;
-            } else {
-            // 鏌ヨ瀵硅薄
-                StructureTestObject testObject = insOrderMapper.selectByPartNo(ifsInventoryQuantity.getPartNo());
-                if (testObject != null && StrUtil.isNotBlank(testObject.getObjectType()) && testObject.getObjectType().equals("1")) {
+            //鏄惁涓哄師鏉愭枡涓嬪崟
+            if(insOrder.getTypeSource().equals(1)){
+                // 鏍规嵁闆朵欢鍙峰垽鏂槸鍚︽槸杈呮潗
+                boolean isRaw = false;
+                StructureTestObject productObject = insOrderMapper.selectProductByPartNo(ifsInventoryQuantity.getPartNo());
+                // 鏌ヨ浜у搧
+                if (productObject != null && StrUtil.isNotBlank(productObject.getObjectType()) && productObject.getObjectType().equals("1")) {
                     isRaw = true;
+                } else {
+                    // 鏌ヨ瀵硅薄
+                    StructureTestObject testObject = insOrderMapper.selectByPartNo(ifsInventoryQuantity.getPartNo());
+                    if (testObject != null && StrUtil.isNotBlank(testObject.getObjectType()) && testObject.getObjectType().equals("1")) {
+                        isRaw = true;
+                    }
                 }
-            }
 
-            if (isRaw) {
-                // 鑾峰彇褰撳墠瀛e害鐨勫紑濮嬫椂闂村拰缁撴潫鏃堕棿
-                LocalDateTime now = LocalDateTime.now();
-                // 鑾峰彇褰撳墠鏈堜唤
-                int month = now.getMonthValue();
-                // 纭畾褰撳墠瀛e害鐨勫紑濮嬫湀浠�
-                int startMonth = (month - 1) / 3 * 3 + 1;
-                // 鏋勯�犲搴︾殑寮�濮嬫椂闂�
-                LocalDateTime startOfQuarter = LocalDateTime.of(now.getYear(), Month.of(startMonth), 1, 0, 0);
-                // 璁$畻涓嬩竴涓搴︾殑寮�濮嬫椂闂�
-                LocalDateTime startOfNextQuarter = startOfQuarter.plusMonths(3);
-                // 璁$畻褰撳墠瀛e害鐨勭粨鏉熸椂闂�
-                LocalDateTime endOfQuarter = startOfNextQuarter.minusSeconds(1);
+                if (isRaw) {
+                    // 鑾峰彇褰撳墠瀛e害鐨勫紑濮嬫椂闂村拰缁撴潫鏃堕棿
+                    LocalDateTime now = LocalDateTime.now();
+                    // 鑾峰彇褰撳墠鏈堜唤
+                    int month = now.getMonthValue();
+                    // 纭畾褰撳墠瀛e害鐨勫紑濮嬫湀浠�
+                    int startMonth = (month - 1) / 3 * 3 + 1;
+                    // 鏋勯�犲搴︾殑寮�濮嬫椂闂�
+                    LocalDateTime startOfQuarter = LocalDateTime.of(now.getYear(), Month.of(startMonth), 1, 0, 0);
+                    // 璁$畻涓嬩竴涓搴︾殑寮�濮嬫椂闂�
+                    LocalDateTime startOfNextQuarter = startOfQuarter.plusMonths(3);
+                    // 璁$畻褰撳墠瀛e害鐨勭粨鏉熸椂闂�
+                    LocalDateTime endOfQuarter = startOfNextQuarter.minusSeconds(1);
 
-                // 鏍规嵁涓嬪崟鐨勮鏍煎瀷鍙峰垽鏂槸鍚︿负瀛e害棣栨鍑虹幇
-                Integer count = ifsInventoryQuantityMapper.selectIsFirst(insOrder.getPartDetail(),
-                        ifsInventoryQuantity.getSupplierName(),
-                        startOfNextQuarter,
-                        endOfQuarter);
+                    // 鏍规嵁涓嬪崟鐨勮鏍煎瀷鍙峰垽鏂槸鍚︿负瀛e害棣栨鍑虹幇
+                    Integer count = ifsInventoryQuantityMapper.selectIsFirst(insOrder.getPartDetail(),
+                            ifsInventoryQuantity.getSupplierName(),
+                            startOfNextQuarter,
+                            endOfQuarter);
 
-                if(count == 0) {
-                    ifsInventoryQuantity.setIsFirst(1);
-                    ifsInventoryQuantityMapper.update(null, Wrappers.<IfsInventoryQuantity>lambdaUpdate()
-                            .eq(IfsInventoryQuantity::getId, insOrder.getIfsInventoryId())
-                            .set(IfsInventoryQuantity::getIsFirst, 1));
+                    if (count == 0) {
+                        ifsInventoryQuantity.setIsFirst(1);
+                        ifsInventoryQuantityMapper.update(null, Wrappers.<IfsInventoryQuantity>lambdaUpdate()
+                                .eq(IfsInventoryQuantity::getId, insOrder.getIfsInventoryId())
+                                .set(IfsInventoryQuantity::getIsFirst, 1));
+                    }
                 }
             }
         }
         return insOrder.getId();
+    }
+
+    /**
+     * 鏂拌仛鏍囧噯搴撶洿缁戞ā鏉跨殑涓嬪崟娴佺▼锛氫竴涓鍗曘�佷竴涓牱鍝侊紝妫�楠岃褰曞畬鍏ㄧ敱妯℃澘鏍囪鐢熸垚銆�
+     */
+    @Override
+    @Transactional(rollbackFor = Exception.class)
+    public int addNewJuInsOrder(InsPlaceOrderDto dto) {
+        if (dto == null || dto.getInsOrder() == null || dto.getStandardTreeId() == null) {
+            throw new ErrorException("涓嬪崟淇℃伅鎴栨爣鍑嗕笉鑳戒负绌�");
+        }
+        String sampleCode = StringUtils.trim(dto.getSampleCode());
+        if (StringUtils.isBlank(sampleCode) || sampleCode.length() < 2) {
+            throw new ErrorException("鏍峰搧缂栧彿涓嶈兘涓虹┖涓斾笉鑳藉皯浜�2浣�");
+        }
+        StandardTree standard = standardTreeService.getById(dto.getStandardTreeId());
+        if (standard == null || StringUtils.isBlank(standard.getSample())
+                || standard.getSampleType() != null || standard.getModel() != null) {
+            throw new ErrorException("璇烽�夋嫨鏍囧噯搴撲簩绾ф爣鍑�");
+        }
+        List<StandardTreeTemplateBindingVo> bindings = standardTreeService.selectTemplateBindings(dto.getStandardTreeId());
+        if (bindings.isEmpty()) {
+            throw new ErrorException("璇ユ爣鍑嗗皻鏈粦瀹氬彲鐢ㄧ殑鍘熷璁板綍妯℃澘");
+        }
+        Map<Integer, StandardTreeTemplateBindingVo> bindingMap = bindings.stream()
+                .collect(Collectors.toMap(StandardTreeTemplateBindingVo::getTemplateId,
+                        binding -> binding, (first, ignored) -> first));
+        List<OrderTemplateSelectionDto> selections = dto.getTemplateList();
+        if (selections == null) {
+            selections = bindings.stream().map(binding -> {
+                OrderTemplateSelectionDto selection = new OrderTemplateSelectionDto();
+                selection.setTemplateId(binding.getTemplateId());
+                selection.setSort(binding.getSort());
+                return selection;
+            }).collect(Collectors.toList());
+        }
+        if (selections.isEmpty()) {
+            throw new ErrorException("璇疯嚦灏戜繚鐣欎竴涓師濮嬭褰曟ā鏉�");
+        }
+        Set<Integer> selectedTemplateIds = new HashSet<>();
+        for (int index = 0; index < selections.size(); index++) {
+            OrderTemplateSelectionDto selection = selections.get(index);
+            if (selection == null || selection.getTemplateId() == null
+                    || !bindingMap.containsKey(selection.getTemplateId())) {
+                throw new ErrorException("鎵�閫夊師濮嬭褰曟ā鏉夸笉灞炰簬褰撳墠鏍囧噯");
+            }
+            if (!selectedTemplateIds.add(selection.getTemplateId())) {
+                throw new ErrorException("鍘熷璁板綍妯℃澘涓嶈兘閲嶅閫夋嫨");
+            }
+            if (selection.getSort() == null) {
+                selection.setSort(index);
+            }
+        }
+        selections.sort(Comparator.comparing(OrderTemplateSelectionDto::getSort)
+                .thenComparing(OrderTemplateSelectionDto::getTemplateId));
+        Map<Integer, Integer> templateSortMap = selections.stream()
+                .collect(Collectors.toMap(OrderTemplateSelectionDto::getTemplateId,
+                        OrderTemplateSelectionDto::getSort));
+        List<TemplateInspectionItemDto> templateItems = standardTreeService
+                .selectTemplateInspectionItems(dto.getStandardTreeId()).stream()
+                .filter(item -> selectedTemplateIds.contains(item.getTemplateId()))
+                .sorted(Comparator
+                        .comparing((TemplateInspectionItemDto item) -> templateSortMap.get(item.getTemplateId()))
+                        .thenComparing(item -> item.getTemplateRowIndex() == null
+                                ? Integer.MAX_VALUE : item.getTemplateRowIndex()))
+                .collect(Collectors.toList());
+
+        StandardMethod standardMethod = standardMethodService.getById(standard.getStandardMethodId());
+        if (standardMethod == null || StringUtils.isBlank(standardMethod.getCode())) {
+            throw new ErrorException("鏍囧噯缂栧彿涓嶅瓨鍦�");
+        }
+        String standardCode = standardMethod.getCode().trim();
+
+        InsOrder order = dto.getInsOrder();
+        order.setId(null);
+        order.setState(0);
+        order.setIsExemption(0);
+        order.setFactory(null);
+        order.setLaboratory(standard.getLaboratory());
+        order.setSampleType(null);
+        order.setSample(standardCode);
+        order.setPrepareUserEn(null);
+        order.setPrepareCode(null);
+        order.setRemarkEn(null);
+        // 鏂拌仛璁㈠崟鐨勭幆澧冩潯浠剁敱妫�楠屼换鍔″~鍐欙紝閬垮厤涓嬪崟妯℃澘鎴栨祻瑙堝櫒缂撳瓨甯﹀叆鏃у�笺��
+        order.setTemperature(null);
+        order.setHumidity(null);
+        insOrderMapper.insert(order);
+
+        InsSample sample = new InsSample();
+        sample.setInsOrderId(order.getId());
+        sample.setSampleCode(sampleCode);
+        sample.setFactory(null);
+        sample.setLaboratory(standard.getLaboratory());
+        sample.setSampleType(null);
+        sample.setSample(standardCode);
+        sample.setModel(null);
+        sample.setQuantity(1);
+        sample.setStandardMethodListId(null);
+        insSampleMapper.insert(sample);
+
+        int productSort = 0;
+        for (TemplateInspectionItemDto item : templateItems) {
+            InsProduct product = new InsProduct();
+            product.setInsSampleId(sample.getId());
+            product.setInspectionItem(item.getInspectionItem());
+            product.setInspectionItemClass("");
+            product.setInspectionItemSubclass("");
+            product.setFactory(null);
+            product.setLaboratory(standard.getLaboratory());
+            product.setSampleType(null);
+            product.setSample(standardCode);
+            product.setModel(null);
+            product.setTemplateId(item.getTemplateId());
+            product.setTemplateRowIndex(item.getTemplateRowIndex());
+            product.setSonLaboratory(DIRECT_TEMPLATE_LABORATORY);
+            product.setState(1);
+            product.setSort(productSort++);
+            insProductMapper.insert(product);
+        }
+        saveTemplateSnapshots(order.getId(), selections);
+        return order.getId();
+    }
+
+    private void saveTemplateSnapshots(Integer orderId, List<OrderTemplateSelectionDto> selections) {
+        for (OrderTemplateSelectionDto selection : selections) {
+            StandardTemplate template = standardTemplateService.getById(selection.getTemplateId());
+            if (template == null) {
+                throw new ErrorException("鍘熷璁板綍妯℃澘涓嶅瓨鍦�");
+            }
+            InsOrderStandardTemplate snapshot = new InsOrderStandardTemplate();
+            snapshot.setInsOrderId(orderId);
+            snapshot.setTemplateId(template.getId());
+            snapshot.setName(template.getName());
+            snapshot.setNumber(template.getNumber());
+            snapshot.setRemark(template.getRemark());
+            snapshot.setThing(template.getThing());
+            snapshot.setSort(selection.getSort());
+            insOrderStandardTemplateMapper.insert(snapshot);
+        }
     }
 
     /**
@@ -468,9 +636,33 @@
             list = insSampleMapper.selectSampleProductListByOrderId2(id);
         }
         Map<String, Object> map1 = insSampleMapper.selectInsOrder(id);
+        List<InsSample> orderSamples = insSampleMapper.selectList(
+                Wrappers.<InsSample>lambdaQuery()
+                        .eq(InsSample::getInsOrderId, id)
+                        .select(InsSample::getSampleCode)
+                        .orderByAsc(InsSample::getId));
+        List<OrderTemplateSummaryVo> templateList = insOrderStandardTemplateMapper.selectList(
+                        Wrappers.<InsOrderStandardTemplate>lambdaQuery()
+                                .eq(InsOrderStandardTemplate::getInsOrderId, id)
+                                .orderByAsc(InsOrderStandardTemplate::getSort,
+                                        InsOrderStandardTemplate::getId))
+                .stream()
+                .map(template -> {
+                    OrderTemplateSummaryVo summary = new OrderTemplateSummaryVo();
+                    summary.setTemplateId(template.getTemplateId());
+                    summary.setName(template.getName());
+                    summary.setNumber(template.getNumber());
+                    summary.setRemark(template.getRemark());
+                    summary.setSort(template.getSort());
+                    return summary;
+                })
+                .collect(Collectors.toList());
         map.put("insOrder", insOrder);
         map.put("sampleProduct", list);
+        // 鏍峰搧缂栧彿鐩存帴浠庢牱鍝佽〃璇诲彇锛屼笉渚濊禆妫�楠岄」鐩叧鑱旀煡璇㈡槸鍚︽湁缁撴灉銆�
+        map.put("sampleCode", orderSamples.isEmpty() ? null : orderSamples.get(0).getSampleCode());
         map.put("insOrderTemplate", map1);
+        map.put("templateList", templateList);
         return map;
     }
 
@@ -484,25 +676,29 @@
         insOrder.setExamineTime(LocalDateTime.now());
         if (insOrder.getState() == 1) {
             //瀹℃牳閫氳繃鎵嶄細鐢熸垚濮旀墭缂栧彿
-            // todo: 妫�楠岀被鍨嬬紪鍙�
             InsOrder order = this.getById(insOrder.getId());
-            String code = "";
-            switch (order.getOrderType()) {
-                case InsOrderTypeConstants.SPOT_CHECK:
-                    code = "C";
-                    break;
-                case InsOrderTypeConstants.CUSTOMER_ORDERED:
-                    code = "W";
-                    break;
-                case InsOrderTypeConstants.ENTER_THE_FACTORY:
-                case InsOrderTypeConstants.QUARTERLY_TEST:
-                    code = "Y";
-                    break;
+            List<InsSample> insSamples = insSampleMapper.selectList(Wrappers.<InsSample>lambdaQuery()
+                    .eq(InsSample::getInsOrderId, insOrder.getId())
+                    .orderByAsc(InsSample::getId));
+            // 濮旀墭缂栧彿鎸夐�佹牱鏃ユ湡鐢熸垚锛涙柊鑱氬崟鏍峰搧璁㈠崟鐨勬湯涓や綅鍙栨牱鍝佺紪鍙锋湯涓や綅銆�
+            // 鍘嗗彶/澶栭儴璁㈠崟鏈~鍐欓�佹牱鏃ユ湡鏃跺洖閫�鍒板綋澶╋紝閬垮厤褰卞搷鍘熸湁娴佺▼銆�
+            LocalDate entrustDate = order.getSampleDate() == null ? LocalDate.now() : order.getSampleDate();
+            String entrustCodePrefix = "LMSY-"
+                    + entrustDate.format(DateTimeFormatter.BASIC_ISO_DATE)
+                    + "-";
+            String no;
+            if (isDirectTemplateOrder(order, insSamples)) {
+                String sampleCode = insSamples.get(0).getSampleCode();
+                if (StringUtils.isBlank(sampleCode) || sampleCode.trim().length() < 2) {
+                    throw new ErrorException("鏍峰搧缂栧彿涓嶈兘涓虹┖涓斾笉鑳藉皯浜�2浣�");
+                }
+                sampleCode = sampleCode.trim();
+                no = entrustCodePrefix + sampleCode.substring(sampleCode.length() - 2);
+            } else {
+                no = numberGenerator.generateNumberWithPrefix(2,
+                        entrustCodePrefix,
+                        InsOrder::getEntrustCode);
             }
-            // 鐢熸垚缂栧彿
-            String no = numberGenerator.generateNumberWithPrefix(3,
-                    "JCZX/ZB-" + code + LimsDateUtil.resetDate(LocalDateTime.now()),
-                    InsOrder::getEntrustCode);
             // 鍒ゆ柇鏄惁鏄搴︽楠�, 鏄搴︽楠屽彇娑堝師鏉愭枡瀛e害妫�楠屼笅鍗�
             if (InsOrderTypeConstants.QUARTERLY_TEST.equals(order.getOrderType())) {
                 ifsInventoryQuantityMapper.update(null,  Wrappers.<IfsInventoryQuantity>lambdaUpdate()
@@ -520,9 +716,6 @@
             }
 
             int count = 1;
-            // 鏌ヨ鏍峰搧琛�
-            List<InsSample> insSamples = insSampleMapper.selectList(Wrappers.<InsSample>lambdaQuery()
-                    .eq(InsSample::getInsOrderId, insOrder.getId()));
             for (InsSample insSample : insSamples) {
                 if (StringUtils.isBlank(insSample.getSampleCode())) {
                     // 濡傛灉鍙湁涓�涓牱鍝佸氨涓嶉渶瑕佹嫾鎺ユ暟瀛�
@@ -544,9 +737,43 @@
     @Override
     public Map<String, Object> getInsOrderAndSample(Integer id, String laboratory) {
         Map<String, Object> map = new HashMap<>();
-        InsOrder insOrder = insOrderMapper.selectById(id);
+//        InsOrder insOrder = insOrderMapper.selectById(id);
+        IfsOrderVO ifsOrderVO = insOrderMapper.selectOrderInfoById(id);
+        Map<Integer, List<Integer>> templateDeviceIds = insOrderTemplateDeviceMapper.selectList(
+                        Wrappers.<InsOrderTemplateDevice>lambdaQuery()
+                                .eq(InsOrderTemplateDevice::getInsOrderId, id)
+                                .orderByAsc(InsOrderTemplateDevice::getSort,
+                                        InsOrderTemplateDevice::getId))
+                .stream().collect(Collectors.groupingBy(
+                        InsOrderTemplateDevice::getTemplateId,
+                        LinkedHashMap::new,
+                        Collectors.mapping(InsOrderTemplateDevice::getDeviceId, Collectors.toList())));
+        List<TemplateConditionVo> templateConditions = insOrderStandardTemplateMapper.selectList(
+                        Wrappers.<InsOrderStandardTemplate>lambdaQuery()
+                                .eq(InsOrderStandardTemplate::getInsOrderId, id)
+                                .select(InsOrderStandardTemplate::getTemplateId,
+                                        InsOrderStandardTemplate::getTemperature,
+                                        InsOrderStandardTemplate::getHumidity,
+                                        InsOrderStandardTemplate::getDetectionTime,
+                                        InsOrderStandardTemplate::getDetectionPlace,
+                                        InsOrderStandardTemplate::getInsResult)
+                                .orderByAsc(InsOrderStandardTemplate::getSort,
+                                        InsOrderStandardTemplate::getId))
+                .stream().map(snapshot -> {
+                    TemplateConditionVo condition = new TemplateConditionVo();
+                    condition.setTemplateId(snapshot.getTemplateId());
+                    condition.setTemperature(snapshot.getTemperature());
+                    condition.setHumidity(snapshot.getHumidity());
+                    condition.setDetectionTime(snapshot.getDetectionTime());
+                    condition.setDetectionPlace(snapshot.getDetectionPlace());
+                    condition.setInsResult(snapshot.getInsResult());
+                    condition.setDeviceIds(templateDeviceIds.getOrDefault(
+                            snapshot.getTemplateId(), Collections.emptyList()));
+                    return condition;
+                }).collect(Collectors.toList());
+        ifsOrderVO.setTemplateConditions(templateConditions);
         List<SampleProductDto> list = insSampleMapper.getInsOrderAndSample(id, laboratory);
-        map.put("insOrder", insOrder);
+        map.put("insOrder", ifsOrderVO);
         map.put("sampleProduct", list);
         //鏌ヨ鎵�鏈夎褰曟ā鐗堝幓閲�
         List<Map<Integer, Object>> list2 = insOrderMapper.selectReportModelByOrderId(id, laboratory);
@@ -578,12 +805,9 @@
      * @return
      */
     @Override
-    public void getIfsOrder() {
-        HashMap<String, Object> map = new HashMap<>();
-        map.put("LOCATION_NO","1302");
-        map.put("STATE_DB","To be Inspected");
+    public void getIfsOrder(Map<String, Object> map,Boolean isSplitOrder) {
         List<Map<String, Object>> inventory = ifsApiUtils.getInventory(JSONUtil.toJsonStr(map));
-        if(inventory.size() == 0) {
+        if(inventory.isEmpty()) {
             return;
         }
         // 杩涜淇濆瓨
@@ -668,12 +892,9 @@
             );
             if(count == 0) {
                 ifsInventoryQuantity.setIsFirst(0);
-                // 鏌ヨ浜т笟閾炬娴嬫暟鎹�
-                String industryChainAttrFields = IndustryChainUtils.getIndustryChainAttrFields(ifsInventoryQuantity.getOrderNo(),
-                        ifsInventoryQuantity.getLineNo(),
-                        ifsInventoryQuantity.getReleaseNo());
-                ifsInventoryQuantity.setIndustryChain(industryChainAttrFields);
-
+                if(isSplitOrder){
+                    ifsInventoryQuantity.setIsSplitOrder(1);
+                }
                 ifsInventoryQuantityMapper.insert(ifsInventoryQuantity);
             }
         }
@@ -750,7 +971,7 @@
      * @param id
      */
     @Transactional
-    public void updateIfsInventoryQuantity(Integer id) {
+    public void updateIfsInventoryQuantity(Long id) {
         ifsInventoryQuantityMapper.update(null, Wrappers.<IfsInventoryQuantity>lambdaUpdate()
                 .set(IfsInventoryQuantity::getIsRegister, 1)
                 .eq(IfsInventoryQuantity::getId, id));
@@ -821,6 +1042,9 @@
         ifsInventoryQuantity.setIsCopper(1);
         ifsInventoryQuantity.setIsQuarter(0);
         ifsInventoryQuantity.setInspectStatus(0);
+        //閾滄潗鏂欎笅鍗曢粯璁ゅ��
+        ifsInventoryQuantity.setOrderType(OrderType.RAW.getValue());
+        ifsInventoryQuantity.setMaterialProp("01Cu");
 
         ifsInventoryQuantity.setQtyArrived(insOrder.getQtyArrived());
         ifsInventoryQuantity.setBuyUnitMeas(insOrder.getBuyUnitMeas());
@@ -830,10 +1054,8 @@
 
         ifsInventoryQuantityMapper.insert(ifsInventoryQuantity);
 
-
         insOrder.setIfsInventoryId(ifsInventoryQuantity.getId());
         insOrder.setState(1);
-
 
         upInsOrderOfState(insOrder);
         upInsOrder(insOrder.getId(), null, appointed != null ? appointed.toString() : null, SecurityUtils.getUserId().intValue(), "鍘熸潗鏂�");
@@ -899,6 +1121,19 @@
     @Override
     @Transactional(rollbackFor = Exception.class)
     public Boolean updateInsOrder(InsOrderUpdateDto insOrderUpdateDto) {
+        InsOrder currentOrder = insOrderMapper.selectById(insOrderUpdateDto.getInsOrder().getId());
+        if (currentOrder == null || !Objects.equals(currentOrder.getState(), 2)) {
+            throw new ErrorException("鍙湁閫�鍥炵殑妫�楠屽崟鍙互淇敼");
+        }
+        boolean hasSelectedProduct = CollectionUtils.isNotEmpty(insOrderUpdateDto.getSampleProduct())
+                && insOrderUpdateDto.getSampleProduct().stream()
+                .filter(sample -> CollectionUtils.isNotEmpty(sample.getInsProduct()))
+                .flatMap(sample -> sample.getInsProduct().stream())
+                .anyMatch(product -> Objects.equals(product.getState(), 1));
+        if (!hasSelectedProduct) {
+            throw new ErrorException("璇疯嚦灏戦�夋嫨涓�涓楠岄」");
+        }
+
         // 淇敼璁㈠崟
         insOrderUpdateDto.getInsOrder().setState(0);
         insOrderUpdateDto.getInsOrder().setTell("");
@@ -906,7 +1141,50 @@
 
         // 淇敼妫�楠岄」
         for (SampleProductDto sampleProductDto : insOrderUpdateDto.getSampleProduct()) {
-            insProductService.updateBatchById(sampleProductDto.getInsProduct());
+            Long sampleCount = insSampleMapper.selectCount(Wrappers.<InsSample>lambdaQuery()
+                    .eq(InsSample::getId, sampleProductDto.getId())
+                    .eq(InsSample::getInsOrderId, insOrderUpdateDto.getInsOrder().getId()));
+            if (sampleCount == 0) {
+                throw new ErrorException("妫�楠屾牱鍝佹暟鎹紓甯�");
+            }
+
+            insSampleService.update(Wrappers.<InsSample>lambdaUpdate()
+                    .eq(InsSample::getId, sampleProductDto.getId())
+                    .set(InsSample::getSpecialStandardMethod, sampleProductDto.getSpecialStandardMethod()));
+
+            List<InsProduct> products = sampleProductDto.getInsProduct();
+            if (CollectionUtils.isEmpty(products)) {
+                continue;
+            }
+
+            Set<Integer> productIds = insProductMapper.selectList(Wrappers.<InsProduct>lambdaQuery()
+                            .eq(InsProduct::getInsSampleId, sampleProductDto.getId()))
+                    .stream()
+                    .map(InsProduct::getId)
+                    .collect(Collectors.toSet());
+            if (products.stream().anyMatch(product -> product.getId() != null && !productIds.contains(product.getId()))) {
+                throw new ErrorException("妫�楠岄」鏁版嵁寮傚父");
+            }
+
+            List<Integer> removedIds = products.stream()
+                    .filter(product -> product.getId() != null && !Objects.equals(product.getState(), 1))
+                    .map(InsProduct::getId)
+                    .collect(Collectors.toList());
+            if (CollectionUtils.isNotEmpty(removedIds)) {
+                insProductService.removeByIds(removedIds);
+            }
+
+            List<InsProduct> existingProducts = products.stream()
+                    .filter(product -> product.getId() != null && Objects.equals(product.getState(), 1))
+                    .collect(Collectors.toList());
+            if (CollectionUtils.isNotEmpty(existingProducts)) {
+                insProductService.updateBatchById(existingProducts);
+            }
+
+            List<InsProduct> newProducts = products.stream()
+                    .filter(product -> product.getId() == null && Objects.equals(product.getState(), 1))
+                    .collect(Collectors.toList());
+            addInsProductMethod(sampleProductDto.getId(), newProducts);
         }
 
         return true;
@@ -922,6 +1200,11 @@
         return insOrderMapper.labelOrderPrinting(ids);
     }
 
+    @Override
+    public List<InventoryDetailDTO> labelOutsideOrderPrinting(List<Integer> ids) {
+        return insOrderMapper.labelOutsideOrderPrinting(ids);
+    }
+
     /**
      * 鏍规嵁鏍峰搧id鏌ヨ妫�楠岄」鏍�
      * @param insSampleId
@@ -933,11 +1216,18 @@
         InsProduct insProduct = insProductMapper.selectOne(Wrappers.<InsProduct>lambdaQuery()
                 .eq(InsProduct::getInsSampleId, insSampleId)
                 .last("limit 1"));
-        String tree = insProduct.getFactory() + " - " +
-                insProduct.getLaboratory() + " - " +
-                insProduct.getSampleType() + " - " +
-                insProduct.getSample() + " - " +
-                insProduct.getModel();
+        String tree;
+        if (insProduct.getSampleType() == null && insProduct.getModel() == null
+                && StringUtils.isNotBlank(insProduct.getLaboratory())
+                && StringUtils.isNotBlank(insProduct.getSample())) {
+            tree = StandardTreePathParser.canonical(insProduct.getLaboratory(), insProduct.getSample());
+        } else {
+            tree = insProduct.getFactory() + " - " +
+                    insProduct.getLaboratory() + " - " +
+                    insProduct.getSampleType() + " - " +
+                    insProduct.getSample() + " - " +
+                    insProduct.getModel();
+        }
         // 鏌ヨ鏍囧噯鏍�
         List<StandardProductList> standardProductLists = standardProductListMapper.selectList(Wrappers.<StandardProductList>lambdaQuery()
                 .eq(StandardProductList::getStandardMethodListId, insProduct.getStandardMethodListId())
@@ -992,16 +1282,21 @@
      */
     @Override
     public void rawAllInsOrderExport(SampleOrderDto sampleOrderDto, HttpServletResponse response) {
-        //鍒ゆ柇鍏ㄩ儴,涓汉,缁勭粐鐨勬潈闄�
-        //todo:浠呯湅鎴戣幏鍙栧綋鍓嶄汉鎵�灞炲疄楠屽id
-        String laboratory = null;
-        // 鍒ゆ柇鏄惁鏄叏閮�
-        String isOrderAll = null;
-        if (sampleOrderDto.getState() != null && sampleOrderDto.getState() == -2) {
-            isOrderAll = "1";
-            sampleOrderDto.setState(null);
+        List<SampleOrderDto> sampleOrderDtoList = new ArrayList<>();
+        if (StringUtils.isNotBlank(sampleOrderDto.getIds())) {
+            List<String> orderIds = StrUtil.split(sampleOrderDto.getIds(), ",");
+            sampleOrderDtoList = insOrderMapper.getInsOrderExportByIds(orderIds);
+        } else {
+            String laboratory = null;
+            // 鍒ゆ柇鏄惁鏄叏閮�
+            String isOrderAll = null;
+            if (sampleOrderDto.getState() != null && sampleOrderDto.getState() == -2) {
+                isOrderAll = "1";
+                sampleOrderDto.setState(null);
+            }
+            sampleOrderDto.setIds(null);
+            sampleOrderDtoList = insOrderMapper.rawAllInsOrderExport(QueryWrappers.queryWrappers(sampleOrderDto), laboratory, isOrderAll);
         }
-        List<SampleOrderDto> sampleOrderDtoList = insOrderMapper.rawAllInsOrderExport(QueryWrappers.queryWrappers(sampleOrderDto), laboratory, isOrderAll);
 
         // 鍒ゆ柇鏄惁鏄笉鍚堟牸, 涓嶅悎鏍兼煡璇笉鍚堟牸椤�
         for (SampleOrderDto orderDto : sampleOrderDtoList) {
@@ -1052,6 +1347,293 @@
                 .set(InsSample::getModel, insSample.getModel()));
     }
 
+    /**
+     * 鏌ヨ褰撳墠鏃堕棿鏄惁娌℃湁璇ユ娴嬮」鐨勬娊鏍疯鍒�
+     * @param sampleList
+     * @param insOrder
+     * @return
+     */
+    @Override
+    public Result judgeNotSpotCheckOrder(List<SampleProductDto> sampleList, InsOrder insOrder) {
+        // todo: 涓嬪崟鍒ゆ柇鎶芥牱璁″垝鐨勫敮涓�鎬�
+        if (insOrder.getQuarterItemId() != null) {
+            Long quarterItemCount = insOrderMapper.selectCount(Wrappers.<InsOrder>lambdaQuery()
+                    .eq(InsOrder::getQuarterItemId, insOrder.getQuarterItemId())
+                    .notIn(InsOrder::getState, -1 ,2 ,3));
+            if (quarterItemCount > 0) {
+                throw new ErrorException("璇ユ娊鏍疯鍒掑凡琚粦瀹氳繃");
+            }
+        }
+
+        // 鍒ゆ柇鏄惁鏄娊鏍锋娴�
+        if (insOrder.getOrderType().equals(InsOrderTypeConstants.SPOT_CHECK)) {
+            Set<String> monthMessageSet = new HashSet<>();
+            Set<String> quarterMessageSet = new HashSet<>();
+            Set<String> yearMessageSet = new HashSet<>();
+
+            String formatTime = "yyyy-MM-dd HH:mm:ss";
+            // 鏌ヨ褰撳墠鎵�鏈夋牱鍝佺殑妫�楠岄」
+            for (SampleProductDto sampleProductDto : sampleList) {
+                List<StandardProductList> standardProductList = getProductTreeBySampleId(sampleProductDto.getId());
+
+                Set<Integer> insIds = sampleProductDto.getInsProduct().stream()
+                        .map(InsProduct::getStructureItemParameterId)
+                        .collect(Collectors.toSet());
+
+                List<StandardProductList> productLists = standardProductList.stream()
+                        .filter(product -> !insIds.contains(product.getStructureItemParameterId()))
+                        .collect(Collectors.toList());
+
+                // 鏌ヨ妫�楠岄」鍩虹琛�, 鏌ヨ鏄惁鏈夋湀搴�, 瀛e害, 骞村害鐨勬楠岄」
+                List<StructureItemParameter> itemParameterList = structureItemParameterMapper.selectList(Wrappers.<StructureItemParameter>lambdaQuery()
+                        .in(StructureItemParameter::getId, productLists.stream().map(StandardProductList::getStructureItemParameterId).collect(Collectors.toList())));
+
+                for (StructureItemParameter item : itemParameterList) {
+                    if (StringUtils.isNotBlank(item.getSpotCheckType())) {
+                        switch (item.getSpotCheckType()) {
+                            case "1": // 鏈堝害
+                                // 鏌ヨ褰撴湀鏄惁鏈夎妫�娴嬮」鐨勬娊鏍疯鍒�
+                                // 褰撴湀寮�濮嬫椂闂�
+                                DateTime monthStart = DateUtil.beginOfMonth(DateUtil.date());
+                                String monthStartTime = monthStart.toString(formatTime);
+                                // 褰撴湀缁撴潫鏃堕棿
+                                DateTime monthEnd = DateUtil.endOfMonth(DateUtil.date());
+                                String monthEndTime = monthEnd.toString(formatTime);
+                                Integer count = insOrderMapper.selectNotSpotCheckOrder(item.getId(), monthStartTime, monthEndTime);
+                                if (count == 0) {
+                                    String monthMessage = item.getInspectionItemClass() +
+                                            item.getInspectionItem() +
+                                            item.getInspectionItemSubclass();
+                                    monthMessageSet.add(monthMessage);
+                                }
+                                break;
+                            case "2": // 瀛e害
+                                DateTime quarterStart = DateUtil.beginOfQuarter(DateUtil.date());
+                                String quarterStartTime = quarterStart.toString(formatTime);
+                                // 褰撴湀缁撴潫鏃堕棿
+                                DateTime quarterEnd = DateUtil.endOfQuarter(DateUtil.date());
+                                String quarterEndTime = quarterEnd.toString(formatTime);
+                                Integer quarterCount = insOrderMapper.selectNotSpotCheckOrder(item.getId(), quarterStartTime, quarterEndTime);
+                                if (quarterCount == 0) {
+                                    String quarterMessage = item.getInspectionItemClass() +
+                                            item.getInspectionItem() +
+                                            item.getInspectionItemSubclass();
+                                    quarterMessageSet.add(quarterMessage);
+                                }
+
+                                break;
+                            case "3": // 骞村害
+                                DateTime yearStart = DateUtil.beginOfQuarter(DateUtil.date());
+                                String yearStartTime = yearStart.toString(formatTime);
+                                // 褰撴湀缁撴潫鏃堕棿
+                                DateTime yearEnd = DateUtil.endOfQuarter(DateUtil.date());
+                                String yearEndTime = yearEnd.toString(formatTime);
+                                Integer yearCount = insOrderMapper.selectNotSpotCheckOrder(item.getId(), yearStartTime, yearEndTime);
+                                if (yearCount == 0) {
+                                    String yearMessage = item.getInspectionItemClass() +
+                                            item.getInspectionItem() +
+                                            item.getInspectionItemSubclass();
+                                    yearMessageSet.add(yearMessage);
+                                }
+
+                                break;
+                        }
+                    }
+                }
+            }
+
+            String message = "";
+            if (CollectionUtils.isNotEmpty(monthMessageSet)) {
+                message += StrUtil.format("<p>妫�楠岄」<span style=\"color: red\">{}</span>褰撴湀杩樻湭杩涜鎶芥牱妫�娴�, 璇锋煡鐪嬫槸鍚﹂渶瑕佹坊鍔犲綋鍓嶆楠岄」</p>", CollUtil.join(monthMessageSet, ", "));
+            }
+
+            if (CollectionUtils.isNotEmpty(quarterMessageSet)) {
+                message += StrUtil.format("<p>妫�楠岄」<span style=\"color: red\">{}</span>褰撳墠瀛e害杩樻湭杩涜鎶芥牱妫�娴�, 璇风湅鏄惁闇�瑕佹坊鍔犲綋鍓嶆楠岄」</p>", CollUtil.join(quarterMessageSet, ", "));
+            }
+
+            if (CollectionUtils.isNotEmpty(yearMessageSet)) {
+                message += StrUtil.format("<p>妫�楠岄」<span style=\"color: red\">{}</span>浠婂勾杩樻湭杩涜鎶芥牱妫�娴�, 璇风湅鏄惁闇�瑕佹坊鍔犲綋鍓嶆楠岄」</p>", CollUtil.join(yearMessageSet, ", "));
+            }
+
+            if (StringUtils.isNotBlank(message)) {
+                return Result.success(false, message);
+            }
+        }
+        return Result.success(true);
+
+    }
+
+    /**
+     * ifs绉诲簱鎿嶄綔
+     * @param inventoryQuantity
+     * @return
+     */
+    @Override
+    @Transactional(rollbackFor = Exception.class,isolation = Isolation.READ_COMMITTED)
+    public String moveRawMaterial(IfsInventoryQuantity inventoryQuantity) {
+        //鏌ヨifs璁㈠崟璇︽儏
+        IfsInventoryQuantity one = ifsInventoryQuantityMapper.selectById(inventoryQuantity.getId());
+        String toLocation;
+        // 鐧昏閲囪喘妫�楠岀粨鏋淪TD
+        if (one.getIsRegister().equals(0)) {
+            Map<String, Object> resultMap = new HashMap<>();
+            List<Map<String, Object>> resultList = new ArrayList<>();
+            Map<String, Object> map = new HashMap<>();
+            map.put("ORDER_NO", one.getOrderNo()); // 閲囪喘璁㈠崟鍙�
+            map.put("LINE_NO", one.getLineNo()); // 琛屽彿
+            map.put("RELEASE_NO", one.getReleaseNo()); // 涓嬭揪鍙�
+            map.put("RECEIPT_NO", one.getReceiptNo()); // 鎺ユ敹鍙�
+            map.put("PURCH_QTY", one.getQtyToInspect()); // 瑕佹楠岀殑閲囪喘鏁伴噺
+            resultList.add(map);
+            resultMap.put("RECORD_ID", UUID.randomUUID().toString());
+            resultMap.put("SYSCODE", "LIMS");
+            resultMap.put("SYSMODEL", "鐧昏閲囪喘妫�楠岀粨鏋�");
+            resultMap.put("BATCH_INFO", resultList);
+            Result result = ifsApiUtils.getProcurementResults(JSONUtil.toJsonStr(resultMap));
+            if (result.getCode() != 200) {
+                throw new ErrorException("IFS鐧昏閲囪喘妫�楠岀粨鏋滃け璐�: " + result.getMessage());
+            }
+            //濡傛灉鏄媶鍒嗚鍗曪紝鍒欏皢鍚屼竴鎺ユ敹鍙风殑璁㈠崟鏍囪宸茬櫥璁版牎楠�
+            if(one.getIsSplitOrder()==1){
+                //鏌ヨ鍏朵綑鎷嗗垎鐨勮鍗�
+                List<IfsInventoryQuantity> quantityList = ifsInventoryQuantityMapper.selectList(Wrappers.<IfsInventoryQuantity>lambdaQuery()
+                        .eq(IfsInventoryQuantity::getOrderNo, one.getOrderNo())
+                        .eq(IfsInventoryQuantity::getPartNo, one.getPartNo())
+                        .eq(IfsInventoryQuantity::getLineNo, one.getLineNo())
+                        .eq(IfsInventoryQuantity::getReleaseNo, one.getReleaseNo())
+                        .eq(IfsInventoryQuantity::getReceiptNo, one.getReceiptNo())
+                        .eq(IfsInventoryQuantity::getIsSplitOrder, 1)
+                );
+                if(Objects.nonNull(quantityList) && !quantityList.isEmpty()){
+                    //淇敼閲囪喘璁㈠崟鐧昏鐘舵��
+                    List<Long> ids = quantityList.stream().map(IfsInventoryQuantity::getId).collect(Collectors.toList());
+                    ifsInventoryQuantityMapper.update(null,Wrappers.<IfsInventoryQuantity>lambdaUpdate()
+                            .set(IfsInventoryQuantity::getIsRegister,1)
+                            .in(IfsInventoryQuantity::getId, ids)
+                    );
+                }
+            }else{
+                this.updateIfsInventoryQuantity(one.getId());
+            }
+        }
+        /**
+         * TODO 鍚庣画闇�瑕佽皟鐢↖FS鐨勬帴鍙� 绉诲叆鐨勫簱浣嶅彿 toLocation
+         */
+        // 妫�楠屽悗绉诲簱
+        //1301:鍘熸潗鏂欏悎鏍煎簱锛孋P-02-001:鎴愬搧搴�
+        if(StringUtils.equals(inventoryQuantity.getOrderType(), OrderType.RAW.getValue())){
+            toLocation = "1301";
+        }else if(StringUtils.equals(inventoryQuantity.getOrderType(), OrderType.WG.getValue())){
+            toLocation = "CP-02-001";
+        }else{
+            toLocation = "1301";
+        }
+        Map<String, Object> moveResultMap = new HashMap<>();
+        List<Map<String, Object>> moveResultList = new ArrayList<>();
+        Map<String, Object> moveMap = new HashMap<>();
+        moveMap.put("ORDER_NO", one.getOrderNo()); // 閲囪喘璁㈠崟鍙�
+        moveMap.put("LINE_NO", one.getLineNo());
+        moveMap.put("RELEASE_NO", one.getReleaseNo());
+        moveMap.put("RECEIPT_NO", one.getReceiptNo());
+        moveMap.put("PART_NO", one.getPartNo());
+        moveMap.put("QTY", one.getPurQtyInStore());
+        moveMap.put("LOCATION_NO", one.getLocationNo());
+        moveMap.put("TO_LOCATION_NO", toLocation);
+        moveMap.put("LOT_BATCH_NO", one.getLotBatchNo());
+        moveMap.put("SERIAL_NO", one.getSerialNo());
+        moveMap.put("WAIV_DEV_REJ_NO", one.getWaivDevRejNo());
+        moveMap.put("ENG_CHG_LEVEL", one.getEngChgLevel());
+        moveMap.put("ACTIVITY_SEQ", one.getActivitySeq());
+        moveResultList.add(moveMap);
+        moveResultMap.put("RECORD_ID", UUID.randomUUID().toString());
+        moveResultMap.put("SYSCODE", "LIMS");
+        moveResultMap.put("SYSMODEL", "妫�楠屽悗绉诲簱");
+        moveResultMap.put("BATCH_INFO", moveResultList);
+
+        Result result1 = ifsApiUtils.moveReceipt(JSONUtil.toJsonStr(moveResultMap));
+        // 濡傛灉鏈夊繀椤讳负闆朵欢鎸囧畾鎵瑰彿鎶ラ敊闇�瑕侀噸鏂版彁浜ょЩ搴撲俊鎭幓鎸囧畾鎵瑰彿
+        if (result1.getCode() != 200) {
+            String message = result1.getMessage();
+            if (message.contains("蹇呴』涓洪浂浠�") && message.contains("鎸囧畾鎵瑰彿")) {
+                updaeBatch(one, toLocation);
+            } else {
+                throw new ErrorException("IFS妫�楠屽悗绉诲簱澶辫触: " + result1.getMessage());
+            }
+        }
+        return toLocation;
+    }
+
+
+    /**
+     * 鍏堜慨鏀归噰璐鍗曟壒娆″彿, 鍚庤繘琛岀Щ搴撴搷浣�
+     * @param one
+     * @param toLocation
+     */
+    private void updaeBatch(IfsInventoryQuantity one, String toLocation) {
+        if (one.getIsUpdateBatch().equals(0)) {
+            // 鍏堜慨鏀规壒娆″彿鍚庤繘琛岀Щ搴�
+            Map<String, Object> resultMap = new HashMap<>();
+            List<Map<String, Object>> resultList = new ArrayList<>();
+            Map<String, Object> map = new HashMap<>();
+            map.put("ORDER_NO", one.getOrderNo()); // 閲囪喘璁㈠崟鍙�
+            map.put("LINE_NO", one.getLineNo()); // 琛屽彿
+            map.put("RELEASE_NO", one.getReleaseNo()); // 涓嬭揪鍙�
+            map.put("RECEIPT_NO", one.getReceiptNo()); // 鎺ユ敹鍙�
+            map.put("PART_NO", one.getPartNo()); //闆朵欢鍙�
+            map.put("CONFIGURATION_ID", one.getConfigurationId()); // 閰嶇疆鏍囪瘑
+            map.put("LOCATION_NO", one.getLocationNo()); // 搴撲綅鍙�
+            map.put("LOT_BATCH_NO", one.getLotBatchNo());// 鎵规鍙�
+            map.put("NEW_LOT_BATCH_NO", one.getUpdateBatchNo()); // 鐩爣鎵规鍙�
+            map.put("SERIAL_NO", one.getSerialNo()); // 搴忓垪鍙�
+            map.put("ENG_CHG_LEVEL", one.getEngChgLevel()); // 鐗堟湰鍙�
+            map.put("WAIV_DEV_REJ_NO", one.getWaivDevRejNo()); // wdr鍙�
+            map.put("ACTIVITY_SEQ", one.getActivitySeq()); // 娲诲姩搴忓彿
+            map.put("QTY_TO_CHANGE", one.getQtyArrived()); // 鍙樻洿鏁伴噺
+            resultList.add(map);
+            resultMap.put("RECORD_ID", UUID.randomUUID().toString());
+            resultMap.put("SYSCODE", "LIMS");
+            resultMap.put("SYSMODEL", "淇敼閲囪喘璁㈠崟鎵规鍙�");
+            resultMap.put("BATCH_INFO", resultList);
+
+            Result result = ifsApiUtils.updateMoveReceiptLot(JSONUtil.toJsonStr(resultMap));
+
+            if (result.getCode() != 200) {
+                throw new ErrorException("IFS淇敼鎵规鍙峰け璐�: " + result.getMessage());
+            }
+            ifsInventoryQuantityMapper.update(null, Wrappers.<IfsInventoryQuantity>lambdaUpdate()
+                    .set(IfsInventoryQuantity::getIsUpdateBatch, 1)
+                    .eq(IfsInventoryQuantity::getId, one.getId()));
+        }
+
+        Map<String, Object> moveResultMap = new HashMap<>();
+        List<Map<String, Object>> moveResultList = new ArrayList<>();
+        Map<String, Object> moveMap = new HashMap<>();
+        moveMap.put("ORDER_NO", one.getOrderNo()); // 閲囪喘璁㈠崟鍙�
+        moveMap.put("LINE_NO", one.getLineNo());
+        moveMap.put("RELEASE_NO", one.getReleaseNo());
+        moveMap.put("RECEIPT_NO", one.getReceiptNo());
+        moveMap.put("PART_NO", one.getPartNo());
+        moveMap.put("QTY", one.getQtyArrived());
+        moveMap.put("LOCATION_NO", one.getLocationNo());
+        moveMap.put("TO_LOCATION_NO", toLocation);
+        moveMap.put("LOT_BATCH_NO", one.getUpdateBatchNo());
+        moveMap.put("SERIAL_NO", one.getSerialNo());
+        moveMap.put("WAIV_DEV_REJ_NO", one.getWaivDevRejNo());
+        moveMap.put("ENG_CHG_LEVEL", one.getEngChgLevel());
+        moveMap.put("ACTIVITY_SEQ", one.getActivitySeq());
+        moveResultList.add(moveMap);
+        moveResultMap.put("RECORD_ID", UUID.randomUUID().toString());
+        moveResultMap.put("SYSCODE", "LIMS");
+        moveResultMap.put("SYSMODEL", "妫�楠屽悗绉诲簱");
+        moveResultMap.put("BATCH_INFO", moveResultList);
+
+        Result result1 = ifsApiUtils.moveReceipt(JSONUtil.toJsonStr(moveResultMap));
+        if (result1.getCode() != 200) {
+            throw new ErrorException("IFS妫�楠屽悗绉诲簱澶辫触: " + result1.getMessage());
+        }
+
+    }
+
 }
 
 

--
Gitblit v1.9.3