zhuo
8 天以前 fc543916cfac06f0cf16d018b9751417e3a119f7
inspect-server/src/main/java/com/ruoyi/inspect/service/impl/InsOrderPlanServiceImpl.java
@@ -30,27 +30,28 @@
import com.ruoyi.basic.pojo.IfsInventoryQuantity;
import com.ruoyi.basic.pojo.StandardTemplate;
import com.ruoyi.basic.service.StandardTemplateService;
import com.ruoyi.common.constant.DictDataConstants;
import com.ruoyi.common.constant.InsOrderTypeConstants;
import com.ruoyi.common.constant.MenuJumpPathConstants;
import com.ruoyi.common.core.domain.entity.Custom;
import com.ruoyi.common.core.domain.entity.InformationNotification;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.User;
import com.ruoyi.common.utils.DateImageUtil;
import com.ruoyi.common.utils.QueryWrappers;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.WxCpUtils;
import com.ruoyi.common.utils.*;
import com.ruoyi.framework.exception.ErrorException;
import com.ruoyi.inspect.dto.*;
import com.ruoyi.inspect.mapper.*;
import com.ruoyi.inspect.pojo.*;
import com.ruoyi.inspect.service.*;
import com.ruoyi.inspect.util.HackLoopTableRenderPolicy;
import com.ruoyi.inspect.vo.InsOrderPlanTaskSwitchVo;
import com.ruoyi.inspect.vo.InsOrderPlanVO;
import com.ruoyi.performance.mapper.AuxiliaryOutputWorkingHoursMapper;
import com.ruoyi.performance.mapper.PerformanceShiftMapper;
import com.ruoyi.performance.mapper.ShiftTimeMapper;
import com.ruoyi.performance.pojo.AuxiliaryOutputWorkingHours;
import com.ruoyi.performance.pojo.AuxiliaryOutputWorkingHoursTemporary;
import com.ruoyi.performance.service.AuxiliaryOutputWorkingHoursService;
import com.ruoyi.performance.service.AuxiliaryOutputWorkingHoursTemporaryService;
import com.ruoyi.system.mapper.CustomMapper;
import com.ruoyi.system.mapper.UserMapper;
import com.ruoyi.system.service.ISysDictTypeService;
@@ -58,6 +59,7 @@
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
@@ -70,13 +72,13 @@
import java.math.RoundingMode;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
@@ -103,14 +105,9 @@
    private InsOrderStateMapper insOrderStateMapper;
    @Resource
    private InsProductMapper insProductMapper;
    @Resource
    private ShiftTimeMapper shiftTimeMapper;
    @Resource
    private PerformanceShiftMapper performanceShiftMapper;
    @Value("${wordUrl}")
    private String wordUrl;
    @Value("${twoCode}")
    private String twoCode;
    @Resource
    private InsReportMapper insReportMapper;
    @Resource
@@ -118,11 +115,9 @@
    @Resource
    private InsProductUserMapper insProductUserMapper;
    @Resource
    private InsUnPassService insUnPassService;
    private AuxiliaryOutputWorkingHoursService auxiliaryOutputWorkingHoursService;
    @Resource
    private AuxiliaryOutputWorkingHoursMapper auxiliaryOutputWorkingHoursMapper;
    @Resource
    private AuxiliaryOutputWorkingHoursService auxiliaryOutputWorkingHoursService;
    @Resource
    private InformationNotificationService informationNotificationService;
    @Resource
@@ -131,7 +126,6 @@
    private CustomMapper customMapper;
    @Value("${file.path}")
    private String imgUrl;
    @Resource
    private InsOrderFileMapper insOrderFileMapper;
    @Resource
@@ -150,8 +144,7 @@
    private InsOrderFactoryVerifyMapper insOrderFactoryVerifyMapper;
    @Resource
    private InsOrderFactoryVerifyItemService insOrderFactoryVerifyItemService;
    @Value("${file.licenseUrl}")
    private String licenseUrl;
    @Resource
    private SpotCheckQuarterItemMapper spotCheckQuarterItemMapper;
    @Resource
@@ -162,6 +155,12 @@
    private InsOrderDeviceRecordService insOrderDeviceRecordService;
    @Resource
    private ISysDictTypeService iSysDictTypeService;
    @Resource
    private InsOrderRatesService insOrderRatesService;
    @Resource
    private InsProductDeviationWarningService insProductDeviationWarningService;
    @Resource
    private InsProductDeviationWarningDetailService insProductDeviationWarningDetailService;
    @Override
