lyh
2 天以前 2ab86210fb27787cb1be8976286b9b827f90997f
src/main/java/com/lxzn/webservice/impl/DncWebServiceImpl.java
@@ -8,14 +8,14 @@
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.lxzn.activiti.service.IAssignFileStreamService;
import com.lxzn.framework.domain.activiti.response.ActivitiCode;
import com.lxzn.framework.domain.filesystem.response.FileUploadResult;
import com.lxzn.framework.domain.nc.*;
import com.lxzn.framework.domain.nc.response.DocumentCode;
import com.lxzn.framework.domain.webservice.DispatchInfo;
import com.lxzn.framework.domain.webservice.PlmProgramSourceInfo;
import com.lxzn.framework.domain.webservice.ProcedureFinish;
import com.lxzn.framework.domain.webservice.request.NcProgramInfo;
import com.lxzn.framework.domain.webservice.request.PlmProgramSource;
import com.lxzn.framework.domain.webservice.request.*;
import com.lxzn.framework.exception.ExceptionCast;
import com.lxzn.framework.model.response.CommonCode;
import com.lxzn.framework.utils.CxfClientUtil;
@@ -24,9 +24,8 @@
import com.lxzn.framework.utils.ZipUtil;
import com.lxzn.framework.utils.file.FileUtil;
import com.lxzn.nc.service.*;
import com.lxzn.nc.service.impl.DeviceInfoServiceImpl;
import com.lxzn.webservice.DncWebService;
import com.lxzn.framework.domain.webservice.request.WsDispatch;
import com.lxzn.framework.domain.webservice.request.WsProcedureFinish;
import com.lxzn.webservice.ext.MesResultModel;
import com.lxzn.webservice.service.IDispatchInfoService;
import com.lxzn.webservice.service.IPlmProgramSourceInfoService;
@@ -62,40 +61,12 @@
 * @Description:
 */
