zouyu
7 天以前 56e6e0bf18c39a933aec78762b636fdf2efa8d68
inspect-server/src/main/java/com/ruoyi/inspect/service/impl/InsOrderPlanServiceImpl.java
@@ -2,6 +2,7 @@
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
@@ -32,9 +33,11 @@
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.User;
import com.ruoyi.common.enums.OrderType;
import com.ruoyi.common.utils.*;
import com.ruoyi.framework.exception.ErrorException;
import com.ruoyi.inspect.dto.*;
@@ -44,9 +47,8 @@
import com.ruoyi.inspect.util.HackLoopTableRenderPolicy;
import com.ruoyi.inspect.vo.InsOrderPlanTaskSwitchVo;
import com.ruoyi.inspect.vo.InsOrderPlanVO;
import com.ruoyi.inspect.vo.InsSampleUserVO;
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.service.AuxiliaryOutputWorkingHoursService;
import com.ruoyi.system.mapper.CustomMapper;
@@ -55,8 +57,8 @@
import com.ruoyi.system.service.InformationNotificationService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xwpf.usermodel.*;
import org.jetbrains.annotations.NotNull;
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;
@@ -69,13 +71,11 @@
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;
@@ -102,14 +102,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
@@ -117,11 +112,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
@@ -130,11 +123,12 @@
    private CustomMapper customMapper;
    @Value("${file.path}")
    private String imgUrl;
    @Resource
    private InsOrderFileMapper insOrderFileMapper;
    @Resource
    private IfsInventoryQuantityMapper ifsInventoryQuantityMapper;
    @Resource
    private IfsPartPropsRecordMapper ifsPartPropsRecordMapper;
    @Resource
    private InsReportService insReportService;
    @Resource
@@ -149,8 +143,7 @@
    private InsOrderFactoryVerifyMapper insOrderFactoryVerifyMapper;
    @Resource
    private InsOrderFactoryVerifyItemService insOrderFactoryVerifyItemService;
    @Value("${file.licenseUrl}")
    private String licenseUrl;
    @Resource
    private SpotCheckQuarterItemMapper spotCheckQuarterItemMapper;
    @Resource
@@ -161,15 +154,19 @@
    private InsOrderDeviceRecordService insOrderDeviceRecordService;
    @Resource
    private ISysDictTypeService iSysDictTypeService;
    @Resource
    private InsOrderRatesService insOrderRatesService;
    @Resource
    private InsProductDeviationWarningService insProductDeviationWarningService;
    @Resource
    private InsProductDeviationWarningDetailService insProductDeviationWarningDetailService;
    @Override
    public IPage<InsOrderPlanVO> selectInsOrderPlanList(Page page, InsOrderPlanDTO insOrderPlanDTO) {
        // todo: 仅看自己或者实验室
        //获取当前人所属实验室id
        String laboratory = null;
        String userName = null;
        Integer userId = null;
        if (ObjectUtil.isNotEmpty(insOrderPlanDTO.getUserId())) {
@@ -235,17 +232,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;
@@ -256,16 +255,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)) {
@@ -278,7 +274,8 @@
    }
    @Override
    public List<String> checkSubmitPlan(Integer orderId, String laboratory) {
    public Map<String,Object> checkSubmitPlan(Integer orderId, String laboratory) {
        Map<String, Object> map = new HashMap<>();
        List<String> collect = new ArrayList<>();
        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());
@@ -304,7 +301,19 @@
                return insProduct.getInspectionItem() + "-" + insProduct.getInspectionItemSubclass();
            }).collect(Collectors.toList());
        }
        return collect;
        //查询ifs拆分订单是否有已下单但是未检完的单子
        long count = 0L;
        InsOrder insOrder = insOrderMapper.selectById(orderId);
        if(Objects.nonNull(insOrder.getIfsInventoryId())){
            IfsInventoryQuantity one = ifsInventoryQuantityMapper.selectById(insOrder.getIfsInventoryId());
            //过滤出不合格或未提交的单子
            count = ifsInventoryQuantityMapper.selectSplitOrderList(one.getPartNo(),one.getLineNo(),one.getReleaseNo(),one.getReceiptNo(),one.getOrderNo())
                    .stream()
                    .filter(f->(Objects.nonNull(f.getInsOrderId()) && !Objects.equals(f.getInsOrderId(),orderId)) && (Objects.isNull(f.getInsResult()) || 0==f.getInsResult())).count();
        }
        map.put("errorMsg",collect);
        map.put("unInsOrderCount",count);
        return map;
    }
    @Override
