cnas-process/src/main/java/com/ruoyi/process/service/impl/InspectionOrderServiceImpl.java
@@ -2,7 +2,6 @@
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
@@ -17,24 +16,23 @@
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.exception.ErrorException;
import com.ruoyi.inspect.dto.InsPlaceOrderDto;
import com.ruoyi.inspect.mapper.InsProductResultMapper;
import com.ruoyi.inspect.mapper.InsSampleMapper;
import com.ruoyi.inspect.pojo.InsOrder;
import com.ruoyi.inspect.pojo.InsProductResult;
import com.ruoyi.inspect.pojo.InsReport;
import com.ruoyi.inspect.service.InsOrderService;
import com.ruoyi.inspect.service.InsReportService;
import com.ruoyi.inspect.util.HackLoopTableRenderPolicy;
import com.ruoyi.process.dto.InspectionOrderDto;
import com.ruoyi.process.dto.InspectionOrderBindingDto;
import com.ruoyi.process.dto.InspectionOrderExportDto;
import com.ruoyi.process.mapper.InspectionOrderBindLogMapper;
import com.ruoyi.process.mapper.InspectionOrderMapper;
import com.ruoyi.process.mapper.ProcessOrderDeviceMapper;
import com.ruoyi.process.mapper.ProcessSampleMapper;
import com.ruoyi.process.mapper.InspectionOrderAttachmentMapper;
import com.ruoyi.process.mapper.InspectionOrderBindingMapper;
import com.ruoyi.process.pojo.InspectionOrder;
import com.ruoyi.process.pojo.InspectionOrderAttachment;
import com.ruoyi.process.pojo.InspectionOrderBinding;
import com.ruoyi.process.pojo.InspectionOrderBindLog;
import com.ruoyi.process.pojo.InspectionOrderDetail;
import com.ruoyi.process.pojo.ProcessOrderDevice;
import com.ruoyi.process.service.*;
import com.ruoyi.system.mapper.UserMapper;
import com.ruoyi.system.mapper.CustomMapper;
@@ -54,13 +52,16 @@
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.LocalDateTime;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.LinkedHashMap;
import java.util.Objects;
import java.util.UUID;
/**
 * <p>
@@ -76,33 +77,21 @@
    @Resource
    private InspectionOrderBindLogMapper inspectionOrderBindLogMapper;
    @Resource
    private InspectionOrderBindingMapper inspectionOrderBindingMapper;
    @Resource
    private InspectionOrderAttachmentMapper inspectionOrderAttachmentMapper;
    @Resource
    private InspectionOrderDetailService inspectionOrderDetailService;
    @Resource
    private InsOrderService insOrderService;
    @Resource
    private InsSampleMapper insSampleMapper;
    @Resource
    private InsReportService insReportService;
    @Value("${wordUrl}")
    private String wordUrl;
    @Resource
    private ProcessReportService processReportService;
    @Resource
    private ProcessOrderDeviceMapper processOrderDeviceMapper;
    @Resource
    private InsProductResultMapper insProductResultMapper;
    @Resource
    private ProcessOrderDeviceService processOrderDeviceService;
    @Resource
    private UserMapper userMapper;
    @Resource
    private CustomMapper customMapper;
    @Resource
    private ProcessSampleService processSampleService;
    @Resource
    private ProcessSampleMapper processSampleMapper;
    @Resource
    private ProcessDealService processDealService;
    @Resource
    private NumberGenerator<InspectionOrder> numberGenerator;
@@ -149,47 +138,6 @@
        return inspectionOrder;
    }
    private synchronized void addDeviceRecord(InspectionOrder inspectionOrder, Integer userId) {
        // 查询设备使用记录查询该订单的使用记录
        Set<String> recordCodeset = processOrderDeviceMapper.selectDeviceNumber(inspectionOrder.getInspectionOrderId());
        // 获取订单设备编号
        List<InsProductResult> resultList = insProductResultMapper.selectResultByOrderId(inspectionOrder.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 = processOrderDeviceMapper.selectDeviceIdsByNumbers(orderDeviceNumbers);
            List<ProcessOrderDevice> collect = orderDeviceIds.stream().map(deviceId -> {
                ProcessOrderDevice processOrderDevice = new ProcessOrderDevice();
                processOrderDevice.setInspectionOrderId(inspectionOrder.getInspectionOrderId());
                processOrderDevice.setDeviceId(deviceId);
                processOrderDevice.setSampleCode(inspectionOrder.getEntrustCode());
                processOrderDevice.setUseBefore(1);
                processOrderDevice.setUseAfter(1);
                processOrderDevice.setUsePerson(userMapper.selectById(userId).getName());//使用人
                processOrderDevice.setUsePersonId(userId);//使用人id
                return processOrderDevice;
            }).collect(Collectors.toList());
            processOrderDeviceService.saveBatch(collect);
        }
    }
    private static Set<String> getDeviceDifference(Set<String> number1, Set<String> number2) {
        return number1.stream().filter(s1 -> number2.stream().noneMatch(s2 -> s1.equals(s2)))
                .collect(Collectors.toSet());
    }
    /**
     * 检验委托单修改
     *
@@ -198,9 +146,14 @@
     */
    @Override
    public boolean updateInspectionOrder(InspectionOrderDto InspectionOrder) {
        InspectionOrder oldInspectionOrder = baseMapper.selectById(InspectionOrder.getInspectionOrderId());
        InspectionOrder oldInspectionOrder = baseMapper.selectByIdForUpdate(InspectionOrder.getInspectionOrderId());
        if (oldInspectionOrder == null) {
            throw new ErrorException("检验委托单不存在");
        }
        Long bindingHistoryCount = inspectionOrderBindingMapper.selectCount(Wrappers.<InspectionOrderBinding>lambdaQuery()
                .eq(InspectionOrderBinding::getInspectionOrderId, InspectionOrder.getInspectionOrderId()));
        if (bindingHistoryCount > 0 && !Objects.equals(oldInspectionOrder.getCommissionUnitId(), InspectionOrder.getCommissionUnitId())) {
            throw new ErrorException("已有下单记录,不允许修改委托单位");
        }
        normalizeCommissionParty(InspectionOrder);
        // 编号、关联关系、正式委托编号和报告地址只能由专用流程维护。
@@ -235,12 +188,19 @@
     */
    @Override
    public boolean delInspectionOrder(Integer inspectionOrderId) {
        InspectionOrder inspectionOrder = baseMapper.selectById(inspectionOrderId);
        InspectionOrder inspectionOrder = baseMapper.selectByIdForUpdate(inspectionOrderId);
        if (inspectionOrder == null) {
            throw new ErrorException("检验委托单不存在");
        }
        if (inspectionOrder.getInsOrderId() != null) {
            throw new ErrorException("已绑定成品下单的检验委托单不允许删除");
        Long bindingHistoryCount = inspectionOrderBindingMapper.selectCount(Wrappers.<InspectionOrderBinding>lambdaQuery()
                .eq(InspectionOrderBinding::getInspectionOrderId, inspectionOrderId));
        Long bindLogCount = inspectionOrderBindLogMapper.selectCount(Wrappers.<InspectionOrderBindLog>lambdaQuery()
                .and(wrapper -> wrapper.eq(InspectionOrderBindLog::getOldInspectionOrderId, inspectionOrderId)
                        .or().eq(InspectionOrderBindLog::getNewInspectionOrderId, inspectionOrderId)));
        Long attachmentCount = inspectionOrderAttachmentMapper.selectCount(Wrappers.<InspectionOrderAttachment>lambdaQuery()
                .eq(InspectionOrderAttachment::getInspectionOrderId, inspectionOrderId));
        if (bindingHistoryCount > 0 || bindLogCount > 0 || attachmentCount > 0) {
            throw new ErrorException("该检验委托单已有下单或附件历史,不允许删除");
        }
        inspectionOrderDetailService.remove(Wrappers.<InspectionOrderDetail>lambdaQuery()
@@ -258,6 +218,9 @@
    @Override
    public InspectionOrderDto getInspectionOrderOne(Integer inspectionOrderId) {
        InspectionOrder inspectionOrder = baseMapper.selectById(inspectionOrderId);
        if (inspectionOrder == null) {
            throw new ErrorException("检验委托单不存在");
        }
        InspectionOrderDto inspectionOrderDto = new InspectionOrderDto();
        BeanUtils.copyProperties(inspectionOrder, inspectionOrderDto);
@@ -273,13 +236,33 @@
    }
    @Override
    public IPage<InspectionOrderBindingDto> pageInspectionOrderBindings(Page page, Integer inspectionOrderId,
                                                                         Boolean includeDeleted) {
        if (inspectionOrderId == null || baseMapper.selectById(inspectionOrderId) == null) {
            throw new ErrorException("检验委托单不存在");
        }
        return inspectionOrderBindingMapper.pageBindings(page, inspectionOrderId, includeDeleted);
    }
    @Override
    public List<InspectionOrderAttachment> listInspectionOrderAttachments(Integer inspectionOrderId, Long bindingId) {
        if (inspectionOrderId == null || baseMapper.selectById(inspectionOrderId) == null) {
            throw new ErrorException("检验委托单不存在");
        }
        if (bindingId != null) {
            InspectionOrderBinding binding = inspectionOrderBindingMapper.selectById(bindingId);
            if (binding == null || !Objects.equals(binding.getInspectionOrderId(), inspectionOrderId)) {
                throw new ErrorException("下单记录不属于该检验委托单");
            }
        }
        return inspectionOrderAttachmentMapper.selectVisibleAttachments(inspectionOrderId, bindingId);
    }
    @Override
    public InspectionOrderDto getInspectionOrderForPlaceOrder(Integer inspectionOrderId) {
        InspectionOrder inspectionOrder = baseMapper.selectById(inspectionOrderId);
        if (inspectionOrder == null) {
            throw new ErrorException("检验委托单不存在");
        }
        if (inspectionOrder.getInsOrderId() != null) {
            throw new ErrorException("该检验委托单已绑定成品下单,不能重复选择");
        }
        return getInspectionOrderOne(inspectionOrderId);
    }
@@ -292,12 +275,26 @@
        if (insPlaceOrderDto.getInsOrder() == null) {
            throw new ErrorException("缺少成品下单信息");
        }
        InspectionOrder inspectionOrder = baseMapper.selectById(insPlaceOrderDto.getInspectionOrderId());
        if (CollectionUtils.isEmpty(insPlaceOrderDto.getSampleList())) {
            throw new ErrorException("请填写本次样品");
        }
        String requestId = normalizeRequestId(insPlaceOrderDto.getRequestId());
        Integer requestUserId = SecurityUtils.getUserId().intValue();
        String requestHash = calculateRequestHash(insPlaceOrderDto);
        if (inspectionOrderBindingMapper.lockRequestUser(requestUserId) == null) {
            throw new ErrorException("当前操作人不存在");
        }
        InspectionOrderBinding existing = inspectionOrderBindingMapper.selectByRequest(requestUserId, requestId);
        if (existing != null) {
            return resolveIdempotentRequest(existing, requestHash);
        }
        InspectionOrder inspectionOrder = baseMapper.selectByIdForUpdate(insPlaceOrderDto.getInspectionOrderId());
        if (inspectionOrder == null) {
            throw new ErrorException("检验委托单不存在");
        }
        if (inspectionOrder.getInsOrderId() != null) {
            throw new ErrorException("该检验委托单已绑定成品下单,不能重复提交");
        existing = inspectionOrderBindingMapper.selectByRequest(requestUserId, requestId);
        if (existing != null) {
            return resolveIdempotentRequest(existing, requestHash);
        }
        if (inspectionOrder.getCommissionUnitId() == null) {
            throw new ErrorException("请先完善委托单位");
@@ -310,16 +307,60 @@
        Integer insOrderId = insOrderService.addInsOrder(insPlaceOrderDto.getSampleList(), insPlaceOrderDto.getInsOrder());
        Long sampleTakerUserId = SecurityUtils.getUserId();
        User sampleTaker = sampleTakerUserId == null ? null : userMapper.selectById(sampleTakerUserId);
        int updated = baseMapper.update(null, Wrappers.<InspectionOrder>lambdaUpdate()
                .eq(InspectionOrder::getInspectionOrderId, inspectionOrder.getInspectionOrderId())
                .isNull(InspectionOrder::getInsOrderId)
                .set(InspectionOrder::getInsOrderId, insOrderId)
                .set(InspectionOrder::getSampleTakerUserId, sampleTakerUserId == null ? null : sampleTakerUserId.intValue())
                .set(InspectionOrder::getSampleTakerUser, sampleTaker == null ? null : sampleTaker.getName()));
        if (updated != 1) {
            throw new ErrorException("检验委托单已被其他下单绑定,请刷新后重试");
        }
        InspectionOrderBinding binding = new InspectionOrderBinding();
        binding.setInspectionOrderId(inspectionOrder.getInspectionOrderId());
        binding.setInsOrderId(insOrderId);
        binding.setSourceType("NEW");
        binding.setRequestId(requestId);
        binding.setRequestHash(requestHash);
        binding.setRequestUserId(requestUserId);
        binding.setSampleTakerUserId(sampleTakerUserId == null ? null : sampleTakerUserId.intValue());
        binding.setSampleTakerUser(sampleTaker == null ? null : sampleTaker.getName());
        binding.setSampleData(LocalDate.now());
        binding.setOrderDeleted(0);
        binding.setCreateUser(requestUserId);
        binding.setCreateTime(LocalDateTime.now());
        inspectionOrderBindingMapper.insert(binding);
        return insOrderId;
    }
    private String normalizeRequestId(String requestId) {
        if (StrUtil.isBlank(requestId)) {
            throw new ErrorException("缺少下单请求号,请刷新页面后重试");
        }
        try {
            return UUID.fromString(requestId.trim()).toString();
        } catch (IllegalArgumentException e) {
            throw new ErrorException("下单请求号格式错误,请刷新页面后重试");
        }
    }
    private Integer resolveIdempotentRequest(InspectionOrderBinding existing, String requestHash) {
        if (!Objects.equals(existing.getRequestHash(), requestHash)) {
            throw new ErrorException("请求号已被其他下单内容使用,请重新发起下单");
        }
        if (Integer.valueOf(1).equals(existing.getOrderDeleted())) {
            throw new ErrorException("原订单已删除,请重新发起下单");
        }
        return existing.getInsOrderId();
    }
    private String calculateRequestHash(InsPlaceOrderDto dto) {
        LinkedHashMap<String, Object> content = new LinkedHashMap<>();
        content.put("inspectionOrderId", dto.getInspectionOrderId());
        content.put("insOrder", dto.getInsOrder());
        content.put("sampleList", dto.getSampleList());
        try {
            byte[] digest = MessageDigest.getInstance("SHA-256")
                    .digest(JSON.toJSONString(content).getBytes(StandardCharsets.UTF_8));
            StringBuilder result = new StringBuilder(64);
            for (byte value : digest) {
                result.append(String.format("%02x", value & 0xff));
            }
            return result.toString();
        } catch (Exception e) {
            throw new ErrorException("下单请求校验失败");
        }
    }
    private void fillInsOrderFromInspectionOrder(InspectionOrder inspectionOrder, InsOrder insOrder) {
@@ -361,16 +402,7 @@
    @Override
    public void syncEntrustCode(Integer insOrderId) {
        if (insOrderId == null) {
            return;
        }
        InsOrder insOrder = insOrderService.getById(insOrderId);
        if (insOrder == null || StrUtil.isBlank(insOrder.getEntrustCode())) {
            return;
        }
        baseMapper.update(null, Wrappers.<InspectionOrder>lambdaUpdate()
                .eq(InspectionOrder::getInsOrderId, insOrderId)
                .set(InspectionOrder::getEntrustCode, insOrder.getEntrustCode()));
        // 委托编号属于具体成品订单,页面通过绑定关系实时读取,不再回写委托单主表。
    }
    @Override
@@ -382,12 +414,15 @@
        if (insReport == null || !Integer.valueOf(1).equals(insReport.getIsRatify())) {
            return;
        }
        InspectionOrder inspectionOrder = baseMapper.selectOne(Wrappers.<InspectionOrder>lambdaQuery()
                .eq(InspectionOrder::getInsOrderId, insReport.getInsOrderId())
        InspectionOrderBinding binding = inspectionOrderBindingMapper.selectOne(Wrappers.<InspectionOrderBinding>lambdaQuery()
                .eq(InspectionOrderBinding::getInsOrderId, insReport.getInsOrderId())
                .eq(InspectionOrderBinding::getOrderDeleted, 0)
                .last("limit 1"));
        if (inspectionOrder == null) {
        if (binding == null) {
            return;
        }
        InspectionOrder inspectionOrder = baseMapper.selectById(binding.getInspectionOrderId());
        if (inspectionOrder == null) return;
        String sourceUrl = StrUtil.isBlank(insReport.getUrlS()) ? insReport.getUrl() : insReport.getUrlS();
        if (StrUtil.isBlank(sourceUrl)) {
@@ -396,8 +431,8 @@
        String sourceFileName = sourceUrl.substring(sourceUrl.lastIndexOf('/') + 1);
        String extension = sourceFileName.lastIndexOf('.') >= 0
                ? sourceFileName.substring(sourceFileName.lastIndexOf('.')) : ".docx";
        String fileName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyMMddHHmmss"))
                + "_" + inspectionOrder.getInspectionOrderCode() + "_委托单报告" + extension;
        String fileName = inspectionOrder.getInspectionOrderCode() + "_order_" + insReport.getInsOrderId()
                + "_report_" + insReportId + "_" + UUID.randomUUID() + extension;
        Path sourcePath = Paths.get(wordUrl + sourceUrl.replaceFirst("/word", ""));
        Path targetPath = Paths.get(wordUrl, fileName);
        try {
@@ -405,9 +440,26 @@
                throw new ErrorException("正式报告文件不存在,无法同步到检验委托单");
            }
            Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
            baseMapper.update(null, Wrappers.<InspectionOrder>lambdaUpdate()
                    .eq(InspectionOrder::getInspectionOrderId, inspectionOrder.getInspectionOrderId())
                    .set(InspectionOrder::getFileUrl, "/word/" + fileName));
            InspectionOrderAttachment attachment = inspectionOrderAttachmentMapper.selectOne(
                    Wrappers.<InspectionOrderAttachment>lambdaQuery()
                            .eq(InspectionOrderAttachment::getInsReportId, insReportId).last("limit 1"));
            if (attachment == null) {
                attachment = new InspectionOrderAttachment();
                attachment.setInsReportId(insReportId);
                attachment.setSourceType("REPORT");
                attachment.setCreateUser(SecurityUtils.getUserId().intValue());
                attachment.setCreateTime(LocalDateTime.now());
            }
            attachment.setInspectionOrderId(binding.getInspectionOrderId());
            attachment.setBindingId(binding.getId());
            attachment.setFileName(fileName);
            attachment.setFileUrl("/word/" + fileName);
            attachment.setUpdateTime(LocalDateTime.now());
            if (attachment.getId() == null) {
                inspectionOrderAttachmentMapper.insert(attachment);
            } else {
                inspectionOrderAttachmentMapper.updateById(attachment);
            }
        } catch (ErrorException e) {
            throw e;
        } catch (Exception e) {
@@ -428,25 +480,32 @@
                || StrUtil.isNotBlank(insOrder.getEntrustCode())) {
            throw new ErrorException("当前下单已进入检验流程或已生成委托编号,不允许变更关联");
        }
        InspectionOrder target = baseMapper.selectById(inspectionOrderId);
        if (target == null || target.getInsOrderId() != null) {
            throw new ErrorException("目标检验委托单不存在或已被绑定");
        InspectionOrderBinding binding = inspectionOrderBindingMapper.selectByOrderIdForUpdate(insOrderId);
        if (binding == null || Integer.valueOf(1).equals(binding.getOrderDeleted())) {
            throw new ErrorException("成品下单未绑定有效检验委托单");
        }
        InspectionOrder oldInspectionOrder = baseMapper.selectOne(Wrappers.<InspectionOrder>lambdaQuery()
                .eq(InspectionOrder::getInsOrderId, insOrderId));
        baseMapper.update(null, Wrappers.<InspectionOrder>lambdaUpdate()
                .eq(InspectionOrder::getInsOrderId, insOrderId)
                .set(InspectionOrder::getInsOrderId, null));
        int updated = baseMapper.update(null, Wrappers.<InspectionOrder>lambdaUpdate()
                .eq(InspectionOrder::getInspectionOrderId, inspectionOrderId)
                .isNull(InspectionOrder::getInsOrderId)
                .set(InspectionOrder::getInsOrderId, insOrderId));
        if (updated != 1) {
            throw new ErrorException("目标检验委托单已被其他下单绑定,请刷新后重试");
        InspectionOrder target = baseMapper.selectByIdForUpdate(inspectionOrderId);
        if (target == null) {
            throw new ErrorException("目标检验委托单不存在");
        }
        if (Objects.equals(binding.getInspectionOrderId(), inspectionOrderId)) {
            throw new ErrorException("目标检验委托单与当前委托单相同");
        }
        if (!Objects.equals(target.getCommissionUnitId(), insOrder.getCompanyId())) {
            throw new ErrorException("目标检验委托单与成品订单的委托单位不一致");
        }
        Integer oldInspectionOrderId = binding.getInspectionOrderId();
        binding.setInspectionOrderId(inspectionOrderId);
        binding.setUpdateUser(SecurityUtils.getUserId().intValue());
        binding.setUpdateTime(LocalDateTime.now());
        inspectionOrderBindingMapper.updateById(binding);
        inspectionOrderAttachmentMapper.update(null, Wrappers.<InspectionOrderAttachment>lambdaUpdate()
                .eq(InspectionOrderAttachment::getBindingId, binding.getId())
                .set(InspectionOrderAttachment::getInspectionOrderId, inspectionOrderId)
                .set(InspectionOrderAttachment::getUpdateTime, LocalDateTime.now()));
        InspectionOrderBindLog bindLog = new InspectionOrderBindLog();
        bindLog.setInsOrderId(insOrderId);
        bindLog.setOldInspectionOrderId(oldInspectionOrder == null ? null : oldInspectionOrder.getInspectionOrderId());
        bindLog.setOldInspectionOrderId(oldInspectionOrderId);
        bindLog.setNewInspectionOrderId(inspectionOrderId);
        bindLog.setChangeReason(reason.trim());
        bindLog.setCreateUser(SecurityUtils.getUserId().intValue());
@@ -464,33 +523,71 @@
     */
    @Override
    public boolean uploadInspectionOrderFile(MultipartFile file, Integer inspectionOrderId) {
        String urlString;
        String pathName;
        try {
            String path = wordUrl;
            File realpath = new File(path);
            if (!realpath.exists()) {
                realpath.mkdirs();
            }
            pathName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyMMddHHmmss")) + "_" + file.getOriginalFilename();
            urlString = realpath + "/" + pathName;
            file.transferTo(new File(urlString));
            baseMapper.update(null, Wrappers.<InspectionOrder>lambdaUpdate()
                    .eq(InspectionOrder::getInspectionOrderId, inspectionOrderId)
                    .set(InspectionOrder::getFileUrl, "/word/" + pathName));
        } catch (Exception e) {
            throw new ErrorException("文件上传失败");
        }
        return true;
        throw new ErrorException("请在下单记录中选择具体订单后上传附件");
    }
    @Override
    public void exportInspectionOrder(Integer inspectionOrderId, HttpServletResponse response) {
    public boolean uploadInspectionOrderBindingFile(MultipartFile file, Long bindingId) {
        if (file == null || file.isEmpty() || bindingId == null) {
            throw new ErrorException("请选择下单记录和上传文件");
        }
        InspectionOrderBinding binding = inspectionOrderBindingMapper.selectById(bindingId);
        if (binding == null || Integer.valueOf(1).equals(binding.getOrderDeleted())) {
            throw new ErrorException("下单记录不存在或订单已删除");
        }
        try {
            File realpath = new File(wordUrl);
            if (!realpath.exists() && !realpath.mkdirs()) {
                throw new ErrorException("文件目录创建失败");
            }
            String originalName = new File(file.getOriginalFilename() == null ? "attachment" : file.getOriginalFilename()).getName();
            String pathName = "binding_" + bindingId + "_" + UUID.randomUUID() + "_" + originalName;
            file.transferTo(new File(realpath, pathName));
            InspectionOrderAttachment attachment = new InspectionOrderAttachment();
            attachment.setInspectionOrderId(binding.getInspectionOrderId());
            attachment.setBindingId(bindingId);
            attachment.setSourceType("MANUAL");
            attachment.setFileName(originalName);
            attachment.setFileUrl("/word/" + pathName);
            attachment.setCreateUser(SecurityUtils.getUserId().intValue());
            attachment.setCreateTime(LocalDateTime.now());
            inspectionOrderAttachmentMapper.insert(attachment);
            return true;
        } catch (ErrorException e) {
            throw e;
        } catch (Exception e) {
            throw new ErrorException("文件上传失败");
        }
    }
    @Override
    public void exportInspectionOrder(Integer inspectionOrderId, Long bindingId, HttpServletResponse response) {
        InspectionOrder inspectionOrder = baseMapper.selectById(inspectionOrderId);
        if (inspectionOrder == null) {
            throw new ErrorException("检验委托单不存在");
        }
        InspectionOrderExportDto inspectionOrderExportDto = extracted(inspectionOrder);
        if (bindingId == null) {
            inspectionOrderExportDto.setEntrustCode(null);
            inspectionOrderExportDto.setSampleTakerUser(null);
            inspectionOrderExportDto.setSampleTakerUserId(null);
            inspectionOrderExportDto.setSampleData(null);
            inspectionOrderExportDto.setSampleDataString(null);
        } else {
            InspectionOrderBinding binding = inspectionOrderBindingMapper.selectById(bindingId);
            if (binding == null || !Objects.equals(binding.getInspectionOrderId(), inspectionOrderId)) {
                throw new ErrorException("下单记录不属于该检验委托单");
            }
            InsOrder insOrder = insOrderService.getById(binding.getInsOrderId());
            inspectionOrderExportDto.setEntrustCode(insOrder == null ? null : insOrder.getEntrustCode());
            inspectionOrderExportDto.setSampleTakerUser(binding.getSampleTakerUser());
            inspectionOrderExportDto.setSampleTakerUserId(binding.getSampleTakerUserId());
            inspectionOrderExportDto.setSampleData(binding.getSampleData());
            if (binding.getSampleData() != null) {
                inspectionOrderExportDto.setSampleDataString(binding.getSampleData()
                        .format(DateTimeFormatter.ofPattern("yyyy年MM月dd日")));
            }
        }
        List<InspectionOrderDetail> list = inspectionOrderDetailService.list(Wrappers.<InspectionOrderDetail>lambdaQuery()
                .eq(InspectionOrderDetail::getInspectionOrderId, inspectionOrderId));
        int index = 1;