@Service
@WebService(name = "DncWebService",
        targetNamespace = "http://lxzn.webservice.com",
        endpointInterface = "com.lxzn.webservice.DncWebService"
)
//@WebService(name = "DncWebService",
//        targetNamespace = "http://lxzn.webservice.com",
//        endpointInterface = "com.lxzn.webservice.DncWebService"
//)
@Slf4j
public class DncWebServiceImpl implements DncWebService {
    @Value("${ncPdm.file_path}")
    private String filePath;
    /**
     * url
     */
    @Value("${webservice.url}")
    private String url;
    /**
     * namespace
     */
    @Value("${webservice.namespace}")
    private String namespace;
    /**
     * method
     */
    @Value("${webservice.method}")
    private String method;
    @Resource
    private IDispatchInfoService dispatchInfoService;
    @Resource
    private IProcedureFinishService procedureFinishService;
    @Resource
    private IDeviceInfoService deviceInfoService;
    @Resource
    private IAssignFileStreamService assignFileStreamService;
    @Resource
    private IPlmProgramSourceInfoService iPlmProgramSourceInfoService;
    @Autowired
@@ -126,112 +97,10 @@
    private IDocClassificationService docClassificationService;
    @Autowired
    private IDeviceManagementService deviceManagementService;
    /**
     * 派工任务下发接口
     * @param msg
     * @return
     */
    @Override
    public String issuedDispatchTask(@WebParam(name = "msg") String msg){
        log.info("MES派工任务下发原始数据 === {}", msg);
        List<WsDispatch> wsDispatchList = JSONObject.parseArray(msg, WsDispatch.class);
        for (WsDispatch wsDispatch : wsDispatchList) {
            DispatchInfo dispatchInfo = new DispatchInfo();
            BeanUtils.copyProperties(wsDispatch, dispatchInfo);
            dispatchInfoService.save(dispatchInfo);
            Map<Boolean,String> ncResult = disPatchTaskNc(dispatchInfo);
            if (ncResult.containsKey(false)) {
                // 返回具体的错误信息
                return MesResultModel.error("NC任务下发失败: " + ncResult.get(false));
            }
        }
        return MesResultModel.success("成功");
    }
    /**
     * 下发程序
     */
    public Map<Boolean,String> disPatchTaskNc(DispatchInfo dispatchInfo) {
        String processCode = dispatchInfo.getOperationSeqNo() + "_" + dispatchInfo.getEquipmentId();
        return assignFileStreamService.disPatchTaskNc(dispatchInfo.getEquipmentId(),
                dispatchInfo.getWorkshop(),dispatchInfo.getMdsItemCode(),processCode,dispatchInfo.getRevisionNo(),dispatchInfo.getId());
    }
    /**
     * 完工
     *
     * @param msg
     * @return
     */
    @Override
    public String issuedProcedureFinish(String msg) {
        log.info("MES完工原始数据 === {}", msg);
        List<WsProcedureFinish> wsProcedureFinishList = JSONObject.parseArray(msg, WsProcedureFinish.class);
        if (CollectionUtils.isEmpty(wsProcedureFinishList)) {
            return MesResultModel.error("MesResultModel");
        }
        List<ProcedureFinish> procedureFinishList = wsProcedureFinishList.stream()
                .map(source -> {
                    ProcedureFinish target = new ProcedureFinish();
                    BeanUtils.copyProperties(source, target);
                    return target;
                })
                .collect(Collectors.toList());
        procedureFinishService.saveBatch(procedureFinishList);
        //DNC系统依据工单号删除设备结构树上对应的NC程序及工控网NC程序
        for (ProcedureFinish procedureFinish : procedureFinishList) {
            //DNC系统依据工单号删除设备结构树上对应的NC程序及工控网NC程序
            if (procedureFinish.getEndineStatus().equals("3")){
                //删除设备结构树上对应的NC程序及工控网NC程序
                ProductInfo productInfo = productInfoService.getByProductNo("PLM");
                if (productInfo == null) {
                    log.error("======= 产品层级异常,请联系开发人员=======");
                    return MesResultModel.error("产品层级异常,请联系开发人员");
                }
                List<ComponentInfo> componentInfoList = componentInfoService.getByProductId(productInfo.getProductId());
                List<String
                        > comlist = new ArrayList<>();
                if (componentInfoList != null && !componentInfoList.isEmpty()) {
                    for (ComponentInfo cc : componentInfoList) {
                        comlist.add(cc.getComponentId());
                    }
                } else {
                    return MesResultModel.error("无部件信息,请联系开发人员");
                }
                String processCode=procedureFinish.getMdsItemCode();
                PartsInfo part = partsInfoService.getByCodeAndComIdList(procedureFinish.getMdsItemCode(),comlist);
                if (part == null) {
                    return MesResultModel.error("无此零件信息"+"__" + processCode+",请联系开发人员");
                }
                processCode = processCode.split("_")[0];
                //工序
                ProcessStream stream = processStreamService.findByProcessEquipment(procedureFinish.getEquipmentId(),
                        processCode,procedureFinish.getRevisionNo(),productInfo.getProductId(),part.getPartsId());
                if (stream == null) {
                    return MesResultModel.error("无此工序信息"+"__" + processCode+",请联系开发人员");
                }
                //查询对应NC程序
                List<ProcessStream> processStreamList = new ArrayList<>();
                processStreamList.add(stream);
                List<DocInfo> docFileList = docInfoService.getByProcessIds(processStreamList);
                if (docFileList == null || docFileList.isEmpty()) {
                    return MesResultModel.error("无此NC程序" + "__" + processCode + ",请联系开发人员");
                }
                docFileList.forEach(docFile -> {
                    docInfoService.deleteDocInfo(docFile.getDocId());
                });
            }
        }
        log.info("接收MES完工原始数据成功!");
        return MesResultModel.success("成功");
    }
    @Autowired
    private DeviceInfoServiceImpl deviceInfoService;
    @Autowired
    private IDeviceGroupService deviceGroupService;
    /**
     * 获取NC文件及属性信息(集成PLM)
     *
@@ -246,7 +115,7 @@
        List<PlmProgramSource> plmProgramSourceList = JSONObject.parseArray(msg, PlmProgramSource.class);
        AtomicReference<MesResultModel> mesResultModel= new AtomicReference<>(new MesResultModel());
        plmProgramSourceList.forEach(item -> {
            mesResultModel.set(setTree(item));
            mesResultModel.set(setPlmTree(item));
        });
        return mesResultModel.get();
    }
@@ -262,7 +131,7 @@
     * @param plmProgramSource
     * @return
     */
    public MesResultModel setTree(PlmProgramSource plmProgramSource) {
    public MesResultModel setPlmTree(PlmProgramSource plmProgramSource) {
        MesResultModel model = new MesResultModel();
        model.setSuccFlag("成功");
        PlmProgramSourceInfo plmProgramSourceInfo = new PlmProgramSourceInfo();
@@ -485,76 +354,407 @@
        return model;
    }
    /**
     * 封装树结构
     * 1. 产品 集成数据
     * 2、部件 按照部门(车间 nc_plant_name )维度建立
     * 3、零件 图号(零件号、零件名称) part_no
     * 4、工序  工艺ID(工艺规程编号/临规编号)
     * 5. nc文件 (工序下)
     * 6.机床型号与机床操作系统组成设备类与工序进行绑定
     * 集成3DE挂树
     * @param thirdDeProgramSource
     * @return
     */
    @Override
    @Transactional
    public MesResultModel processThirdDEProgram(ThirdDeProgramSource thirdDeProgramSource) {
        MesResultModel model = new MesResultModel();
        model.setSuccFlag("成功");
        try {
            log.info("3DE NC文件及属性信息原始数据 === {}", JSONObject.toJSONString(thirdDeProgramSource));
            // 产品 - 使用默认的3DE产品
            ProductInfo productInfo = productInfoService.getByProductNo("3DE");
            if (productInfo == null) {
                return createErrorModel(model, "3DE产品层级异常,请联系开发人员");
            }
            // 部件 - 按照车间维度建立
            ComponentInfo componentInfo = componentInfoService.getByCode(thirdDeProgramSource.getNcPlantNo());
            if (componentInfo == null) {
                componentInfo = new ComponentInfo();
                componentInfo.setComponentId(IdWorker.getIdStr());
                componentInfo.setComponentCode(thirdDeProgramSource.getNcPlantNo());
                componentInfo.setComponentName(thirdDeProgramSource.getNcPlantName());
                componentInfo.setComponentStatus(1);
                componentInfo.setRankLevel(1);
                componentInfo.setParentId(productInfo.getProductId());
                componentInfo.setProductId(productInfo.getProductId());
                if (!componentInfoService.save(componentInfo)) {
                    return createErrorModel(model, "添加3DE部件层级失败,请联系开发人员");
                }
                if (!savePermissionList(componentInfo, productInfo.getProductId())) {
                    return createErrorModel(model, "添加3DE部件权限失败,请联系开发人员");
                }
            }
            // 零件 - 图号(零件号、零件名称)
            PartsInfo partsInfo = partsInfoService.getByCode(thirdDeProgramSource.getPartNo());
            if (partsInfo == null) {
                partsInfo = new PartsInfo();
                partsInfo.setPartsId(IdWorker.getIdStr());
                partsInfo.setComponentId(componentInfo.getComponentId());
                partsInfo.setProductId(productInfo.getProductId());
                partsInfo.setPartsStatus(1);
                partsInfo.setPartsCode(thirdDeProgramSource.getPartNo());
                partsInfo.setPartsName(thirdDeProgramSource.getPartName());
                partsInfo.setPartsModel(thirdDeProgramSource.getPartNo());
                if (!partsInfoService.save(partsInfo)) {
                    return createErrorModel(model, "添加3DE零件层级失败,请联系开发人员");
                }
                // 添加零件权限
                if (!savePartsPermission(partsInfo, productInfo.getProductId())) {
                    return createErrorModel(model, "添加3DE零件权限失败,请联系开发人员");
                }
            }
            // 工序 - 工艺ID(工艺规程编号/临规编号)
            ProcessStream processStream = processStreamService.findByProcessNoAndPartsId(
                    thirdDeProgramSource.getSkgxId(), partsInfo.getPartsId());
            List<ProcessStream> addProcessList = new ArrayList<>();
            List<ProcessStream> updateProcessList = new ArrayList<>();
            if (processStream == null) {
                processStream = new ProcessStream();
                processStream.setProcessId(IdWorker.getIdStr());
                processStream.setProductId(productInfo.getProductId());
                processStream.setComponentId(componentInfo.getComponentId());
                processStream.setPartsId(partsInfo.getPartsId());
                processStream.setProcessCode(thirdDeProgramSource.getSkgxId());
                processStream.setProcessName(thirdDeProgramSource.getSkgxName());
                processStream.setCraftVersion(thirdDeProgramSource.getRevisionNo()); // 设置工艺版本
                // 设备信息处理
                DeviceManagement deviceManagement = deviceManagementService.findEquipmentIdsFromEqId(
                        thirdDeProgramSource.getNcPlantName(), thirdDeProgramSource.getEquipmentId());
                if (deviceManagement != null && StringUtils.isNotEmpty(deviceManagement.getEquipmentIds())) {
                    processStream.setProcessingEquipmentCode(deviceManagement.getEquipmentIds());
                } else {
                    processStream.setProcessingEquipmentCode(thirdDeProgramSource.getEquipmentId());
                }
                processStream.setProcessingEquipmentOs(thirdDeProgramSource.getNcOs());
                processStream.setProcessingEquipmentModel(thirdDeProgramSource.getNcJcid());
                addProcessList.add(processStream);
            } else {
                // 更新时检查版本是否变更
                if (!Objects.equals(processStream.getCraftVersion(), thirdDeProgramSource.getRevisionNo())) {
                    processStream.setCraftVersion(thirdDeProgramSource.getRevisionNo());
                }
                processStream.setProcessName(thirdDeProgramSource.getSkgxName());
                updateProcessList.add(processStream);
            }
            if (!addProcessList.isEmpty() && !processStreamService.saveBatch(addProcessList)) {
                return createErrorModel(model, "添加3DE工序失败,请联系开发人员");
            }
            if (!updateProcessList.isEmpty() && !processStreamService.updateBatchById(updateProcessList)) {
                return createErrorModel(model, "更新3DE工序失败,请联系开发人员");
            }
            // 文档分类
            DocClassification ncDocClass = docClassificationService.getByCode("NC");
            if (ncDocClass == null) {
                return createErrorModel(model, "NC文档分类不存在,请联系开发人员");
            }
            // send文档分类
            DocClassification sendDocClass = docClassificationService.getByCode("SEND");
            if (sendDocClass == null) {
                return createErrorModel(model, "SEND文档分类不存在,请联系开发人员");
            }
            // 处理NC文件
            if (thirdDeProgramSource.getNcFiles() != null && !thirdDeProgramSource.getNcFiles().isEmpty()) {
                for (Map.Entry<String, byte[]> entry : thirdDeProgramSource.getNcFiles().entrySet()) {
                    String fileName = entry.getKey();
                    byte[] fileContent = entry.getValue();
                    String suffix = FileUtil.getFileSuffix(fileName);
                    String baseName = FileUtil.getFilenameNonSuffix(fileName);
                    // 查找现有文档
                    DocInfo docInfo = docInfoService.findByAttrAndDocName(baseName, 5,
                            processStream.getProcessId(), suffix);
                    FileUploadResult fileUploadResult = FileUtil.uploadFileByFileNameAndFis(
                            fileName, new ByteArrayInputStream(fileContent));
                    if (fileUploadResult == null) {
                        return createErrorModel(model, "上传3DE NC文件失败");
                    }
                    boolean success;
                    if (docInfo == null) {
                        // 新增文档
                        docInfo = new DocInfo();
                        String docId = IdWorker.getIdStr();
                        docInfo.setDocId(docId);
                        docInfo.setDocName(fileUploadResult.getFileName());
                        docInfo.setDocSuffix(fileUploadResult.getFileSuffix());
                        docInfo.setDocStatus(5);
                        // 创建文档关联
                        DocRelative docRelative = new DocRelative();
                        docRelative.setAttributionId(processStream.getProcessId());
                        docRelative.setDocId(docInfo.getDocId());
                        docRelative.setAttributionType(5);
                        docRelative.setClassificationId(ncDocClass.getClassificationId());
                        if (!docRelativeService.save(docRelative)) {
                            return createErrorModel(model, "创建3DE文档关联失败");
                        }
                        // 保存文档文件
                        if (getFile(docInfo, fileUploadResult, docFileService)) {
                            return createErrorModel(model, "保存3DE文档文件失败");
                        }
                        success = docInfoService.save(docInfo);
                        // 获取最新文档文件
                        DocFile docFile = docFileService.getDocFileNearest(docId);
                        // 添加到设备
                        if (!linkToDevice(thirdDeProgramSource.getEquipmentId(), docInfo.getDocId(), docFile, sendDocClass)) {
                            return createErrorModel(model, "添加设备文档关联失败");
                        }
                    } else {
                        // 更新文档 - 处理版本控制
                        if (StringUtils.isNotEmpty(processStream.getCraftVersion()) &&
                                StringUtils.isNotEmpty(thirdDeProgramSource.getRevisionNo())) {
                            // 版本变更,保存旧版本文件
                            if (!Objects.equals(processStream.getCraftVersion(), thirdDeProgramSource.getRevisionNo())) {
                                this.createFileOldNcPathAndCopyFor3DE(docInfo, thirdDeProgramSource);
                            }
                        }
                        DocFile docFile = getDocFile(docInfo, fileUploadResult);
                        success = docFileService.addDocFile(docFile);
                        if (success) {
                            docInfo.setPublishVersion(docFile.getDocVersion());
                            docInfo.setPublishFileId(docFile.getFileId());
                            success = docInfoService.updateById(docInfo);
                            // 更新设备关联
                            if (!updateDeviceLink(thirdDeProgramSource.getEquipmentId(), docInfo.getDocId(), sendDocClass)) {
                                return createErrorModel(model, "更新设备文档关联失败");
                            }
                        }
                    }
                    if (!success) {
                        return createErrorModel(model, "处理3DE NC文件失败");
                    }
                }
            }
            return model;
        } catch (Exception e) {
            log.error("处理3DE程序数据异常: {}", e.getMessage(), e);
            return createErrorModel(model, "处理3DE程序数据异常: " + e.getMessage());
        }
    }
    /**
     * 添加到设备
     */
    private boolean linkToDevice(String equipmentId, String docId, DocFile docFile, DocClassification sendDocClass) {
        try {
            DeviceInfo deviceInfo = deviceInfoService.getByDeviceNo(equipmentId);
            if (deviceInfo == null) {
                log.error("DNC中设备不存在: {}", equipmentId);
                return false;
            }
            DocRelative deviceDocRelative = new DocRelative();
            deviceDocRelative.setAttributionId(deviceInfo.getDeviceId());
            deviceDocRelative.setDocId(docId);
            deviceDocRelative.setAttributionType(4);
            deviceDocRelative.setClassificationId(sendDocClass.getClassificationId());
            boolean saved = docRelativeService.save(deviceDocRelative);
            if (!saved) {
                log.error("保存设备文档关联失败: device={}, doc={}", equipmentId, docId);
                return false;
            }
            // 复制文件到设备路径
            List<String> groupPaths = deviceGroupService.findListParentTreeAll(deviceInfo.getGroupId());
            if (groupPaths != null && !groupPaths.isEmpty()) {
                String devicePath = String.join("/", groupPaths) + "/" + deviceInfo.getDeviceNo();
                // 复制文件
                boolean copySuccess = FileUtil.copyFileNc(
                        docFile.getFilePath(),
                        devicePath,
                        docFile.getFileEncodeName(),
                        docFile.getFileName(),
                        docFile.getFileSuffix());
                if (!copySuccess) {
                    log.error("文件复制失败: {} -> {}", docFile.getFilePath(), devicePath);
                    return false;
                }
                // 删除旧版本文件
                FileUtil.deleteZipFromToSend(
                        devicePath,
                        docFile.getFileName(),
                        docFile.getFileSuffix());
            }
            return true;
        } catch (Exception e) {
            log.error("添加设备文档关联异常: {}", e.getMessage(), e);
            return false;
        }
    }
    /**
     * 更新设备关联
     */
    private boolean updateDeviceLink(String equipmentId, String docId, DocClassification sendDocClass) {
        try {
            DeviceInfo deviceInfo = deviceInfoService.getByDeviceNo(equipmentId);
            if (deviceInfo == null) {
                log.error("DNC中设备不存在: {}", equipmentId);
                return false;
            }
            // 检查关联是否已存在
            DocRelative existingRel = docRelativeService.findDocRelative(docId,sendDocClass.getClassificationId(), 4,deviceInfo.getDeviceId());
            if (existingRel == null) {
                // 创建新关联
                DocRelative deviceDocRelative = new DocRelative();
                deviceDocRelative.setAttributionId(deviceInfo.getDeviceId());
                deviceDocRelative.setDocId(docId);
                deviceDocRelative.setAttributionType(4);
                deviceDocRelative.setClassificationId(sendDocClass.getClassificationId());
                return docRelativeService.save(deviceDocRelative);
            }
            return true;
        } catch (Exception e) {
            log.error("更新设备关联异常: {}", e.getMessage(), e);
            return false;
        }
    }
    /**
     * 为3DE数据创建旧版本NC文件备份
     */
    private boolean createFileOldNcPathAndCopyFor3DE(DocInfo docInfo, ThirdDeProgramSource thirdDeProgramSource) {
        DocFile docFile = docFileService.getDocFileNearest(docInfo.getDocId());
        if (docFile == null) {
            log.error("未找到最近版本的3DE文档文件,docId: {}", docInfo.getDocId());
            return false;
        }
        String directoryPath = String.join(File.separator,
                "3de_bak",
                thirdDeProgramSource.getNcPlantName(),
                thirdDeProgramSource.getPartNo(),
                thirdDeProgramSource.getSkgxId(),
                "");
        File directory = new File(directoryPath);
        if (!directory.exists() && !directory.mkdirs()) {
            log.error("创建3DE目录失败: {}", directoryPath);
            return false;
        }
        // 构建目标文件路径
        String targetFileName = buildTargetFileName(docFile);
        String targetFilePath = directoryPath + targetFileName;
        try {
            Path sourcePath = Paths.get(docFile.getFilePath());
            Path targetPath = Paths.get(targetFilePath);
            Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
            log.info("3DE文件复制成功: {} -> {}", docFile.getFilePath(), targetFilePath);
            return true;
        } catch (IOException e) {
            log.error("3DE文件复制失败: {}", e.getMessage(), e);
            if (directory.exists() && isDirectoryEmpty(directory)) {
                directory.delete();
            }
            return false;
        }
    }
    /**
     * 保存零件权限
     */
    private boolean savePartsPermission(PartsInfo partsInfo, String productId) {
        List<PermissionStream> oldPermissionList = permissionStreamService.getAllByProductId(productId);
        if (CollectionUtils.isEmpty(oldPermissionList)) {
            return true;
        }
        List<PartsDepartment> partsDepartPermList = new ArrayList<>();
        List<PermissionStream> partsPermList = new ArrayList<>();
        List<PartsPermission> partsUserPermList = new ArrayList<>();
        for (PermissionStream p : oldPermissionList) {
            if (ValidateUtil.validateString(p.getUserId())) {
                // 用户权限
                PartsPermission permission = new PartsPermission();
                permission.setPartsId(partsInfo.getPartsId());
                permission.setUserId(p.getUserId());
                partsUserPermList.add(permission);
                PermissionStream stream = new PermissionStream();
                stream.setUserId(p.getUserId());
                stream.setProductId(partsInfo.getProductId());
                stream.setComponentId(partsInfo.getComponentId());
                stream.setPartsId(partsInfo.getPartsId());
                partsPermList.add(stream);
            }
            if (ValidateUtil.validateString(p.getDepartId())) {
                // 部门权限
                PartsDepartment department = new PartsDepartment();
                department.setPartsId(partsInfo.getPartsId());
                department.setDepartId(p.getDepartId());
                partsDepartPermList.add(department);
                PermissionStream stream = new PermissionStream();
                stream.setProductId(partsInfo.getProductId());
                stream.setComponentId(partsInfo.getComponentId());
                stream.setPartsId(partsInfo.getPartsId());
                stream.setDepartId(p.getDepartId());
                partsPermList.add(stream);
            }
        }
        boolean success = true;
        if (!partsUserPermList.isEmpty()) {
            success = success && partsPermissionService.saveBatch(partsUserPermList);
        }
        if (!partsDepartPermList.isEmpty()) {
            success = success && partsDepartmentService.saveBatch(partsDepartPermList);
        }
        if (!partsPermList.isEmpty()) {
            success = success && permissionStreamService.saveBatch(partsPermList);
        }
        return success;
    }
    private MesResultModel createErrorModel(MesResultModel model, String errorMsg) {
        model.setSuccFlag("失败");
        model.setError(errorMsg);
        return model;
    }
    /**
     * * NC程序齐套接口(MES)-DNC系统接收到PLM传的NC程序,将程序包对应的零件号、工序号、设备编号传给MES系统
     * 定时扫描PlmProgramSourceInfo表中的数据,进行数据同步,每分钟同步一次
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void syncWorkmanship() {
        // 获取所有需要同步的数据
        List<PlmProgramSourceInfo> plmProgramSourceInfos = iPlmProgramSourceInfoService.list(
                new LambdaQueryWrapper<PlmProgramSourceInfo>()
                        .eq(PlmProgramSourceInfo::getMesStatus, "0")
                        .orderByAsc(PlmProgramSourceInfo::getId)
        );
        if (plmProgramSourceInfos.isEmpty()) {
            log.info("无待同步数据,跳过处理");
            return;
        }
        List<NcProgramInfo> ncProgramInfos = plmProgramSourceInfos.stream().map(item -> {
            NcProgramInfo ncProgramInfo = new NcProgramInfo();
            ncProgramInfo.setMdsItemCode(item.getCzkAe8nPartNo());
            ncProgramInfo.setRevisionNo(item.getRevisionNo());
            ncProgramInfo.setNcProgramName(item.getFileName());
            ncProgramInfo.setOpreationSeqNo(item.getCzkAe8nOpNo());
            ncProgramInfo.setEquipmentId(item.getCzkAe8nEquipNo());
            ncProgramInfo.setWorkshop(item.getCzkAe8nDivision());
//            ncProgramInfo.setMesId(item.getId()); // 确保生成符合要求的mesId
//            ncProgramInfo.setOperFlag();
            return ncProgramInfo;
        }).collect(Collectors.toList());
        log.info("WebService-NC程序齐套接口(MES)同步开始,时间: {}", new Date());
        try {
            String jsonPayload = JSONObject.toJSONString(ncProgramInfos);
            log.debug("上报数据: {}", jsonPayload);
            // 调用WebService并获取详细响应
            String result = CxfClientUtil.invokeService(url, jsonPayload, namespace, method);
            log.info("接口响应: {}", result);
            // 解析响应结果,只会有成功和失败
            if (result.contains("成功")) {
                List<PlmProgramSourceInfo> toUpdate = new ArrayList<>();
                plmProgramSourceInfos.forEach(item -> {
                    item.setMesStatus("1");
                    toUpdate.add(item);
                });
                // 批量更新状态
                if (!toUpdate.isEmpty()) {
                    iPlmProgramSourceInfoService.updateBatchById(toUpdate);
                    log.info("成功更新{}条数据状态", toUpdate.size());
                }
            }else {
                log.error("同步MES系统失败: {}", result);
            }
        } catch (Exception e) {
            log.error("同步MES系统失败: {}", e.getMessage(), e);
            // 仅标记处理失败的记录
            plmProgramSourceInfos.forEach(item -> item.setMesStatus("0"));
            iPlmProgramSourceInfoService.updateBatchById(plmProgramSourceInfos);
            throw new RuntimeException("同步失败,已回滚状态", e); // 触发事务回滚
        }
    }
    /**
@@ -644,17 +844,6 @@
        }
        String[] files = directory.list();
        return files == null || files.length == 0;
    }
    private static String buildRequestBody(NcProgramInfo ncProgramInfo) {
        StringBuilder body = new StringBuilder();
        body.append("mesId=").append(ncProgramInfo.getMesId())
                .append("&mdsItemCode=").append(ncProgramInfo.getMdsItemCode())
                .append("&revisionNo=").append(ncProgramInfo.getRevisionNo())
                .append("&opreationSeqNo=").append(ncProgramInfo.getOpreationSeqNo())
                .append("&equipmentId=").append(ncProgramInfo.getEquipmentId())
                .append("&workshop=").append(ncProgramInfo.getWorkshop());
        return body.toString();
    }