@@ -236,17 +235,19 @@
        // 查询厂家密度
        String supplierDensity = "";
        SampleProductDto sampleProductDto = list.get(0);
        if (CollectionUtils.isNotEmpty(list)) {
            SampleProductDto sampleProductDto = list.get(0);
        // 判断有没有绑定型号
        String modelValue = insSampleMapper.selectSupplierDensityModel(sampleProductDto.getSample(),
                order.getProduction(),
                sampleProductDto.getModel());
        if (StringUtils.isNotBlank(modelValue)) {
            supplierDensity = modelValue;
        } else {
            supplierDensity = insSampleMapper.selectSupplierDensity(sampleProductDto.getSample(),
                    order.getProduction());
            // 判断有没有绑定型号
            String modelValue = insSampleMapper.selectSupplierDensityModel(sampleProductDto.getSample(),
                    order.getProduction(),
                    sampleProductDto.getModel());
            if (StringUtils.isNotBlank(modelValue)) {
                supplierDensity = modelValue;
            } else {
                supplierDensity = insSampleMapper.selectSupplierDensity(sampleProductDto.getSample(),
                        order.getProduction());
            }
        }
        map.put("supplierDensity", supplierDensity);
        return map;
@@ -257,16 +258,13 @@
        List<InsProduct> insProducts = new ArrayList<>();
        switch (dto.getType()) {
            case 0:
                insProducts = insSampleMapper.getInsProduct1(dto.getId(), dto.getLaboratory(), dto.getCableTag(), dto.getRepetitionTag(), null);
                //样品
                break;
            case 4:
                //电缆配置
                insProducts = insSampleMapper.getInsProduct1(dto.getId(), dto.getLaboratory(), dto.getCableTag(), dto.getRepetitionTag(), null);
                //委托
                insProducts = insSampleMapper.getInsProduct1(dto.getId(), dto.getLaboratory(), dto.getCableTag(), dto.getRepetitionTag());
                break;
            case 5:
                //原材料下单
                insProducts = insSampleMapper.getInsProduct6(dto.getId(), dto.getLaboratory(), dto.getRawMaterialTag(), null);
                insProducts = insSampleMapper.getInsProduct6(dto.getId(), dto.getLaboratory(), dto.getRawMaterialTag());
                break;
        }
        if (BeanUtil.isEmpty(insProducts)) {
@@ -363,15 +361,16 @@
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveInsContext(Map<String, Object> insContext, Integer currentTable, Integer currentSampleId, Integer orderId, String sonLaboratory) {
    public void saveInsContext(SaveInsContextDto saveInsContextDto) {
        Map<String, Object> insContext = JSON.parseObject(saveInsContextDto.getParam(), Map.class);
        Integer userId = SecurityUtils.getUserId().intValue();
        InsSample insSample = insSampleMapper.selectById(currentSampleId);
        InsSample insSample = insSampleMapper.selectById(saveInsContextDto.getSampleId());
        insContext.forEach((k, v) -> {
            JSONObject jo = JSON.parseObject(JSON.toJSONString(v));
            InsProduct insProduct = new InsProduct();
            insProduct.setId(Integer.parseInt(k));
            InsProduct product = insProductMapper.selectById(insProduct.getId());
            if (currentTable.equals(product.getTemplateId()) && currentSampleId.equals(product.getInsSampleId())) {
            if (saveInsContextDto.getCurrentTable().equals(product.getTemplateId()) && saveInsContextDto.getSampleId().equals(product.getInsSampleId())) {
                List<InsProductResult> oldResults = insProductResultMapper.selectList(Wrappers.<InsProductResult>lambdaQuery()
                        .eq(InsProductResult::getInsProductId, insProduct.getId()));
                InsProductResult newResult = new InsProductResult();
@@ -501,22 +500,32 @@
                    }
                }
                //查询检验单信息
                // 添加工时
                // 判断是否只是参与计算值, 参与计算值实际没有填写
                InsProduct finalInsProduct = insProductMapper.selectById(product.getId());
                threadPoolTaskExecutor.execute(() -> {
                    InsOrder insOrder = insOrderMapper.selectById(insSample.getInsOrderId());
                    this.addAuxiliary(userId, finalInsProduct, insOrder);
                });
                InsOrder insOrder = insOrderMapper.selectById(insSample.getInsOrderId());
                if (StringUtils.isNotBlank(newResult.getInsValue()) && !newResult.getInsValue().equals("[]")) {
                    threadPoolTaskExecutor.execute(() -> {
                        this.addAuxiliary(userId, finalInsProduct, insOrder);
                    });
                } else {
                    // 判断是否是没有检验值的内容
                    if (saveInsContextDto.getIsNoTestValue() != null && saveInsContextDto.getIsNoTestValue() == 1) {
                        threadPoolTaskExecutor.execute(() -> {
                            this.addAuxiliary(userId, finalInsProduct, insOrder);
                        });
                    }
                }
            }
        });
        String sampleIdStr = insContext.keySet().stream().findFirst().orElse(null);
        if (sampleIdStr != null) {
            int count = insProductMapper.selectInsProductCountByOrderId(orderId);
            int count = insProductMapper.selectInsProductCountByOrderId(saveInsContextDto.getOrderId());
            if (count == 0) {
                insOrderStateMapper.update(new InsOrderState(), Wrappers.<InsOrderState>lambdaUpdate()
                        .eq(InsOrderState::getInsOrderId, orderId)
                        .eq(InsOrderState::getLaboratory, sonLaboratory)
                        .eq(InsOrderState::getInsOrderId, saveInsContextDto.getOrderId())
                        .eq(InsOrderState::getLaboratory, saveInsContextDto.getSonLaboratory())
                        .set(InsOrderState::getInsState, 2));
            }
        }
@@ -524,55 +533,60 @@
        // 添加设备记录
        threadPoolTaskExecutor.execute(() -> {
            InsOrder order = insOrderMapper.selectById(insSample.getInsOrderId());
            User user = userMapper.selectById(userId);
            // 查询设备使用记录查询该订单的使用记录
            List<InsOrderDeviceRecordDto> deviceRecordDtoList = insOrderDeviceRecordMapper.selectDeviceNumber(insSample.getInsOrderId());
            Set<String> recordCodeset = deviceRecordDtoList.stream().map(InsOrderDeviceRecordDto::getManagementNumber).collect(Collectors.toSet());
            // 添加设备使用记录
            addDeviceRecord(insSample, userId);
        });
    }
            // 获取订单设备编号
            List<InsProductResult> resultList = insProductResultMapper.selectResultByOrderId(insSample.getInsOrderId());
            Set<String> deviceCodeSet = new HashSet<>();
            for (InsProductResult result : resultList) {
                // 添加设备编号
                List<JSONObject> jsonObjects = JSON.parseArray(result.getEquipValue(), JSONObject.class);
                for (JSONObject jsonObject : jsonObjects) {
                    if (!"".equals(jsonObject.get("v") + "")) {
                        List<String> v = StrUtil.split(jsonObject.get("v") + "", ",");
                        deviceCodeSet.addAll(v);
                    }
    private synchronized void addDeviceRecord(InsSample insSample, Integer userId) {
        InsOrder order = insOrderMapper.selectById(insSample.getInsOrderId());
        User user = userMapper.selectById(userId);
        // 查询设备使用记录查询该订单的使用记录
        List<InsOrderDeviceRecordDto> deviceRecordDtoList = insOrderDeviceRecordMapper.selectDeviceNumber(insSample.getInsOrderId());
        Set<String> recordCodeset = deviceRecordDtoList.stream().map(InsOrderDeviceRecordDto::getManagementNumber).collect(Collectors.toSet());
        // 获取订单设备编号
        List<InsProductResult> resultList = insProductResultMapper.selectResultByOrderId(insSample.getInsOrderId());
        Set<String> deviceCodeSet = new HashSet<>();
        for (InsProductResult result : resultList) {
            // 添加设备编号
            List<JSONObject> jsonObjects = JSON.parseArray(result.getEquipValue(), JSONObject.class);
            for (JSONObject jsonObject : jsonObjects) {
                if (!"".equals(jsonObject.get("v") + "")) {
                    List<String> v = StrUtil.split(jsonObject.get("v") + "", ",");
                    deviceCodeSet.addAll(v);
                }
            }
            // 1.判断是否有没有添加的使用记录
            Set<String> orderDeviceNumbers = getDeviceDifference(deviceCodeSet, recordCodeset);
            // 添加使用记录, 根据编号查询设备id
            if (CollectionUtils.isNotEmpty(orderDeviceNumbers)) {
                List<Integer> orderDeviceIds = insOrderDeviceRecordMapper.selectDeviceIdsByNumbers(orderDeviceNumbers);
                List<InsOrderDeviceRecord> collect = orderDeviceIds.stream().map(deviceId -> {
                    InsOrderDeviceRecord insOrderDeviceRecord = new InsOrderDeviceRecord();
                    insOrderDeviceRecord.setInsOrderId(insSample.getInsOrderId());
                    insOrderDeviceRecord.setDeviceId(deviceId);
                    insOrderDeviceRecord.setSampleCode(order.getEntrustCode());
                    insOrderDeviceRecord.setUseBefore(1);
                    insOrderDeviceRecord.setUseAfter(1);
                    insOrderDeviceRecord.setUsePerson(user.getName());
                    insOrderDeviceRecord.setUsePersonId(user.getId());
                    return insOrderDeviceRecord;
                }).collect(Collectors.toList());
        }
        // 1.判断是否有没有添加的使用记录
        Set<String> orderDeviceNumbers = getDeviceDifference(deviceCodeSet, recordCodeset);
        // 添加使用记录, 根据编号查询设备id
        if (CollectionUtils.isNotEmpty(orderDeviceNumbers)) {
            List<Integer> orderDeviceIds = insOrderDeviceRecordMapper.selectDeviceIdsByNumbers(orderDeviceNumbers);
            List<InsOrderDeviceRecord> collect = orderDeviceIds.stream().map(deviceId -> {
                InsOrderDeviceRecord insOrderDeviceRecord = new InsOrderDeviceRecord();
                insOrderDeviceRecord.setInsOrderId(insSample.getInsOrderId());
                insOrderDeviceRecord.setDeviceId(deviceId);
                insOrderDeviceRecord.setSampleCode(order.getEntrustCode());
                insOrderDeviceRecord.setUseBefore(1);
                insOrderDeviceRecord.setUseAfter(1);
                insOrderDeviceRecord.setUsePerson(user.getName());
                insOrderDeviceRecord.setUsePersonId(user.getId());
                return insOrderDeviceRecord;
            }).collect(Collectors.toList());
                insOrderDeviceRecordService.saveBatch(collect);
            insOrderDeviceRecordService.saveBatch(collect);
            }
        }
            // 2.判断是否取消了设备使用
            Set<String> repoprNumbers = getDeviceDifference(recordCodeset, deviceCodeSet);
            if (CollectionUtils.isNotEmpty(repoprNumbers)) {
                List<Integer> reportDeviceIds = insOrderDeviceRecordMapper.selectDeviceIdsByNumbers(repoprNumbers);
                insOrderDeviceRecordMapper.delete(Wrappers.<InsOrderDeviceRecord>lambdaQuery()
                        .in(InsOrderDeviceRecord::getDeviceId, reportDeviceIds)
                        .eq(InsOrderDeviceRecord::getInsOrderId, insSample.getInsOrderId()));
            }
        });
        // 2.判断是否取消了设备使用
        Set<String> repoprNumbers = getDeviceDifference(recordCodeset, deviceCodeSet);
        if (CollectionUtils.isNotEmpty(repoprNumbers)) {
            List<Integer> reportDeviceIds = insOrderDeviceRecordMapper.selectDeviceIdsByNumbers(repoprNumbers);
            insOrderDeviceRecordMapper.delete(Wrappers.<InsOrderDeviceRecord>lambdaQuery()
                    .in(InsOrderDeviceRecord::getDeviceId, reportDeviceIds)
                    .eq(InsOrderDeviceRecord::getInsOrderId, insSample.getInsOrderId()));
        }
    }
    private static Set<String> getDeviceDifference(Set<String> number1, Set<String> number2) {
@@ -592,6 +606,11 @@
        return insSampleUserMapper.insert(insSampleUser);
    }
    /**
     * 查询模板内容
     * @param order
     * @param insProducts
     */
    private void getTemplateThing(InsOrder order, List<InsProduct> insProducts) {
        Set<Integer> set = new HashSet<>();
        // 查询订单状态判断是否是查历史模板
@@ -613,8 +632,9 @@
                                .eq(InsOrderStandardTemplate::getInsOrderId, order.getId()));
                        thing = one.getThing();
                        if (StrUtil.isNotEmpty(thing)) {
                            JSONObject sheet = JSON.parseObject(JSON.toJSONString(JSON.parseArray(JSON.toJSONString(JSON.parseObject(thing).get("data"))).get(0)));
                            JSONObject config = JSON.parseObject(JSON.toJSONString(sheet.get("config")));
                            thing = GZipUtil.uncompress(thing);
                            JSONObject sheet = JSON.parseObject(thing).getJSONArray("data").getJSONObject(0);
                            JSONObject config = sheet.getJSONObject("config");
                            List<JSONObject> cellData = JSON.parseArray(JSON.toJSONString(sheet.get("celldata")), JSONObject.class);
                            Map<String, Object> style = new HashMap<>();
                            style.put("rowlen", config.get("rowlen"));
@@ -634,33 +654,111 @@
            }
            String thing = null;
            if (product.getTemplateId() != null && set.add(product.getTemplateId())) {
                long begin = System.currentTimeMillis();
                thing = standardTemplateService.getStandTempThingById(product.getTemplateId());
                long end = System.currentTimeMillis();
                System.out.println("=========时间====" + (end - begin));
            }
            if (StrUtil.isNotEmpty(thing)) {
                JSONObject sheet = JSON.parseObject(JSON.toJSONString(JSON.parseArray(JSON.toJSONString(JSON.parseObject(thing).get("data"))).get(0)));
                JSONObject config = JSON.parseObject(JSON.toJSONString(sheet.get("config")));
                JSONObject sheet = JSON.parseObject(thing).getJSONArray("data").getJSONObject(0);
                JSONObject config = sheet.getJSONObject("config");
                List<JSONObject> cellData = JSON.parseArray(JSON.toJSONString(sheet.get("celldata")), JSONObject.class);
                Map<String, Object> style = new HashMap<>();
                style.put("rowlen", config.get("rowlen"));
                style.put("columnlen", config.get("columnlen"));
                product.setTemplate(cellData);
                product.setStyle(style);
                long begin = System.currentTimeMillis();
                product.setTemplateName(standardTemplateService.getStandTempNameById(product.getTemplateId()));
                long end = System.currentTimeMillis();
                System.out.println("=========时间22222====" + (end - begin));
            }
        }
    }
    /**
     * todo: 原始记录模板清除没有使用的检验项(暂时有bug无法使用)
     * @param sheet
     * @param itemNameList
     */
    private static void eliminateItem(JSONObject sheet, List<String> itemNameList) {
        // 获取到 检验项分类+检验项+检验子项的拼接,如果模板里的信息跟接口返回的检验项信息能够匹配则展示出来
        // 循环行数判断是否
        JSONArray dataListJSONArray = sheet.getJSONArray("data");
        // 添加坐标map
        Map<String, String> coordinatesMap = new HashMap<>();
        // 需要移除的索引
        List<Integer> deleteIndex = new ArrayList<>();
        // 循环列
        for (int r = 0; r < dataListJSONArray.size(); r++) {
            JSONArray dataList = dataListJSONArray.getJSONArray(r);
            // 循环行
            String itemName = "";
            // 判断是否显示
            boolean isShow = false;
            for (int c = 0; c < dataList.size(); c++) {
                // 查询批注
                JSONObject jsonObject = dataList.getJSONObject(c);
                try {
                    if (jsonObject.getJSONObject("ps").getString("value").equals("检验项分类")) {
                        String value = jsonObject.getString("v").trim();
                        itemName += value;
                        // 添加坐标
                        String coordinates = coordinatesJoint(r, c);
                        coordinatesMap.put(coordinates, value);
                        isShow = true;
                    } else if (jsonObject.getJSONObject("ps").getString("value").equals("检验项")) {
                        String value = jsonObject.getString("v").trim();
                        itemName += value;
                        // 添加坐标
                        String coordinates = coordinatesJoint(r, c);
                        coordinatesMap.put(coordinates, value);
                        isShow = true;
                    } else if (jsonObject.getJSONObject("ps").getString("value").equals("检验子项")) {
                        String value = jsonObject.getString("v").trim();
                        itemName += value;
                        // 添加坐标
                        String coordinates = coordinatesJoint(r, c);
                        coordinatesMap.put(coordinates, value);
                        isShow = true;
                    }
                } catch (Exception e) {
                    // 判断是否有mc合并单元格
                    if (jsonObject != null && jsonObject.getJSONObject("mc") != null) {
                        // 查询坐标进行添加
                        String value = coordinatesMap.get(coordinatesJoint(jsonObject.getJSONObject("mc").getInteger("r"), jsonObject.getJSONObject("mc").getInteger("c")));
                        if (StringUtils.isNotBlank(value) && !itemName.contains(value)) {
                            itemName += value;
                        }
                    }
                }
            }
            // 判断该订单是否有改检验项, 没有剔除
            if (isShow) {
                if (!itemNameList.contains(itemName)) {
                    dataListJSONArray.remove(r);
                    r--;
                }
            }
        }
    }
    /**
     * 坐标拼接
     * @param r 横坐标
     * @param c 纵坐标
     * @return
     */
    private static String coordinatesJoint(int r, int c) {
        String coordinates = "";
        coordinates = "r:" + r + ",c:" + c;
        return coordinates;
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int submitPlan(Integer orderId, String laboratory, Integer verifyUser, String entrustCode) {
        InsOrder order = insOrderMapper.selectById(orderId);
        // 判断是否有重复编号, 有重复编号做提醒
        // 1. 判断是否有重复编号, 有重复编号做提醒
        Long codeCount = insOrderMapper.selectCount(Wrappers.<InsOrder>lambdaQuery()
                .ne(InsOrder::getState, -1)
                .ne(InsOrder::getIfsInventoryId, order.getIfsInventoryId())
@@ -669,7 +767,7 @@
            throw new ErrorException("当前编号有重复, 请先去修改重复编号");
        }
        // 判断该订单是否是第一次生产
        // 2. 判断该订单是否是第一次生产(后续报告生成只取第一次提交时间)
        if (!(order.getIsFirstSubmit() != null && order.getIsFirstSubmit().equals(1))) {
            insOrderMapper.update(null, Wrappers.<InsOrder>lambdaUpdate()
                    .eq(InsOrder::getId, orderId)
@@ -677,11 +775,12 @@
                    .set(InsOrder::getFirstSubmitDate, LocalDateTime.now()));
        }
        // 3. 判断是否有未检项
        List<InsSample> insSamples = insSampleMapper.selectList(Wrappers.<InsSample>lambdaQuery()
                .eq(InsSample::getInsOrderId, orderId).select(InsSample::getId));
        List<Integer> ids = insSamples.stream().map(a -> a.getId()).collect(Collectors.toList());
        List<Integer> InsSampleIds = insSamples.stream().map(InsSample::getId).collect(Collectors.toList());
        List<InsProduct> insProducts = insProductMapper.selectList(Wrappers.<InsProduct>lambdaQuery()
                .in(InsProduct::getInsSampleId, ids)
                .in(InsProduct::getInsSampleId, InsSampleIds)
                .eq(InsProduct::getSonLaboratory, laboratory)
                .eq(InsProduct::getState, 1)
                .and(wrapper -> wrapper
@@ -689,37 +788,37 @@
                        .or()
                        .eq(InsProduct::getInsResult, 2)
                )
                .isNull(InsProduct::getInsFiberId)
                .isNull(InsProduct::getInsFibersId)
                .ne(InsProduct::getIsBinding, 1));
        insProducts.addAll(insProductMapper.selectFiberInsProduct(ids, laboratory));
        insProducts.addAll(insProductMapper.selectFiberInsProduct(InsSampleIds, laboratory));
        if (insProducts.size() > 0) {
            String str = "";
            int count = 0;
            for (InsProduct product : insProducts) {
                count++;
                str += "<br/>" + count + ":" + product.getInspectionItem() + " " + product.getInspectionItemSubclass() + "<br/>";
                str +=  (count != 0 ? "\n" : "") + count + ":" +
                        product.getInspectionItemClass() + " " +
                        product.getInspectionItem() + " " +
                        product.getInspectionItemSubclass();
            }
            if (ObjectUtils.isNotEmpty(str)) {
                throw new ErrorException("<strong>存在待检验的项目:</strong><br/>" + str);
                throw new ErrorException("存在待检验的项目:" + str);
            }
        }
        // 4.修改检测结果
        insOrderStateMapper.update(null, Wrappers.<InsOrderState>lambdaUpdate().eq(InsOrderState::getInsOrderId, orderId)
                .eq(InsOrderState::getLaboratory, laboratory)
                .set(InsOrderState::getInsTime, LocalDateTime.now())
                .set(InsOrderState::getInsState, 3)
                .set(InsOrderState::getVerifyUser, verifyUser));
        // 发送消息
        // 5.发送消息通知给复核人
        // 查询当前人信息
        Integer userId = SecurityUtils.getUserId().intValue();
        String userName = insProductMapper.selectUserById(userId).get("name");
        // 查询发送人信息
        String sendUserAccount = insProductMapper.selectUserById(verifyUser).get("account");
        InformationNotification info = new InformationNotification();
        info.setCreateUser(userName);
        info.setMessageType("2");
@@ -728,18 +827,19 @@
        info.setSenderId(userId);
        info.setConsigneeId(verifyUser);
        info.setViewStatus(false);
        info.setJumpPath("b1-inspect-orderPlan-review");
        info.setJumpPath(MenuJumpPathConstants.INSPECTION_REVIEW);
        informationNotificationService.addInformationNotification(info);
        //复核人--检验单相关负责人
        // 6.复核人--新增检验单相关负责人
        InsSampleUser insSampleUser = new InsSampleUser();
        insSampleUser.setUserId(verifyUser);
        insSampleUser.setInsSampleId(orderId);
        insSampleUser.setState(1);
        insSampleUser.setSonLaboratory(laboratory);
        insSampleUserMapper.insert(insSampleUser);
        /*校验一下result表*/
        CompletableFuture.supplyAsync(() -> {
        // 7.校验一下result表(避免出现多个检验项结果)
        threadPoolTaskExecutor.execute(() -> {
            List<Integer> ips = insProducts.stream().map(InsProduct::getId).distinct().collect(Collectors.toList());
            for (Integer ip : ips) {
                List<InsProductResult> insProductResults = insProductResultMapper.selectList(Wrappers.<InsProductResult>lambdaQuery()
@@ -750,29 +850,228 @@
                    }
                }
            }
            return null;
        });
        // todo: 删除数采采集次数
//        String key = "frequency" + ":" + entrustCode + ":*";
//        RedisUtil.delsLike(key);
        // 提交生成报告
        // 8.提交生成报告
        this.generateReport(orderId);
        // 添加临时pdf生成地址
        // 9.添加临时pdf生成地址
        InsReport report = insReportMapper.selectOne(Wrappers.<InsReport>lambdaQuery()
                .eq(InsReport::getInsOrderId, orderId));
        String tempUrlPdf = this.wordToPdfTemp(report.getUrl().replace("/word", wordUrl));
        report.setTempUrlPdf("/word/" + tempUrlPdf);
        insReportMapper.updateById(report);
        // 查询订单
        // 10.原始记录模板复制(添加备份, 避免修改原始模板影响到已经完成的单子)
        this.templateCopy(orderId, InsSampleIds);
        // 11.成品抽样添加合格状态
        // 判断是否有抽样信息
        if (order.getQuarterItemId() != null) {
            // 判断是否有不合格
            this.addProductSpotCheck(insSamples, order);
        }
        // 12.添加订单费用统计信息
        List<InsProduct> productList = insProductMapper.selectProductByOrderId(orderId);
        // 删除原本费用信息
        insOrderRatesService.remove(Wrappers.<InsOrderRates>lambdaQuery()
                .eq(InsOrderRates::getInsOrderId, orderId));
        List<InsOrderRates> orderRatesList = productList.stream().map(insProduct -> {
            InsOrderRates insOrderRates = new InsOrderRates();
            insOrderRates.setInsOrderId(orderId);
            insOrderRates.setInsSampleId(insProduct.getInsSampleId());
            insOrderRates.setInsProductId(insProduct.getId());
            insOrderRates.setSampleCode(insProduct.getSampleCode());
            insOrderRates.setEntrustCode(order.getEntrustCode());
            insOrderRates.setInspectionItemClass(insProduct.getInspectionItemClass());
            insOrderRates.setInspectionItem(insProduct.getInspectionItem());
            insOrderRates.setInspectionItemSubclass(insProduct.getInspectionItemSubclass());
            insOrderRates.setCableTag(insProduct.getCableTag());
            insOrderRates.setRates(insProduct.getRates());
            insOrderRates.setManHourGroup(insProduct.getManHourGroup());
            return insOrderRates;
        }).collect(Collectors.toList());
        insOrderRatesService.saveBatch(orderRatesList);
        // 13.发送企业微信通知
        // 查询原材料
        IfsInventoryQuantity ifsInventoryQuantity = ifsInventoryQuantityMapper.selectById(order.getIfsInventoryId());
        // 查询样品信息
        InsSample insSample = insSampleMapper.selectOne(Wrappers.<InsSample>lambdaQuery()
                .eq(InsSample::getInsOrderId, orderId)
                .last("limit 1"));
        // 查询原材料
        IfsInventoryQuantity ifsInventoryQuantity = ifsInventoryQuantityMapper.selectById(order.getIfsInventoryId());
        threadPoolTaskExecutor.execute(() -> {
            String message = "";
            message += "检验任务复核通知";
            message += "\n提交人: " + userName;
            message += "\n委托编号: " + order.getEntrustCode();
            message += "\n样品名称: " + insSample.getModel();
            message += "\n规格型号: " + order.getPartDetail();
            if (ifsInventoryQuantity != null) {
                message += "\n批次号: " + ifsInventoryQuantity.getUpdateBatchNo();
            }
            //发送企业微信消息通知  提交复核
            try {
                WxCpUtils.inform(sendUserAccount, message, null);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
        // 14.ifs移库(原材料需要进行移库操作) --> 最后执行,因为失败无法回滚
        if (ifsInventoryQuantity != null) {
            // 登记检验结果
            // 判断是否有不合格, 有不合格不能移库
            // todo: ifs移库
            insReportService.isRawMaterial(order);
            // 15 判断当前样品是否为原材料, 原材料需要进行数据分析, 判断之前10条数据同一个供应商, 同一个检验项的偏差是否超过10%
            // 查询ifs信息获取获取前10个供应商一样的, 检验项一样信息
            threadPoolTaskExecutor.execute(() -> {
                // 添加分析数据
                addAnalysis(productList, ifsInventoryQuantity, order, sendUserAccount);
            });
        } else {
            // 修改成品状态
            // 判断是否有不合格
            Long unqualifiedCount = insReportService.getUnqualifiedCount(order);
            if (unqualifiedCount.equals(0L)) {
                insOrderMapper.update(null, Wrappers.<InsOrder>lambdaUpdate()
                        .eq(InsOrder::getId, order.getId())
                        .set(InsOrder::getInsResult, 1));
            } else {
                insOrderMapper.update(null, Wrappers.<InsOrder>lambdaUpdate()
                        .eq(InsOrder::getId, order.getId())
                        .set(InsOrder::getInsResult, 0));
            }
        }
        return 1;
    }
    /**
     * *****添加分析数据******
     * @param productList
     * @param ifsInventoryQuantity
     * @param order
     */
    private void addAnalysis(List<InsProduct> productList, IfsInventoryQuantity ifsInventoryQuantity, InsOrder order, String sendUserAccount) {
        for (InsProduct insProduct : productList) {
            // 判断是否是数值类型
            if (insProduct.getInspectionValueType().equals("1") && insProduct.getInsResult().equals(1)) {
                List<InsProductDeviationWarningDetail> insProductAnalysisDtoList = insProductMapper.selectAnalysis(insProduct, ifsInventoryQuantity.getSupplierName());
                if (insProductAnalysisDtoList.size() < 10) {
                    continue;
                }
                // 判断当前检测项是否偏差超过10%
                List<String> laseValueList = insProductAnalysisDtoList.stream().map(InsProductDeviationWarningDetail::getTestValue)
                        .collect(Collectors.toList());
                double deviation = isDeviationOverTenPercent(laseValueList, insProduct.getLastValue());
                // 判断偏差是否大于10
                if (deviation > 10) {
                    // 判断之前是否添加过, 添加过不需要添加
                    long count = insProductDeviationWarningService.count(Wrappers.<InsProductDeviationWarning>lambdaQuery()
                            .eq(InsProductDeviationWarning::getInsProductId, insProduct.getId()));
                    if (count == 0L) {
                        // 发送通知, 并且添加数据
                        // 添加主表信息
                        InsProductDeviationWarning deviationWarning = new InsProductDeviationWarning();
                        deviationWarning.setInsOrderId(order.getId());
                        deviationWarning.setInsSampleId(insProduct.getInsSampleId());
                        deviationWarning.setInsProductId(insProduct.getId());
                        deviationWarning.setEntrustCode(order.getEntrustCode());
                        deviationWarning.setSampleCode(insProduct.getSampleCode());
                        deviationWarning.setSupplierName(ifsInventoryQuantity.getSupplierName());
                        deviationWarning.setDeviationValue(Double.toString(deviation));
                        deviationWarning.setDetectionTime(insProduct.getUpdateTime());
                        insProductDeviationWarningService.save(deviationWarning);
                        // 添加详情数据
                        InsProductDeviationWarningDetail deviationWarningDetail = new InsProductDeviationWarningDetail();
                        deviationWarningDetail.setInsOrderId(order.getId());
                        deviationWarningDetail.setInsSampleId(insProduct.getInsSampleId());
                        deviationWarningDetail.setInsProductId(insProduct.getId());
                        deviationWarningDetail.setEntrustCode(order.getEntrustCode());
                        deviationWarningDetail.setSampleCode(insProduct.getSampleCode());
                        deviationWarningDetail.setSupplierName(ifsInventoryQuantity.getSupplierName());
                        deviationWarningDetail.setTestValue(insProduct.getLastValue());
                        deviationWarningDetail.setDetectionTime(insProduct.getCreateTime());
                        deviationWarningDetail.setIsIssue(1);
                        insProductAnalysisDtoList.add(deviationWarningDetail);
                        // 添加id
                        for (InsProductDeviationWarningDetail warningDetail : insProductAnalysisDtoList) {
                            warningDetail.setDeviationWarningId(deviationWarning.getDeviationWarningId());
                        }
                        insProductDeviationWarningDetailService.saveBatch(insProductAnalysisDtoList);
                        //发送企业微信消息通知  检验项预警预警通知
                        try {
                            String message = "";
                            message += "检验项预警预警通知";
                            message += "\n委托编号: " + order.getEntrustCode();
                            message += "\n样品名称: " + order.getSample();
                            message += "\n规格型号: " + order.getPartDetail();
                            message += "\n批次号: " + ifsInventoryQuantity.getUpdateBatchNo();
                            message += "\n供应商名称: " + ifsInventoryQuantity.getSupplierName();
                            message += "\n检验项: " + insProduct.getInspectionItem() + insProduct.getInspectionItemSubclass();
                            message += "\n偏差超过了 10%";
                            // 发送给提交人
//                            WxCpUtils.inform(sendUserAccount, message, null);
//
//                            // todo: 发送给检测中心主任(固定死)
//                            WxCpUtils.inform("ZT-004704", message, null);
                        } catch (Exception e) {
                            e.printStackTrace();
                            log.error("偏差预警企业微信通知报错");
                        }
                    }
                }
            }
        }
    }
    /**
     * *****计算偏差****
     * @param data
     * @param targetStr
     * @return
     */
    public static double isDeviationOverTenPercent(List<String> data, String targetStr) {
        if (data.isEmpty()) {
            return 0;
        }
        List<Double> doubleData = data.stream()
                .map(Double::parseDouble)
                .collect(Collectors.toList());
        double sum = doubleData.stream().mapToDouble(Double::doubleValue).sum();
        double average = sum / doubleData.size();
        double target = Double.parseDouble(targetStr);
        double deviationPercent = Math.abs(target - average) / average * 100;
        // 保留两位小数
        DecimalFormat df = new DecimalFormat("#.00");
        String formatted = df.format(deviationPercent);
        return Double.parseDouble(formatted);
    }
    /**
     * ******原始记录模板复制*****
     * @param orderId
     * @param ids
     */
    private void templateCopy(Integer orderId, List<Integer> ids) {
        // 删除原本模板
        insOrderStandardTemplateService.remove(Wrappers.<InsOrderStandardTemplate>lambdaQuery()
                .eq(InsOrderStandardTemplate::getInsOrderId, orderId));
@@ -796,138 +1095,6 @@
                    insOrderStandardTemplateService.save(insOrderStandardTemplate);
                }
            }
        }
        // todo: 成品抽样添加合格状态
        // 判断是否有抽样信息
        if (order.getQuarterItemId() != null) {
            // 判断是否有不合格
            Long unqualifiedCount = 0L;
            if (CollectionUtils.isNotEmpty(insSamples)) {
                unqualifiedCount = insProductMapper.selectCount(Wrappers.<InsProduct>lambdaQuery()
                        .in(InsProduct::getInsSampleId, insSamples.stream().map(InsSample::getId).collect(Collectors.toList()))
                        .eq(InsProduct::getInsResult, 0));
                // 判断如果有不合格的检验项, 判断有没有检验项复测, 复核合格也算合格通过
                if (!unqualifiedCount.equals(0L)) {
                    List<InsProduct> productList = insProductMapper.selectList(Wrappers.<InsProduct>lambdaQuery()
                            .in(InsProduct::getInsSampleId, insSamples.stream().map(InsSample::getId).collect(Collectors.toList()))
                            .eq(InsProduct::getInsResult, 0));
                    boolean flag = true;
                    for (InsProduct insProduct : productList) {
                        Long unqualifiedProductCount = insUnqualifiedRetestProductMapper.selectCount(Wrappers.<InsUnqualifiedRetestProduct>lambdaQuery()
                                .eq(InsUnqualifiedRetestProduct::getInsProductId, insProduct.getId())
                                .ne(InsUnqualifiedRetestProduct::getInsResult, 0));
                        if (unqualifiedProductCount != 2) {
                            flag = false;
                        }
                    }
                    if (flag) {
                        unqualifiedCount = 0L;
                    }
                }
            }
            spotCheckQuarterItemMapper.update(null, Wrappers.<SpotCheckQuarterItem>lambdaUpdate()
                    .eq(SpotCheckQuarterItem::getQuarterItemId, order.getQuarterItemId())
                    .set(SpotCheckQuarterItem::getResult, unqualifiedCount.equals(0L) ? "合格" : "不合格"));
        }
        // 发送企业微信通知
        threadPoolTaskExecutor.execute(() -> {
            String message = "";
            message += "检验任务复核通知";
            message += "\n提交人: " + userName;
            message += "\n委托编号: " + order.getEntrustCode();
            message += "\n样品名称: " + insSample.getModel();
            message += "\n规格型号: " + order.getPartDetail();
            if (ifsInventoryQuantity != null) {
                message += "\n批次号: " + ifsInventoryQuantity.getUpdateBatchNo();
            }
            //发送企业微信消息通知  提交复核
            try {
                WxCpUtils.inform(sendUserAccount, message, null);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
        // ifs移库
        if (ifsInventoryQuantity != null) {
            // 登记检验结果
            // 判断是否有不合格, 有不合格不能移库
            // todo: ifs移库
            insReportService.isRawMaterial(order);
        } else {
            // 修改成品状态
            // 判断是否有不合格
            Long unqualifiedCount = insReportService.getUnqualifiedCount(order);
            if (unqualifiedCount.equals(0L)) {
                insOrderMapper.update(null, Wrappers.<InsOrder>lambdaUpdate()
                        .eq(InsOrder::getId, order.getId())
                        .set(InsOrder::getInsResult, 1));
            } else {
                insOrderMapper.update(null, Wrappers.<InsOrder>lambdaUpdate()
                        .eq(InsOrder::getId, order.getId())
                        .set(InsOrder::getInsResult, 0));
            }
        }
        return 1;
    }
    public int pxToCm(int px) {
        return px / 9;
    }
    // 获取两个localDateTime的每一天
    public static List<LocalDateTime> getLocalDateTimesBetween(LocalDateTime start, LocalDateTime end) {
        List<LocalDateTime> localDateTimes = new ArrayList<>();
        LocalDate currentDate = start.toLocalDate();
        LocalDateTime currentLocalDateTime = start;
        while (!currentDate.isAfter(end.toLocalDate())) {
            localDateTimes.add(currentLocalDateTime);
            currentLocalDateTime = currentLocalDateTime.plusDays(1);
            currentDate = currentDate.plusDays(1);
        }
        return localDateTimes;
    }
    public static String getWeek(String dayStr) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = sdf.parse(dayStr);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
            int day = calendar.get(Calendar.DAY_OF_MONTH);
            return getWeekDay(dayOfWeek);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public static String getWeekDay(int dayOfWeek) {
        switch (dayOfWeek) {
            case Calendar.MONDAY:
                return "周一";
            case Calendar.TUESDAY:
                return "周二";
            case Calendar.WEDNESDAY:
                return "周三";
            case Calendar.THURSDAY:
                return "周四";
            case Calendar.FRIDAY:
                return "周五";
            case Calendar.SATURDAY:
                return "周六";
            case Calendar.SUNDAY:
                return "周日";
            default:
                return "未知";
        }
    }
@@ -1066,7 +1233,6 @@
     * @param orderId
     */
    private void generateReport(Integer orderId) {
        List<InsUnPass> insUnPasses = new ArrayList<>();
        /*样品下的项目只要有一个项目不合格则检验结果为0,否则为1*/
        //这里的insSamples是订单下的所有样品包括("/")
        List<InsSample> insSamples = insSampleMapper.selectList(Wrappers.<InsSample>lambdaQuery().eq(InsSample::getInsOrderId, orderId));
@@ -1082,25 +1248,7 @@
                insSample.setInsResult(1);
            }
            insSampleMapper.updateById(insSample);
            /*复核通过后,将不合格的项目信息添加到ins_un_pass表中*/
            for (InsProduct insProduct : insProducts) {
                if (insProduct.getInsResult() == 0) {
                    InsUnPass insUnPass = new InsUnPass();
                    insUnPass.setId(null);
                    insUnPass.setModel(insSample.getModel());
                    insUnPass.setSample(insSample.getSample());
                    insUnPass.setInspectionItem(insProduct.getInspectionItem());
                    insUnPass.setInspectionItemSubclass(insProduct.getInspectionItemSubclass());
                    insUnPass.setLastValue(insProduct.getLastValue());
                    insUnPass.setEntrustCode(insOrderMapper.selectById(orderId).getEntrustCode());
                    List<Integer> userIds = insProductUserMapper.selectList(Wrappers.<InsProductUser>lambdaQuery().eq(InsProductUser::getInsProductId, insProduct.getId())).stream().map(InsProductUser::getCreateUser).distinct().collect(Collectors.toList());
                    String name = userMapper.selectBatchIds(userIds).stream().map(User::getName).collect(Collectors.joining(","));
                    insUnPass.setName(name);
                    insUnPasses.add(insUnPass);
                }
            }
        }
        insUnPassService.saveBatch(insUnPasses);
        InsOrder insOrder = insOrderMapper.selectById(orderId);
        // 抽检变成委托检验
        if (insOrder.getOrderType().equals(InsOrderTypeConstants.SPOT_CHECK)) {
@@ -1153,36 +1301,13 @@
    }
    /**
     * 获取不合格数据
     * @return
     */
    @Override
    public List<InsProduct> getInsProductUnqualified(InsOrderPlanProductDto dto) {
        List<InsProduct> insProducts = new ArrayList<>();
        switch (dto.getType()) {
            case 0:
                //样品
                insProducts = insSampleMapper.getInsProduct1(dto.getId(), dto.getLaboratory(), dto.getCableTag(), dto.getRepetitionTag(), "1");
                break;
            case 4:
                //电缆配置
                insProducts = insSampleMapper.getInsProduct1(dto.getId(), dto.getLaboratory(), dto.getCableTag(), dto.getRepetitionTag(), "1");
                break;
            case 5:
                //原材料下单
                insProducts = insSampleMapper.getInsProduct6(dto.getId(), dto.getLaboratory(), dto.getRawMaterialTag(), "1");
                break;
        }
        return insProducts;
    }
    /**
     * 新增不合格复测内容
     * @param ids
     * @return
     */
    @Override
    public boolean addDisqualificationRetest(List<Integer> ids) {
    public boolean addDisqualificationRetest(List<InsProduct> insProductsList) {
        List<Integer> ids = insProductsList.stream().map(InsProduct::getId).collect(Collectors.toList());
        // 判断之前是否添加过
        Long count = insUnqualifiedRetestProductMapper.selectCount(Wrappers.<InsUnqualifiedRetestProduct>lambdaQuery()
                .in(InsUnqualifiedRetestProduct::getInsProductId, ids));
@@ -1192,6 +1317,20 @@
        // 查询不合格内容
        List<InsUnqualifiedRetestProduct> list = insUnqualifiedRetestProductMapper.selectRetestProduct(ids);
        // 循环判断是否是绑定值, 绑定值修改检验要求
        for (InsUnqualifiedRetestProduct insUnqualifiedRetestProduct : list) {
            for (InsProduct insProduct : insProductsList) {
                if (insProduct.getIsBinding().equals(1)) {
                    insUnqualifiedRetestProduct.setIsBinding(1);
                    insUnqualifiedRetestProduct.setAsk(null);
                    insUnqualifiedRetestProduct.setTell(null);
                    insUnqualifiedRetestProduct.setPrice(null);
                    insUnqualifiedRetestProduct.setManHour(null);
                    insUnqualifiedRetestProduct.setSection(null);
                }
            }
        }
        // 新增不合格内容
        insUnqualifiedRetestProductService.saveBatch(list);
        list.forEach(insUnqualifiedRetestProduct -> {
@@ -1203,38 +1342,29 @@
    }
    @Override
    public List<InsProduct> getInsProductUnqualifiedRetest(Integer id, Integer type, String laboratory, String cableTag, String rawMaterialTag, String retestTag) {
    public List<InsProduct> getInsProductUnqualifiedRetest(InsOrderPlanProductDto dto) {
        List<InsProduct> insProducts = new ArrayList<>();
        switch (type) {
        switch (dto.getType()) {
            case 0:
                //样品
                insProducts = insUnqualifiedRetestProductMapper.getInsProductUnqualifiedRetest1(id, laboratory, retestTag);
                break;
            case 4:
                //电缆配置
                insProducts = insUnqualifiedRetestProductMapper.getInsProductUnqualifiedRetest5(id, laboratory, cableTag, retestTag);
                //委托
                insProducts = insUnqualifiedRetestProductMapper.getInsProductUnqualifiedRetest1(dto.getId(), dto.getLaboratory(), dto.getCableTag(), dto.getRepetitionTag(), dto.getRetestTag());
                break;
            case 5:
                //原材料下单
                insProducts = insUnqualifiedRetestProductMapper.getInsProductUnqualifiedRetest6(id, laboratory, rawMaterialTag, retestTag);
                insProducts = insUnqualifiedRetestProductMapper.getInsProductUnqualifiedRetest6(dto.getId(), dto.getLaboratory(), dto.getRawMaterialTag(), dto.getRetestTag());
                break;
        }
        if (BeanUtil.isEmpty(insProducts)) {
            return null;
        }
        InsOrder order = insOrderMapper.selectFirstSubmit(id);
        InsOrder order = insOrderMapper.selectFirstSubmit(dto.getId());
        getTemplateThing(order, Collections.unmodifiableList(insProducts));
        return insProducts;
    }
    /**
     * 保存不合格复测检验内容
     * @param currentTable
     * @param orderId
     * @param sonLaboratory
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveUnqualifiedContext(Map<String, Object> insContext, Integer currentTable, Integer currentSampleId, Integer orderId, String sonLaboratory) {
@@ -1252,13 +1382,12 @@
                    BeanUtil.copyProperties(oldResults.get(0), newResult);
                }
                newResult.setRetestProductId(Integer.parseInt(k));
                /*校验一下result表*/
                if (oldResults.size() > 1) {
                    for (int i = 1; i < oldResults.size(); i++) {
                        insUnqualifiedRetestResultMapper.deleteById(oldResults.get(i));
                    }
                }
                //检验值
                if (jo.get("insValue") != null) {
                    JSONArray jsonArray = JSON.parseArray(JSON.toJSONString(jo.get("insValue")));
@@ -1289,6 +1418,8 @@
                    for (Object o : jsonArray2) {
                        JSONObject comValue = JSON.parseObject(JSON.toJSONString(o));
                        Map<String, Object> map = new HashMap<>();
                        map.put("r", JSON.toJSONString(comValue.get("r")));
                        map.put("c", JSON.toJSONString(comValue.get("c")));
                        map.put("v", JSON.parseObject(JSON.toJSONString(comValue.get("v"))).get("v"));
                        cv.add(map);
                    }
@@ -1351,41 +1482,18 @@
                insProductUserMapper.insert(new InsProductUser(null, userId, LocalDateTime.now(), insProduct.getId()));
                InsSample insSample = insSampleMapper.selectById(insProductMapper.selectById(insProduct.getId()).getInsSampleId());
                insSample.setInsState(1);
                Long l = insProductMapper.selectCount(Wrappers.<InsProduct>lambdaQuery()
                        .eq(InsProduct::getInsSampleId, insSample.getId()));
                Long l1 = insProductMapper.selectCount(Wrappers.<InsProduct>lambdaQuery()
                        .eq(InsProduct::getInsSampleId, insSample.getId())
                        .and(wrapper -> wrapper
                                .isNotNull(InsProduct::getInsResult)
                                .or()
                                .ne(InsProduct::getInsResult, 2)
                        ));
                if (Objects.equals(l, l1)) {
                    insSample.setInsState(2);
                }
                insSampleMapper.updateById(insSample);
                /*校验一下result表*/
                List<InsUnqualifiedRetestResult> insProductResults = insUnqualifiedRetestResultMapper.selectList(Wrappers.<InsUnqualifiedRetestResult>lambdaQuery()
                        .eq(InsUnqualifiedRetestResult::getRetestProductId, insProduct.getId()));
                        .eq(InsUnqualifiedRetestResult::getRetestProductId, product.getId()));
                if (insProductResults.size() > 1) {
                    for (int i = 1; i < insProductResults.size(); i++) {
                        insUnqualifiedRetestResultMapper.deleteById(insProductResults.get(i));
                    }
                }
            }
        });
        String sampleIdStr = insContext.keySet().stream().findFirst().orElse(null);
        if (sampleIdStr != null) {
            int count = insProductMapper.selectInsProductCountByOrderId(orderId);
            if (count == 0) {
                insOrderStateMapper.update(new InsOrderState(), Wrappers.<InsOrderState>lambdaUpdate()
                        .eq(InsOrderState::getInsOrderId, orderId)
                        .eq(InsOrderState::getLaboratory, sonLaboratory)
                        .set(InsOrderState::getInsState, 2));
            }
        }
    }
    /**
@@ -1527,9 +1635,9 @@
            standardMethod2.append("、").append(s);
        }
        standardMethod2.replace(0, 1, "");
        // todo: 检测类型
//        List<SysDictData> sysDictData = iSysDictTypeService.selectDictDataByName("");
        String orderType = null;
        // 样品类型
        String orderType = iSysDictTypeService.selectLabelByDict(DictDataConstants.CHECK_TYPE, insOrder.getOrderType());
        List<RowRenderData> rows = new ArrayList<>();
        List<TextRenderData> text = new ArrayList<>();
@@ -1870,10 +1978,6 @@
        ConfigureBuilder builder = Configure.builder();
        builder.useSpringEL(true);
        // 获取当前时间
        LocalDate currentDate = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String formattedDate = currentDate.format(formatter);
        InputStream inputStream = this.getClass().getResourceAsStream("/static/small-report-template.docx");
        XWPFTemplate template = XWPFTemplate.compile(inputStream, builder.build()).render(
@@ -1892,6 +1996,8 @@
                    put("seal1", null);
                }});
        try {
            // 修改换行和合并问题
            updaeMerge(template.getXWPFDocument(), true);
            String name = insReport.getCode().replace("/", "") + "-J.docx";
            template.writeAndClose(Files.newOutputStream(Paths.get(wordUrl + "/" + name)));
            insReport.setUrl("/word/" + name);
@@ -1902,12 +2008,10 @@
            insReportMapper.delete(Wrappers.<InsReport>lambdaQuery()
                    .eq(InsReport::getInsOrderId, insOrder.getId()));
            insReportMapper.insert(insReport);
            inputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 修改换行和合并问题
        updaeMerge(insReport, null, true);
    }
    /**
@@ -2045,7 +2149,6 @@
     * @param
     */
    private void addBitReport(Integer orderId, InsOrder insOrder) {
        Map<String, String> user = insProductMapper.selectUserById(insOrder.getUserId());
        //samples是不包括带有"/"的样品
        List<SampleProductDto> samples = insSampleMapper.selectSampleProductListByOrderId(orderId);
        InsReport insReport = new InsReport();
@@ -2064,7 +2167,6 @@
        boolean isOneSample = samples.size() == 1 ? true : false;
        /*基础报告(根据绘制的原始记录模版形成)*/
        samples.forEach(a -> {
            Map<Integer, String> map2 = new HashMap<>();
            models.add(a.getModel());
            String standardMethodCode = baseMapper.getStandardMethodCode(a.getStandardMethodListId());
            if (StrUtil.isNotBlank(a.getSpecialStandardMethod())) {
@@ -2275,10 +2377,19 @@
        tables.forEach(table -> {
            table.put("tableSize", tables.size() + 1);
        });
        // 设备信息
        List<Map<String, String>> deviceList = null;
        if (deviceSet.size() != 0) {
        if (CollectionUtils.isNotEmpty(deviceSet)) {
            deviceList = insOrderMapper.selectDeviceList(deviceSet);
        }
        if (CollectionUtils.isNotEmpty(deviceList)) {
            int count = 1;
            for (Map<String, String> stringMap : deviceList) {
                stringMap.put("index", String.valueOf(count));
                count++;
            }
        }
        Map<String, String> codeStr = new HashMap<>();
        codeStr.put("报告编号", insReport.getCode());
        codeStr.put("样品名称", insOrder.getSample());
@@ -2286,19 +2397,23 @@
        codeStr.put("发放日期", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        String modelStr = CollUtil.join(models, "\n");
        String finalModelStr = modelStr;
        // todo: 查询字典
        // 检测类型
        String orderType = null;
        String formType = null;
        orderType = iSysDictTypeService.selectLabelByDict(DictDataConstants.CHECK_TYPE, insOrder.getOrderType());
        // 判断第一个字典是否为空
        if (StringUtils.isBlank(orderType)) {
            orderType = iSysDictTypeService.selectLabelByDict(DictDataConstants.CHECK_TYPE1, insOrder.getOrderType());
        }
        // 来样方式
        String formType = iSysDictTypeService.selectLabelByDict(DictDataConstants.FORM_TYPE, insOrder.getFormType());
        // 样品状态
        String sampleStatus = null;
        String sampleStatus = iSysDictTypeService.selectLabelByDict(DictDataConstants.SAMPLE_STATUS_LIST, insOrder.getSampleStatus());
        ;
        ConfigureBuilder builder = Configure.builder();
        builder.useSpringEL(true);
        List<Map<String, String>> finalDeviceList = deviceList;
        Integer userId = insSampleUserMapper.selectOne(Wrappers.<InsSampleUser>lambdaQuery().eq(InsSampleUser::getInsSampleId, orderId).last("limit 1")).getUserId();
        // 公司信息
        Custom custom = customMapper.selectById(insOrder.getCompanyId());
        // 查询判断是否有不判定项目,和全都是判定项
@@ -2388,11 +2503,19 @@
        environment = (ObjectUtils.isNotEmpty(insOrder.getTemperature()) ? insOrder.getTemperature() + "℃ " : "") + (ObjectUtils.isNotEmpty(insOrder.getHumidity()) ? insOrder.getHumidity() + "%" : "");
        String finalEnvironment = environment;
        LocalDateTime finalSendTime = sendTime;
        String finalResultCh = resultCh;
        String finalResultEn = resultEn;
        String finalOrderType = orderType;
        List<Map<String, String>> finalDeviceList = deviceList;
        String finalModelStr = modelStr;
        InputStream inputStream = this.getClass().getResourceAsStream("/static/report-template.docx");
        XWPFTemplate template = XWPFTemplate.compile(inputStream, builder.build()).render(
        Configure configure = Configure.builder()
                .bind("deviceList", new HackLoopTableRenderPolicy())
                .useSpringEL(true)
                .build();
        XWPFTemplate template = XWPFTemplate.compile(inputStream, configure).render(
                new HashMap<String, Object>() {{
                    put("order", insOrder);
                    put("report", insReport);
@@ -2415,7 +2538,7 @@
                    put("images", images);
                    put("examineUrl", null);
                    put("ratifyUrl", null);
                    put("orderType", orderType);
                    put("orderType", finalOrderType);
                    put("getTime", finalSendTime.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日")));
                    put("getTimeEn", monthNames[finalSendTime.getMonthValue() - 1] + " " + finalSendTime.format(DateTimeFormatter.ofPattern("dd, yyyy")));
                    put("seal1", null);
@@ -2427,6 +2550,8 @@
                    put("sampleStatus", sampleStatus);
                }});
        try {
            // 修改换行和合并问题
            updaeMerge(template.getXWPFDocument(), false);
            String name = insReport.getCode().replace("/", "") + ".docx";
            template.writeAndClose(Files.newOutputStream(Paths.get(wordUrl + "/" + name)));
            insReport.setUrl("/word/" + name);
@@ -2436,11 +2561,10 @@
            insReportMapper.delete(Wrappers.<InsReport>lambdaQuery()
                    .eq(InsReport::getInsOrderId, insOrder.getId()));
            insReportMapper.insert(insReport);
            inputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 修改换行和合并问题
        updaeMerge(insReport, deviceList, false);
    }
    /**
@@ -2511,188 +2635,165 @@
    /**
     * 合并单元格
     * @param insReport
     * @param deviceList
     */
    private void updaeMerge(InsReport insReport, List<Map<String, String>> deviceList, boolean isSmall) {
    private void updaeMerge(XWPFDocument document, boolean isSmall) {
        // 处理合并单元格的问题
        String path = wordUrl + insReport.getUrl().replaceFirst("/word", "");
        try {
            // 获取文档中的所有表格
            FileInputStream stream = new FileInputStream(path);
            XWPFDocument document = new XWPFDocument(stream);
            List<XWPFTable> xwpfTables = document.getTables();
            // 遍历表格,但跳过第一个表格(如果deviceList为null,则额外跳过第二个)
            for (int i = 1; i < xwpfTables.size() - (deviceList == null ? 1 : 2); i++) {
                // 创建一个HashSet来存储唯一的字符串(这里基于"∑"分割后的第二部分)
                Set<String> set1 = new HashSet<>();
                // 创建一个HashMap来存储每个唯一字符串及其对应的单元格位置信息
                Map<String, Map<String, Integer>> maps = new HashMap<>();
                // 遍历当前表格的所有行
                for (int j = 0; j < xwpfTables.get(i).getRows().size(); j++) {
                    // 遍历当前行的所有单元格
                    for (int k = 0; k < xwpfTables.get(i).getRows().get(j).getTableCells().size(); k++) {
                        // 检查单元格文本中是否包含"∑"
                        if (xwpfTables.get(i).getRows().get(j).getTableCells().get(k).getText().indexOf("∑") > -1) {
                            String[] split = xwpfTables.get(i).getRows().get(j).getTableCells().get(k).getText().split("∑");
                            // 如果分割后的第二部分是新的(即之前未出现过),则添加到set1并创建位置信息map
                            if (set1.add(split[1])) {
                                Map<String, Integer> map = new HashMap<>();
                                // 存储起始行、起始列、结束行(当前行)、结束列(当前列)
                                map.put("sr", j);
                                map.put("sc", k);
                                map.put("er", j + 0);
                                map.put("ec", k + 0);
                                maps.put(split[1], map);
                            } else {
                                // 如果已存在,则更新结束行或结束列
                                Map<String, Integer> map1 = maps.get(split[1]);
                                if (j == map1.get("sr")) {
                                    map1.put("ec", map1.get("ec") + 1);
                                } else if (k == map1.get("sc")) {
                                    map1.put("er", map1.get("er") + 1);
                                }
        // 获取文档中的所有表格
        List<XWPFTable> xwpfTables = document.getTables();
        // 遍历表格
        for (int i = 1; i < xwpfTables.size(); i++) {
            // 创建一个HashSet来存储唯一的字符串(这里基于"∑"分割后的第二部分)
            Set<String> set1 = new HashSet<>();
            // 创建一个HashMap来存储每个唯一字符串及其对应的单元格位置信息
            Map<String, Map<String, Integer>> maps = new HashMap<>();
            // 遍历当前表格的所有行
            for (int j = 0; j < xwpfTables.get(i).getRows().size(); j++) {
                // 遍历当前行的所有单元格
                for (int k = 0; k < xwpfTables.get(i).getRows().get(j).getTableCells().size(); k++) {
                    // 检查单元格文本中是否包含"∑"
                    if (xwpfTables.get(i).getRows().get(j).getTableCells().get(k).getText().indexOf("∑") > -1) {
                        String[] split = xwpfTables.get(i).getRows().get(j).getTableCells().get(k).getText().split("∑");
                        // 如果分割后的第二部分是新的(即之前未出现过),则添加到set1并创建位置信息map
                        if (set1.add(split[1])) {
                            Map<String, Integer> map = new HashMap<>();
                            // 存储起始行、起始列、结束行(当前行)、结束列(当前列)
                            map.put("sr", j);
                            map.put("sc", k);
                            map.put("er", j + 0);
                            map.put("ec", k + 0);
                            maps.put(split[1], map);
                        } else {
                            // 如果已存在,则更新结束行或结束列
                            Map<String, Integer> map1 = maps.get(split[1]);
                            if (j == map1.get("sr")) {
                                map1.put("ec", map1.get("ec") + 1);
                            } else if (k == map1.get("sc")) {
                                map1.put("er", map1.get("er") + 1);
                            }
                            // 判断小高报告还是大报告
                            if (isSmall) {
                                // 获取单元格
                                XWPFTableCell cell = xwpfTables.get(i).getRows().get(j).getTableCells().get(k);
                                XWPFParagraph paragraph = cell.getParagraphArray(0);
                                String originalText = paragraph.getText();
                                String newText = originalText.split("∑")[0];
                                List<XWPFRun> runs = paragraph.getRuns();
                                for (XWPFRun run : runs) {
                                    run.setText("", 0); // 清空 run 中的文本
                                }
                                if (!runs.isEmpty()) {
                                    XWPFRun run = runs.get(0);
                                    run.setText(newText);
                                    // 复制样式
                                    run.setFontFamily(paragraph.getRuns().get(0).getFontFamily());
                                    run.setFontSize(paragraph.getRuns().get(0).getFontSize());
                                    run.setBold(paragraph.getRuns().get(0).isBold());
                                    run.setItalic(paragraph.getRuns().get(0).isItalic());
                                    run.setUnderline(paragraph.getRuns().get(0).getUnderline());
                                    run.setColor(paragraph.getRuns().get(0).getColor());
                                }
                                cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
                                paragraph.setAlignment(ParagraphAlignment.CENTER);
                            } else {
                                // 移除包含"∑"的段落,并重新设置单元格文本和样式
                                String str = xwpfTables.get(i).getRows().get(j).getTableCells().get(k).getText().split("∑")[0];
                                xwpfTables.get(i).getRows().get(j).getTableCells().get(k).removeParagraph(0);
                                xwpfTables.get(i).getRows().get(j).getTableCells().get(k).setText(str);
                                xwpfTables.get(i).getRows().get(j).getTableCells().get(k).setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
                                xwpfTables.get(i).getRows().get(j).getTableCells().get(k).getParagraphArray(0).setAlignment(ParagraphAlignment.CENTER);
                        }
                        // 判断小高报告还是大报告
                        if (isSmall) {
                            // 获取单元格
                            XWPFTableCell cell = xwpfTables.get(i).getRows().get(j).getTableCells().get(k);
                            XWPFParagraph paragraph = cell.getParagraphArray(0);
                            String originalText = paragraph.getText();
                            String newText = originalText.split("∑")[0];
                            List<XWPFRun> runs = paragraph.getRuns();
                            for (XWPFRun run : runs) {
                                run.setText("", 0); // 清空 run 中的文本
                            }
                            if (!runs.isEmpty()) {
                                XWPFRun run = runs.get(0);
                                run.setText(newText);
                                // 复制样式
                                run.setFontFamily(paragraph.getRuns().get(0).getFontFamily());
                                run.setFontSize(paragraph.getRuns().get(0).getFontSize());
                                run.setBold(paragraph.getRuns().get(0).isBold());
                                run.setItalic(paragraph.getRuns().get(0).isItalic());
                                run.setUnderline(paragraph.getRuns().get(0).getUnderline());
                                run.setColor(paragraph.getRuns().get(0).getColor());
                            }
                            cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
                            paragraph.setAlignment(ParagraphAlignment.CENTER);
                        } else {
                            // 移除包含"∑"的段落,并重新设置单元格文本和样式
                            String str = xwpfTables.get(i).getRows().get(j).getTableCells().get(k).getText().split("∑")[0];
                            xwpfTables.get(i).getRows().get(j).getTableCells().get(k).removeParagraph(0);
                            xwpfTables.get(i).getRows().get(j).getTableCells().get(k).setText(str);
                            xwpfTables.get(i).getRows().get(j).getTableCells().get(k).setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
                            xwpfTables.get(i).getRows().get(j).getTableCells().get(k).getParagraphArray(0).setAlignment(ParagraphAlignment.CENTER);
                        }
                    }
                }
            }
                // 单元格排序, 避免格式错乱
                List<Map.Entry<String, Map<String, Integer>>> entries = new ArrayList<>(maps.entrySet());
                entries.sort((o1, o2) -> o1.getValue().get("sc") - o2.getValue().get("sc"));
            // 单元格排序, 避免格式错乱
            List<Map.Entry<String, Map<String, Integer>>> entries = new ArrayList<>(maps.entrySet());
            entries.sort((o1, o2) -> o1.getValue().get("sc") - o2.getValue().get("sc"));
                // 按照顺序添加进集合
                List<String> list = new ArrayList<>();
                for (Map.Entry<String, Map<String, Integer>> entry : entries) {
                    list.add(entry.getKey());
                }
            // 按照顺序添加进集合
            List<String> list = new ArrayList<>();
            for (Map.Entry<String, Map<String, Integer>> entry : entries) {
                list.add(entry.getKey());
            }
                for (int a = list.size() - 1; a >= 0; a--) {
                    Map<String, Integer> v = maps.get(list.get(a));
                    for (int j = 0; j < v.get("er") - v.get("sr") + 1; j++) {
                        if (v.get("ec") > v.get("sc")) {
                            try {
                                TableTools.mergeCellsHorizonal(xwpfTables.get(i), v.get("sr") + j, v.get("sc"), v.get("ec"));
                            } catch (Exception e) {
                            }
                        }
                    }
                    if (v.get("er") > v.get("sr")) {
            for (int a = list.size() - 1; a >= 0; a--) {
                Map<String, Integer> v = maps.get(list.get(a));
                for (int j = 0; j < v.get("er") - v.get("sr") + 1; j++) {
                    if (v.get("ec") > v.get("sc")) {
                        try {
                            TableTools.mergeCellsVertically(xwpfTables.get(i), v.get("sc"), v.get("sr"), v.get("er"));
                            TableTools.mergeCellsHorizonal(xwpfTables.get(i), v.get("sr") + j, v.get("sc"), v.get("ec"));
                        } catch (Exception e) {
                        }
                    }
                }
                if (v.get("er") > v.get("sr")) {
                    try {
                        TableTools.mergeCellsVertically(xwpfTables.get(i), v.get("sc"), v.get("sr"), v.get("er"));
                    } catch (Exception e) {
                    }
                }
            }
            FileOutputStream fileOutputStream = new FileOutputStream(path);
            document.write(fileOutputStream);
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //处理中英文换行的问题
        try {
            FileInputStream stream1 = new FileInputStream(path);
            XWPFDocument document1 = new XWPFDocument(stream1);
            List<XWPFTable> xwpfTables1 = document1.getTables();
            for (int i = 1; i < xwpfTables1.size() - (deviceList == null ? 1 : 2); i++) {
                for (int j = 0; j < xwpfTables1.get(i).getRows().size(); j++) {
                    for (int k = 0; k < xwpfTables1.get(i).getRows().get(j).getTableCells().size(); k++) {
                        if (xwpfTables1.get(i).getRows().get(j).getTableCells().get(k).getText().contains("@")) {
                            if (isSmall) {
                                // 获取原有段落的第一个 XWPFRun
                                String text = xwpfTables1.get(i).getRows().get(j).getTableCells().get(k).getText();
                                XWPFParagraph oldParagraph = xwpfTables1.get(i).getRows().get(j).getTableCells().get(k).getParagraphs().get(0);
                                XWPFRun oldRun = oldParagraph.getRuns().get(0);
                                // 保存原有样式
                                String fontFamily = oldRun.getFontFamily();
                                int fontSize = oldRun.getFontSize();
                                boolean isBold = oldRun.isBold();
                                boolean isItalic = oldRun.isItalic();
                                boolean isUnderline = oldRun.getUnderline() != UnderlinePatterns.NONE;
                                // 删除原有段落
                                xwpfTables1.get(i).getRows().get(j).getTableCells().get(k).removeParagraph(0);
                                // 添加新段落
                                XWPFParagraph newParagraph = xwpfTables1.get(i).getRows().get(j).getTableCells().get(k).addParagraph();
                                XWPFRun newRun = newParagraph.createRun();
                                // 应用保存的样式
                                newRun.setFontFamily(fontFamily);
                                newRun.setFontSize(fontSize);
                                newRun.setBold(isBold);
                                newRun.setItalic(isItalic);
                                if (isUnderline) {
                                    newRun.setUnderline(UnderlinePatterns.SINGLE);
                                }
                                // 设置新文本
                                String[] split = text.split("@");
                                newRun.setText(split[0]);
                                if (split.length > 1) {
                                    newRun.addBreak();
                                    newRun.setText(split[1]);
                                }
                                // 设置段落对齐方式
                                newParagraph.setAlignment(ParagraphAlignment.CENTER);
                            } else {
                                String text = xwpfTables1.get(i).getRows().get(j).getTableCells().get(k).getText();
                                String[] split = text.split("@");
                                xwpfTables1.get(i).getRows().get(j).getTableCells().get(k).removeParagraph(0);
                                XWPFParagraph xwpfParagraph = xwpfTables1.get(i).getRows().get(j).getTableCells().get(k).addParagraph();
                                XWPFRun run = xwpfParagraph.createRun();
                                run.setText(split[0]);
                                if (ObjectUtils.isNotNull(split[1])) {
                                    run.addBreak();
                                    run.setText(split[1]);
                                }
                                xwpfParagraph.setAlignment(ParagraphAlignment.CENTER);
        List<XWPFTable> xwpfTables1 = document.getTables();
        for (int i = 1; i < xwpfTables1.size(); i++) {
            for (int j = 0; j < xwpfTables1.get(i).getRows().size(); j++) {
                for (int k = 0; k < xwpfTables1.get(i).getRows().get(j).getTableCells().size(); k++) {
                    if (xwpfTables1.get(i).getRows().get(j).getTableCells().get(k).getText().contains("@")) {
                        if (isSmall) {
                            // 获取原有段落的第一个 XWPFRun
                            String text = xwpfTables1.get(i).getRows().get(j).getTableCells().get(k).getText();
                            XWPFParagraph oldParagraph = xwpfTables1.get(i).getRows().get(j).getTableCells().get(k).getParagraphs().get(0);
                            XWPFRun oldRun = oldParagraph.getRuns().get(0);
                            // 保存原有样式
                            String fontFamily = oldRun.getFontFamily();
                            int fontSize = oldRun.getFontSize();
                            boolean isBold = oldRun.isBold();
                            boolean isItalic = oldRun.isItalic();
                            boolean isUnderline = oldRun.getUnderline() != UnderlinePatterns.NONE;
                            // 删除原有段落
                            xwpfTables1.get(i).getRows().get(j).getTableCells().get(k).removeParagraph(0);
                            // 添加新段落
                            XWPFParagraph newParagraph = xwpfTables1.get(i).getRows().get(j).getTableCells().get(k).addParagraph();
                            XWPFRun newRun = newParagraph.createRun();
                            // 应用保存的样式
                            newRun.setFontFamily(fontFamily);
                            newRun.setFontSize(fontSize);
                            newRun.setBold(isBold);
                            newRun.setItalic(isItalic);
                            if (isUnderline) {
                                newRun.setUnderline(UnderlinePatterns.SINGLE);
                            }
                            // 设置新文本
                            String[] split = text.split("@");
                            newRun.setText(split[0]);
                            if (split.length > 1) {
                                newRun.addBreak();
                                newRun.setText(split[1]);
                            }
                            // 设置段落对齐方式
                            newParagraph.setAlignment(ParagraphAlignment.CENTER);
                        } else {
                            String text = xwpfTables1.get(i).getRows().get(j).getTableCells().get(k).getText();
                            String[] split = text.split("@");
                            xwpfTables1.get(i).getRows().get(j).getTableCells().get(k).removeParagraph(0);
                            XWPFParagraph xwpfParagraph = xwpfTables1.get(i).getRows().get(j).getTableCells().get(k).addParagraph();
                            XWPFRun run = xwpfParagraph.createRun();
                            run.setText(split[0]);
                            if (ObjectUtils.isNotNull(split[1])) {
                                run.addBreak();
                                run.setText(split[1]);
                            }
                            xwpfParagraph.setAlignment(ParagraphAlignment.CENTER);
                        }
                    }
                }
            }
            FileOutputStream fileOutputStream1 = new FileOutputStream(path);
            document1.write(fileOutputStream1);
            fileOutputStream1.close();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
@@ -4015,7 +4116,7 @@
    }
    /**
     * 保存元此阿里进货验证原始记录
     * *****保存元此阿里进货验证原始记录*****
     * @param insOrderId 订单Id
     * @param examineUserId  复核人Id
     * @param writeUserId  检验员Id
@@ -4135,6 +4236,11 @@
        // 保存到附件里面
        uploadFile(insOrderId, multipartFile);
        try {
            inputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
@@ -4165,7 +4271,7 @@
    /**
     * 格式化进厂验证内容
     * ***格式化进厂验证内容****
     * @param basicType
     * @return
     */
@@ -4194,7 +4300,7 @@
    }
    /**
     * word转换pdf
     * ***word转换pdf***
     * @param path
     * @return
     */
@@ -4211,11 +4317,10 @@
        FileOutputStream os = null;
        try {
            //凭证 不然切换后有水印
            InputStream is = Files.newInputStream(new File(licenseUrl).toPath());
            InputStream is = new ClassPathResource("/lib/license.xml").getInputStream();
            License license = new License();
            license.setLicense(is);
            if (!license.getIsLicensed()) {
                System.out.println("License验证不通过...");
                return null;
            }
            //生成一个空的PDF文件
@@ -4243,6 +4348,43 @@
    }
    /**
     * *****修改成品抽样状态******
     * @param insSamples
     * @param order
     */
    private void addProductSpotCheck(List<InsSample> insSamples, InsOrder order) {
        Long unqualifiedCount = 0L;
        if (CollectionUtils.isNotEmpty(insSamples)) {
            unqualifiedCount = insProductMapper.selectCount(Wrappers.<InsProduct>lambdaQuery()
                    .in(InsProduct::getInsSampleId, insSamples.stream().map(InsSample::getId).collect(Collectors.toList()))
                    .eq(InsProduct::getInsResult, 0));
            // 判断如果有不合格的检验项, 判断有没有检验项复测, 复核合格也算合格通过
            if (!unqualifiedCount.equals(0L)) {
                List<InsProduct> productList = insProductMapper.selectList(Wrappers.<InsProduct>lambdaQuery()
                        .in(InsProduct::getInsSampleId, insSamples.stream().map(InsSample::getId).collect(Collectors.toList()))
                        .eq(InsProduct::getInsResult, 0));
                boolean flag = true;
                for (InsProduct insProduct : productList) {
                    Long unqualifiedProductCount = insUnqualifiedRetestProductMapper.selectCount(Wrappers.<InsUnqualifiedRetestProduct>lambdaQuery()
                            .eq(InsUnqualifiedRetestProduct::getInsProductId, insProduct.getId())
                            .ne(InsUnqualifiedRetestProduct::getInsResult, 0));
                    if (unqualifiedProductCount != 2) {
                        flag = false;
                    }
                }
                if (flag) {
                    unqualifiedCount = 0L;
                }
            }
        }
        spotCheckQuarterItemMapper.update(null, Wrappers.<SpotCheckQuarterItem>lambdaUpdate()
                .eq(SpotCheckQuarterItem::getQuarterItemId, order.getQuarterItemId())
                .set(SpotCheckQuarterItem::getResult, unqualifiedCount.equals(0L) ? "合格" : "不合格"));
    }
    /**
     * 添加工时
     * @param userId
     * @param insProduct
@@ -4253,43 +4395,80 @@
            return;
        }
        //首先判断当前人的当前时间是否是排班时间内,如果不是就是加班
        LocalDateTime today = LocalDateTime.of(LocalDate.now(), LocalTime.MIDNIGHT);
        //校验如果这个人这个检测项目已经添加过了
        List<AuxiliaryOutputWorkingHours> count2s = auxiliaryOutputWorkingHoursMapper.selectList(Wrappers.<AuxiliaryOutputWorkingHours>lambdaQuery()
                .eq(AuxiliaryOutputWorkingHours::getCheck, userId)
                .eq(AuxiliaryOutputWorkingHours::getInsProductId, insProduct.getId()));
        if (CollectionUtils.isNotEmpty(count2s)) {
            auxiliaryOutputWorkingHoursMapper.deleteBatchIds(count2s.stream().map(auxiliaryOutputWorkingHours -> auxiliaryOutputWorkingHours.getId()).collect(Collectors.toList()));
        }
        if (ObjectUtils.isNotEmpty(insProduct.getManHour()) && StringUtils.isNotBlank(insProduct.getLastValue())) {
            AuxiliaryOutputWorkingHours auxiliaryOutputWorkingHours = new AuxiliaryOutputWorkingHours();
            auxiliaryOutputWorkingHours.setInspectionItemClass(insProduct.getInspectionItemClass());//检测项分类
            auxiliaryOutputWorkingHours.setInspectionItem(insProduct.getInspectionItem());//检测父项
            auxiliaryOutputWorkingHours.setInspectionItemSubclass(insProduct.getInspectionItemSubclass());//检测子项
            auxiliaryOutputWorkingHours.setSample(insSampleMapper.selectById(insProduct.getInsSampleId()).getSampleCode());//样品编号
            auxiliaryOutputWorkingHours.setOrderId(insOrder.getId());//订单id
            auxiliaryOutputWorkingHours.setOrderNo(insOrder.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
            for (AuxiliaryOutputWorkingHours auxiliaryOutputWorkingHours : count2s) {
                auxiliaryOutputWorkingHours.setCheck(userId);//检测人
            }
            auxiliaryOutputWorkingHoursService.updateBatchById(count2s);
        } else {
            if (ObjectUtils.isNotEmpty(insProduct.getManHour()) && StringUtils.isNotBlank(insProduct.getLastValue())) {
                AuxiliaryOutputWorkingHours auxiliaryOutputWorkingHours = new AuxiliaryOutputWorkingHours();
                auxiliaryOutputWorkingHours.setInspectionItemClass(insProduct.getInspectionItemClass());//检测项分类
                auxiliaryOutputWorkingHours.setInspectionItem(insProduct.getInspectionItem());//检测父项
                auxiliaryOutputWorkingHours.setInspectionItemSubclass(insProduct.getInspectionItemSubclass());//检测子项
                auxiliaryOutputWorkingHours.setSample(insSampleMapper.selectById(insProduct.getInsSampleId()).getSampleCode());//样品编号
                auxiliaryOutputWorkingHours.setOrderId(insOrder.getId());//订单id
                auxiliaryOutputWorkingHours.setOrderNo(insOrder.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
            auxiliaryOutputWorkingHoursMapper.insert(auxiliaryOutputWorkingHours);
                auxiliaryOutputWorkingHoursMapper.insert(auxiliaryOutputWorkingHours);
            }
        }
    }
    public static String getWeek(String dayStr) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = sdf.parse(dayStr);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
            int day = calendar.get(Calendar.DAY_OF_MONTH);
            return getWeekDay(dayOfWeek);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public static String getWeekDay(int dayOfWeek) {
        switch (dayOfWeek) {
            case Calendar.MONDAY:
                return "周一";
            case Calendar.TUESDAY:
                return "周二";
            case Calendar.WEDNESDAY:
                return "周三";
            case Calendar.THURSDAY:
                return "周四";
            case Calendar.FRIDAY:
                return "周五";
            case Calendar.SATURDAY:
                return "周六";
            case Calendar.SUNDAY:
                return "周日";
            default:
                return "未知";
        }
    }
}