@@ -362,15 +371,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();
@@ -500,22 +510,34 @@
                    }
                }
                //查询检验单信息
                // 添加工时
                InsProduct finalInsProduct = insProductMapper.selectById(product.getId());
                threadPoolTaskExecutor.execute(() -> {
                    InsOrder insOrder = insOrderMapper.selectById(insSample.getInsOrderId());
                    this.addAuxiliary(userId, finalInsProduct, insOrder);
                });
                // 判断是否只是参与计算值, 参与计算值实际没有填写
                if (StringUtils.isNotBlank(newResult.getInsValue()) && !newResult.getInsValue().equals("[]")) {
                    threadPoolTaskExecutor.execute(() -> {
                        InsProduct finalInsProduct = insProductMapper.selectById(product.getId());
                        InsOrder insOrder = insOrderMapper.selectById(insSample.getInsOrderId());
                        this.addAuxiliary(userId, finalInsProduct, insOrder);
                    });
                } else {
                    // 判断是否是没有检验值的内容
                    if (saveInsContextDto.getIsNoTestValue() != null && saveInsContextDto.getIsNoTestValue() == 1) {
                        threadPoolTaskExecutor.execute(() -> {
                            InsProduct finalInsProduct = insProductMapper.selectById(product.getId());
                            InsOrder insOrder = insOrderMapper.selectById(insSample.getInsOrderId());
                            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));
            }
        }
@@ -523,55 +545,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) {
@@ -598,20 +625,6 @@
     */
    private void getTemplateThing(InsOrder order, List<InsProduct> insProducts) {
        Set<Integer> set = new HashSet<>();
        // 检验项分类+检验项+检验子项的拼接
//        List<String> itemNameList = insProducts.stream().map(insProduct -> {
//            String itemName = "";
//            if (StringUtils.isNotBlank(insProduct.getInspectionItemClass())) {
//                itemName += insProduct.getInspectionItemClass().trim();
//            }
//            if (StringUtils.isNotBlank(insProduct.getInspectionItem())) {
//                itemName += insProduct.getInspectionItem().trim();
//            }
//            if (StringUtils.isNotBlank(insProduct.getInspectionItemSubclass())) {
//                itemName += insProduct.getInspectionItemSubclass().trim();
//            }
//            return itemName;
//        }).collect(Collectors.toList());
        // 查询订单状态判断是否是查历史模板
        if (order.getIsFirstSubmit() != null && order.getIsFirstSubmit().equals(1)) {
            InsOrderState insOrderState = insOrderStateMapper.selectOne(Wrappers.<InsOrderState>lambdaQuery()
@@ -670,7 +683,7 @@
    }
    /**
     * todo: 清除没有使用的检验项
     * todo: 原始记录模板清除没有使用的检验项(暂时有bug无法使用)
     * @param sheet
     * @param itemNameList
     */
@@ -755,9 +768,9 @@
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int submitPlan(Integer orderId, String laboratory, Integer verifyUser, String entrustCode) {
    public int submitPlan(Integer orderId, String laboratory, Integer verifyUser, String entrustCode,Boolean registerInsResults) {
        InsOrder order = insOrderMapper.selectById(orderId);
        // 判断是否有重复编号, 有重复编号做提醒
        // 1. 判断是否有重复编号, 有重复编号做提醒
        Long codeCount = insOrderMapper.selectCount(Wrappers.<InsOrder>lambdaQuery()
                .ne(InsOrder::getState, -1)
                .ne(InsOrder::getIfsInventoryId, order.getIfsInventoryId())
@@ -766,7 +779,7 @@
            throw new ErrorException("当前编号有重复, 请先去修改重复编号");
        }
        // 判断该订单是否是第一次生产
        // 2. 判断该订单是否是第一次生产(后续报告生成只取第一次提交时间)
        if (!(order.getIsFirstSubmit() != null && order.getIsFirstSubmit().equals(1))) {
            insOrderMapper.update(null, Wrappers.<InsOrder>lambdaUpdate()
                    .eq(InsOrder::getId, orderId)
@@ -774,11 +787,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
@@ -786,37 +800,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");
@@ -825,18 +839,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()
@@ -847,26 +862,245 @@
                    }
                }
            }
            return null;
        });
        // 提交生成报告
        // 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,registerInsResults,false);
            // 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 (CollectionUtils.isEmpty(insProductAnalysisDtoList)) {
                    continue;
                }
                // 判断当前检测项是否偏差超过10%
                List<String> laseValueList = insProductAnalysisDtoList.stream().map(InsProductDeviationWarningDetail::getTestValue)
                        .collect(Collectors.toList());
                double deviation = isDeviationOverTenPercent(laseValueList, insProduct.getLastValue());
                double asked = isDeviationOverTenPercentByAsked(insProduct.getAsk(), insProduct.getLastValue());
                // 判断偏差是否大于10
                if (deviation > 10 || asked > 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(deviation > 10 ? 1 : 0);
                        deviationWarningDetail.setIsIssueAsked(asked > 10 ? 1 : 0);
                        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 targetStr
     * @return
     */
    public static double isDeviationOverTenPercentByAsked(String asked, String targetStr) {
        if(!isNumeric(asked)) return 0;
        double average = Double.parseDouble(asked);
        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));
@@ -890,137 +1124,6 @@
                    insOrderStandardTemplateService.save(insOrderStandardTemplate);
                }
            }
        }
        // 成品抽样添加合格状态
        // 判断是否有抽样信息
        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 "未知";
        }
    }
@@ -1092,7 +1195,7 @@
                IfsInventoryQuantity ifsInventoryQuantity = ifsInventoryQuantityMapper.selectById(order.getIfsInventoryId());
                String message = "";
                message += "报告编制审批通知";
                message += "耐丝系统报告编制审批通知";
                message += "\n检验人: " + userName;
                message += "\n复核人: " + chenkUserName;
                message += "\n委托编号: " + order.getEntrustCode();
@@ -1134,7 +1237,7 @@
                IfsInventoryQuantity ifsInventoryQuantity = ifsInventoryQuantityMapper.selectById(order.getIfsInventoryId());
                String message = "";
                message += "检验任务复核退回通知";
                message += "耐丝系统检验任务复核退回通知";
                message += "\n复核人: " + userName;
                message += "\n委托编号: " + order.getEntrustCode();
                message += "\n样品名称: " + insSample.getModel();
@@ -1159,7 +1262,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));
@@ -1175,25 +1277,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)) {
@@ -1246,36 +1330,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));
@@ -1285,6 +1346,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 -> {
@@ -1296,38 +1371,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) {
@@ -1345,13 +1411,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")));
@@ -1382,6 +1447,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);
                    }
@@ -1444,41 +1511,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));
            }
        }
    }
    /**
@@ -1588,6 +1632,95 @@
    /*****************************************************  小报告    ***************************************************************************/
    /**
     * 设置表格样式
     * @param max 标识最大个数
     * @return
     */
    private TableStyle setTableStyle(int max){
        //设置样式
        TableStyle tableStyle = new TableStyle();
        if(max<=5){
            for (int i = 1; i <= max; i++) {
                // 根据检验结果个数修改长度
                switch (i) {
                    case 1:
                        tableStyle.setColWidths(new int[]{650, 2900, 850, 2300, 2100, 1200});
                        break;
                    case 2:
                        tableStyle.setColWidths(new int[]{650, 2700, 850, 2200, 1200, 1200, 1200});
                        break;
                    case 3:
                        tableStyle.setColWidths(new int[]{650, 2700, 850, 1600, 1000, 1000, 1000, 1200});
                        break;
                    case 4:
                        tableStyle.setColWidths(new int[]{650, 2400, 850, 1500, 850, 850, 850, 850, 1200});
                        break;
                    case 5:
                        tableStyle.setColWidths(new int[]{650, 2200, 850, 1350, 770, 770, 770, 770, 770, 1100});
                        break;
                }
            }
        }
        tableStyle.setWidth("10000");
        tableStyle.setAlign(TableRowAlign.CENTER);
        BorderStyle borderStyle = new BorderStyle();
        borderStyle.setColor("000000");
        borderStyle.setType(XWPFTable.XWPFBorderType.SINGLE);
        borderStyle.setSize(4);
        tableStyle.setLeftBorder(borderStyle);
        tableStyle.setRightBorder(borderStyle);
        tableStyle.setInsideHBorder(borderStyle); // 设置水平内边框
        tableStyle.setInsideVBorder(borderStyle);
        return tableStyle;
    }
    /**
     * 处理有电缆颜色标识的检测项
     * @param cableTags 电缆颜色标识
     * @param collect   检测项列表
     * @param startIndex 起始下标
     * @param endIndex   结束下标
     * @return
     */
    private List<SampleProductExportDto> transformSampleProduct(List<String> cableTags,Map<String, List<SampleProductExportDto>> collect,int startIndex,int endIndex){
        List<SampleProductExportDto> sampleProductExportDtos = new ArrayList<>();
        for (String s : collect.keySet()) {
            List<String> lastValueList = new ArrayList<>();
            SampleProductExportDto dto = new SampleProductExportDto();
            BeanUtil.copyProperties(collect.get(s).get(0),dto);
            Set<String> tellSet = new HashSet<>();
            for (int i = startIndex; i < endIndex; i++) {
                String cableTag = cableTags.get(i);
                for (SampleProductExportDto sDto : collect.get(s)) {
                    tellSet.add(sDto.getTell());
                    if(sDto.getCableTag().equals(cableTag)){
                        lastValueList.add(sDto.getLastValue());
                    }
                }
            }
            //切割电缆配置项
            dto.setTell(String.join("\n",tellSet));
            dto.setLastValueList(lastValueList);
            sampleProductExportDtos.add(dto);
        }
        return sampleProductExportDtos;
    }
    /**
     * 检测项排序
     * @param sourceMap
     * @param targetMap
     */
    private void sortSampleProduct(Map<String, List<SampleProductExportDto>> sourceMap,Map<String, List<SampleProductExportDto>> targetMap){
        List<Map.Entry<String, List<SampleProductExportDto>>> entries = new ArrayList<>(sourceMap.entrySet());
        entries.sort(Comparator.comparingInt(o -> (o.getValue().get(0).getSort() == null ? 0 : o.getValue().get(0).getSort())));
        for (Map.Entry<String, List<SampleProductExportDto>> entry : entries) {
            targetMap.put(entry.getKey(), entry.getValue());
        }
    }
    /**
     * 小报告生成
     * @param orderId
     * @param insOrder
@@ -1605,11 +1738,17 @@
        enterFactoryReport.setSample(insOrder.getSample());
        // 获取ifs数据
        IfsInventoryQuantity ifsInventoryQuantity = ifsInventoryQuantityMapper.selectById(insOrder.getIfsInventoryId());
        //查询零件属性
        IfsPartPropsRecord ifsPartPropsRecord = ifsPartPropsRecordMapper.selectOne(Wrappers.<IfsPartPropsRecord>lambdaQuery()
                .eq(IfsPartPropsRecord::getIfsInventoryId, ifsInventoryQuantity.getId()));
        if(Objects.nonNull(ifsPartPropsRecord)){
            enterFactoryReport.setOuterColor(ifsPartPropsRecord.getOuterColor());
        }
        enterFactoryReport.setQtyArrived(ifsInventoryQuantity.getQtyArrived() == null ? "" :
                ifsInventoryQuantity.getQtyArrived().stripTrailingZeros().toPlainString() + ifsInventoryQuantity.getBuyUnitMeas());
        enterFactoryReport.setQuantity(insOrder.getTestQuantity());
        enterFactoryReport.setPartDesc(insOrder.getPartDetail());
        enterFactoryReport.setSupplierName("**********");
        enterFactoryReport.setSupplierName(ifsInventoryQuantity.getSupplierName());
        enterFactoryReport.setLotBatchNo(ifsInventoryQuantity.getUpdateBatchNo());
        // 检测依据
@@ -1627,6 +1766,7 @@
        List<RowRenderData> rows = new ArrayList<>();
        List<TextRenderData> text = new ArrayList<>();
        RowRenderData rowRenderData = null;
        List<Map<String,Object>> cableTagEnclosureTables = new ArrayList<>();
        // 查询检验内容
        List<SampleProductExportDto> sampleProductDto2s = insOrderMapper.selectSampleBySampleId(insSamples.stream()
@@ -1637,21 +1777,173 @@
        List<SampleProductExportDto> sampleList = new ArrayList<>();
        Integer max = insSamples.stream().mapToInt(InsSample::getQuantity).sum();
        TableRenderData tableRenderData = new TableRenderData();
        String templateName;
        if(StringUtils.equals(OrderType.WG.getValue(),ifsInventoryQuantity.getOrderType())){
            //过滤不判定的检测项
            List<SampleProductExportDto> filterItems = sampleProductDto2s.stream().filter(f -> f.getInsResult() != 3).collect(Collectors.toList());
            int maxCableTag = 5;//单个表格,电缆颜色标识最大个数
            templateName = "/static/small-wg-report-template.docx";
            //查询检验单消息
            InsSampleUserVO insSampleUser = insSampleUserMapper.selectUserNameByOrderId(orderId);
            if(Objects.nonNull(insSampleUser)){
                enterFactoryReport.setPartDesc(insSampleUser.getModel());
                enterFactoryReport.setInspector(insSampleUser.getInspector());
                enterFactoryReport.setInspectDate(insSampleUser.getInspectDate());
            }
        // 转成Mpa进行排序
        Map<String, List<SampleProductExportDto>> sortedMap = sampleProductDto2s.stream()
                .filter(sampleProductDto2 -> StringUtils.isNotBlank(sampleProductDto2.getInspectionItem()))
                .collect(Collectors.groupingBy(SampleProductExportDto::getInspectionItem));
        List<Map.Entry<String, List<SampleProductExportDto>>> entries = new ArrayList<>(sortedMap.entrySet());
        entries.sort((o1, o2) -> (o1.getValue().get(0).getSort() == null ? 0 : o1.getValue().get(0).getSort())
                - (o2.getValue().get(0).getSort() == null ? 0 : o2.getValue().get(0).getSort()));
        // 创建一个 LinkedHashMap 来保持插入顺序
        Map<String, List<SampleProductExportDto>> item = new LinkedHashMap<>();
        for (Map.Entry<String, List<SampleProductExportDto>> entry : entries) {
            item.put(entry.getKey(), entry.getValue());
            Map<String, List<SampleProductExportDto>> item = new LinkedHashMap<>();//非电缆配置检测项
            Map<String, List<SampleProductExportDto>> cableTagItem = new LinkedHashMap<>();//电缆配置检测项
            Map<String, List<SampleProductExportDto>> cableTagEnclosureItem = new LinkedHashMap<>();//电缆配置检测项附件
            AtomicInteger finalIndex = new AtomicInteger(1);
            List<String> cableTags = insOrderMapper.selectSampleCableTag(insSample.getId());
            max = cableTags.size();
            //处理电缆配置检测项
            Map<String, List<SampleProductExportDto>> tempMap = new HashMap<>();
            Map<String, List<SampleProductExportDto>> tempMap2 = new HashMap<>();
            Map<String, List<SampleProductExportDto>> listMap2 = filterItems.stream()
                    .filter(f -> StringUtils.isNotBlank(f.getCableTag()) && StringUtils.isNotBlank(f.getInspectionItem()))
                    .collect(Collectors.groupingBy(SampleProductExportDto::getInspectionItem));
            for (String key : listMap2.keySet()) {
                List<SampleProductExportDto> sampleProductExportDtos;
                List<SampleProductExportDto> sampleProductExportDtos2;
                //处理电缆配置项
                Map<String, List<SampleProductExportDto>> collect = listMap2.get(key).stream().collect(Collectors.groupingBy(SampleProductExportDto::getInspectionItemSubclass));
                if(cableTags.size()>maxCableTag){
                    sampleProductExportDtos = transformSampleProduct(cableTags,collect,0,maxCableTag);
                    sampleProductExportDtos2 = transformSampleProduct(cableTags,collect,maxCableTag,cableTags.size());
                    tempMap2.put(key,sampleProductExportDtos2);
                }else{
                    sampleProductExportDtos = transformSampleProduct(cableTags,collect,0,cableTags.size());
                }
                tempMap.put(key,sampleProductExportDtos);
            }
            sortSampleProduct(tempMap,cableTagItem);
            int tagNum = Math.min(max,maxCableTag);
            List<String> tagList = cableTags.subList(0,tagNum);
            handlerSampleItems(cableTagItem,finalIndex,sampleList,tagNum,text,rows,rowRenderData,resultCh,tagList,true);
            if(CollectionUtil.isNotEmpty(tempMap2)){
                sortSampleProduct(tempMap2,cableTagEnclosureItem);
                //生成附件电缆表格
                TableRenderData tableRenderData2 = new TableRenderData();
                List<String> newCableTags = cableTags.subList(maxCableTag,cableTags.size());
                AtomicInteger finalIndex2 = new AtomicInteger(1);
                List<TextRenderData> newText = new ArrayList<TextRenderData>();
                List<RowRenderData> newRows = new ArrayList<>();
                RowRenderData newRowRenderData = null;
                handlerSampleItems(cableTagEnclosureItem,finalIndex2, new ArrayList<>(),newCableTags.size(),newText,newRows,newRowRenderData,resultCh,newCableTags,true);
                tableRenderData2.setRows(newRows);
                tableRenderData2.setTableStyle(setTableStyle(newCableTags.size()));
                HashMap<String, Object> tableMap = new HashMap<>();
                tableMap.put("enclosureTable",tableRenderData2);
                tableMap.put("resultCh", resultCh);
                tableMap.put("writeUrl", null);
                tableMap.put("examineUrl", null);
                tableMap.put("ratifyUrl", null);
                tableMap.put("writeDateUrl", null);
                tableMap.put("examineDateUrl", null);
                tableMap.put("ratifyDateUrl", null);
                tableMap.put("seal1", null);
                cableTagEnclosureTables.add(tableMap);
            }
            //处理非电缆配置检测项
            Map<String, List<SampleProductExportDto>> listMap = filterItems.stream()
                    .filter(f -> StringUtils.isBlank(f.getCableTag()) && StringUtils.isNotBlank(f.getInspectionItem()))
                    .collect(Collectors.groupingBy(SampleProductExportDto::getInspectionItem));
            sortSampleProduct(listMap,item);
            text = new ArrayList<>();
            sampleList = new ArrayList<>();
            handlerSampleItems(item,finalIndex,sampleList,tagNum,text,rows,rowRenderData,resultCh,cableTags,false);
            tableRenderData.setRows(rows);
            tableRenderData.setTableStyle(setTableStyle(tagNum));
            if (!resultCh.get().equals("")) {
                resultCh.set("经检验," + resultCh.get() + "所检项目不合格,其余所检项目均合格。(盖章有效)");
            } else {
                resultCh.set("本产品符合相关标准要求,经检验合格准予出厂(盖章有效)");
            }
        }else{
            templateName = "/static/small-report-template.docx";
            // 转成Mpa进行排序
            Map<String, List<SampleProductExportDto>> sortedMap = sampleProductDto2s.stream()
                    .filter(sampleProductDto2 -> StringUtils.isNotBlank(sampleProductDto2.getInspectionItem()))
                    .collect(Collectors.groupingBy(SampleProductExportDto::getInspectionItem));
//            List<Map.Entry<String, List<SampleProductExportDto>>> entries = new ArrayList<>(sortedMap.entrySet());
//            entries.sort(Comparator.comparingInt(o -> (o.getValue().get(0).getSort() == null ? 0 : o.getValue().get(0).getSort())));
//            // 创建一个 LinkedHashMap 来保持插入顺序
            Map<String, List<SampleProductExportDto>> item = new LinkedHashMap<>();
//            for (Map.Entry<String, List<SampleProductExportDto>> entry : entries) {
//                item.put(entry.getKey(), entry.getValue());
//            }
            sortSampleProduct(sortedMap,item);
            AtomicInteger finalIndex = new AtomicInteger(1);
            handlerSampleItems(item,finalIndex,sampleList,max,text,rows,rowRenderData,resultCh,null,true);
            tableRenderData.setRows(rows);
            tableRenderData.setTableStyle(setTableStyle(max));
            if (!resultCh.get().equals("")) {
                resultCh.set("经检验," + resultCh.get() + "所检项目不合格,其余所检项目均合格。");
            } else {
                resultCh.set("经检验此批" + enterFactoryReport.getSample() + "各项目均符合检验规范要求。");
            }
        }
        AtomicInteger finalIndex = new AtomicInteger(1);
        ConfigureBuilder builder = Configure.builder();
        builder.useSpringEL(true);
        InputStream inputStream = this.getClass().getResourceAsStream(templateName);
        XWPFTemplate template = XWPFTemplate.compile(inputStream, builder.build()).render(
                new HashMap<String, Object>() {{
                    put("report", enterFactoryReport);
                    put("standardMethod", standardMethod2.toString().equals("null") ? "" : standardMethod2);
                    put("orderType", orderType);
                    put("table", tableRenderData);
                    put("enclosureTables", cableTagEnclosureTables.isEmpty()?null:cableTagEnclosureTables);
                    put("resultCh", resultCh);
                    put("writeUrl", null);
                    put("examineUrl", null);
                    put("ratifyUrl", null);
                    put("writeDateUrl", null);
                    put("examineDateUrl", null);
                    put("ratifyDateUrl", null);
                    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);
            insReport.setIsPass(0);
            insReport.setWriteUserId(SecurityUtils.getUserId().intValue());//提交人
            insReport.setWriteTime(LocalDateTime.now());//提交时间
            // 查询报告, 判断之前是否添加过, 添加过删除
            insReportMapper.delete(Wrappers.<InsReport>lambdaQuery()
                    .eq(InsReport::getInsOrderId, insOrder.getId()));
            insReportMapper.insert(insReport);
            inputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 处理常规检测项
     * @param item
     * @param finalIndex
     * @param sampleList
     * @param max
     * @param text
     * @param rows
     * @param rowRenderData
     * @param resultCh
     */
    private static void handlerSampleItems(Map<String, List<SampleProductExportDto>> item,AtomicInteger finalIndex,List<SampleProductExportDto> sampleList,Integer max,List<TextRenderData> text,List<RowRenderData> rows,RowRenderData rowRenderData,AtomicReference<String> resultCh,List<String> cableTagList,Boolean hasAddHead ){
        item.forEach((s, sampleProductDtoInside) -> {
            // 添加检验项
            SampleProductExportDto dto2 = new SampleProductExportDto();
@@ -1667,16 +1959,20 @@
                    String productName = productDto2.getInspectionItemClass() + productDto2.getInspectionItem();
                    if (map.containsKey(productName)) {
                        // 如果名称已经存在,添加 lastValue 值到 lastValueList 列表
                        map.get(productName)
                                .getLastValueList()
                                .add(productDto2.getLastValue());
                        if(CollectionUtil.isEmpty(map.get(productName).getLastValueList())){
                            map.get(productName)
                                    .getLastValueList()
                                    .add(productDto2.getLastValue());
                        }
                        map.get(productName)
                                .getInsResultList()
                                .add(productDto2.getInsResult());
                    } else {
                        // 如果名称不存在,直接放入 map
                        productDto2.setLastValueList(new ArrayList<>()); // 检验内容
                        productDto2.getLastValueList().add(productDto2.getLastValue());
                        if(CollectionUtil.isEmpty(productDto2.getLastValueList())){
                            productDto2.setLastValueList(new ArrayList<>()); // 检验内容
                            productDto2.getLastValueList().add(productDto2.getLastValue());
                        }
                        productDto2.setInsResultList(new ArrayList<>()); // 结果
                        productDto2.getInsResultList().add(productDto2.getInsResult());
@@ -1708,16 +2004,20 @@
                    String productName = productDto2.getInspectionItemClass() + productDto2.getInspectionItem() + productDto2.getInspectionItemSubclass();
                    if (map.containsKey(productName)) {
                        // 如果名称已经存在,添加 lastValue 值到 lastValueList 列表
                        map.get(productName)
                                .getLastValueList()
                                .add(productDto2.getLastValue());
                        if(CollectionUtil.isEmpty(map.get(productName).getLastValueList())){
                            map.get(productName)
                                    .getLastValueList()
                                    .add(productDto2.getLastValue());
                        }
                        map.get(productName)
                                .getInsResultList()
                                .add(productDto2.getInsResult());
                    } else {
                        // 如果名称不存在,直接放入 map
                        productDto2.setLastValueList(new ArrayList<>()); // 检验内容
                        productDto2.getLastValueList().add(productDto2.getLastValue());
                        if(CollectionUtil.isEmpty(productDto2.getLastValueList())){
                            productDto2.setLastValueList(new ArrayList<>()); // 检验内容
                            productDto2.getLastValueList().add(productDto2.getLastValue());
                        }
                        productDto2.setInsResultList(new ArrayList<>()); // 结果
                        productDto2.getInsResultList().add(productDto2.getInsResult());
@@ -1735,8 +2035,9 @@
        });
        // 添加小报告表头
        text = addSmallHead(text, max, rows);
        if(hasAddHead){
            text = addSmallHead(text, max, rows,cableTagList);
        }
        // 中间检测值添加
        for (int i = 0; i < sampleList.size(); i++) {
@@ -1753,7 +2054,7 @@
            // 检验项目
            TextRenderData middleRenderData2 = new TextRenderData();
            middleRenderData2.setText(sample.getInspectionName());
            middleRenderData2.setText(sample.getInspectionName()+"∑"+sample.getInspectionName()+i);
            Style middleStyle2 = new Style();
            middleStyle2.setFontFamily("宋体");
            middleStyle2.setColor("000000");
@@ -1840,7 +2141,7 @@
                    TextRenderData middleRenderData6 = new TextRenderData();
                    middleRenderData6.setText((StringUtils.isNotEmpty(sample.getLastValue()) ?
                            sample.getLastValue() : "")
                            + "∑" + (7 + i));
                            + "∑" + (finalIndex.get() +"_"+ i));
                    Style middleStyle6 = new Style();
                    middleStyle6.setFontFamily("宋体");
                    middleStyle6.setColor("000000");
@@ -1878,7 +2179,7 @@
                            String type;
                            if (count.equals(0)) {
                                // 添加不合格描述
                                String item1 = (max == 1 ? "" : "第" + Integer.toString(index) + "次")
                                String item1 = (max == 1 ? "" : "第" + index + "次")
                                        + sample.getInspectionItem()
                                        + (StringUtils.isBlank(sample.getInspectionItemSubclass()) ? "" : "" + sample.getInspectionItemSubclass());
                                if (resultCh.get().equals("")) {
@@ -1918,99 +2219,17 @@
            text = new ArrayList<>();
        }
        TableRenderData tableRenderData = new TableRenderData();
        tableRenderData.setRows(rows);
        //设置样式
        TableStyle tableStyle = new TableStyle();
        for (int i = 1; i <= max; i++) {
            // 根据减压那结果个数修改长度
            switch (i) {
                case 1:
                    tableStyle.setColWidths(new int[]{650, 2900, 850, 2300, 2100, 1200});
                    break;
                case 2:
                    tableStyle.setColWidths(new int[]{650, 2700, 850, 2200, 1200, 1200, 1200});
                    break;
                case 3:
                    tableStyle.setColWidths(new int[]{650, 2700, 850, 1600, 1000, 1000, 1000, 1200});
                    break;
                case 4:
                    tableStyle.setColWidths(new int[]{650, 2400, 850, 1500, 850, 850, 850, 850, 1200});
                    break;
                case 5:
                    tableStyle.setColWidths(new int[]{650, 2200, 850, 1350, 750, 750, 750, 750, 750, 1200});
                    break;
            }
        }
        tableStyle.setWidth("10000");
        tableStyle.setAlign(TableRowAlign.CENTER);
        BorderStyle borderStyle = new BorderStyle();
        borderStyle.setColor("000000");
        borderStyle.setType(XWPFTable.XWPFBorderType.SINGLE);
        borderStyle.setSize(4);
        tableStyle.setLeftBorder(borderStyle);
        tableStyle.setRightBorder(borderStyle);
        tableStyle.setInsideHBorder(borderStyle); // 设置水平内边框
        tableStyle.setInsideVBorder(borderStyle);
        tableRenderData.setTableStyle(tableStyle);
        if (!resultCh.get().equals("")) {
            resultCh.set("经检验," + resultCh.get() + "所检项目不合格,其余所检项目均合格。");
        } else {
            resultCh.set("经检验此批" + enterFactoryReport.getSample() + "各项目均符合检验规范要求。");
        }
        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(
                new HashMap<String, Object>() {{
                    put("report", enterFactoryReport);
                    put("standardMethod", standardMethod2.toString().equals("null") ? "" : standardMethod2);
                    put("orderType", orderType);
                    put("table", tableRenderData);
                    put("resultCh", resultCh);
                    put("writeUrl", null);
                    put("examineUrl", null);
                    put("ratifyUrl", null);
                    put("writeDateUrl", null);
                    put("examineDateUrl", null);
                    put("ratifyDateUrl", null);
                    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);
            insReport.setIsPass(0);
            insReport.setWriteUserId(SecurityUtils.getUserId().intValue());//提交人
            insReport.setWriteTime(LocalDateTime.now());//提交时间
            // 查询报告, 判断之前是否添加过, 添加过删除
            insReportMapper.delete(Wrappers.<InsReport>lambdaQuery()
                    .eq(InsReport::getInsOrderId, insOrder.getId()));
            insReportMapper.insert(insReport);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 添加小宝表头
     * 添加小报告表头
     * @param text
     * @param max
     * @param rows
     * @return
     */
    private static List<TextRenderData> addSmallHead(List<TextRenderData> text, Integer max, List<RowRenderData> rows) {
    private static List<TextRenderData> addSmallHead(List<TextRenderData> text, Integer max, List<RowRenderData> rows,List<String> cableTagList) {
        RowRenderData rowRenderData;
//        // 头
        TextRenderData headRenderData1 = new TextRenderData();
@@ -2068,7 +2287,7 @@
        text = new ArrayList<>();
        // 第二行(可能没有)
        if (max > 1) {
        if (max > 1 && CollectionUtil.isEmpty(cableTagList)) {
            TextRenderData tagRenderData1 = new TextRenderData();
            tagRenderData1.setText("");
            Style tagStyle1 = new Style();
@@ -2122,8 +2341,62 @@
            rowRenderData = Rows.of(text4).center().rowAtleastHeight(1).create();
            rows.add(rowRenderData);
            text = new ArrayList<>();
        }
        //如果有电缆颜色,生成颜色标识行
        if(CollectionUtil.isNotEmpty(cableTagList)){
            TextRenderData tagRenderData1 = new TextRenderData();
            tagRenderData1.setText("");
            Style tagStyle1 = new Style();
            tagStyle1.setFontFamily("宋体");
            tagStyle1.setColor("000000");
            tagRenderData1.setStyle(tagStyle1);
            text.add(tagRenderData1);
            TextRenderData tagRenderData2 = new TextRenderData();
            tagRenderData2.setText("绝缘线芯颜色和标志");
            Style tagStyle2 = new Style();
            tagStyle2.setFontFamily("宋体");
            tagStyle2.setColor("000000");
            tagRenderData2.setStyle(tagStyle2);
            text.add(tagRenderData2);
            TextRenderData tagRenderData4 = new TextRenderData();
            tagRenderData4.setText("/");
            Style tagStyle4 = new Style();
            tagStyle4.setFontFamily("宋体");
            tagStyle4.setColor("000000");
            tagRenderData4.setStyle(tagStyle4);
            text.add(tagRenderData4);
            TextRenderData tagRenderData5 = new TextRenderData();
            tagRenderData5.setText("/");
            Style tagStyle5 = new Style();
            tagStyle5.setFontFamily("宋体");
            tagStyle5.setColor("000000");
            tagRenderData5.setStyle(tagStyle5);
            text.add(tagRenderData5);
            for (String cableTag : cableTagList) {
                TextRenderData tagRenderData6 = new TextRenderData();
                tagRenderData6.setText(cableTag);
                Style tagStyle6 = new Style();
                tagStyle6.setFontFamily("宋体");
                tagStyle6.setColor("000000");
                tagRenderData6.setStyle(tagStyle6);
                text.add(tagRenderData6);
            }
            TextRenderData tagRenderData7 = new TextRenderData();
            tagRenderData7.setText("/");
            Style tagStyle7 = new Style();
            tagStyle7.setFontFamily("宋体");
            tagStyle7.setColor("000000");
            tagRenderData7.setStyle(tagStyle7);
            text.add(tagRenderData7);
            TextRenderData[] text4 = text.toArray(new TextRenderData[0]);
            rowRenderData = Rows.of(text4).center().rowAtleastHeight(1).create();
            rows.add(rowRenderData);
            text = new ArrayList<>();
        }
        return text;
@@ -2138,7 +2411,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();
@@ -2157,7 +2429,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())) {
@@ -2503,6 +2774,7 @@
        InputStream inputStream = this.getClass().getResourceAsStream("/static/report-template.docx");
        Configure configure = Configure.builder()
                .bind("deviceList", new HackLoopTableRenderPolicy())
                .useSpringEL(true)
                .build();
        XWPFTemplate template = XWPFTemplate.compile(inputStream, configure).render(
@@ -2551,6 +2823,7 @@
            insReportMapper.delete(Wrappers.<InsReport>lambdaQuery()
                    .eq(InsReport::getInsOrderId, insOrder.getId()));
            insReportMapper.insert(insReport);
            inputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
@@ -4105,7 +4378,7 @@
    }
    /**
     * 保存元此阿里进货验证原始记录
     * *****保存元此阿里进货验证原始记录*****
     * @param insOrderId 订单Id
     * @param examineUserId  复核人Id
     * @param writeUserId  检验员Id
@@ -4225,6 +4498,11 @@
        // 保存到附件里面
        uploadFile(insOrderId, multipartFile);
        try {
            inputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
@@ -4255,7 +4533,7 @@
    /**
     * 格式化进厂验证内容
     * ***格式化进厂验证内容****
     * @param basicType
     * @return
     */
@@ -4284,7 +4562,7 @@
    }
    /**
     * word转换pdf
     * ***word转换pdf***
     * @param path
     * @return
     */
@@ -4301,11 +4579,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文件
@@ -4333,6 +4610,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
@@ -4343,43 +4657,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 "未知";
        }
    }
}