压缩为zip和gzip工具类

一、压缩为zip工具类

package com.chinamobile.interfaces.biz.utils;

import com.chinamobile.interfaces.biz.config.SignConfig;
import com.chinamobile.interfaces.biz.constant.Constants;
import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.model.enums.AesKeyStrength;
import net.lingala.zip4j.model.enums.EncryptionMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * Zip工具类
 *
 * @author: lp
 */
public class ZipUtil {

    private static final Logger log = LoggerFactory.getLogger(ZipUtil.class);

    /**
     * 生成zip文件
     * 1.csv文件->压缩成zip
     * 2.产生DataSign.txt文件
     * 3.将1和2两个文件,压缩成zip,密码在yml配置
     *
     * @param list
     * @param fileName
     * @param clazz
     * @param <T>
     */
    public static <T> void generateZip(List<T> list, String fileName, Class<T> clazz) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, SignatureException, InvalidKeyException {
        byte[] bytes = CsvUtil.exportToByteArray(list, clazz);
        byte[] innerZipBytes = ZipUtil.createZipFromByteArray(bytes, fileName + ".csv");
        byte[] signBytes = SignUtil.getEncryptedSignature(bytes);
        List<byte[]> fileDatas = new ArrayList<>();
        List<String> fileNames = new ArrayList<>();
        fileDatas.add(signBytes);
        fileDatas.add(innerZipBytes);
        fileNames.add(Constants.SIGN_TEXT_NAME);
        fileNames.add(fileName + ".zip");
        ZipUtil.createEncryptedZip(fileDatas, fileNames, SignConfig.getZipPath() + fileName + ".zip");
    }

    /**
     * 创建ZIP文件
     *
     * @param data      数据
     * @param entryName 条目名称
     * @return
     * @throws IOException
     */
    public static byte[] createZipFromByteArray(byte[] data, String entryName) throws IOException {
        File tempFile = new File(entryName);
        File tempZip = null;
        try (FileOutputStream fileOutputStream = new FileOutputStream(tempFile)) {
            fileOutputStream.write(data);
            tempZip = cn.hutool.core.util.ZipUtil.zip(tempFile);
            return cn.hutool.core.io.FileUtil.readBytes(tempZip);
        } finally {
            boolean fileFlag = tempFile.delete();
            if (!fileFlag) {
                log.error("文件删除异常{}", entryName);
            }
            if (tempZip != null) {
                boolean fileZipFlag=tempZip.delete();
                if (!fileZipFlag) {
                    log.error("压缩文件删除异常{}", entryName);
                }
            }
        }
    }

    /**
     * 创建zip文件(设置默认密码)
     *
     * @param filesData  数据集合
     * @param fileNames  文件名集合
     * @param outputPath 输出路径
     * @throws IOException
     */
    public static void createEncryptedZip(List<byte[]> filesData, List<String> fileNames, String outputPath) throws IOException {
        createEncryptedZip(filesData, fileNames, outputPath, SignConfig.getZipPwd());
    }

    /**
     * 创建zip文件并设置密码
     *
     * @param filesData  数据集合
     * @param fileNames  文件名集合
     * @param outputPath 输出路径
     * @param password   压缩密码
     * @throws IOException
     */
    public static void createEncryptedZip(List<byte[]> filesData, List<String> fileNames, String outputPath, String password) throws IOException {
        // 创建输出文件
        File outputFile = new File(outputPath);
        // 创建ZipFile对象
        ZipFile zipFile = new ZipFile(outputFile, password.toCharArray());
        // 设置ZIP参数,包括加密
        ZipParameters zipParameters = new ZipParameters();
        zipParameters.setEncryptFiles(true);
        zipParameters.setEncryptionMethod(EncryptionMethod.AES);
        zipParameters.setAesKeyStrength(AesKeyStrength.KEY_STRENGTH_256);
        // 添加每个文件到ZIP文件
        for (int i = 0; i < filesData.size(); i++) {
            byte[] fileData = filesData.get(i);
            String fileName = fileNames.get(i);
            // 设置ZIP参数中的文件名
            zipParameters.setFileNameInZip(fileName);
            // 创建一个ByteArrayInputStream来读取字节数组
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(fileData);
            // 添加流到ZIP文件
            zipFile.addStream(byteArrayInputStream, zipParameters);
            // 关闭流
            byteArrayInputStream.close();
        }
    }

    /**
     * 解压文件到指定的目录
     *
     * @param zipFilePath 文件所在路径
     * @param outputPath  解压的路径
     * @throws IOException
     */
    public static void extractZipFile(String zipFilePath, String outputPath) throws IOException {
        File zipFile = new File(zipFilePath);
        ZipFile zip = new ZipFile(zipFile);
        zip.extractAll(outputPath);
    }


    /**
     * 压缩多个文件,指定文件夹为.zip
     *
     * @param sourceDirPath 源文件所在文件夹路径
     * @param zipFilePath   目标压缩文件全路径,包含文件名
     * @throws IOException
     */
    public static void compressFiles(String sourceDirPath, String zipFilePath) throws IOException {
        FileOutputStream fos = new FileOutputStream(zipFilePath);
        ZipOutputStream zos = new ZipOutputStream(fos);
        try {
            File dir = new File(sourceDirPath);
            compress(dir, dir, zos);
        } finally {
            if (zos != null) {
                zos.close();
            }
            if (fos != null) {
                fos.close();
            }
        }
    }


    /**
     * 压缩单个指定文件为.zip
     *
     * @param sourceFilePath 源文件路径,包含文件名
     * @param sourceDirPath  源文件所在文件夹路径
     * @param zipFilePath    目标压缩文件全路径,包含文件名
     * @throws IOException
     */
    public static void compressFile(String sourceFilePath, String sourceDirPath, String zipFilePath) throws IOException {
        FileOutputStream fos = new FileOutputStream(zipFilePath);
        ZipOutputStream zos = new ZipOutputStream(fos);
        try {
            File file = new File(sourceFilePath);
            File dir = new File(sourceDirPath);
            compress(file, dir, zos);
        } finally {
            if (zos != null) {
                zos.close();
            }
            if (fos != null) {
                fos.close();
            }
        }
    }


    private static void compress(File sourceFile, File sourceDir, ZipOutputStream zos) throws IOException {
        if (sourceFile.isDirectory()) {
            File[] files = sourceFile.listFiles();
            if (files != null) {
                for (File file : files) {
                    compress(file, sourceDir, zos);
                }
            }
        } else {
            ZipEntry entry = new ZipEntry(sourceFile.getPath().substring(sourceDir.getPath().length() + 1));
            zos.putNextEntry(entry);
            try (FileInputStream fis = new FileInputStream(sourceFile)) {
                byte[] buffer = new byte[1024];
                int len;
                while ((len = fis.read(buffer)) != -1) {
                    zos.write(buffer, 0, len);
                }
            }
            zos.closeEntry();
        }
    }

}

二、压缩为gzip工具类

package com.chinamobile.interfaces.biz.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipException;

/**
 * gzip工具类
 *
 * @author: cwf
 */
public class GzipUtil {
    private static final Logger log = LoggerFactory.getLogger(GzipUtil.class);

    /**
     * 使用gzip压缩文件
     *
     * @param sourceFilePath 要压缩的文件路径
     * @param targetGzipFilePath 压缩后的gzip文件路径
     * @throws IOException 如果发生I/O异常
     */
    public static void compressGzipFile(String sourceFilePath, String targetGzipFilePath) throws IOException {
        try(
        FileInputStream fileInputStream = new FileInputStream(sourceFilePath);
        FileOutputStream fileOutputStream = new FileOutputStream(targetGzipFilePath);
        GZIPOutputStream gzipOutputStream = new GZIPOutputStream(fileOutputStream);
        ) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = fileInputStream.read(buffer)) > 0) {
                gzipOutputStream.write(buffer, 0, bytesRead);
            }
        }
//        gzipOutputStream.close();
//        fileOutputStream.close();
//        fileInputStream.close();
    }

    /**
     * 解压gzip文件
     *
     * @param inputFilePath        待解压文件的具体路径
     * @param outputDirectoryPath  目标目录路径
     * @throws IOException 如果文件读取或写入发生错误
     */
    public static void decompressGzipFile(String inputFilePath, String outputDirectoryPath) throws IOException {
        // 确保目标目录存在
        File outputDirectory = new File(outputDirectoryPath);
        if (!outputDirectory.exists()) {
           boolean flag= outputDirectory.mkdirs();
           if(!flag){
               log.error("文件夹创建异常",outputDirectoryPath);
           }
        }

        // 获取解压后的文件名
        String outputFileName = new File(inputFilePath).getName().replace(".gz", "");
        File outputFile = new File(outputDirectoryPath, outputFileName);

        try (
                FileInputStream fis = new FileInputStream(inputFilePath);
        		BufferedInputStream bis = new BufferedInputStream(fis);
                GZIPInputStream gzis = new GZIPInputStream(bis);
                FileOutputStream fos = new FileOutputStream(outputFile);
                BufferedOutputStream bos = new BufferedOutputStream(fos)
        ) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = gzis.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
        }
    }

    public static void decompressGzipFileNew(String gzFile, String resultFile){
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(gzFile));
             GZIPInputStream gis = new GZIPInputStream(bis);
             FileOutputStream fos = new FileOutputStream(resultFile)) {

            byte[] buffer = new byte[1024];
            int len;
            while ((len = gis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }

            System.out.println("Done decompressing the file: " + resultFile);

        } catch (FileNotFoundException e) {
            System.err.println("File not found: " + e.getMessage());
        } catch (IOException e) {
            System.err.println("Error decompressing file: " + e.getMessage());
            if (e instanceof ZipException) {
                System.err.println("This file is not in GZIP format.");
            }
        }
    }
}

三、SftpUtils  工具类

package com.chinamobile.interfaces.biz.utils;

import cn.hutool.crypto.CryptoException;
import cn.hutool.crypto.SecureUtil;
import com.chinamobile.interfaces.biz.config.FileConfig;
import com.chinamobile.interfaces.biz.config.SftpConfig;
import com.chinamobile.interfaces.biz.config.SignConfig;
import com.chinamobile.interfaces.biz.entity.Enterprisepension;
import com.chinamobile.interfaces.biz.service.EnterprisepensionService;
import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.GeneralSecurityException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Sftp工具类
 *
 * @author: cwf
 */
@Slf4j
@Component
@ConditionalOnProperty(name = "sftp.enable", havingValue = "true")
public class SftpUtils {

    private static EnterprisepensionService eppService;

    static {
        eppService = ApplicationContextUtil.getApplicationContext().getBean(EnterprisepensionService.class);
    }

    /**
     * 根据日期范围从SFTP服务器上下载文件
     * @param startDate 开始日期
     * @param endDate 结束日期
     * @param cMftCfgId  MFT配置ID
     * @param folderName 下载到本地的文件夹名称
     */
    public static String fetchFilesBetweenDates(String startDate, String endDate, String folderName, String cMftCfgId) {
        String downloadedPath = null;
        try {
            Enterprisepension configData = eppService.queryConfigData(cMftCfgId);
            // 连接到SFTP
            JSch jsch = new JSch();
            Session session = jsch.getSession(configData.getUserid(), configData.getIpAddress(), configData.getCPort());
            session.setPassword(configData.getPassword());
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();

            ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
            sftpChannel.connect();

            // 日期格式化
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
            LocalDate start = LocalDate.parse(startDate, formatter);
            LocalDate end = LocalDate.parse(endDate, formatter);

            // 获取SFTP远程目录下的文件列表
            Vector<ChannelSftp.LsEntry> files = sftpChannel.ls(configData.getFilePath());

            for (ChannelSftp.LsEntry file : files) {
                String fileName = file.getFilename();
                // 判断文件名是否符合要求
                if (fileName.startsWith("MFT_HLP_SALARY_") && fileName.endsWith(".zip")) {
                    // 正则表达式匹配日期格式
                    Pattern pattern = Pattern.compile("\\d{8}");
                    Matcher matcher = pattern.matcher(fileName);
                    if (matcher.find()) {
                        String dateString = matcher.group();
                        LocalDate fileDate = LocalDate.parse(dateString, formatter);
                        // 判断文件日期是否在指定范围内
                        if (!fileDate.isBefore(start) && !fileDate.isAfter(end)) {
                            // 创建本地目录
                            if(configData.getLocalPath() == null){
                                log.info("MFT文件本地存放路径为空!");
                                return null;
                            }
                            String dirPath = configData.getLocalPath() + "/" + folderName + "/" + dateString;
                            Files.createDirectories(Paths.get(dirPath));
                            log.info("本地目录创建成功:" + dirPath);
                            String localFilePath = dirPath + "/" + fileName;

                            // 下载文件
                            log.info("开始下载文件");
                            try (InputStream inputStream = sftpChannel.get(configData.getFilePath() + "/" + fileName);
                                 FileOutputStream outputStream = new FileOutputStream(localFilePath)) {
                                    byte[] buffer = new byte[1024];
                                    int len;
                                    while ((len = inputStream.read(buffer)) != -1) {
                                        outputStream.write(buffer, 0, len);
                                    }
                            }
                            log.info("文件下载完成:" + localFilePath);
                            log.info("文件开始解密:" + configData.getCPasscode());
                            // 解密文件
                            String decryptedFilePath = localFilePath.replace(".zip", ".sign");

                            File file2 = new File(localFilePath);
                            byte[] fileContent2 = FileUtils.readFileToByteArray(file2);
                            log.info("zip file length:{}",file2.length());
                            log.info("zip文件Hash:{}",String.valueOf(file2.hashCode()));
                            String md5Checksum2 = DigestUtils.md5Hex(fileContent2);
                            log.info("zip MD5 Checksum: {}",md5Checksum2);

                            //CipherUtil.decrypt(localFilePath, decryptedFilePath,configData.getCPasscode());
                            EnhanceAesDecry.decrypt(configData.getCPasscode(),localFilePath,decryptedFilePath);
                            File file1 = new File(decryptedFilePath);
                            byte[] fileContent1 = FileUtils.readFileToByteArray(file1);
                            log.info("sign file length:{}",file1.length());
                            log.info("sign文件Hash:{}",String.valueOf(file1.hashCode()));
                            String md5Checksum1 = DigestUtils.md5Hex(fileContent1);
                            log.info("sign MD5 Checksum: {}",md5Checksum1);

                            log.info("文件解密完成: "+ decryptedFilePath);
                            Files.delete(Paths.get(localFilePath));
                            log.info("删除源文件完成");

                            // 解压文件
                            log.info("文件开始解压");
                            ZipUtil.extractZipFile(decryptedFilePath, dirPath);
                            log.info("文件解压完成");
                            Files.delete(Paths.get(decryptedFilePath));
                            log.info("删除解密文件完成");
                            if(downloadedPath == null){
                                downloadedPath = configData.getLocalPath() + "/" + folderName + "/";
                            }
                        }
                    }
                }
            }

            // 关闭SFTP连接
            sftpChannel.disconnect();
            session.disconnect();

        } catch (JSchException | IOException | SftpException e) {
            log.info(e.getMessage());
        }

        // 返回下载的文件路径
        return downloadedPath;
    }

    /**
     * 根据日期范围从SFTP服务器上下载gz文件
     * @param startDate 开始日期
     * @param endDate 结束日期
     * @param folderName 下载到本地的文件夹名称
     * @param cMftCfgId  MFT配置ID
     */
    public static String fetchGzFilesBetweenDates(String startDate, String endDate, String folderName, String cMftCfgId) {
        String downloadedPath = null;
        String depass;
        try {
            Enterprisepension configData = eppService.queryConfigData(cMftCfgId);
            // 连接到SFTP
            JSch jsch = new JSch();
            Session session = jsch.getSession(configData.getUserid(), configData.getIpAddress(), configData.getCPort());
            session.setPassword(configData.getPassword());
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();

            ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
            sftpChannel.connect();

            // 日期格式化
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
            LocalDate start = LocalDate.parse(startDate, formatter);
            LocalDate end = LocalDate.parse(endDate, formatter);

            // 获取SFTP远程目录下的文件列表
            Vector<ChannelSftp.LsEntry> files = sftpChannel.ls(configData.getFilePath());

            for (ChannelSftp.LsEntry file : files) {
                String fileName = file.getFilename();
                // 判断文件名是否符合要求
                if (fileName.contains("_BAS_22658_") && fileName.endsWith(".dat.gz")) {
                    // 正则表达式匹配日期格式
                    Pattern pattern = Pattern.compile("\\d{8}");
                    Matcher matcher = pattern.matcher(fileName);
                    if (matcher.find()) {
                        String dateString = matcher.group();
                        LocalDate fileDate = LocalDate.parse(dateString, formatter);
                        // 判断文件日期是否在指定范围内
                        if (!fileDate.isBefore(start) && !fileDate.isAfter(end)) {
                            // 创建本地目录
                            if(configData.getLocalPath() == null){
                                log.info("MFT文件本地存放路径为空!");
                                return null;
                            }
                            String dirPath = configData.getLocalPath() + "/" + folderName + "/" + dateString;
                            Files.createDirectories(Paths.get(dirPath));
                            String localFilePath = dirPath + "/" + fileName;

                            // 下载文件
                            try (InputStream inputStream = sftpChannel.get(configData.getFilePath() + "/" + fileName);
                                 FileOutputStream outputStream = new FileOutputStream(localFilePath)) {
                                byte[] buffer = new byte[1024];
                                int len;
                                while ((len = inputStream.read(buffer)) != -1) {
                                    outputStream.write(buffer, 0, len);
                                }
                            }
                            Path path = Paths.get(localFilePath);
                            if (!Files.exists(path)) {
                                log.info("文件:" + fileName + "下载失败!");
                            }else{
                                // 解压文件
                                GzipUtil.decompressGzipFile(localFilePath, dirPath);
                                //删除压缩文件
                                Files.delete(Paths.get(localFilePath));
                                if(downloadedPath == null){
                                    downloadedPath = configData.getLocalPath() + "/" + folderName + "/";
                                }
                            }
                        }
                    }
                }
            }

            // 关闭SFTP连接
            sftpChannel.disconnect();
            session.disconnect();

        } catch (JSchException | SftpException | IOException e) {
            log.error(e.getMessage());
        }

        // 返回下载的文件路径
        return downloadedPath;
    }

    /**
     * 根据远程目录从SFTP服务器上下载文件
     * @param remoteDirectory 远程目录
     * @param folderName 下载到本地的文件夹名称
     */
    public static String fetchFilesByRemoteDirectory(String remoteDirectory, String folderName, String cMftCfgId) {
        String downloadedPath = null;
        try {
            Enterprisepension configData = eppService.queryConfigData(cMftCfgId);
            // 连接到SFTP
            JSch jsch = new JSch();
            Session session = jsch.getSession(configData.getUserid(), configData.getIpAddress(), configData.getCPort());
            session.setPassword(configData.getPassword());
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();

            ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
            sftpChannel.connect();

            // 获取SFTP远程目录下的文件列表
            Vector<ChannelSftp.LsEntry> files = sftpChannel.ls(configData.getFilePath());

            for (ChannelSftp.LsEntry file : files) {
                String fileName = file.getFilename();
                // 正则表达式匹配日期格式
                Pattern pattern = Pattern.compile("\\d{8}");
                Matcher matcher = pattern.matcher(fileName);
                if (matcher.find()) {
                    String dateString = matcher.group();
                    // 创建本地目录
                    if(configData.getLocalPath() == null){
                        log.info("MFT文件本地存放路径为空!");
                        return null;
                    }
                    String dirPath = configData.getLocalPath() + "/" + folderName + "/" + dateString;
                    Files.createDirectories(Paths.get(dirPath));
                    String localFilePath = dirPath + "/" + fileName;

                    // 下载文件
                    try (InputStream inputStream = sftpChannel.get(configData.getFilePath() + "/" + fileName);
                         FileOutputStream outputStream = new FileOutputStream(localFilePath)) {
                        byte[] buffer = new byte[1024];
                        int len;
                        while ((len = inputStream.read(buffer)) != -1) {
                            outputStream.write(buffer, 0, len);
                        }
                    }

                    if(downloadedPath == null){
                        downloadedPath = configData.getLocalPath() + "/" + folderName + "/" + dateString;
                    }
                }
            }

            // 关闭SFTP连接
            sftpChannel.disconnect();
            session.disconnect();

        } catch (JSchException | IOException | SftpException e) {
            log.error(e.getMessage());
        }

        // 返回下载的文件路径
        return downloadedPath;
    }

    /**
     * 将文件上传至FTP服务器指定目录
     */
    public static void uploadFile(String fileName,String cMftCfgId){

        Session session = null;
        ChannelSftp sftpChannel;
        try {
            Enterprisepension configData = eppService.queryConfigData(cMftCfgId);
            // 连接到SFTP
            JSch jsch = new JSch();
            session = jsch.getSession(configData.getUserid(), configData.getIpAddress(), configData.getCPort());
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();

            sftpChannel = (ChannelSftp) session.openChannel("sftp");
            sftpChannel.connect();

            sftpChannel.put(SignConfig.getZipPath(), configData.getFilePath());

            System.out.println("File uploaded successfully.");

            // 关闭SFTP连接
            sftpChannel.disconnect();
            session.disconnect();

        } catch (JSchException | SftpException e) {
            log.error(e.getMessage());
        }
    }


    /**
     * 在SFTP上查找指定文件
     * @param configData
     * @param assignFileName
     * @param folderName
     * @return
     */

    public static String fetchFilesByRemoteDirectory(Enterprisepension configData, String assignFileName, String folderName) {
        String downloadedPath = null;
        try {
            // 连接到SFTP
            JSch jsch = new JSch();
            Session session = jsch.getSession(configData.getUserid(), configData.getIpAddress(), configData.getCPort());
            session.setPassword(configData.getPassword());
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();

            ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
            sftpChannel.connect();

            // 获取SFTP远程目录下的文件列表
            Vector<ChannelSftp.LsEntry> files = sftpChannel.ls(configData.getFilePath());
            String fileName = "";
            for (ChannelSftp.LsEntry file : files) {
                fileName = file.getFilename();
                //只要指定的文件
                if(!fileName.equals(assignFileName)){
                    continue;
                }
                // 正则表达式匹配日期格式
                Pattern pattern = Pattern.compile("\\d{8}");
                Matcher matcher = pattern.matcher(fileName);
                if (matcher.find()) {
                    String dateString = matcher.group();
                    // 创建本地目录
                    if(configData.getLocalPath() == null){
                        log.info("MFT文件本地存放路径为空!");
                        return null;
                    }
                    String dirPath = configData.getLocalPath() + "/" + dateString;
                    Files.createDirectories(Paths.get(dirPath));
                    String localFilePath = dirPath + "/" + fileName;

                    // 下载文件
                    try (InputStream inputStream = sftpChannel.get(configData.getFilePath() + "/" + fileName);
                         FileOutputStream outputStream = new FileOutputStream(localFilePath)) {
                        byte[] buffer = new byte[1024];
                        int len;
                        while ((len = inputStream.read(buffer)) != -1) {
                            outputStream.write(buffer, 0, len);
                        }
                    }
                    if(downloadedPath == null){
                        downloadedPath = localFilePath;//SignConfig.getZipPath() + "/" + folderName + "/";
                    }
                }
            }

            // 关闭SFTP连接
            sftpChannel.disconnect();
            session.disconnect();

        } catch (JSchException | SftpException | IOException e) {
            log.error(e.getMessage());
        }
        // 返回下载的文件路径
        return downloadedPath;
    }

    /**
     * 删除指定的文件夹及其下的所有内容。
     * @param folder 要删除的文件夹路径
     */
    public static void deleteFolder(File folder) {
        if (folder.isDirectory()) {
            File[] files = folder.listFiles();
            if (files != null) { // 有些JDK版本中,listFiles()可能会返回null,所以这里做一下检查
                for (File file : files) {
                    deleteFolder(file); // 递归调用
                }
            }
        }
        // 删除当前文件或文件夹
        boolean deleted = folder.delete();
        if (!deleted) {
            System.out.println("Failed to delete folder: " + folder.getAbsolutePath());
        }
    }
    /**
     * 根据文件名在SFTP下载文件
     * @param configData
     * @param assignFileName
     * @return
     */

    public static String filenameDownload(Enterprisepension configData, String assignFileName) {
        String downloadedPath = null;
        try {
            // 连接到SFTP
            JSch jsch = new JSch();
            Session session = jsch.getSession(configData.getUserid(), configData.getIpAddress(), configData.getCPort());
            session.setPassword(configData.getPassword());
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();

            ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
            sftpChannel.connect();

            // 获取SFTP远程目录下的文件列表
            Vector<ChannelSftp.LsEntry> files = sftpChannel.ls(configData.getFilePath());
            String fileName = "";
            for (ChannelSftp.LsEntry file : files) {
                fileName = file.getFilename();
                //只要指定的文件
                if(!fileName.equals(assignFileName)){
                    continue;
                }
                // 正则表达式匹配日期格式
                Pattern pattern = Pattern.compile("\\d{8}");
                Matcher matcher = pattern.matcher(fileName);
                if (matcher.find()) {
                    String dateString = matcher.group();
                    // 创建本地目录
                    if(configData.getLocalPath() == null){
                        log.info("MFT文件本地存放路径为空!");
                        return null;
                    }
                    String dirPath = configData.getLocalPath() +"/"+assignFileName.replaceAll("\\.[^.\\s]+$", "")+ "/" + dateString;
                    Files.createDirectories(Paths.get(dirPath));
                    String localFilePath = dirPath + "/" + fileName;

                    // 下载文件
                    try (InputStream inputStream = sftpChannel.get(configData.getFilePath() + "/" + fileName);
                         FileOutputStream outputStream = new FileOutputStream(localFilePath)) {
                        byte[] buffer = new byte[1024];
                        int len;
                        while ((len = inputStream.read(buffer)) != -1) {
                            outputStream.write(buffer, 0, len);
                        }
                    }
                    //zip解压
                    Path path = Paths.get(localFilePath);
                    if (!Files.exists(path)) {
                        log.info("文件:" + fileName + "下载失败!");
                    }else{
                        // 解压文件
                        ZipUtil.extractZipFile(localFilePath, dirPath);
                        //删除压缩文件
                        Files.delete(Paths.get(localFilePath));
                        if(downloadedPath == null){
                            downloadedPath = dirPath;
                        }
                    }
                }
            }

            // 关闭SFTP连接
            sftpChannel.disconnect();
            session.disconnect();

        } catch (JSchException | SftpException | IOException e) {
            log.error(e.getMessage());
        }
        // 返回下载的文件路径
        return downloadedPath;
    }



}

四、实现类

package com.chinamobile.interfaces.biz.service.impl;

import cn.hutool.core.bean.BeanUtil;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.chinamobile.common.base.bonc.Framework.Data.CommandType;
import com.chinamobile.common.base.bonc.Framework.Data.DBHelp;
import com.chinamobile.common.base.bonc.Framework.Data.IDBHelp;
import com.chinamobile.common.base.bonc.Framework.Data.SqlCompat;
import com.chinamobile.interfaces.api.entity.request.osb.*;
import com.chinamobile.interfaces.api.entity.response.ihrcore.IhrCore200000077Res;
import com.chinamobile.interfaces.api.entity.response.mhrcore.MhrCore200000011Res;
import com.chinamobile.interfaces.api.entity.response.mhrcore.MhrCore200000025Res;
import com.chinamobile.interfaces.api.entity.response.mhrcore.MhrCore200000064Res;
import com.chinamobile.interfaces.api.entity.response.mhrcore.ResultDataVo;
import com.chinamobile.interfaces.api.entity.response.osb.OsbHragHragHq00002Res;
import com.chinamobile.interfaces.biz.config.InterfaceConfig;
import com.chinamobile.interfaces.biz.entity.*;
import com.chinamobile.interfaces.biz.entity.in.read.req.MftHrCoreHq00034Req;
import com.chinamobile.interfaces.biz.exception.CustomException;
import com.chinamobile.interfaces.api.entity.request.osb.OsbBpSoaHq00038;
import com.chinamobile.interfaces.api.entity.request.osb.OsbErpPaHq00006Req;
import com.chinamobile.interfaces.api.entity.request.osb.OsbRbsCmfHq00091Req;
import com.chinamobile.interfaces.api.entity.response.osb.OsbErpPaHq00006Res;
import com.chinamobile.interfaces.api.entity.system.Result;
import com.chinamobile.interfaces.biz.constant.Constants;
import com.chinamobile.interfaces.biz.mapper.CFinPrjTblMapper;
import com.chinamobile.interfaces.biz.service.*;
import com.chinamobile.interfaces.biz.utils.*;
import com.cmcc.ihr.cmm.core.web.domain.AjaxResult;
import com.cmcc.ihr.cmm.user.service.IHrCoreService;
import com.cmcc.ihr.cmm.user.vo.req.ImportItemAdjusInfoReq;
import com.cmcc.ihr.cmm.user.vo.req.QueryBilLetInfoReq;
import com.cmcc.ihr.cmm.user.vo.req.QueryProjectTaskInfoReq;
import com.cmcc.ihr.cmm.user.vo.req.QuerySupplierInfoReq;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.*;
import java.sql.Wrapper;
import java.util.*;
import java.util.stream.Collectors;

/**
 * osb
 */
@Service
@Slf4j
public class OsbServiceImpl implements OsbService {

    @Autowired
    private IHrCoreService iHrCoreService;
    @Autowired
    private CPrjTaskTblService cPrjTaskTblService;
    @Resource(name = "taskExecutor")
    private ThreadPoolTaskExecutor executor;
    @Autowired
    private InterfaceConfig interfaceConfig;

    @Autowired
    private CFinPrjWrkService cFinPrjWrkService;

    @Autowired
    private CFinPrjDtlService cFinPrjDtlService;

    @Autowired
    private CTsDtlService cTsDtlService;

    @Autowired
    private EnterprisepensionService enterprisepensionService;

    @Autowired
    private CFinPrjTblMapper cFinPrjTblMapper;

    @Override
    public Result<String> importTransExpenseInfoRouteSrv(OsbBpSoaHq00038 osbBpSoaHq00038) {
        return Result.ok();
    }

    @Override
    public Result<String> importProjectExpendClaimDocSrv(OsbRbsCmfHq00091Req osbRbsCmfHq00091req) {
        log.info(Thread.currentThread().getName() + ":OSB_RBS_CMF_HQ_00091");
        //绑定参数
        HeaderUtil.bindHeaderMsg(osbRbsCmfHq00091req, interfaceConfig);
        String key = osbRbsCmfHq00091req.getKey(); //报账单号
        String priKey = "IHR" + System.currentTimeMillis();
        String clcaimTypeCode = "";
//        根据报账单号查询报账单
        QueryWrapper<CFinPrjWrk> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("c_rpt_num", key);
        CFinPrjWrk cFinPrjWrk = cFinPrjWrkService.getOne(queryWrapper);
        List<CFinPrjDtl> cFinPrjDtlList = cFinPrjDtlService.getListByCRptNum(key);

        if ("A".equals(cFinPrjWrk.getCFinPrjType())) {
            clcaimTypeCode = "PADT03";
        }
        Integer count = cFinPrjDtlList.size();
        Integer maxCount = 1;
        if (count > maxCount) {
            String jsonString = null;
            try {
                jsonString = getJsonString(cFinPrjWrk, cFinPrjDtlList, priKey, clcaimTypeCode);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
            Result result = uploadProjectExpendClaim(jsonString, cFinPrjWrk);
            return result;
        } else {
            OsbRbsCmfHq00091Req.InputCollection inputCollection = new OsbRbsCmfHq00091Req.InputCollection();
            OsbRbsCmfHq00091Req.Item item = new OsbRbsCmfHq00091Req.Item();
//        赋值报账单信息
            item.setPriKey(priKey);
            item.setOprEmployeeCode(cFinPrjWrk.getAlterEmplid());
            item.setOprUnitCode(cFinPrjWrk.getCOrganizationCod());
            item.setOprCompanyCode(cFinPrjWrk.getCOuCode());

//        判断是否共享财务公司、共享组织编码
            item.setATTRIBUTE14(cFinPrjWrk.getCOuCode1());
            item.setATTRIBUTE15(cFinPrjWrk.getCFinOrgCode1());

            item.setSourceSystemCode(cFinPrjWrk.getCFinOrgCode1());
            item.setSourceDocumentNum(cFinPrjWrk.getCRptNum());

            item.setBusinessMajorClassCode(cFinPrjWrk.getCMajorBusClass());
            item.setAccountDate(DateUtils.getDate());
            item.setSummary(cFinPrjWrk.getDescr200());
            item.setTotalAmount(cFinPrjWrk.getCTotalAmount());
            item.setCurrencyCode("CNY");
            item.setClaimTypeCode(clcaimTypeCode);
            item.setStatusCode("NEW");

            List<OsbRbsCmfHq00091Req.Item> items = new ArrayList<>();
            OsbRbsCmfHq00091Req.RetireLine retireLine = new OsbRbsCmfHq00091Req.RetireLine();
//        循环赋值项目分摊明细数据
            int j = 0;
            List<OsbRbsCmfHq00091Req.RetireLineItem> retireLineItems = new ArrayList<>();
            for (CFinPrjDtl cFinPrjDtl : cFinPrjDtlList) {

                OsbRbsCmfHq00091Req.RetireLineItem retireLineItem = new OsbRbsCmfHq00091Req.RetireLineItem();
                retireLineItem.setPriKey(priKey);
                j++;
                retireLineItem.setSourceDocLineNum(j + "");
                retireLineItem.setCostCenterCode(cFinPrjDtl.getCCostCenter());
                retireLineItem.setBusinessMajorClassCode(cFinPrjWrk.getCMajorBusClass());
                retireLineItem.setBusinessMinorClassCode(cFinPrjDtl.getCMinBusClass());
                retireLineItem.setBusinessActivityCode(cFinPrjDtl.getCBusActivity());
                retireLineItem.setProjectNum(cFinPrjDtl.getCAccountingNo());

                retireLineItem.setCrBusinessMajorClassCode(cFinPrjDtl.getCrBuMajorClsCd());
                retireLineItem.setCrBusinessMinorClassCode(cFinPrjDtl.getCrBuMinorClsCd());
                retireLineItem.setCrBusinessActivityCode(cFinPrjDtl.getCrBuActivityCd());
                retireLineItem.setDescription(cFinPrjDtl.getDescr200());

                String cTaskNumber = "";
                switch (cFinPrjDtl.getCompany()) {
                    case "4500":
                        cTaskNumber = "451010.01";
                        break;
                    case "7810":
                        cTaskNumber = "781010.01";
                        break;
                    case "7801":
                        cTaskNumber = "782110.01";
                        break;
                    default:
                        cTaskNumber = cFinPrjDtl.getCTaskNumber();
                        break;
                }
                if (StringUtils.isNotBlank(cTaskNumber)) {
                    retireLineItem.setTaskNumber(cTaskNumber);
                }
                retireLineItem.setAmount(cFinPrjDtl.getCAmt001());
                if (StringUtils.isNotBlank(cFinPrjDtl.getCMarketCode()) || StringUtils.isNotBlank(cFinPrjDtl.getCProdunctCode())) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("marketSegment", cFinPrjDtl.getCMarketCode());
                    jsonObject.put("productSegment", cFinPrjDtl.getCProdunctCode());
                    retireLineItem.setInputExt(jsonObject.toString());
                }
                retireLineItems.add(retireLineItem);
            }
            retireLine.setRetireLineItem(retireLineItems);
            item.setRetireLine(retireLine);
            items.add(item);
            inputCollection.setInputcollectionItem(items);
            osbRbsCmfHq00091req.setInputCollection(inputCollection);

            ImportItemAdjusInfoReq importItemAdjusInfoReq = null;
            importItemAdjusInfoReq = JacksonUtil.getJsonToBean(JacksonUtil.getBeanToJson(osbRbsCmfHq00091req), ImportItemAdjusInfoReq.class);
//        推送返回结果
            AjaxResult<JSONObject> ajaxResult = iHrCoreService.ImportItemAdjusInfoReq(null, importItemAdjusInfoReq);

            // 解析返回数据
            if (ajaxResult != null) {
                Result result = retResult(ajaxResult, cFinPrjDtlList);// 彻底剥离逻辑,使方法可以公用。有需要可以提取公用。
                if (result.isOk()) {// 操作成功后,直接更新
//                LambdaUpdateWrapper<CFundPlanTbl> tblLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
//                tblLambdaUpdateWrapper.inSql(CFundPlanTbl::getCOuCode,cfpt_sql).set(CFundPlanTbl::getCSendStatus,"S");
//                this.cFundPlanTblMapper.update(tblLambdaUpdateWrapper);
                }
                return result;
            }
        }


/*//        根据结果回显
        if (!StringUtils.equals(Constants.SUCCESS_CODE, ajaxResult.getCode())) {
            log.error("OSB_RBS_CMF_HQ_00091_导入项目类支出调整报账单信息服务: 调用第三方接口异常,错误信息 >>" + ajaxResult.getMsg());
            return Result.failed("OSB_RBS_CMF_HQ_00091_导入项目类支出调整报账单信息服务: 调用第三方接口异常,错误信息 >>" + ajaxResult.getMsg());
        }*/
        return Result.ok();
    }

    /**
     * getJsonString 的方法,此处与API推送的报文内容基本一致
     *
     * @param cFinPrjWrk
     * @param cFinPrjDtlList
     * @param priKey
     * @param clcaimTypeCode
     * @return
     * @throws JsonProcessingException
     */
    public String getJsonString(CFinPrjWrk cFinPrjWrk, List<CFinPrjDtl> cFinPrjDtlList, String priKey, String clcaimTypeCode) throws JsonProcessingException {

//            超过9999条,生成json文件,并推送文件到服务器
        OsbRbsCmfHq00091Req2 osbRbsCmfHq00091Req2 = new OsbRbsCmfHq00091Req2();
        //        赋值报账单信息
        osbRbsCmfHq00091Req2.setPriKey(priKey);
        osbRbsCmfHq00091Req2.setOprEmployeeCode(cFinPrjWrk.getAlterEmplid());
        osbRbsCmfHq00091Req2.setOprUnitCode(cFinPrjWrk.getCOrganizationCod());
        osbRbsCmfHq00091Req2.setOprCompanyCode(cFinPrjWrk.getCOuCode());

//        判断是否共享财务公司、共享组织编码
        osbRbsCmfHq00091Req2.setAttribute14(cFinPrjWrk.getCOuCode1());
        osbRbsCmfHq00091Req2.setAttribute15(cFinPrjWrk.getCFinOrgCode1());

        osbRbsCmfHq00091Req2.setSourceSystemCode(cFinPrjWrk.getCFinOrgCode1());
        osbRbsCmfHq00091Req2.setSourceDocumentNum(cFinPrjWrk.getCRptNum());

        osbRbsCmfHq00091Req2.setBusinessMajorClassCode(cFinPrjWrk.getCMajorBusClass());
        osbRbsCmfHq00091Req2.setAccountDate(DateUtils.getDate());
        osbRbsCmfHq00091Req2.setSummary(cFinPrjWrk.getDescr200());
        osbRbsCmfHq00091Req2.setTotalAmount(cFinPrjWrk.getCTotalAmount());
        osbRbsCmfHq00091Req2.setCurrencyCode("CNY");
        osbRbsCmfHq00091Req2.setClaimTypeCode(clcaimTypeCode);
        osbRbsCmfHq00091Req2.setStatusCode("NEW");
        int j = 0;
        List<OsbRbsCmfHq00091Req2.RetireLineItem> retireLineItems = new ArrayList<>();
        for (CFinPrjDtl cFinPrjDtl : cFinPrjDtlList) {
            OsbRbsCmfHq00091Req2.RetireLineItem retireLineItem = new OsbRbsCmfHq00091Req2.RetireLineItem();
            retireLineItem.setPriKey(priKey);
            j++;
            retireLineItem.setSourceDocLineNum(j + "");
            retireLineItem.setCostCenterCode(cFinPrjDtl.getCCostCenter());
            retireLineItem.setBusinessMajorClassCode(cFinPrjWrk.getCMajorBusClass());
            retireLineItem.setBusinessMinorClassCode(cFinPrjDtl.getCMinBusClass());
            retireLineItem.setBusinessActivityCode(cFinPrjDtl.getCBusActivity());
            retireLineItem.setProjectNum(cFinPrjDtl.getCAccountingNo());

            retireLineItem.setCrBusinessMajorClassCode(cFinPrjDtl.getCrBuMajorClsCd());
            retireLineItem.setCrBusinessMinorClassCode(cFinPrjDtl.getCrBuMinorClsCd());
            retireLineItem.setCrBusinessActivityCode(cFinPrjDtl.getCrBuActivityCd());
            retireLineItem.setDescription(cFinPrjDtl.getDescr200());

            String cTaskNumber = "";
            switch (cFinPrjDtl.getCompany()) {
                case "4500":
                    cTaskNumber = "451010.01";
                    break;
                case "7810":
                    cTaskNumber = "781010.01";
                    break;
                case "7801":
                    cTaskNumber = "782110.01";
                    break;
                default:
                    cTaskNumber = cFinPrjDtl.getCTaskNumber();
                    break;
            }
            if (StringUtils.isNotBlank(cTaskNumber)) {
                retireLineItem.setTaskNumber(cTaskNumber);
            }
            retireLineItem.setAmount(cFinPrjDtl.getCAmt001());
            if (StringUtils.isNotBlank(cFinPrjDtl.getCMarketCode()) || StringUtils.isNotBlank(cFinPrjDtl.getCProdunctCode())) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("marketSegment", cFinPrjDtl.getCMarketCode());
                jsonObject.put("productSegment", cFinPrjDtl.getCProdunctCode());
                retireLineItem.setInputExt(jsonObject.toString());
            }
            retireLineItems.add(retireLineItem);
        }
        osbRbsCmfHq00091Req2.setRetireLine(retireLineItems);
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(osbRbsCmfHq00091Req2);

    }

    /**
     * 生成json文件并推送到服务器
     *
     * @return
     */
    public Result uploadProjectExpendClaim(String jsonString, CFinPrjWrk cFinPrjWrk) {
        //获取配置表目录地址
        Enterprisepension configData = enterprisepensionService.queryConfigData("UPLOAD_FIN01");
        String localPath = configData.getLocalPath();
        if (localPath == null) {
            return Result.failed("MFT文件本地存放路径为空!");
        }
        String remotePath = configData.getFilePath();
        String uuid = IdWorker.getIdStr();
        String filename = "HQ_MftProjectExpendClaimDocSrv" + uuid + "_" + DateUtils.dateTime() + ".json";
        String zipFileName = "HQ_MftProjectExpendClaimDocSrv" + uuid + ".zip";
        String filePath = localPath + "/" + filename;
        String zipFilePath = localPath + "/" + zipFileName;
        File directory = new File(localPath);
        File file = new File(filePath);
        // 创建目录和文件
        if (!directory.exists()) {
            directory.mkdirs();
        }
        // 写入数据
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
            writer.write(jsonString);
        } catch (IOException e) {
            log.error("项目报账数据传送,推送文件失败", e);
        }
        //压缩文件
        try {
            ZipUtil.compressFile(filePath, localPath, zipFilePath);
            //上传文件
            SftpUtil.sftpUploadFile(configData.getIpAddress(), configData.getCPort(), configData.getUserid(), configData.getPassword(), remotePath, zipFilePath, remotePath + "/" + zipFileName);
        } catch (IOException e) {
            log.error("项目报账数据传送,推送文件失败", e);
            return Result.failed(null, "项目报账数据传送,推送文件失败。");
        }
//        更改传送状态
//        select * from C_FIN_PRJ_TBL where C_RPT_NUM = '11'
        CFinPrjTbl cFinPrjTbl = cFinPrjTblMapper.selectByCRptNum(cFinPrjWrk.getCRptNum());
        if (null != cFinPrjTbl) {
            cFinPrjTbl.setCFinPrjSta("I");
            cFinPrjTbl.setCRetFilename(zipFileName);
            cFinPrjTbl.setCRetJsonfile(filename);
            cFinPrjTblMapper.updateById(cFinPrjTbl);
        } else {
            CFinPrjTbl cFinPrjTbl2 = new CFinPrjTbl();
            BeanUtil.copyProperties(cFinPrjWrk, cFinPrjTbl2);
            cFinPrjTbl2.setCFinPrjSta("I");
            cFinPrjTbl2.setCRetFilename(zipFileName);
            cFinPrjTbl2.setCRetJsonfile(filename);
            Object objRunId = SqlCompat.GetSeqValue("seq_C_FIN_PRJ_TBL");
            cFinPrjTbl2.setId(objRunId.toString());
            cFinPrjTblMapper.insert(cFinPrjTbl2);
        }
        //                    把selected为1的对象 C_SEND_STATUS 字段赋值为 "S"
        cFinPrjDtlService.updateCSendStatus(cFinPrjWrk.getCRptNum());
        //        条件传送成功
        IDBHelp db = DBHelp.getInstanct();
        String updateWrk = "update C_FIN_PRJ_WRK set C_FIN_PRJ_STA = '3' where C_RPT_NUM = '" + cFinPrjWrk.getCRptNum() + "' ";
        db.ExecuteNonQuery(updateWrk, null, CommandType.Text);
        return Result.ok(null, "后台正在推送报账文件,请稍后查看结果!");

    }

    /**
     * 解析返回结果
     *
     * @param ajaxResult
     * @return
     */
    private Result retResult(AjaxResult<JSONObject> ajaxResult, List<CFinPrjDtl> cFinPrjDtlList) {
        ResultDataVo resultDataVo = new ResultDataVo();
        if (ajaxResult.getCode().equals("500")) {
            return Result.failed("未配置授权");
        }
        boolean result;
        //TODO 记录日志
        String errormsg = "";
        BeanUtil.copyProperties(ajaxResult.getData(), resultDataVo);
        ResultDataVo.Result resultVo = resultDataVo.getResult();
        if ("TRUE".equals(resultVo.getESB_FLAG())) {
            String statusCode = resultVo.getBIZ_SERVICE_FLAG();
            if ("TRUE".equals(statusCode)) {
                ResultDataVo.RESPONSECOLLECTION objResponseCollection = resultVo.getRESPONSECOLLECTION();
                List<ResultDataVo.RESPONSECOLLECTION_ITEM> aryResponseCollectionItem = objResponseCollection.getRESPONSECOLLECTION_ITEM();
                String resPriKey = aryResponseCollectionItem.get(0).getPRI_KEY();
                result = true;
                for (CFinPrjDtl cFinPrjDtl : cFinPrjDtlList) {
                    cTsDtlService.updateStatus(cFinPrjDtl);
                }
//                    把selected为1的对象 C_SEND_STATUS 字段赋值为 "S"
                cFinPrjDtlService.updateCSendStatus(cFinPrjDtlList.get(0).getCRptNum());
            } else {
                ResultDataVo.ERRORCOLLECTION objErrorCollection = resultVo.getERRORCOLLECTION();
                String errorMessage = "";
                if (null == objErrorCollection) {
                    errorMessage = resultVo.getBIZ_RETURN_MESSAGE();
                } else {
                    List<ResultDataVo.ERRORCOLLECTION_ITEM> aryErrorCollectionItem = objErrorCollection.getERRORCOLLECTION_ITEM();
                    for (ResultDataVo.ERRORCOLLECTION_ITEM errorcollectionItem : aryErrorCollectionItem) {
                        errorMessage = errorMessage + errorcollectionItem.getERROR_MESSAGE();
                    }
                }
                errormsg = "报账单传送失败,原因" + errorMessage + ",实例编号为:" + resultVo.getINSTANCE_ID() + "。";
                result = false;
                return Result.failed(errormsg);
            }
        } else {
            return Result.failed(errormsg);
        }
        return Result.ok(null, "报账单传送成功,实例编号为" + resultVo.getINSTANCE_ID() + ",请知悉。");
    }


    /**
     * OSB_RBS_CMF_HQ_00091(M_HR_CORE_200000039、OSB_RBS_CMF_HQ_000XX)-获取报账结果 downloadAndParse  getProjectExpendClaimDocSrv
     */
    @Override
    public Result<String> getProjectExpendClaimDocSrv(Map<String, String> jo) {
        String cRptNum = jo.get("rptNum");
        CFinPrjTbl cFinPrjTbl = cFinPrjTblMapper.selectByCRptNum(cRptNum);
        if (null != cFinPrjTbl && ("I".equals(cFinPrjTbl.getCFinPrjSta()) || "F".equals(cFinPrjTbl.getCFinPrjSta()))) {
            String zipFileName = cFinPrjTbl.getCRetFilename();
            String jsonFileName = cFinPrjTbl.getCRetJsonfile();
            return downloadAndParse(zipFileName, jsonFileName, cRptNum);
        }
        return Result.failed();
    }


    private Result<String> downloadAndParse(String zipFileName, String jsonFileName, String cRptNum) {

        Enterprisepension configData = enterprisepensionService.queryConfigData("UPLOAD_FIN02");
        String localPath = configData.getLocalPath();
        if (localPath == null) {
            return Result.failed("MFT文件本地存放路径为空!");
        }
        File directory = new File(localPath);
        // 创建目录和文件
        if (!directory.exists()) {
            directory.mkdirs();
        }
        String remoteFileName = "MftXfeClaimFileResultSrv_" + zipFileName;
        String unZipFileName = zipFileName.replace(".zip", ".json");
        String path = SftpUtils.filenameDownload(configData, zipFileName);
        if (path == null) {
            log.error("下载或解压缩文件失败");
            return Result.failed("下载或解压缩文件失败");
        }
        Boolean isSuccess = false;
        //判断文件是否存在
        isSuccess = FileUtil.checkFile(path, unZipFileName);
        if (isSuccess) {
            String filePath = path + File.separator + unZipFileName;
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "GB2312"))) {
                StringBuilder contentBuilder = new StringBuilder();
                String currentLine;
                while ((currentLine = reader.readLine()) != null) {
                    contentBuilder.append(currentLine).append("\n"); // 追加换行符以保持原始文件的格式
                }
                String content = contentBuilder.toString();
                ObjectMapper mapper = new ObjectMapper();
                OsbRbsCmfHq00091Req3 req3 = mapper.readValue(content, OsbRbsCmfHq00091Req3.class);
                String prcsCode = req3.getProcessCode();
                String errorMsg = req3.getErrorMessage();
                List<OsbRbsCmfHq00091Req3.Claim> claimInfo = req3.getClaimInfo();
                if (!CollectionUtils.isEmpty(claimInfo)) {
                    for (OsbRbsCmfHq00091Req3.Claim claim : claimInfo) {
                        String finRptNum = claim.getSourceDocumentNum();
                        String processCode = claim.getProcessCode();
                        String errorMessage = claim.getErrorMessage();
                        CFinPrjTbl cFinPrjTbl = cFinPrjTblMapper.selectByCRptNum(finRptNum);
                        if (null != cFinPrjTbl) {
                            if ("ERROR".equals(processCode)) {
                                cFinPrjTbl.setCFinPrjSta("F");
                                cFinPrjTbl.setErrormsg(errorMessage);
                            } else {
                                cFinPrjTbl.setCFinPrjSta("S");
                                cFinPrjDtlService.updateCSendStatus(finRptNum);
                            }
                            cFinPrjTblMapper.updateById(cFinPrjTbl);
                        }
                        List<OsbRbsCmfHq00091Req3.ClaimLine> claimLineInfo = claim.getClaimLineInfo();
                        for (OsbRbsCmfHq00091Req3.ClaimLine claimLine : claimLineInfo) {
                            String lineNum = claimLine.getSourceDocLineNum();
                            String lineProcessCode = claimLine.getSourceDocLineNum();
                            if ("ERROR".equals(lineProcessCode)) {
                                String LineMessage = claimLine.getErrorMessage();
                                if (StringUtils.isNotBlank(LineMessage)) {
                                    cFinPrjDtlService.updateCSendStatusAndErrormsg(LineMessage, finRptNum, lineNum);
                                }
                            }
                        }
                    }
                } else {
                    String retZipFile = req3.getFileName();
                    if ("E".equals(prcsCode)) {
                        cFinPrjTblMapper.updateStaAndErrormsg(errorMsg, retZipFile);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            //清空本地文件
            FileUtil.cleanFile(configData.getLocalPath() + File.separator + zipFileName.replaceAll("\\.[^.\\s]+$", ""));
        } else {
            log.error(zipFileName + "文件不存在");
            return Result.failed("文件不存在");
        }
//        条件传送成功
        IDBHelp db = DBHelp.getInstanct();
        String updateWrk = "update C_FIN_PRJ_WRK set C_FIN_PRJ_STA = '3' where C_RPT_NUM = '" + cRptNum + "' ";
        db.ExecuteNonQuery(updateWrk, null, CommandType.Text);
        return Result.ok();

    }

    @Override
    public OsbHragHragHq00002Res importProjExpendClaimDocStaSrv(OsbHragHragHq00002Req req) {

        OsbHragHragHq00002Res osbHragHragHq00002Res = new OsbHragHragHq00002Res();
        osbHragHragHq00002Res.setStatus("S");
        OsbHragHragHq00002Res.ResponseNode responseNode = new OsbHragHragHq00002Res.ResponseNode();
        responseNode.setBizServiceFlag("TRUE");
        responseNode.setBizReturnMessage("数据更新完成");
        OsbHragHragHq00002Res.Errorcollection errorcollection = new OsbHragHragHq00002Res.Errorcollection();
        List<OsbHragHragHq00002Res.ErrorItem> errorItems = new ArrayList<>();
        OsbHragHragHq00002Res.Responsecollection responsecollection = new OsbHragHragHq00002Res.Responsecollection();
        List<OsbHragHragHq00002Res.ResponseItem> responseItems = new ArrayList<>();
        String inputString = req.getRequestNode().getInputCollection();
        OsbHragHragHq00002Req.InputCollection inputCollection = JSONUtil.toBean(inputString, OsbHragHragHq00002Req.InputCollection.class);
        List<OsbHragHragHq00002Req.Item> items = inputCollection.getInputcollectionItem();
        for (OsbHragHragHq00002Req.Item item : items) {
            List<CFinPrjWrk> cFinPrjWrkList = cFinPrjWrkService.lambdaQuery().eq(CFinPrjWrk::getCRptNum, item.getClaimNum()).eq(CFinPrjWrk::getCFinPrjSta, 1).list();
            if (CollectionUtils.isEmpty(cFinPrjWrkList)) {
                OsbHragHragHq00002Res.ErrorItem errorItem = new OsbHragHragHq00002Res.ErrorItem();
                errorItem.setErrorMessage("没有找到相应数据!");
                errorItem.setPriKey(item.getPriKey());
                errorItems.add(errorItem);
            } else {
                cFinPrjWrkService.lambdaUpdate().eq(CFinPrjWrk::getCRptNum, item.getClaimNum()).eq(CFinPrjWrk::getCFinPrjSta, 1).set(CFinPrjWrk::getCFinPrjSta, 2).update();
                OsbHragHragHq00002Res.ResponseItem responseItem = new OsbHragHragHq00002Res.ResponseItem();
                responseItem.setClaimNum(item.getClaimNum());
                responseItem.setPriKey(item.getPriKey());
                responseItem.setUpdateSta("S");
                responseItems.add(responseItem);
            }
        }
        responsecollection.setDatas(responseItems);
        errorcollection.setDatas(errorItems);
        responseNode.setErrorcollection(errorcollection);
        responseNode.setResponsecollection(responsecollection);
        osbHragHragHq00002Res.setResponseNode(responseNode);
        return osbHragHragHq00002Res;
    }

    @Async("taskExecutor")
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void queryProjectTaskInfo(OsbErpPaHq00006Req req) {
        String uuid = java.util.UUID.randomUUID().toString();
        log.info("OSB_ERP_PA_HQ_00006_查询项目任务信息接口服务开始执行, 标识码: " + uuid);
        //绑定参数
        HeaderUtil.bindHeaderMsg(req, interfaceConfig);
        //转成集成平台所需实体
        QueryProjectTaskInfoReq taskInfoReq = new QueryProjectTaskInfoReq();
        QueryProjectTaskInfoReq.InputParameters inputParameters = JacksonUtil.getJsonToBean(JacksonUtil.getBeanToJson(req), QueryProjectTaskInfoReq.InputParameters.class);
        if (inputParameters == null) {
            inputParameters = new QueryProjectTaskInfoReq.InputParameters();
        }
        inputParameters.setMSGHEADER(JacksonUtil.getJsonToBean(JacksonUtil.getBeanToJson(req.getMsgHeader()), QueryProjectTaskInfoReq.MsgHeader.class));
        taskInfoReq.setInputParameters(inputParameters);

        List<CPrjTaskTbl> tblList = new ArrayList<>();
        AjaxResult<JSONObject> ajaxResult = iHrCoreService.queryProjectTaskInfo(null, taskInfoReq);
        //判断返回状态
        if (!StringUtils.equals(Constants.SUCCESS_CODE, ajaxResult.getCode())) {
            log.error("OSB_ERP_PA_HQ_00006_查询项目任务信息服务: 调用第三方接口异常,错误信息>> " + ajaxResult.getMsg());
            return;
        }

        //判断有无数据
        JSONObject datas = ajaxResult.getData();
        if (datas.getJSONObject(Constants.OUT_PUT_COLLECTION) == null || CollectionUtils.isEmpty(datas.getJSONObject(Constants.OUT_PUT_COLLECTION).getJSONArray(Constants.DATA_ITEMS))) {
            log.info("OSB_ERP_PA_HQ_00006_查询项目任务信息接口服务执行完成, 标识码: " + uuid);
            return;
        }

        try {
            for (Object data : datas.getJSONObject(Constants.OUT_PUT_COLLECTION).getJSONArray(Constants.DATA_ITEMS)) {
                OsbErpPaHq00006Res bean = JacksonUtil.getJsonToBean(JacksonUtil.getBeanToJson(data), OsbErpPaHq00006Res.class);
                CPrjTaskTbl cPrjTaskTbl = BeanUtil.toBean(bean, CPrjTaskTbl.class);
                tblList.add(cPrjTaskTbl);
            }
        } catch (CustomException e) {
            log.error("OSB_ERP_PA_HQ_00006_查询项目任务信息服务: 实体转换异常,错误信息>>" + e.getMessage());
            return;
        }

        //写入数据
        cPrjTaskTblService.saveOrUpdateBatch(tblList, 300);
        log.info("OSB_ERP_PA_HQ_00006_查询项目任务信息接口服务执行完成, 标识码: " + uuid);
    }

    @Async("taskExecutor")
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void queryBilLetInfoReq(OsbErpPaHq00032Req req) {
        String uuid = UUID.randomUUID().toString();
        log.info("进入syncVendorTbl查询供应商信息服务, 标识码: " + uuid);
        //绑定参数
        HeaderUtil.bindHeaderMsg(req, interfaceConfig);
        //转成集成平台所需实体
        QueryBilLetInfoReq queryBilLetInfoReq = JacksonUtil.getJsonToBean(JacksonUtil.getBeanToJson(req), QueryBilLetInfoReq.class);
        if (queryBilLetInfoReq == null) {
            queryBilLetInfoReq = new QueryBilLetInfoReq();
        }
        queryBilLetInfoReq.setMSGHEADER(JacksonUtil.getJsonToBean(JacksonUtil.getBeanToJson(req.getMsgHeader()), QueryBilLetInfoReq.MsgHeader.class));

        List<CPrjTaskTbl> resList = new ArrayList<>();
        while (true) {
            log.info("syncVendorTbl,循环" + queryBilLetInfoReq.getMSGHEADER().getCURRENT_PAGE() + "请求报文:" + JSONUtil.toJsonStr(queryBilLetInfoReq));
            AjaxResult<JSONObject> ajaxResult = iHrCoreService.QueryBilLetInfoReq(null, queryBilLetInfoReq);
            log.info("syncVendorTbl,循环" + queryBilLetInfoReq.getMSGHEADER().getCURRENT_PAGE() + "返回报文:" + JSONUtil.toJsonStr(ajaxResult));
            //判断返回状态
            if (!Constants.SUCCESS_CODE.equals(ajaxResult.getCode())) {
                log.error("M_HR_CORE_200000025_查询供应商信息服务: 调用第三方接口异常,错误信息>> " + ajaxResult.getMsg());
                return;
            }

            //判断有无数据
            JSONObject datas = ajaxResult.getData();
            if (datas.getJSONObject("OUTPUTCOLLECTION") == null || CollectionUtils.isEmpty(datas.getJSONObject("OUTPUTCOLLECTION").getJSONArray("OUTPUTCOLLECTION_ITEM"))) {
                return;

            }
            try {
                for (Object data : datas.getJSONObject(Constants.OUT_PUT_COLLECTION).getJSONArray(Constants.DATA_ITEMS)) {
                    MhrCore200000025Res bean = JacksonUtil.getJsonToBean(JacksonUtil.getBeanToJson(data), MhrCore200000025Res.class);
                    CPrjTaskTbl cPrjTaskTbl = BeanUtil.toBean(bean, CPrjTaskTbl.class);
                    resList.add(cPrjTaskTbl);
                }
            } catch (CustomException e) {
                log.error("OSB_ERP_PA_HQ_00032_查询项目任务信息服务: 实体转换异常,错误信息>>" + e.getMessage());
                return;
            }
            log.info("OSB_ERP_PA_HQ_00032_查询项目任务信息接口服务执行完成, 标识码: " + uuid);
        }
    }

}

五、AES加密 EnhanceAesEncrypt工具类

package com.chinamobile.interfaces.biz.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;  
import javax.crypto.spec.SecretKeySpec;  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileOutputStream;  
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;  
import java.security.SecureRandom;  
import java.util.Base64;  

public class EnhanceAesEncrypt {
	
    private static final Logger log = LoggerFactory.getLogger(EnhanceAesEncrypt.class);
    private static final String ALGORITHM = "AES";
    private static final String TRANSFORMATION_CBC = "AES/CBC/PKCS5Padding";
    private static final String TRANSFORMATION_ECB = "AES/ECB/PKCS5Padding";
    
    public synchronized static void encrypt(String key, String inputFile, String outputFile) {  
        try {  
        	KeyGenerator kgen = KeyGenerator.getInstance("AES");
            byte[] seed = key.getBytes();
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(seed);
            log.info("secureRandom:{}",secureRandom.getAlgorithm());
            kgen.init(128, secureRandom);
            SecretKey secretKey = kgen.generateKey();
            Cipher cipher = Cipher.getInstance(TRANSFORMATION_ECB);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
      
            // 检查并创建目录  
            File outputfile = new File(outputFile);  
            boolean dirsCreated = outputfile.getParentFile().mkdirs() || outputfile.getParentFile().exists();  
            if (dirsCreated) {  
                boolean fileCreated = outputfile.createNewFile();  
                if (fileCreated) {  
                    System.out.println("Create file: " + outputfile.getAbsolutePath() + " successful!");  
                } else {  
                    System.err.println("Failed to create file: " + outputfile.getAbsolutePath());  
                    return;  
                }  
            } else {  
                System.err.println("Unable to create directory structure to save file: " + outputfile.getParent());  
                return;  
            }  
      
            try (FileInputStream inputStream = new FileInputStream(inputFile);  
                 FileOutputStream outputStream = new FileOutputStream(outputFile)) {  
                byte[] buffer = new byte[1024];  
                int bytesRead;  
      
                while ((bytesRead = inputStream.read(buffer)) != -1) {  
                    byte[] output = cipher.update(buffer, 0, bytesRead);  
                    if (output != null) {  
                        outputStream.write(output);  
                    }  
                }  
                byte[] outputBytes = cipher.doFinal();  
                if (outputBytes != null) {  
                    outputStream.write(outputBytes);  
                }  
            } catch (BadPaddingException e) {
				e.printStackTrace();
			}  
      
            // 删除原文件  
            File orifile = new File(inputFile);  
            if (orifile.isFile()) {  
                if (orifile.delete()) {  
                    System.out.println("removeTempFile: " + orifile.getAbsolutePath() + " successful!");  
                } else {  
                    System.err.println("Failed to delete temporary file: " + orifile.getAbsolutePath());  
                }  
            }  
        } catch (NoSuchAlgorithmException e) {  
            throw new RuntimeException(e);  
        } catch (NoSuchPaddingException e) {  
            throw new RuntimeException(e);  
        } catch (InvalidKeyException e) {  
            throw new RuntimeException(e);  
        } catch (IllegalBlockSizeException e) {  
            throw new RuntimeException(e);  
        } catch (IOException e) {  
            throw new RuntimeException(e);  
        } catch (IllegalArgumentException e) {  
            // 如果密钥长度不正确或Base64解码失败  
            throw new RuntimeException("Invalid key provided: " + e.getMessage());  
        }  
    }

}

六、实现类

package com.chinamobile.interfaces.biz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.chinamobile.common.base.LsHrBusiness.LsPublic.TSysUser;
import com.chinamobile.common.base.bonc.Model.Server.UserInfo;
import com.chinamobile.interfaces.api.entity.request.mftCore.*;
import com.chinamobile.interfaces.api.entity.system.Result;
import com.chinamobile.interfaces.biz.config.FileConfig;
import com.chinamobile.interfaces.biz.config.InterfaceConfig;
import com.chinamobile.interfaces.biz.constant.Constants;
import com.chinamobile.interfaces.biz.entity.*;
import com.chinamobile.interfaces.biz.entity.in.read.req.MftHrCoreHq00033Req;
import com.chinamobile.interfaces.biz.entity.in.read.req.MftHrCoreHq00034Req;
import com.chinamobile.interfaces.biz.entity.in.read.req.MftRmsRmsHq00002Req;
import com.chinamobile.interfaces.biz.entity.in.write.res.*;
import com.chinamobile.interfaces.biz.entity.vo.CMfttogrReadyVo;
import com.chinamobile.interfaces.biz.entity.vo.JobVo;
import com.chinamobile.interfaces.biz.exception.CustomException;
import com.chinamobile.interfaces.biz.mapper.CFinRptEmpMapper;
import com.chinamobile.interfaces.biz.mapper.CMfttogrReadyMapper;
import com.chinamobile.interfaces.biz.service.*;
import com.chinamobile.interfaces.biz.utils.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jcraft.jsch.SftpException;
import lombok.extern.slf4j.Slf4j;
import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;


/**
 * @author LWY
 */
@Service
@Slf4j
public class MftCoreServiceImpl implements MftCoreService {

    @Autowired
    private CHighSyncTaskService cHighSyncTaskService;
    @Autowired
    private CHighSyncFileService cHighSyncFileService;
    @Autowired
    private CHighSubjectService cHighSubjectService;
    @Autowired
    private CHighMapDtlService cHighMapDtlService;
    @Autowired
    private CHighSalaryService cHighSalaryService;
    @Autowired
    private CHighMapUnitService cHighMapUnitService;
    @Autowired
    private A01Service a01Service;
    @Autowired
    private C21Service c21Service;
    @Autowired
    private JobService jobService;
    @Autowired
    private CEmpsalitemsService cEmpsalitemsService;
    @Autowired
    private CPerAssetTblService cPerAssetTblService;
    @Autowired
    private EnterprisepensionService enterprisepensionService;

    @Autowired
    @Qualifier("taskExecutor")
    private ThreadPoolTaskExecutor executor;


    @Autowired
    private CNsRntService cNsRntService;
    @Autowired
    private CNsFileLogService cNsFileLogService;
    @Autowired
    private CNsFileDtlService cNsFileDtlService;
    @Autowired
    private CNsDataLogService cNsDataLogService;
    @Autowired
    private CNsDtlService cNsDtlService;
    @Autowired
    private OrgGridInfoService orgGridInfoService;
    private static final Map<String, String> fixedMap = new ConcurrentHashMap<>();
    @Autowired
    private OrgGridInfoResultService orgGridInfoResultService;
    @Autowired
    private FfProvinceTblService ffProvinceTblService;
    @Autowired
    private CNrdDtlService cNrdDtlService;
    @Autowired
    private B01FrgsService b01FrgsService;

    @Autowired
    private A827Service a827Service;
    @Autowired
    private A843Service a843Service;
    @Autowired
    private A844Service a844Service;
    @Autowired
    private A842Service a842Service;
    @Autowired
    private WsTaskLogService wsTaskLogService;
    @Autowired
    private CFinRptTblService cFinRptTblService;
    @Autowired
    private CFinRptEmpMapper cFinRptEmpMapper;

    @Autowired
    private InterfaceConfig interfaceConfig;
    //发送消息的业务类
    @Autowired
    private MHrCoreService mHrCoreService;
    @Autowired
    private CMfttogrReadyMapper cMfttogrReadyMapper;

    @Value("${file.localPath}")
    private String ROOT;

    // 非研发工时-文件本地路径
    private static final String C_NS_LOCAL_BASE_PATH = FileConfig.getDownloadPath() + "/";

    // 高管薪酬映射文件的文件名
    private static final String DETAIL_File_Name = "MFT_HLP_SALARY_DETAIL_INFO_";

    // 高管薪酬数据文件的文件名
    private static final String MAPPING_File_Name = "MFT_HLP_SALARY_ITEM_MAPPING_";

    static {
        //高管薪酬同步固定项
        fixedMap.put("员工编号", "A0190");
        fixedMap.put("是否主要发薪", "PRIMARY_FLAG");
        fixedMap.put("所属公司编码", "COMPANY_CODE");
        //fixedMap.put("所属公司名称", "COMPANY_NAME");
        fixedMap.put("发薪用途", "RUN_TYPE");
        fixedMap.put("期间", "PERIOD");
    }

    /**
     * 高管薪酬文件下载到本地并写入文件表
     *
     * @param dateTitle
     */
    @Override
    public void salaryDetailInfoApi(String dateTitle) {
        //文件名
        String dtFileName = DETAIL_File_Name + dateTitle + ".txt";
        String mgFileName = MAPPING_File_Name + dateTitle + ".txt";

        String path = SftpUtils.fetchFilesBetweenDates(dateTitle, dateTitle, "HQ_00034", "PSFT_FROM_HQ");
        String downLoadFilePath = path + dateTitle + "/";

        //判断文件是否生成成功
        Boolean isSuccess = FileUtil.checkFile(downLoadFilePath, dtFileName, mgFileName);
        if (isSuccess) {
            String dtFilePath = downLoadFilePath + dtFileName;
            String mgFilePath = downLoadFilePath + mgFileName;

            //查询文件是否已经写入
            CHighSyncFile dtFile = cHighSyncFileService.lambdaQuery().eq(CHighSyncFile::getFilePath, dtFilePath).eq(CHighSyncFile::getDeleted, Constants.NOT_DELETED).one();
            CHighSyncFile mgFile = cHighSyncFileService.lambdaQuery().eq(CHighSyncFile::getFilePath, mgFilePath).eq(CHighSyncFile::getDeleted, Constants.NOT_DELETED).one();

            //写入文件记录表
            CHighSyncFile detailData = CHighSyncFile.builder()
                    .id(cHighSyncFileService.selectSeq())
                    .fileIdent(dateTitle)
                    .filePath(dtFilePath)
                    .effdt(DateUtils.getDateNow()).build();
            CHighSyncFile mappingData = CHighSyncFile.builder()
                    .id(cHighSyncFileService.selectSeq())
                    .fileIdent(dateTitle)
                    .filePath(mgFilePath)
                    .effdt(DateUtils.getDateNow()).build();

            if (ObjectUtils.isNotEmpty(dtFile)) {
                detailData.setId(dtFile.getId());
            }
            if (ObjectUtils.isNotEmpty(mgFile)) {
                mappingData.setId(mgFile.getId());
            }
            cHighSyncFileService.saveOrUpdate(detailData);
            cHighSyncFileService.saveOrUpdate(mappingData);
        } else {
            log.info("定时拉取薪酬文件任务>>>创建文件失败");
        }
    }

    @Override
    public void salaryDetailInfoProcess(MftHrCoreHq00034Req message) {

        String base64EncParams = message.getBase64EncParams();
        if (StringUtils.isEmpty(base64EncParams)) {
            throw new RuntimeException("params is null!");
        }
        byte[] decodeBytes = null;
        Map<String, String> map = null;
        try {
            decodeBytes = Base64.getDecoder().decode(message.getBase64EncParams().getBytes());
            map = JSONObject.parseObject(new String(decodeBytes), HashMap.class);
        } catch (IllegalArgumentException e) {
            // 处理 Base64 解码错误(包括非法字符等)
            log.error("Base64 解码失败:{}", e.getMessage());
        } catch (JSONException e) {
            // 处理 JSON 解析错误
            log.error("JSON 解析失败:{}", e.getMessage());
        }

        String remotePath = map.get("remotePath");
        String downLoadPath = map.get("downLoadPath");
        String dateTitle = map.get("dateTitle");
        String startDt = map.get("startDt");
        String endDt = map.get("endDt");
        String fileName = map.get("fileName");
        String cPassCode = map.get("cPassCode");
        String cfgId = map.get("cfgId");

        Enterprisepension configData = enterprisepensionService.queryConfigData(cfgId);
        EnhanceSftp enhanceSftp = new EnhanceSftp(configData);
        //下载文件
        try {
            enhanceSftp.downloadFile(remotePath + "/" + fileName,
                    downLoadPath, fileName);
        } catch (IOException | SftpException e) {
            e.printStackTrace();
        } finally {
            enhanceSftp.destroy();
        }

        Boolean isSuccess = false;
        if (StringUtils.isEmpty(fileName) || !fileName.contains(".")) {
            throw new RuntimeException("fileName is Null!");
        }
        String oriFileName = fileName.split("\\.")[0];
        //解密文件
        String decryptedPath = downLoadPath + "/" + oriFileName;
        String localFilePath = downLoadPath + "/" + fileName;
        String decryptedFilePath = decryptedPath + "/" + fileName;
        isSuccess = FileUtil.checkFile(downLoadPath, fileName);
        if (!isSuccess) {
            throw new RuntimeException("downLoadFile is null!");
        }
        EnhanceAesDecry.decrypt(cPassCode, localFilePath, decryptedFilePath);
        isSuccess = FileUtil.checkFile(decryptedPath, fileName);
        if (!isSuccess) {
            throw new RuntimeException("zipFile is null!");
        }
        File file1 = new File(decryptedFilePath);
        log.info("sign file length:{}", file1.length());
        log.info("sign文件Hash:{}", String.valueOf(file1.hashCode()));
        log.info("文件解密完成:{}", decryptedFilePath);


        // 解压文件
        log.info("文件开始解压");
        decryptedPath = EnhanceHandleData.handleData(decryptedPath, fileName);
        isSuccess = FileUtil.checkFile(decryptedPath, oriFileName + ".txt");
        if (isSuccess) {
            String xxFilePath = decryptedPath + "/" + oriFileName + ".txt";
            //查询文件是否已经写入
            CHighSyncFile xxFile = cHighSyncFileService.lambdaQuery().eq(CHighSyncFile::getFilePath, xxFilePath).eq(CHighSyncFile::getDeleted, Constants.NOT_DELETED).one();
            //写入文件记录表
            CHighSyncFile xxData = CHighSyncFile.builder()
                    .id(cHighSyncFileService.selectSeq())
                    .fileIdent(dateTitle)
                    .filePath(xxFilePath)
                    .effdt(DateUtils.getDateNow()).build();
            if (ObjectUtils.isNotEmpty(xxFile)) {
                xxData.setId(xxFile.getId());
            }
            cHighSyncFileService.saveOrUpdate(xxData);

        } else {
            log.info("定时拉取薪酬文件任务>>>创建文件失败");
        }

    }

    @Override
    public Result synchronousFunds(MftFmsHq00010Req req) {
        //获取配置表目录地址
        Enterprisepension configData = enterprisepensionService.queryConfigData("UPLOAD_PT01");
        String localPath = StringUtils.hasText(configData.getLocalPath()) ? configData.getLocalPath() : ROOT;
        if (!localPath.endsWith("/")) {
            localPath = localPath + "/";
        }
//        String localPath = configData.getLocalPath();
        if (localPath == null) {
            return Result.failed("MFT文件本地存放路径为空!");
        }
        // 加密前文件路径
        String filename = "MFT_SALARY_INFO_" + req.getPriKey() + ".txt";
        //String filePath = "D:\\"+filename;
        String filePath = localPath + filename;
//        File file = new File(filePath);
//        // 写入txt文件
//        try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
//            String jsonLine = getJsonLine(req);
//            //String json = objectMapper.writeValueAsString(jsonLine);
//            // 写入文件
//            writer.write(jsonLine);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        // 写入txt文件并指定编码为 GB2312
        try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath), "GB2312"))) {
            String jsonLine = getJsonLine(req);
            writer.write(jsonLine);
        } catch (IOException e) {
            log.error("写入文件失败 :{}", e);
            return Result.failed("写入文件失败 :" + e.getMessage());
        }
        //加密后文件路径
        String fileAesname = "MFT_SALARY_INFO_" + req.getPriKey() + "_" + DateUtils.dateTimeNow("yyyyMMddHHmmss") + ".txt";
//        String fileAesPath="D:\\"+fileAesname;
        String fileAesPath = localPath + fileAesname;
        Sm4Encrypt.encryptFile(configData.getCPasscode(), filePath, fileAesPath);
        //EnhanceAesEncrypt.encrypt(configData.getCPasscode(), filePath, fileAesPath);
        //上传sftp
        SftpUtil.uploadZipFile(configData.getIpAddress(), configData.getCPort(), configData.getUserid(),
                configData.getPassword(), configData.getFilePath(), fileAesPath);
        //清空本地文件
        FileUtil.cleanFile(fileAesPath);

        return Result.ok(fileAesname);

    }

    /**
     * MFT_SMHR_SMHR_HQ_00001  iHR薪酬上月行权收益信息传输服务(MFT)
     *
     * @return
     */
    @Override
    public Result mftXfeExecExerciseIncomeSrv(MftHrCoreHq00001Req req) {
        //获取配置表目录地址
        Enterprisepension configData = enterprisepensionService.queryConfigData("PSFT_TO_GRID");
        String localPath = configData.getLocalPath();
        if (localPath == null) {
            return Result.failed("MFT文件本地存放路径为空!");
        }
        String remotePath = configData.getFilePath();
        String businessUnit = req.getBusinessUnit();
        String calPrdId = req.getCalPrdId();
        String gpPaygroup = req.getCalPrdId();
        if (org.apache.commons.lang3.StringUtils.isBlank(calPrdId)) {
            calPrdId = cFinRptEmpMapper.selectCalPrdId();
            String closed = cFinRptEmpMapper.selectCClosed(calPrdId);
            if (!"Y".equals(closed)) {
                return Result.ok(null, "当前期间ID为关账,不进行推送:" + calPrdId);
            }
            String sendFlag = cFinRptEmpMapper.selectSendFlag(calPrdId);
            if ("Y".equals(sendFlag)) {
                return Result.ok(null, "当前期间之前已推送过,本次不推送。");
            }
        }
        Date prdEndDt = cFinRptEmpMapper.selectPrdEndDt(calPrdId);
        String fileName = "MftXfeExecExerciseIncomeSrv_" + DateUtils.dateTime() + ".json";
        String filePath = localPath + File.separator + fileName;
        String zipFileName = "MftXfeExecExerciseIncomeSrv_" + DateUtils.dateTime() + ".zip";
        String zipFilePath = localPath + File.separator + zipFileName;
        String aesFileName = "MftXfeExecExerciseIncomeSrv_" + DateUtils.dateTime() + ".zip";
        String aesFilePath = localPath + File.separator + "aes" + File.separator + aesFileName;
        File directory = new File(localPath);
        File file = new File(filePath);
        // 创建目录和文件
        if (!directory.exists()) {
            directory.mkdirs();
        }
        // 写入txt文件
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
            String head = "员工姓名,员工编码,所属公司编码,所属公司名称,期间,上月行权总收入(人民币)";
            // 写入文件
            writer.write(head);
            writer.newLine();
            List<Job> jobList = jobService.C_EXER_INC_GET_JOB_ALTER_EMPLI(businessUnit, prdEndDt);
            String tmpEmplid;
            for (Job job : jobList) {
                if (org.apache.commons.lang3.StringUtils.isNotBlank(job.getEmplid())) {
                    tmpEmplid = job.getEmplid();
                    List<JobVo> jobVoList = jobService.C_EXER_INC_GET_PAY_COMPANY(job.getEmplid(), job.getAlterEmplid(), job.getEffdt(), prdEndDt);
                    JobVo jobVo = jobVoList.get(0);
                    String company = jobService.C_EXER_INC_GET_COMPANY(jobVo.getPayCompany());
                    String totalAmount = jobService.selectSumCOptTotalEarnR(calPrdId, job.getEmplid());
                    String strLine = jobVo.getName() + "," + job.getEmplid() + "," + company + "," + jobVo.getPayCompanyDescr() + "," + calPrdId + "," + totalAmount;
                    writer.write(strLine);
                }
                if (!job.getEmplid().equals(job.getAlterEmplid())) {
                    List<JobVo> jobVoList = jobService.C_EXER_INC_GET_PAY_COMPANY(job.getEmplid(), job.getAlterEmplid(), job.getEffdt(), prdEndDt);
                    JobVo jobVo = jobVoList.get(0);
                    String company = jobService.C_EXER_INC_GET_COMPANY(jobVo.getPayCompany());
                    String totalAmount = jobService.selectSumCOptTotalEarnR(calPrdId, job.getEmplid());
                    String strLine = jobVo.getName() + "," + job.getAlterEmplid() + "," + company + "," + jobVo.getPayCompanyDescr() + "," + calPrdId + "," + totalAmount;
                    writer.write(strLine);
                }
            }
        } catch (IOException e) {
            log.error("薪酬上月行权收益信息传输服务传送,推送文件失败", e);
            return Result.failed(null, "薪酬上月行权收益信息传输服务传送,推送文件失败。");
        }
        //压缩文件
        try {
            ZipUtil.compressFile(filePath, localPath, zipFilePath);
            //上传文件
            EnhanceAesEncrypt.encrypt(configData.getCPasscode(), zipFilePath, aesFilePath);
            SftpUtil.sftpUploadFile(configData.getIpAddress(), configData.getCPort(), configData.getUserid(), configData.getPassword(), remotePath, aesFilePath, remotePath + File.separator + aesFileName);
            //清空本地文件
            FileUtil.cleanFile(configData.getLocalPath() + File.separator + zipFileName.replaceAll("\\.[^.\\s]+$", ""));
        } catch (IOException e) {
            log.error("项目报账数据传送,推送文件失败", e);
            return Result.failed(null, "项目报账数据传送,推送文件失败。");
        }
//      更新状态
        CExerIncLog cExerIncLog = new CExerIncLog();
        cExerIncLog.setCalPrdId(calPrdId);
        UserInfo u = TSysUser.getCurrentA01();
        if (null != u) {
            cExerIncLog.setLastupdoprid(u.getA0188() + "");
        }
        cExerIncLog.setLastupddttm(new Date());
        return Result.ok(null, "处理完成!");
    }

    /**
     * MFT_HR_CORE_HQ_00058 _网格人员信息传输服务(MFT)-V0.1
     *
     * @return
     */
    @Override
    public Result mftXfeGridStaffInfoSrv(MftHrCoreHq00001Req req) {

        //获取配置表目录地址
        Enterprisepension configData = enterprisepensionService.queryConfigData("PSFT_TO_SMHR");
        String localPath = configData.getLocalPath();
        if (localPath == null) {
            return Result.failed("MFT文件本地存放路径为空!");
        }
        String remotePath = configData.getFilePath();
        String businessUnit = req.getBusinessUnit();
        String gpPaygroup = req.getCalPrdId();

        String fileName = "MFT_HR_CORE_GRID_PERSINFO_" + DateUtils.dateTime() + ".dat";
        String filePath = localPath + File.separator + fileName;
        String uuid = IdWorker.getIdStr();
        String zipFileName = "MFT_HR_CORE_GRID_PERSINFO_" + DateUtils.dateTime() + uuid + ".zip";
        String zipFilePath = localPath + File.separator + zipFileName;
        String aesFileName = "MFT_HR_CORE_GRID_PERSINFO_" + DateUtils.dateTime() + uuid + ".zip";
        String aesFilePath = localPath + File.separator + "aes" + File.separator + aesFileName;
        File directory = new File(localPath);
        File file = new File(filePath);
        // 创建目录和文件
        if (!directory.exists()) {
            directory.mkdirs();
        }
        // 写入txt文件
        cMfttogrReadyMapper.truncateTable();
        cMfttogrReadyMapper.C_MFT_TOGR_INFO_READY_SQL();
        List<String> dataArrHeader = new ArrayList<>();
        List<String> dataStrArrHeader = new ArrayList<>();
        dataArrHeader.add("recordNum");
        dataArrHeader.add("staffNum");
        dataArrHeader.add("staffOldNum");
        dataArrHeader.add("staffName");
        dataArrHeader.add("staffPhone");
        dataArrHeader.add("provId");
        dataArrHeader.add("provCmyName");
        dataArrHeader.add("gridCode");
        dataArrHeader.add("gridName");
        dataArrHeader.add("staffRolecode");
        dataArrHeader.add("staffRolename");
        dataArrHeader.add("isInvalid");
        dataArrHeader.add("isMaingrid");
        dataArrHeader.add("startTime");
        dataArrHeader.add("endTime");
        dataArrHeader.add("updateTime");
        dataArrHeader.add("statDate");
        dataArrHeader.add("bakRemark1");
        dataArrHeader.add("bakRemark2");
        dataArrHeader.add("bakRemark3");
        dataArrHeader.add("bakRemark4");
        dataArrHeader.add("bakRemark5");
        String txtLineHeader = dataArrHeader.toString();
        String char31 = String.valueOf((char) 31);
        txtLineHeader = txtLineHeader.replace(", ", char31).replace("[", "").replace("]", "");
        txtLineHeader = txtLineHeader + char31 + "Array";
        List<CMfttogrReadyVo> cMfttogrReadyVoList = cMfttogrReadyMapper.C_MFT_TOGR_INFO_WRITE_SQL();
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
            // 写入文件
            writer.write(txtLineHeader);
            for (CMfttogrReadyVo cMfttogrReadyVo : cMfttogrReadyVoList) {
                String txtLine = JacksonUtil.getObjectValues(cMfttogrReadyVo);
                writer.write(txtLine);
            }
        } catch (IOException e) {
            log.error("网格人员信息传输服务,推送文件失败", e);
            return Result.failed(null, "网格人员信息传输服务,推送文件失败。");
        }
        //压缩文件
        try {
            ZipUtil.compressFile(filePath, localPath, zipFilePath);
            if ("Y".equals(configData.getCAesFlag())) {
                EnhanceAesEncrypt.encrypt(configData.getCPasscode(), zipFilePath, aesFilePath);
                SftpUtil.sftpUploadFile(configData.getIpAddress(), configData.getCPort(), configData.getUserid(), configData.getPassword(), remotePath, aesFilePath, remotePath + File.separator + aesFileName);
            } else {
                SftpUtil.sftpUploadFile(configData.getIpAddress(), configData.getCPort(), configData.getUserid(), configData.getPassword(), remotePath, zipFilePath, remotePath + File.separator + zipFileName);
            }
            //上传文件
            //清空本地文件
            FileUtil.cleanFile(configData.getLocalPath() + File.separator + zipFileName.replaceAll("\\.[^.\\s]+$", ""));
            FileUtil.cleanFile(configData.getLocalPath() + File.separator + fileName.replaceAll("\\.[^.\\s]+$", ""));
        } catch (IOException e) {
            log.error("网格人员信息传输服务,推送文件失败", e);
            return Result.failed(null, "网格人员信息传输服务,推送文件失败。");
        }
        return Result.ok(null, "处理完成!");
    }


    /**
     * 获取一行的json数据
     *
     * @param req
     * @return
     */
    public String getJsonLine(MftFmsHq00010Req req) {
        int j = 0;
        String jsonStr = "";
        String payDetailId;
        CFinRptTbl cFinRptTbl = cFinRptTblService.selectByCPriKey(req.getPriKey());
        if (null != cFinRptTbl) {
            MftFmsHq00010Req2 req2 = new MftFmsHq00010Req2();
            req2.setPriKey(req.getCSequenceno());
            req2.setProvinceCode(req.getProvinceCode());
            req2.setBatchId(cFinRptTbl.getCPriKey());
            req2.setPaymentNo(req.getCPaymentNo());
            req2.setInputExt("");
            //绑定参数
            MftFmsHq00010Req2.MsgHeader msgHeader = new MftFmsHq00010Req2.MsgHeader();
            msgHeader.setSOURCESYSTEMID(interfaceConfig.getSourceSystemId());
            msgHeader.setSOURCESYSTEMNAME(interfaceConfig.getSourceSystemName());
            msgHeader.setTOKEN(DigestUtils.md5Hex(interfaceConfig.getToken() + DateUtils.dateTimeNow(DateUtils.YYYYMMDD)));
            msgHeader.setPROVINCE_CODE(interfaceConfig.getProvinceCode());
            msgHeader.setCURRENT_PAGE(1);
            msgHeader.setPAGE_SIZE(200);
            msgHeader.setTOTAL_RECORD("-1");
            req2.setMsgHeader(msgHeader);
//            req2.setMsgHeader(JacksonUtil.getJsonToBean(JacksonUtil.getBeanToJson(req2.getMsgHeader()), MftFmsHq00010Req2.MsgHeader.class));
            MftFmsHq00010Req2.DocumentsInfo documentsInfo = new MftFmsHq00010Req2.DocumentsInfo();
            documentsInfo.setDocumentsNum(cFinRptTbl.getCDocumentsNum());
            documentsInfo.setDocumentAmount(cFinRptTbl.getCAmt001());
            documentsInfo.setATTRIBUTE1("");
            documentsInfo.setATTRIBUTE2("");
            documentsInfo.setATTRIBUTE3("");
            documentsInfo.setATTRIBUTE4("");
            documentsInfo.setATTRIBUTE5("");
            documentsInfo.setATTRIBUTE6("");
            documentsInfo.setATTRIBUTE7("");
            documentsInfo.setATTRIBUTE8("");
            documentsInfo.setInputExt("");
            List<MftFmsHq00010Req2.DocumentsInfo> documentsInfoList = new ArrayList<>();
            List<MftFmsHq00010Req2.PayrollDetailInfo> payrollDetailInfoList = new ArrayList<>();
            documentsInfoList.add(documentsInfo);
            req2.setDocumentsInfoList(documentsInfoList);
            List<CFinRptEmp> cFinRptEmpList = cFinRptEmpMapper.selectByCPriKey(req.getPriKey());

            for (CFinRptEmp cFinRptEmp : cFinRptEmpList) {
                /* j++;
               if (org.apache.commons.lang3.StringUtils.isNotBlank(cFinRptEmp.getCSequenceno())) {
                    payDetailId = cFinRptEmp.getCSequenceno();
                } else {
                    payDetailId = cFinRptEmp.getCPriKey() + j;
                }*/
                payDetailId = cFinRptEmp.getCSequenceno();
                MftFmsHq00010Req2.PayrollDetailInfo payrollDetailInfo = new MftFmsHq00010Req2.PayrollDetailInfo();
                payrollDetailInfo.setPayDetailId(payDetailId);
                payrollDetailInfo.setStaffBankAccount(cFinRptEmp.getAccountEcId());
                payrollDetailInfo.setStaffName(cFinRptEmp.getAccountName());
                payrollDetailInfo.setCorporateBank(cFinRptEmp.getBankCd());
                payrollDetailInfo.setUnionBank(cFinRptEmp.getCBranchNm());
                payrollDetailInfo.setOpeningbankName(cFinRptEmp.getDescr());
                //AMOUNT 去除不必要的尾随零
                String amount = cleanDecimalStringIfPositive(cFinRptEmp.getCAmt001());
                payrollDetailInfo.setAmount(amount);

                payrollDetailInfo.setCurrency(cFinRptEmp.getCurrencyCd());
                payrollDetailInfo.setDesc(cFinRptEmp.getComments256());
                payrollDetailInfo.setCity(cFinRptEmp.getCCityName());
                payrollDetailInfo.setProvince(cFinRptEmp.getCProvinceCode());
                payrollDetailInfo.setHrZdrno(cFinRptEmp.getCHrZdrno());
                payrollDetailInfo.setHrZdrname(cFinRptEmp.getCHrZdrname());
                payrollDetailInfo.setHrTel(cFinRptEmp.getCHrTel());
                payrollDetailInfo.setATTRIBUTE1("");
                payrollDetailInfo.setATTRIBUTE2("");
                payrollDetailInfo.setATTRIBUTE3("");
                payrollDetailInfo.setATTRIBUTE4("");
                payrollDetailInfo.setATTRIBUTE5("");
                payrollDetailInfo.setATTRIBUTE6("");
                payrollDetailInfo.setATTRIBUTE7("");
                payrollDetailInfo.setATTRIBUTE8("");
                payrollDetailInfo.setInputExt("");
                payrollDetailInfoList.add(payrollDetailInfo);
            }
            req2.setPayrollDetailInfoList(payrollDetailInfoList);
            ObjectMapper mapper = new ObjectMapper();
            try {
                return mapper.writeValueAsString(req2);
            } catch (com.fasterxml.jackson.core.JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
        return jsonStr;
    }

    private String cleanDecimalStringIfPositive(String decimalStr) {
        if (decimalStr == null || decimalStr.trim().isEmpty()) {
            return ""; // 或者抛出异常或返回其他默认值
        }

        try {
            BigDecimal decimal = new BigDecimal(decimalStr);
            // 如果是正数且包含小数点,则去除尾随零
            if (decimal.compareTo(BigDecimal.ZERO) > 0 && decimal.scale() > 0) {
                String cleanedDecimal = decimal.stripTrailingZeros().toPlainString();
                return cleanedDecimal;
            } else {
                // 不是正数或没有小数部分,保持原值
                return decimalStr;
            }
        } catch (NumberFormatException e) {
            log.error("数值字符串清理失败: {}", decimalStr, e);
            throw new IllegalArgumentException("无效的数值格式: " + decimalStr, e);
        }
    }
    @Override
    public Result fileFundingDownload(String zipFileName) {
        Enterprisepension configData = enterprisepensionService.queryConfigData("UPLOAD_PT02");
        String path = SftpUtils.filenameDownload(configData, zipFileName);
        if (path == null) {
            log.error("下载或解压缩文件失败");
            return Result.failed("下载或解压缩文件失败");
        }
        String fileName = zipFileName.replace(".zip", ".txt");
        Boolean isSuccess = false;
        //判断文件是否存在
        isSuccess = FileUtil.checkFile(path, fileName);
        cn.hutool.json.JSONObject jsonObject = null;
        if (isSuccess) {
            String filePath = path + File.separator + fileName;
//            try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "GB2312"))) {
                StringBuilder contentBuilder = new StringBuilder();
                String currentLine;
                while ((currentLine = reader.readLine()) != null) {
                    contentBuilder.append(currentLine).append("\n"); // 追加换行符以保持原始文件的格式
                }
                String content = contentBuilder.toString();
                jsonObject = new cn.hutool.json.JSONObject(content);
            } catch (IOException e) {
                e.printStackTrace();
            }
            //清空本地文件
            FileUtil.cleanFile(configData.getLocalPath() + File.separator + zipFileName.replaceAll("\\.[^.\\s]+$", ""));
        } else {
            log.error(zipFileName + "文件不存在");
            return Result.failed("文件不存在");
        }
        return Result.ok(jsonObject);
    }

    @Override
    public Result filePaymentStatus(String zipFileName) {
        Enterprisepension configData = enterprisepensionService.queryConfigData("UPLOAD_PT02");
        String path = SftpUtils.designatedFilenameDownload(configData, zipFileName);
        if (path == null) {
            log.error("下载或解压缩文件失败");
            return Result.failed("下载或解压缩文件失败");
        }
        String fileName = zipFileName.replace(".zip", ".txt");
        Boolean isSuccess = false;
        //判断文件是否存在
        isSuccess = FileUtil.checkFile(path, fileName);

        cn.hutool.json.JSONObject jsonObject = null;
        JSONArray jsonArray = new JSONArray();
        if (isSuccess) {
            String filePath = path + File.separator + fileName;
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "GB2312"))) {
                String currentLine;
                while ((currentLine = reader.readLine()) != null) {
                    String content = currentLine.toString();
                    jsonObject = new cn.hutool.json.JSONObject(content);
                    jsonArray.add(jsonObject);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            //清空本地文件
            FileUtil.cleanFile(configData.getLocalPath() + File.separator + zipFileName.replaceAll("\\.[^.\\s]+$", ""));
        } else {
            log.error(zipFileName + "文件不存在");
            return Result.failed("文件不存在");
        }
        return Result.ok(jsonArray);
    }

    /**
     * 高管薪酬文件解析并写入到业务表
     *
     * @param req
     * @return
     */
    @Override
    public Result syncExecCompSalary(MftHrCoreHq00033Req req) {

        CHighSyncTask cHighSyncTask = cHighSyncTaskService.getById(req.getTaskId());
        if (null == cHighSyncTask) {
            return Result.ok("没有需要同步的数据");
        }

        QueryWrapper<CHighSyncFile> queryWrapper = new QueryWrapper<>();
        queryWrapper.between("FILE_IDENT", req.getStartDt(), req.getEndDt());
        queryWrapper.eq("deleted", 0);
        List<CHighSyncFile> fileLists = cHighSyncFileService.list(queryWrapper);
        if (CollectionUtils.isEmpty(fileLists)) {
            cHighSyncTask.setSyncStatus("2");
            cHighSyncTask.setDescription("当前日期文件列表没有要同步的数据,请检查文件列表并下载文件!");
            cHighSyncTaskService.updateById(cHighSyncTask);
            return Result.ok();
        }

        try {
            Map<String, List<CHighSyncFile>> groupFile = fileLists.stream().collect(Collectors.groupingBy(CHighSyncFile::getFileIdent));
            log.info("高管薪酬同步接口>>>开始日期:{},结束日期:{},已查询到需要同步的薪酬数据,数量:{},开始同步薪酬数据", req.getStartDt(), req.getEndDt(), groupFile.size());
            Map<String, Object> global = new HashMap<>();
            for (Map.Entry<String, List<CHighSyncFile>> entry : groupFile.entrySet()) {
                log.info("高管薪酬同步接口>>>日期标识:{},的数据开始同步", entry.getKey());
                List<CHighSyncFile> value = entry.getValue();
                //if (value.size() != 2) {
                //    log.info("高管薪酬同步接口>>>薪酬同步的明细和映射文件不全,跳过这次同步。日期标识:{}",entry.getKey());
                //    continue;
                //}

                //将DETAIL和MAPPING文件区分开
                Map<String, CHighSyncFile> syncFileMap = value.stream().collect(Collectors.toMap(t -> {

                    String mapping_regex = "MFT_HLP_SALARY_ITEM_MAPPING_\\d{8}\\.txt";
                    String detail_regex = "MFT_HLP_SALARY_DETAIL_INFO_\\d{8}\\.txt";
                    // 编译正则表达式
                    Pattern mapping_pattern = Pattern.compile(mapping_regex);
                    Pattern detail_pattern = Pattern.compile(detail_regex);
                    // 创建匹配器
                    Matcher mapping_matcher = mapping_pattern.matcher(t.getFilePath());
                    Matcher detail_matcher = detail_pattern.matcher(t.getFilePath());
                    if (mapping_matcher.find()) {
                        return "MAPPING";
                    } else if (detail_matcher.find()) {
                        return "DETAIL";
                    }
                    return "UnKnow";
                }, Function.identity()));

                //处理映射文件
                Boolean isSuccess = handleMappingFile(syncFileMap.get("MAPPING"), cHighSyncTask);
                if (isSuccess) {
                    //处理明细文件
                    Map<String, String> result = handleDetailFile(syncFileMap.get("DETAIL"), req, cHighSyncTask);
                    global.put(entry.getKey(), result);
                }
            }
            cHighSyncTask.setSyncStatus("1");
            cHighSyncTask.setDescription(JSONObject.toJSONString(global));
            cHighSyncTaskService.updateById(cHighSyncTask);

            return Result.ok();
        } catch (ParseException | CustomException ex) {
            log.info("高管薪酬同步接口>>>同步报错,错误信息:{}", ex.getMessage());
            cHighSyncTask.setDescription("同步数据报错,错误信息:" + ex.getMessage());
            cHighSyncTaskService.updateById(cHighSyncTask);
            return Result.failed();
        }
    }

    /**
     * 高管薪酬处理映射文件写入映射表
     *
     * @param data 文件数据实体
     * @return 是否写入成功
     */
    private Boolean handleMappingFile(CHighSyncFile data, CHighSyncTask cHighSyncTask) {
        //获取文件内容
        List<String> lineList = TxtUtil.readTxt2(data.getFilePath());
        if (CollectionUtils.isEmpty(lineList)) {
            log.info("高管薪酬同步接口>>>没有获取到映射文件内容,停止同步");
            cHighSyncTask.setSyncStatus("2");
            cHighSyncTask.setDescription("没有获取到映射文件内容,停止同步!");
            cHighSyncTaskService.updateById(cHighSyncTask);
            return false;
        }

        //解析文件内容
        List<CHighSubject> saveDatas = new ArrayList<>();
        for (String line : lineList) {
            CHighSubject cHighSubject = new CHighSubject();
            String[] split = line.split(",");
            cHighSubject.setId(cHighSubjectService.selectSeq());
            cHighSubject.setSeqNo(split[0]);
            cHighSubject.setSalItemCode(split[1]);
            cHighSubject.setSalItemName(split[2]);
            cHighSubject.setCreationtime(new Date());
            saveDatas.add(cHighSubject);
        }
        //清空旧映射数据
        cHighSubjectService.lambdaUpdate().remove();
        //写入映射数据
        return cHighSubjectService.saveBatch(saveDatas);
    }

    /**
     * 高管薪酬处理明细文件写入中间表
     *
     * @param data
     */
    private Map<String, String> handleDetailFile(CHighSyncFile data, MftHrCoreHq00033Req req, CHighSyncTask cHighSyncTask) throws ParseException {
        Map<String, String> result = null;
        //获取文件内容
        List<Map<String, String>> lineList = TxtUtil.readTxtToMap(data.getFilePath());
        if (CollectionUtils.isEmpty(lineList)) {
            //log.info("高管薪酬同步接口>>>明细内容未获取到,停止同步");
            //cHighSyncTask.setSyncStatus("2");
            //cHighSyncTask.setDescription("高管薪酬同步接口>>>明细内容未获取到,停止同步");
            //cHighSyncTaskService.updateById(cHighSyncTask);
            result = new HashMap<>();
            result.put("status", "2");
            result.put("message", "高管薪酬同步接口>>>明细内容未获取到,停止同步!");
            return result;
        }

        //查询需要同步的字段名称
        List<CHighSubject> subList = cHighSubjectService.lambdaQuery().select(CHighSubject::getSalItemCode).list();
        if (CollectionUtils.isEmpty(subList)) {
            //log.info("高管薪酬同步接口>>>配置表未查到需要同步的字段信息,停止同步");
            //cHighSyncTask.setSyncStatus("2");
            //cHighSyncTask.setDescription("高管薪酬同步接口>>>配置表未查到需要同步的字段信息,停止同步");
            //cHighSyncTaskService.updateById(cHighSyncTask);
            //throw new CustomException();
            result = new HashMap<>();
            result.put("status", "2");
            result.put("message", "高管薪酬同步接口>>>配置表未查到需要同步的字段信息,停止同步!");
            return result;
        }

        List<String> mappingName = subList.stream().map(CHighSubject::getSalItemCode).collect(Collectors.toList());

        //查询映射信息表判断是否都有配置映射
        List<CHighMapDtl> dtlList = cHighMapDtlService.queryByEffdt(mappingName);
        Set<String> dtlSalItemCodeSet = dtlList.stream()
                .map(CHighMapDtl::getSalItemCode) // 假设CHighMapDtl有getSalItemCode()方法
                .collect(Collectors.toSet());

        Set<String> difference = mappingName.stream()
                .filter(code -> !dtlSalItemCodeSet.contains(code))
                .collect(Collectors.toSet());

        if (difference.size() > 0) {
            log.info("difference.size:{}", difference.size());
            log.info("difference:{}", JSONObject.toJSONString(difference));
            //log.info("高管薪酬同步接口>>>映射表配置的映射信息不全,无法完全和配置表匹配,停止同步");
            //cHighSyncTask.setSyncStatus("2");
            //cHighSyncTask.setDescription("映射表配置的映射信息不全,无法完全和配置表匹配。相差数据:" + JSONObject.toJSONString(difference));
            //cHighSyncTaskService.updateById(cHighSyncTask);
            //throw new CustomException();
            result = new HashMap<>();
            result.put("status", "2");
            result.put("message", "映射表配置的映射信息不全,无法完全和配置表匹配。相差数据:" + JSONObject.toJSONString(difference));
            return result;
        }

        //将映射信息做成MAP
        Map<String, String> titleMap = dtlList.stream().collect(Collectors.toMap(CHighMapDtl::getSalItemCode, CHighMapDtl::getAmtFieldName));
        //写入基础映射
        titleMap.putAll(fixedMap);
        //清空中间表信息
        cHighSalaryService.lambdaUpdate().remove();

        //清除C21表期间范围内的高管薪酬数据
        //LambdaQueryWrapper<C21> deleteQueryWrapper = new LambdaQueryWrapper<>();
        //deleteQueryWrapper.ge(req.getStartDt() != null, C21::getGzYm, req.getStartDt())
        //        .le(req.getEndDt() != null, C21::getGzYm, req.getEndDt()).eq(C21::getCChr20001, Constants.IS_SENIOR_EXE);
        //c21Service.remove(deleteQueryWrapper);

        List<String> peopleGotIt = new ArrayList<>();
        //明细数据处理
        for (Map<String, String> lineMap : lineList) {
            Map<String, String> saveData = new HashMap<>();
            //循环要写入的映射信息
            for (Map.Entry<String, String> entry : titleMap.entrySet()) {
                String title = entry.getKey();
                saveData.put(entry.getValue(), lineMap.get(title) == null ? "" : lineMap.get(title));
            }

            //基础的明细数据Map转为中间表的CHighSalary实体
            CHighSalary cHighSalary = JacksonUtil.getJsonToBean(JacksonUtil.getBeanToJson(saveData), CHighSalary.class);
            A01 a01 = a01Service.selectUserInfoByAlterA0190(cHighSalary.getA0190());
            if (ObjectUtil.isNull(a01)) {
                a01 = a01Service.selectByA0190(cHighSalary.getA0190());
                if (ObjectUtil.isNull(a01)) {
                    log.info("高管薪酬同步接口>>>人员编号:{},,未找到对应的人员信息,跳过这条信息", cHighSalary.getA0190());
                    continue;
                }
            }

            //写入基础信息
            cHighSalary.setId(cHighSalaryService.selectSeq());
            cHighSalary.setA0188(a01.getA0188());
            cHighSalary.setCreationtime(new Date());
            //同步数据到中间表
            try {
                cHighSalaryService.save(cHighSalary);
            } catch (CustomException e) {
                log.error("中间表写入异常:{},数据是:{}", e.getMessage(), cHighSalary.getA0190());
            }

            //中间表信息转为C21实体
            C21 c21Data = BeanUtil.toBean(cHighSalary, C21.class);
            //处理C21表的明细信息
            c21Data.setA0190(a01.getA0190());
            //国家/地区
            c21Data.setCountry(a01.getCountry());
            //人员类别
            c21Data.setA0191(a01.getA0191());
            //JTYPE 兼职信息
            c21Data.setJtype(a01.getJtype());

            //获取公司编码
            List<CHighMapUnit> unitInfos = cHighMapUnitService.queryByEffdt(cHighSalary.getCompanyCode());
            log.info("job信息:{}", JSONObject.toJSONString(unitInfos));
            if (CollectionUtils.isEmpty(unitInfos)) {
                log.info("高管薪酬同步接口>>>人员编号:{},未找到对应的发薪单位,停止同步,跳过这条信息", cHighSalary.getA0190());
                continue;
            }
            CHighMapUnit unitInfo = unitInfos.get(0);
            if (ObjectUtils.isEmpty(unitInfo)) {
                log.info("高管薪酬同步接口>>>人员编号:{},未找到对应的发薪单位,停止同步,跳过这条信息", cHighSalary.getA0190());
                continue;
            }
            //查询JOB表获取记录号和公司编码
            //写入记录号和部门
            List<Job> jobList = jobService.queryByEffdt(c21Data.getA0188(), StringUtil.toString(unitInfo.getSalaryUnit()));
            if (CollectionUtils.isEmpty(jobList)) {
                log.info("高管薪酬同步接口>>>人员编号:{},未找到对应的JOB信息,停止同步,跳过这条信息", cHighSalary.getA0190());
                continue;
            }
            Job jobData = jobList.get(0);
            if (ObjectUtils.isEmpty(jobData)) {
                log.info("高管薪酬同步接口>>>人员编号:{},未找到对应的JOB信息,停止同步,跳过这条信息", cHighSalary.getA0190());
                continue;
            }
            c21Data.setEmplRcd(jobData.getEmplRcd());
            //DEPT_ID  系统部门编码
            c21Data.setDept_id(jobData.getDept_id());
            //DEPTID PS部门编码
            c21Data.setDeptId(jobData.getDeptid());
            //职务级别
            c21Data.setCChr40001(jobData.getJ01013());
            //职位条线
            c21Data.setCChr40007(jobData.getJ01007());
            //职位类别
            c21Data.setCChr40008(jobData.getCJobType());
            //归属条线
            c21Data.setCChr40009(jobData.getCAttrLine());
            //员工执行职级
            c21Data.setCChr40010(jobData.getCJobGrade());
            //职务分类
            c21Data.setCChr40011(jobData.getJ01012());
            //干部层级
            c21Data.setCChr40012(jobData.getCCadreLevel());

            //使用Job表信息查询薪资组成表
            List<CEmpsalitems> wageDatas = cEmpsalitemsService.quertByEffdt(c21Data.getA0188());
            if (CollectionUtils.isEmpty(wageDatas)) {
                log.info("高管薪酬同步接口>>>人员编号:{},未找到对应的薪资组成信息,停止同步,跳过这条信息", cHighSalary.getA0190());
                continue;
            }
            CEmpsalitems cEmpsalitems = wageDatas.get(0);
            //薪资方案
            c21Data.setPatbm(cEmpsalitems.getPatbm());
            //列支费用类别
            c21Data.setCChr40003(cEmpsalitems.getCExpenseType());
            获取薪资方案列表
            //List<String> patbms = new ArrayList<>();
            //if (!StringUtils.isEmpty(wageData.getPatbm())) {
            //    patbms = Arrays.asList(wageData.getPatbm().split(","));
            //}

            //Long count = c21Service.lambdaQuery().eq(C21::getGzYm, c21Data.getGzYm().replaceAll("M","")).eq(C21::getA0188, c21Data.getA0188()).count();
            //String payType;
            //if (count == 0) {
            //    payType = "RT_GZ";
            //    c21Data.setAId("1");
            //} else {
            //    payType = "RT_DC";
            //    c21Data.setAId(count.toString());
            //}
            //String patSet = a01Service.queryPatSetData(payType);
            //if (StringUtils.isEmpty(patSet) || !patbms.contains(patSet)) {
            //    log.info("高管薪酬同步接口>>>人员编号:{},未找到对应的薪资方案或薪资组成中未设置,停止同步,跳过这条信息", cHighSalary.getA0190());
            //    continue;
            //}
            //c21Data.setPatbm(patSet);
            //数据写到薪酬表(C21)
            c21Data.setId(c21Service.selectSeq());
            c21Data.setGzYm(cHighSalary.getGzYm().replace("M", ""));
            //主职
            c21Data.setJtype("01");
            //高管薪酬标识
            c21Data.setCChr20001(Constants.IS_SENIOR_EXE);
            peopleGotIt.add(c21Data.getA0190());
            Integer c21Id = c21Service.querDataIfExist(c21Data);
            if (c21Id != null && c21Id > 0) {
                c21Data.setId(c21Id);
                c21Service.updateById(c21Data);
            } else {
                c21Service.save(c21Data);
            }

            log.info("明细数据保存:{}", JSONObject.toJSONString(c21Data));
        }
        //cHighSyncTask.setSyncStatus("1");
        //cHighSyncTask.setDescription("成功导入的人员:" + JSONObject.toJSONString(peopleGotIt));
        //cHighSyncTaskService.updateById(cHighSyncTask);

        result = new HashMap<>();
        result.put("status", "1");
        result.put("message", "成功导入的人员:" + JSONObject.toJSONString(peopleGotIt));
        return result;
    }


    @Override
    public Result nonHourDataPushService(Long rntId) {
        CNsRnt nsRnt = cNsRntService.getById(rntId);
        if (nsRnt == null) {
            return Result.failed("nsRnt 未找到对应的同步记录");
        }
        Integer syncDataStatus = nsRnt.getSyncStatus();
        if (syncDataStatus != 0) {
            return Result.failed("nsRnt 同步状态不为0(初始)");
        }
        Enterprisepension readConfig = enterprisepensionService.queryConfigData("PSFT_FROM_NS");
        Enterprisepension writeConfig = enterprisepensionService.queryConfigData("PSFT_TO_NS");
        if (readConfig == null || writeConfig == null) {
            return Result.failed("PSFT配置不存在,请配置后重试");
        }
        //清空本地文件
        String nsZipLocalPath = C_NS_LOCAL_BASE_PATH + "ns-local-zip-" + DateUtils.getDate();
        String nsExtLocalPath = C_NS_LOCAL_BASE_PATH + "ns-local-ext-" + DateUtils.getDate();
        String nsCsvLocalPath = C_NS_LOCAL_BASE_PATH + "ns-local-csv-" + DateUtils.getDate();
        FileUtil.cleanFile(nsZipLocalPath);
        FileUtil.cleanFile(nsExtLocalPath);
        FileUtil.cleanFile(nsCsvLocalPath);

        // 下载远程文件
        String localZipPath = SftpUtils.fetchFilesByRemoteDirectory(readConfig.getFilePath(), "ns-local-zip-" + DateUtils.getDate(), "PSFT_FROM_NS");
        // 解压缩
        try {
            if (localZipPath == null) {
                log.error("hourDataPushService 下载远程文件失败");
                return Result.failed("下载远程文件失败");
            }
            File folder = new File(localZipPath);
            File[] files = folder.listFiles();
            if (files != null) { // 有些JDK版本中,listFiles()可能会返回null,所以这里做一下检查
                for (File file : files) {
                    // 记录filelog
                    CNsFileLog cNsFileLog = new CNsFileLog();
                    cNsFileLog.setCSequence(cNsFileLogService.selectSeq().toString());
                    cNsFileLog.setAttachuserfilednld(file.getName());
                    cNsFileLog.setAttachsysfilename(UUID.fastUUID().toString());
                    cNsFileLog.setProcessInstance(rntId.toString());
                    cNsFileLogService.save(cNsFileLog);
                    ZipUtil.extractZipFile(file.getAbsolutePath(), nsExtLocalPath + "/" + file.getName().split("\\.")[0]);
                }
            }
        } catch (IOException e) {
            log.error("hourDataPushService 解压缩失败", e);
            return Result.failed(e.getMessage());
        }
        LambdaQueryChainWrapper<CNsFileLog> nsFileLogLQCW = new LambdaQueryChainWrapper<>(cNsFileLogService.getBaseMapper());
        List<CNsFileLog> list = nsFileLogLQCW.eq(CNsFileLog::getProcessInstance, rntId).list();
        for (int i = 0; i < list.size(); i++) {
            CNsFileLog cNsFileLog = list.get(i);
            String fileName = cNsFileLog.getAttachuserfilednld();
            String[] split = fileName.split("\\.");
            List<MftRmsRmsHq00002Res> mftRmsRmsHq00002Res = new ArrayList<>();
            //读取csv文件
            File folder = new File(nsExtLocalPath + "/" + split[0]);
            File[] files = folder.listFiles();
            if (files != null) { // 有些JDK版本中,listFiles()可能会返回null,所以这里做一下检查
                String csvPath = nsCsvLocalPath + "/" + split[0];
                String zipPath = nsCsvLocalPath + "/" + "zip";
                File directory = new File(csvPath);
                directory.mkdirs();
                for (File file : files) {
                    try {
                        String[] fileNameSplit = file.getName().split("\\.");
                        // 记录filedtl
                        CNsFileDtl cNsFileDtl = new CNsFileDtl();
                        cNsFileDtl.setCSequence(cNsFileLog.getCSequence());
                        cNsFileDtl.setSeqNbr(String.valueOf(i));
                        cNsFileDtl.setAttachuserfilednld(file.getName());
                        cNsFileDtlService.save(cNsFileDtl);
                        mftRmsRmsHq00002Res = CsvUtil.convertCSVToEntityList(file.getAbsolutePath(), MftRmsRmsHq00002Res.class);
                        List<MftHrCoreHq00107Res> mftHrCoreHq00107Res = new ArrayList<>();
                        int successCount = 0;
                        try {
                            successCount = handleNonHourPushData(nsRnt, mftHrCoreHq00107Res, mftRmsRmsHq00002Res,
                                    cNsFileLog.getCSequence(),
                                    String.valueOf(i));
                        } catch (CustomException e) {
                            log.error("hourDataPushService 处理数据失败", e);
                        }
                        if (successCount == 0) {
                            nsRnt.setSyncStatus(-1);
                            cNsRntService.updateById(nsRnt);
                            return Result.ok();
                        }
                        if (successCount < mftRmsRmsHq00002Res.size()) {
                            nsRnt.setSyncStatus(2);
                            cNsRntService.updateById(nsRnt);
                            return Result.ok();
                        }
                        nsRnt.setSyncStatus(3);
                        cNsRntService.updateById(nsRnt);

                        if (!mftHrCoreHq00107Res.isEmpty()) {
                            CsvUtil.exportCsv(mftHrCoreHq00107Res, MftHrCoreHq00107Res.class, csvPath + "/" + fileNameSplit[0] + ".csv");
                        }
                    } catch (IOException e) {
                        log.error("hourDataPushService 读取csv文件失败", e);
                        nsRnt.setSyncStatus(-1);
                        nsRnt.setResultmsg(e.getMessage().substring(100));
                        cNsRntService.updateById(nsRnt);
                        return Result.failed(e.getMessage());
                    }
                }
                // 推送
                try {
                    Files.createDirectories(Paths.get(zipPath));
                    ZipUtil.compressFiles(csvPath, zipPath + "/" + split[0] + ".zip");
                    SftpUtil.sftpUploadFile(writeConfig.getIpAddress(), writeConfig.getCPort(), writeConfig.getUserid(), writeConfig.getPassword(), writeConfig.getFilePath(), zipPath + "/" + split[0] + ".zip", writeConfig.getFilePath() + split[0] + ".zip");
                } catch (IOException e) {
                    log.error("hourDataPushService 推送文件失败", e);
                    return Result.failed(e.getMessage());
                }
            }
        }
        return Result.ok();
    }

    /**
     * @param message
     */
    @Override
    public void nonHourDataProcessService(MftRmsRmsHq00002Req message) {

        String base64EncParams = message.getBase64EncParams();
        if (StringUtils.isEmpty(base64EncParams)) {
            throw new RuntimeException("params is null!");
        }
        byte[] decodeBytes = null;
        Map<String, String> map = null;
        try {
            decodeBytes = Base64.getDecoder().decode(message.getBase64EncParams().getBytes());
            map = JSONObject.parseObject(new String(decodeBytes), HashMap.class);
        } catch (IllegalArgumentException e) {
            // 处理 Base64 解码错误(包括非法字符等)
            log.error("Base64 解码失败:{}", e.getMessage());
        } catch (JSONException e) {
            // 处理 JSON 解析错误
            log.error("JSON 解析失败:{}", e.getMessage());
        }

        String rntId = map.get("rntId");
        String remotePath = map.get("remotePath");
        String downLoadPath = map.get("downLoadPath");
        String dateTitle = map.get("dateTitle");
        String fileName = map.get("fileName");

        Enterprisepension readConfig = enterprisepensionService.queryConfigData("PSFT_FROM_NS");
        EnhanceSftp enhanceSftp = new EnhanceSftp(readConfig);

        //下载文件
        try {
            enhanceSftp.downloadFile(remotePath + "/" + fileName,
                    downLoadPath, fileName);
        } catch (IOException | SftpException e) {
            e.printStackTrace();
        }

        CNsRnt nsRnt = cNsRntService.getById(rntId);
        if (nsRnt == null) {
            log.error("nsRnt 未找到对应的同步记录");
        }
        Integer syncDataStatus = nsRnt.getSyncStatus();
        if (syncDataStatus != 0) {
            log.error("nsRnt 同步状态不为0(初始)");
        }

        if (downLoadPath == null) {
            log.error("hourDataPushService 下载远程文件失败");
            throw new RuntimeException("下载远程文件失败!");
        }
        CNsFileLog cNsFileLog = new CNsFileLog();
        cNsFileLog.setCSequence(cNsFileLogService.selectSeq().toString());
        cNsFileLog.setAttachuserfilednld(fileName);
        cNsFileLog.setAttachsysfilename(UUID.fastUUID().toString());
        cNsFileLog.setProcessInstance(rntId);
        cNsFileLogService.save(cNsFileLog);
        try {
            ZipUtil.extractZipFile(downLoadPath, downLoadPath.split("\\.")[0]);
        } catch (IOException e) {
            log.error("hourDataPushService 解压缩失败", e);
            throw new RuntimeException(e);
        }
        LambdaQueryChainWrapper<CNsFileLog> nsFileLogLQCW = new LambdaQueryChainWrapper<>(cNsFileLogService.getBaseMapper());
        List<CNsFileLog> list = nsFileLogLQCW.eq(CNsFileLog::getProcessInstance, rntId).list();
        for (int i = 0; i < list.size(); i++) {
            cNsFileLog = list.get(i);
            String[] split = fileName.split("\\.");
            List<MftRmsRmsHq00002Res> mftRmsRmsHq00002Res = new ArrayList<>();
            //读取csv文件
            File folder = new File(downLoadPath + "/" + split[0]);
            File[] files = folder.listFiles();
            if (files != null) {
                String csvPath = downLoadPath + "/" + split[0];
                String zipPath = downLoadPath + "/" + "zip";
                File directory = new File(csvPath);
                directory.mkdirs();
                for (File file : files) {
                    try {
                        String[] fileNameSplit = file.getName().split("\\.");
                        // 记录filedtl
                        CNsFileDtl cNsFileDtl = new CNsFileDtl();
                        cNsFileDtl.setCSequence(cNsFileLog.getCSequence());
                        cNsFileDtl.setSeqNbr(String.valueOf(i));
                        cNsFileDtl.setAttachuserfilednld(file.getName());
                        cNsFileDtlService.save(cNsFileDtl);
                        mftRmsRmsHq00002Res = CsvUtil.convertCSVToEntityList(file.getAbsolutePath(), MftRmsRmsHq00002Res.class);
                        List<MftHrCoreHq00107Res> mftHrCoreHq00107Res = new ArrayList<>();
                        int successCount = 0;
                        try {
                            successCount = handleNonHourPushData(nsRnt, mftHrCoreHq00107Res, mftRmsRmsHq00002Res,
                                    cNsFileLog.getCSequence(),
                                    String.valueOf(i));
                        } catch (CustomException e) {
                            log.error("hourDataPushService 处理数据失败", e);
                        }
                        if (successCount == 0) {
                            nsRnt.setSyncStatus(-1);
                            cNsRntService.updateById(nsRnt);
                            break;
                        }
                        if (successCount < mftRmsRmsHq00002Res.size()) {
                            nsRnt.setSyncStatus(2);
                            cNsRntService.updateById(nsRnt);
                            break;
                        }
                        nsRnt.setSyncStatus(3);
                        cNsRntService.updateById(nsRnt);

                        if (!mftHrCoreHq00107Res.isEmpty()) {
                            CsvUtil.exportCsv(mftHrCoreHq00107Res, MftHrCoreHq00107Res.class, csvPath + "/" + fileNameSplit[0] + ".csv");
                        }
                    } catch (IOException e) {
                        log.error("hourDataPushService 读取csv文件失败", e);
                        nsRnt.setSyncStatus(-1);
                        nsRnt.setResultmsg(e.getMessage().substring(100));
                        cNsRntService.updateById(nsRnt);
                        break;
                    }
                }
                Enterprisepension writeConfig = enterprisepensionService.queryConfigData("PSFT_TO_NS");
                if (writeConfig == null) {
                    log.error("PSFT配置不存在,请配置后重试!");
                    break;
                }
                // 推送
                try {
                    Files.createDirectories(Paths.get(zipPath));
                    ZipUtil.compressFiles(csvPath, zipPath + "/" + split[0] + ".zip");
                    SftpUtil.sftpUploadFile(writeConfig.getIpAddress(), writeConfig.getCPort(), writeConfig.getUserid(), writeConfig.getPassword(), writeConfig.getFilePath(), zipPath + "/" + split[0] + ".zip", writeConfig.getFilePath() + split[0] + ".zip");
                } catch (IOException e) {
                    log.error("hourDataPushService 推送文件失败", e);
                    break;
                }
            }
        }

    }


    private int handleNonHourPushData(CNsRnt nsRnt,
                                      List<MftHrCoreHq00107Res> mftHrCoreHq00107Res,
                                      List<MftRmsRmsHq00002Res> mftRmsRmsHq00002Res,
                                      String cSequence,
                                      String seqNbr) {
        int successCount = 0;
        for (int i = 0; i < mftRmsRmsHq00002Res.size(); i++) {
            MftRmsRmsHq00002Res res = mftRmsRmsHq00002Res.get(i);
            MftHrCoreHq00107Res exportRes = new MftHrCoreHq00107Res();
            exportRes.setPriKey(res.getId());
            mftHrCoreHq00107Res.add(exportRes);
            res.setGzYm(convertToNumericDateFormat(res.getGzYm()));
            CNsDtl dtl = BeanUtil.toBean(res, CNsDtl.class);
            CNsDataLog dataLog = BeanUtil.toBean(res, CNsDataLog.class);
            dataLog.setCSequence(cSequence);
            dataLog.setSeqNbr(seqNbr);
            dataLog.setCPriKey(res.getId());
            dataLog.setProcessInstance(String.valueOf(nsRnt.getId()));
            dataLog.setSequenceno(String.valueOf(i));
            A01 a01 = a01Service.selectByA0190(res.getEmplid());
            if (a01 == null) {
                exportRes.setStatus(Constants.EXPORT_STATUS_EMP);
                continue;
            } else {
                dtl.setA0188(a01.getA0188().toString());
                dataLog.setEmployeeId(String.valueOf(a01.getA0188()));
            }
            try {
                cNsDtlService.deleteByPriKey(dtl.getCPriKey());
                BeanUtils.copyProperties(dataLog, dtl);
                switch (dataLog.getCTsDataType()) {
                    case "1":
                        break;
                    case "2":
                        dtl.setSeqnbr(1);
                        break;
                    case "3":
                        int maxSeqNbr = cNsDtlService.getSeqNbrByEmplidAndProCd(dataLog.getEmplid(), dataLog.getCProductCd());
                        dtl.setSeqnbr(maxSeqNbr + 1);
                        break;
                    default:
                        dtl.setSeqnbr(1);
                        dataLog.setMessageDescr("其他错误");
                        dataLog.setCTsStatus(Constants.EXPORT_STATUS_OTHER);
                }
                cNsDtlService.saveOrUpdateByPriKey(dtl);
                dataLog.setMessageDescr("success");
                dataLog.setCTsStatus(Constants.EXPORT_STATUS_SUCCESS);
                exportRes.setStatus(Constants.EXPORT_STATUS_SUCCESS);
                successCount++;
            } catch (CustomException e) {
                dataLog.setMessageDescr(e.getMessage().substring(100));
                dataLog.setCTsStatus(Constants.EXPORT_STATUS_OTHER);
                exportRes.setStatus(Constants.EXPORT_STATUS_OTHER);
                exportRes.setMessage(e.getMessage());
            }
            cNsDataLogService.saveOrUpdateByPriKey(dataLog);
        }
        return successCount;
    }

    private String convertToNumericDateFormat(String date) {
        if (date == null || date.length() < 6) {
            throw new IllegalArgumentException("(convertToNumericDateFormat) Invalid date format: " + date);
        }
        String year = date.substring(0, 4);
        String month = date.substring(4);

        if (month.startsWith("M")) {
            month = month.substring(1);
            if (month.length() == 1) {
                month = "0" + month;
            }
        }

        return year + month;
    }

    @Override
    public Result syncAnnPaymentPersonnelBalance(ExecCompSalaryReq req) {

        executor.execute(() -> {

            // 2,获取文件名,读取文件,解压文件
            String dateTitle = req.getStartDt() == null ? DateUtils.dateTimeNow(DateUtils.YYYYMMDD) : req.getStartDt();
            String folderName = "M_HR_CORE_200000067";
            String fileName = "GP_ASSET_" + dateTitle + ".zip";
            //解密解压后的文件名
            String DataSignfileName = "DataSign.txt";
            String dtFileName = fileName;
            String cMftCfgId = "PSFT_FROM_PA";
            Enterprisepension configData = enterprisepensionService.queryConfigData(cMftCfgId);
            String path = SftpUtils.fetchFilesByRemoteDirectory(configData, fileName, folderName);
            String downLoadFilePath = configData.getLocalPath() + "/" + dateTitle + "/" + dtFileName.replaceAll(".zip", "") + "/";
            String tempFilePath = downLoadFilePath;
            log.info("path:" + path);
            if ("".equals(path) || path == null || path == "") {
                log.error("找不到文件!");
                Thread.currentThread().interrupt();
            }
            String childFolderName = configData.getLocalPath() + "/" + dateTitle;
            //解密文件后再进行解压
            log.info("unzippass_after_dec:" + configData.getUnZipPassword());
            handleData(childFolderName, fileName, configData.getUnZipPassword());
            log.info("文件解压一次完成");

            //判断文件是否生成成功
            Boolean isSuccess = FileUtil.checkFile(downLoadFilePath, DataSignfileName, dtFileName);
            log.info("是否生成文件成功:" + isSuccess);
            if (isSuccess) {
                downLoadFilePath = downLoadFilePath + dtFileName.replaceAll(".zip", "") + "/";
                // 解压内部文件,得到CSV
                childFolderName = childFolderName + "/" + fileName.replaceAll(".zip", "");
                handleData(childFolderName, dtFileName, configData.getUnZipPassword());
                log.info("文件解压二次次完成");
                String csvFileName = dtFileName.replaceAll(".zip", ".csv");
                isSuccess = FileUtil.checkFile(downLoadFilePath, csvFileName);
                log.info("生成csv文件完成:" + isSuccess);
                if (isSuccess) {
                    // 查询文件是否已经写入
                    List<MftHrCore200000067Res> mftHrCore200000067Res = null;
                    String csvFilePath = downLoadFilePath + csvFileName;
                    log.info("生成csv文件路径:" + csvFilePath);
                    // 3,读取csv文件
                    try {
                        mftHrCore200000067Res = CsvUtil.convertCSVToEntityList(csvFilePath, MftHrCore200000067Res.class, 1);
                        log.info("读取完成,共读取到:" + mftHrCore200000067Res.size() + "条");

                    } catch (IOException e) {
                        log.error("读取csv文件失败", e);
                    }
                    // 4,csv文件入库
                    if (mftHrCore200000067Res != null && !mftHrCore200000067Res.isEmpty() && mftHrCore200000067Res.size() > 0) {
                        int i = 1;
                        List<CPerAssetTbl> cPerAssetTblList = new ArrayList<>();
                        for (MftHrCore200000067Res res : mftHrCore200000067Res) {
                            CPerAssetTbl cPerAssetTbl = new CPerAssetTbl();
                            BeanUtils.copyProperties(res, cPerAssetTbl);
                            cPerAssetTblList.add(cPerAssetTbl);
                            if (i >= 300) {
                                cPerAssetTblService.saveOrUpdateBatch(cPerAssetTblList);
                                cPerAssetTblList.clear();
                                i = 0;
                            }
                            i++;
                            //cPerAssetTblService.saveOrUpdate(cPerAssetTbl);
                        }
                        if (cPerAssetTblList.size() > 0) {
                            cPerAssetTblService.saveOrUpdateBatch(cPerAssetTblList);
                            cPerAssetTblList.clear();
                            i = 0;
                        }
                    }

                }
                removeTempFilePath(configData.getLocalPath() + "/" + dateTitle);
            }

        });

        return Result.ok();
    }

    @Override
    public Result uploadFile2Sftp(MultipartFile file, String paramId) {
        Enterprisepension configData = enterprisepensionService.queryConfigData(paramId);
        log.info("paramId:{} fileName:{} fileSize:{}", paramId, file.getOriginalFilename(), file.getSize());
        if (ObjectUtil.isNull(configData)) {
            return Result.failed("PSFT配置不存在,请配置后重试");
        }
        try {
            //上传
            SftpUtil.sftpUploadFile(
                    configData.getIpAddress(),
                    configData.getCPort(),
                    configData.getUserid(),
                    configData.getPassword(),
                    configData.getFilePath(),
                    file.getInputStream(),
                    configData.getFilePath() + file.getOriginalFilename()
            );

        } catch (IOException e) {
            log.error("uploadFile2Sftp error:", e);
            return Result.failed(e.getMessage());
        }
        return Result.ok();
    }

    @Deprecated
    private void removeTempFilePath(String tempFilePath) {
        //判断文件夹是否存在
        try {
            File directory = new File(tempFilePath);
            if (directory.isDirectory()) {
                FileUtils.deleteDirectory(directory);
            }
        } catch (IOException | CustomException e) {
            log.error("", e);
        }

    }

    @Deprecated
    private void handleData(String path, String fileName, String zipPassword) {
        //判断文件是否存在
        File directory = new File(path);
        File fileData = new File(directory, fileName);
        if (fileData.exists() && fileData.isFile()) {
            //解密文件
            try {
                //解密并解压文件
                ZipFile zipFile = new ZipFile(fileData);
                if (zipFile.isEncrypted()) {
                    //设置密码并解压
                    zipFile.setPassword(zipPassword.toCharArray());
                    zipFile.extractAll(directory.getAbsolutePath() + "/" + fileName.replaceAll(".zip", ""));
                } else {
                    zipFile.extractAll(directory.getAbsolutePath() + "/" + fileName.replaceAll(".zip", ""));
                }

            } catch (ZipException | CustomException e) {
                log.info("解密解压文件异常: " + e.getMessage());
            }
        }
    }

    @Override
    public Result syncGridBasicInfoXXL(String dateStr) {
        String path = SftpUtils.fetchGzFilesBetweenDates(dateStr, dateStr, "HQ_00001", "PSFT_FROM_BIGDT");
        return handleGrid(path, dateStr, dateStr);

    }

    @Override
    public Result syncGridBasicInfo(GridBasicInfoReq req) {
        String path = SftpUtils.fetchGzFilesBetweenDates(req.getStartDt(), req.getEndDt(), "HQ_00001", "PSFT_FROM_BIGDT");
        return handleGrid(path, req.getStartDt(), req.getEndDt());
    }

    public Result handleGrid(String path, String startDt, String endDt) {
        if (path == null) {
            return Result.failed("没有数据需要同步,总条数:0条,成功条数:0条,失败条数:0条");
        }

        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        // 将开始和结束日期字符串转换为 LocalDate
        LocalDate startDate = LocalDate.parse(startDt, formatter);
        LocalDate endDate = LocalDate.parse(endDt, formatter);

        boolean dataExists = false; // 用于标记是否有数据需要同步
        boolean isAllSuccess = true; // 用于标记所有文件是否同步成功
        Integer successCount = 0; // 成功同步的文件数量
        Integer failCount = 0; // 同步失败的文件数量

        // 从开始日期到结束日期遍历
        for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) {
            // 格式化当前日期
            String formattedDate = date.format(formatter);
            String filepath = path + formattedDate; // 设置本地文件路径
            //清空网格结果表
            LambdaUpdateWrapper<OrgGridInfoResult> wrapper = new LambdaUpdateWrapper<>();
            orgGridInfoResultService.remove(wrapper);
            File dir = new File(filepath);
            File[] files = dir.listFiles();

            // 处理找到的文件
            if (files != null && files.length > 0) {
                dataExists = true; // 标记有数据
                for (File file : files) {
                    // 获取文件内容
                    List<Map<String, String>> lineList = TxtUtil.readDatToMap(file.getAbsolutePath());
                    //成功获取文件内容处理
                    for (Map<String, String> lineMap : lineList) {
                        try {
                            OrgGridInfo orgGridInfo = JacksonUtil.getJsonToBean(JacksonUtil.getBeanToJson(lineMap), OrgGridInfo.class);
                            //获取CONDITON_TEXT
                            StringJoiner joiner = new StringJoiner("|");
                            for (String value : lineMap.values()) {
                                joiner.add(value);
                            }
                            String conditionText = joiner.toString();
                            //处理网格数据
                            Boolean checkRslt = handleGridInfo(orgGridInfo, file.getName(), conditionText);
                            if (!checkRslt) {
                                failCount += 1;
                                if (isAllSuccess) {
                                    isAllSuccess = false;
                                }
                            } else {
                                successCount += 1;
                            }
                        } catch (CustomException e) {
                            return Result.failed("同步数据报错,错误信息:" + e.getMessage());
                        }
                    }
                }
            }
        }

        Integer totalCount = successCount + failCount;
        // 如果没有数据需要同步,返回相应信息
        if (!dataExists) {
            return Result.failed("没有数据需要同步,总条数:0条,成功条数:0条,失败条数:0条");
        } else if (!isAllSuccess) {
            return Result.failed("数据同步中存在错误,总条数:" + totalCount + "条,成功条数:" + successCount + "条,失败条数:" + failCount + "条");
        } else {
            return Result.ok("数据同步成功,总条数:" + totalCount + "条,成功条数:" + successCount + "条,失败条数:" + failCount + "条");
        }
    }

    /**
     * 处理网格信息
     *
     * @param orgGridInfo
     * @param filename
     * @return
     * @throws IOException
     */
    private boolean handleGridInfo(OrgGridInfo orgGridInfo, String filename, String conditionText) {
        String strError = "";
        String errorType = "";
        boolean checkRslt = true;
        // 校验网格编码
        if (orgGridInfo.getGridCode().isEmpty()) {
            checkRslt = false;
            errorType = "999";
            strError += "网格编码为空;";
        }

        // 校验网格名称
        if (orgGridInfo.getGridName().isEmpty()) {
            checkRslt = false;
            errorType = "999";
            strError += "网格名称为空;";
        }

        // 校验省代码
        if (orgGridInfo.getProvince().isEmpty()) {
            checkRslt = false;
            errorType = "002";
            strError += "省代码为空;";
        } else {
            FfProvinceTbl fpt = ffProvinceTblService.lambdaQuery().eq(FfProvinceTbl::getFfProvince, orgGridInfo.getProvince()).one();
            if (fpt == null) {
                checkRslt = false;
                errorType = "999";
                strError += "省代码(" + orgGridInfo.getProvince() + ")未找到匹配的单位;";
            } else {
                if (fpt.getFfBusinessUnit() == null) {
                    checkRslt = false;
                    errorType = "999";
                    strError += "省代码(" + orgGridInfo.getProvince() + ")未找到匹配的单位;";
                }
            }
        }
        // 校验地市公司编码
        if (orgGridInfo.getCityCode().isEmpty()) {
            checkRslt = false;
            errorType = "999";
            strError += "地市公司编码为空;";
        }

        // 校验区县代码
        if (orgGridInfo.getCountryCode().isEmpty()) {
            checkRslt = false;
            errorType = "999";
            strError += "区县编码为空;";
        }

        // 校验网格属性
        if (orgGridInfo.getGridAttribute().isEmpty()) {
            checkRslt = false;
            errorType = "999";
            strError += "网格属性为空;";
        } else {
            Integer count = orgGridInfoService.selectCountByGridAtbt(orgGridInfo.getGridAttribute());
            if (count == 0) {
                checkRslt = false;
                errorType = "004";
                strError += "请确认网格属性(" + orgGridInfo.getGridAttribute() + ")是否正确;";
            }
        }

        // 校验网格类型
        if (orgGridInfo.getGridClass().isEmpty()) {
            checkRslt = false;
            errorType = "004";
            strError += "请确认网格归属分类是否为空;";
        } else {
            Integer count = orgGridInfoService.selectCountByGridClass(orgGridInfo.getGridClass());
            if (count == 0) {
                checkRslt = false;
                errorType = "004";
                strError += "请确认网格归属分类(" + orgGridInfo.getGridClass() + ")是否正确;";
            }
        }

        // 校验生效时间
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        if (orgGridInfo.getValidtime().isEmpty()) {
            checkRslt = false;
            errorType = "001";
            strError += "生效时间为空;";
        } else {
            try {
                LocalDateTime.parse(orgGridInfo.getValidtime(), formatter);
            } catch (DateTimeParseException e) {
                checkRslt = false;
                errorType = "001";
                strError += "生效时间" + orgGridInfo.getValidtime() + "日期时间值无效,请填入正确的生效时间;";
            }
        }

        // 校验失效时间
        if (!orgGridInfo.getInvalidtime().isEmpty()) {
            try {
                LocalDateTime.parse(orgGridInfo.getInvalidtime(), formatter);
            } catch (DateTimeParseException e) {
                checkRslt = false;
                errorType = "001";
                strError += "失效时间" + orgGridInfo.getInvalidtime() + "日期时间值无效,请填入正确的失效时间;";
            }
        } else {
            if (!orgGridInfo.getValidtime().isEmpty() && !orgGridInfo.getInvalidtime().isEmpty()) {
                LocalDate validTime = LocalDate.parse(orgGridInfo.getValidtime(), formatter);
                LocalDate invalidTime = LocalDate.parse(orgGridInfo.getInvalidtime(), formatter);
                // 检查生效时间和失效时间冲突
                if (invalidTime.isBefore(validTime)) {
                    checkRslt = false;
                    errorType = "999";
                    strError += "失效时间与生效时间冲突;";
                }
            }
        }

        // 校验数据日期是否为yyyyMMdd格式
        if (!orgGridInfo.getStatDate().matches("^\\d{4}(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$") && !orgGridInfo.getStatDate().isEmpty()) {
            checkRslt = false;
            errorType = "001";
            strError += "数据日期" + orgGridInfo.getStatDate() + "日期格式无效,请填入正确的数据日期;";
        }

        // 操作为空时默认更新
        if (orgGridInfo.getAction().isEmpty()) {
            orgGridInfo.setAction("2");
        }

        // 校验人力系统省编码
        if (orgGridInfo.getHumanProvince().isEmpty()) {
            checkRslt = false;
            errorType = "006";
            strError += "人力系统省编码为空;";
        }

        // 校验人力系统地市编码
        if (orgGridInfo.getHumanProvince().isEmpty()) {
            checkRslt = false;
            errorType = "007";
            strError += "人力系统地市编码为空;";
        }

        //网格信息写入网格信息表
        FfProvinceTbl fpt = ffProvinceTblService.lambdaQuery().eq(FfProvinceTbl::getFfProvince, orgGridInfo.getProvince()).one();
        if (fpt != null) {
            if (fpt.getFfBusinessUnit() != null) {
                orgGridInfo.setSetid(fpt.getFfBusinessUnit());
            }
        }
        orgGridInfo.setA0188(Integer.parseInt(Constants.CREATOR_ID));
        orgGridInfo.setCreationtime(new Date());
        orgGridInfo.setModifiedtime(new Date());
        orgGridInfo.setSigned(Constants.SIGNED_CODE_PASS);
        orgGridInfo.setCreator(Constants.CREATOR_ID);
        orgGridInfo.setModifier(Constants.CREATOR_ID);
        orgGridInfo.setFfpk(UUID.randomUUID().toString());

        //网格同步结果写入网格信息结果表
        OrgGridInfoResult orgGridInfoResult = new OrgGridInfoResult();
        orgGridInfoResult.setFileName(filename);
        orgGridInfoResult.setRecordNum(orgGridInfo.getRecordNum());
        orgGridInfoResult.setConditionText(conditionText);
        orgGridInfoResult.setIsSuccess("N");
        orgGridInfoResult.setGridCode(orgGridInfo.getGridCode());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        String formattedDateTime = sdf.format(now);
        orgGridInfoResult.setDatetime(formattedDateTime);

        //判断校验是否通过
        if (checkRslt) {
            orgGridInfo.setStatusCode("N");
            orgGridInfoResult.setErrorMessage("000");
            orgGridInfoResult.setErrorMessage("导入成功!");
        } else {
            orgGridInfo.setStatusCode("AE");
            orgGridInfo.setMessageDescr(strError);
            orgGridInfoResult.setImpStatus(errorType);
            orgGridInfoResult.setErrorMessage(strError);
        }

        //网格信息写入网格信息表
        LambdaUpdateWrapper<OrgGridInfo> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(OrgGridInfo::getGridCode, orgGridInfo.getGridCode());
        Long count = orgGridInfoService.count(wrapper);
        if (count > 0) {
            orgGridInfoService.update(orgGridInfo, wrapper);
        } else {
            orgGridInfo.setId(orgGridInfoService.selectSeq());
            orgGridInfoService.save(orgGridInfo);
        }

        //网格结果信息写入网格结果表
        LambdaUpdateWrapper<OrgGridInfoResult> wrapper1 = new LambdaUpdateWrapper<>();
        wrapper1.eq(OrgGridInfoResult::getGridCode, orgGridInfo.getGridCode());
        count = orgGridInfoResultService.count(wrapper1);
        if (count > 0) {
            orgGridInfoResultService.update(orgGridInfoResult, wrapper1);
        } else {
            orgGridInfoResult.setId(orgGridInfoResultService.selectSeq());
            orgGridInfoResultService.save(orgGridInfoResult);
        }
        return checkRslt;
    }

    @Override
    public Result uploadGridAnalysisResult() {
        //获取配置表目录地址
        Enterprisepension configData = enterprisepensionService.queryConfigData("PSFT_TO_BIGDT");
        String localPath = configData.getLocalPath();
        if (localPath == null) {
            return Result.failed("MFT文件本地存放路径为空!");
        }
        String remotePath = configData.getFilePath();
        //获取所有文件名
        List<OrgGridInfoResult> list = orgGridInfoResultService.query().list();
        Set<String> fileNameSet = list.stream()
                .map(OrgGridInfoResult::getFileName)
                .collect(Collectors.toSet());
        List<String> fileNames = fileNameSet.stream().collect(Collectors.toList());
        for (String filename : fileNames) {
            LambdaQueryWrapper<OrgGridInfoResult> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(OrgGridInfoResult::getIsSuccess, "N");
            list = orgGridInfoResultService.list(wrapper);
            String filePath = localPath + "/" + filename;
            File directory = new File(localPath);
            File file = new File(filePath);
            // 创建目录和文件
            if (!directory.exists()) {
                directory.mkdirs();
            }
            // 写入数据
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
                for (OrgGridInfoResult data : list) {
                    String line = String.join(",",
                            String.valueOf(data.getRecordNum()),
                            data.getGridCode(),
                            data.getIsSuccess(),
                            data.getErrorMessage(),
                            data.getDatetime(),
                            data.getConditionText()
                    );
                    writer.write(line);
                    writer.newLine();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            //压缩文件
            try {
                GzipUtil.compressGzipFile(filePath, filePath + ".gz");
            } catch (IOException e) {
                e.printStackTrace();
            }
            //上传文件
            SftpUtil.sftpUploadFile(configData.getIpAddress(), configData.getCPort(), configData.getUserid(), configData.getPassword(), remotePath, filePath + ".gz", remotePath + "/" + filename + ".gz");
        }
        return Result.ok();
    }

    @Override
    public Result mftXfeIhrNWorkTimSheCostAllSrv(MftHrCoreHq00106Req req) {
        String nsCsvLocalPath = C_NS_LOCAL_BASE_PATH + "ns-local-ft-" + DateUtils.getDate();
        List<MftHrCoreHq00106Res> byCalPrdId = cNrdDtlService.getByCalPrdId(req.getCalPrdId());
        Enterprisepension writeConfig = enterprisepensionService.queryConfigData("PSFT_TO_CRP");
        String csvPath = nsCsvLocalPath + "/" + "csv";
        String zipPath = nsCsvLocalPath + "/" + "zip";
        if (writeConfig == null) {
            return Result.failed("PSFT配置不存在,请配置后重试");
        }
        // todo 逻辑待确认
        FileUtil.cleanFile(nsCsvLocalPath);
        Map<String, List<MftHrCoreHq00106Res>> proMap = new HashMap<>();
        if (!byCalPrdId.isEmpty()) {
            proMap = groupByProvince(byCalPrdId);
            if (!CollectionUtils.isEmpty(proMap)) {
                File directory = new File(csvPath);
                directory.mkdirs();
                proMap.forEach((proKey, resList) -> {
                    String csvFileName = csvPath + "/" + proKey + "_" + req.getCalPrdId() + ".csv";
                    CsvUtil.exportCsv(resList, MftHrCoreHq00106Res.class, csvFileName);
                });
                // 推送
                try {
                    Files.createDirectories(Paths.get(zipPath));
                    String zipName = "MftIhrNWorkTimeSheetCostAllocationSrv_" + req.getCalPrdId() + ".zip";
                    SftpUtil.sftpUploadFile(writeConfig.getIpAddress(), writeConfig.getCPort(), writeConfig.getUserid(), writeConfig.getPassword(),
                            writeConfig.getFilePath(), zipPath + "/" + zipName, writeConfig.getFilePath() + zipName);
                } catch (IOException e) {
                    log.error("IT公司非研发工时成本分摊信息传输服务 推送文件失败", e);
                }
            }
        }
        return Result.ok();
    }

    private Map<String, List<MftHrCoreHq00106Res>> groupByProvince(List<MftHrCoreHq00106Res> byCalPrdId) {
        Map<String, List<MftHrCoreHq00106Res>> proMap = new HashMap<>();
        if (!byCalPrdId.isEmpty()) {
            byCalPrdId.forEach(e -> {
                String province = b01FrgsService.getProvinceByCompany(e.getCompany());
                if (org.apache.commons.lang3.StringUtils.isNotBlank(province)) {
                    List<MftHrCoreHq00106Res> mftHrCoreHq00106Res = proMap.get(province);
                    if (CollectionUtils.isEmpty(mftHrCoreHq00106Res)) {
                        mftHrCoreHq00106Res = new ArrayList<>();
                        proMap.put(province, mftHrCoreHq00106Res);
                    }
                    mftHrCoreHq00106Res.add(e);
                }
            });
        }
        return proMap;
    }

    @Override
    public Result financeProfessionalSkill() {
        List<WsTaskLog> wsTaskLogList = wsTaskLogService.lambdaQuery().eq(WsTaskLog::getTablename, "A827").list();
        List<Integer> ids = wsTaskLogList.stream().map(i -> Integer.parseInt(i.getPrimarykey())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(ids)) {
            return Result.ok("没有需要同步的数据");
        }
        List<MftHrCoreHq00074Res> mftHrCoreHq00074ResList = a827Service.selectByIds(ids);

        // 创建 ObjectMapper 实例
        ObjectMapper objectMapper = new ObjectMapper();
        // 指定文件路径
        String filename = "MFT_HR_CORE_HQ_00074_" + DateUtils.getDate() + mftHrCoreHq00074ResList.size() + ".TXT";
        String filePath = "D:\\" + filename;
        File file = new File(filePath);
        // 写入txt文件
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
            for (MftHrCoreHq00074Res mftHrCoreHq00074Res : mftHrCoreHq00074ResList) {
                // 将每个MftHrCoreHq00074Res对象转换为JSON字符串
                String json = objectMapper.writeValueAsString(mftHrCoreHq00074Res);
                // 写入文件
                writer.write(json);
                writer.newLine(); // 添加换行符
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        Enterprisepension configData = enterprisepensionService.queryConfigData("PSFT_TO_CWJY");
        if (ObjectUtil.isNull(configData)) {
            return Result.failed("PSFT配置不存在,请配置后重试");
        }
        //上传
        SftpUtil.sftpUploadFile(configData.getIpAddress(), configData.getCPort(), configData.getUserid(),
                configData.getPassword(), configData.getFilePath(), filePath, configData.getFilePath() + "/" + filename);

        //清空本地文件
        FileUtil.cleanFile(filePath);

        updateWrapperList(ids);
        return Result.ok();
    }


    @Override
    public Result financeVocationalSkills() {
        List<WsTaskLog> wsTaskLogList = wsTaskLogService.lambdaQuery().eq(WsTaskLog::getTablename, "A843").list();
        List<Integer> ids = wsTaskLogList.stream().map(i -> Integer.parseInt(i.getPrimarykey())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(ids)) {
            return Result.ok("没有需要同步的数据");
        }
        List<MftHrCoreHq00073Res> mftHrCoreHq00073ResList = a843Service.selectByIds(ids);
        // 创建 ObjectMapper 实例
        ObjectMapper objectMapper = new ObjectMapper();
        // 指定文件路径
        String filename = "MFT_HR_CORE_HQ_00073_" + DateUtils.getDate() + mftHrCoreHq00073ResList.size() + ".TXT";
        String filePath = "D:\\" + filename;
        File file = new File(filePath);
        // 写入txt文件
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
            for (MftHrCoreHq00073Res mftHrCoreHq00073Res : mftHrCoreHq00073ResList) {
                // 将每个MftHrCoreHq00073Res对象转换为JSON字符串
                String json = objectMapper.writeValueAsString(mftHrCoreHq00073Res);
                // 写入文件
                writer.write(json);
                writer.newLine(); // 添加换行符
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        Enterprisepension configData = enterprisepensionService.queryConfigData("PSFT_TO_CWJY");
        if (ObjectUtil.isNull(configData)) {
            return Result.failed("PSFT配置不存在,请配置后重试");
        }
        //上传
        SftpUtil.sftpUploadFile(configData.getIpAddress(), configData.getCPort(), configData.getUserid(),
                configData.getPassword(), configData.getFilePath(), filePath, configData.getFilePath() + "/" + filename);

        //清空本地文件
        FileUtil.cleanFile(filePath);

        updateWrapperList(ids);
        return Result.ok();
    }

    @Override
    public Result financePersonalInformation() {
        List<WsTaskLog> wsTaskLogList = wsTaskLogService.lambdaQuery().eq(WsTaskLog::getTablename, "VIEW_A01").list();
        List<Integer> ids = wsTaskLogList.stream().map(i -> Integer.parseInt(i.getPrimarykey())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(ids)) {
            return Result.ok("没有需要同步的数据");
        }
        List<MftHrCoreHq00071Res> mftHrCoreHq00071ResList = a01Service.selectByIds(ids);
        // 创建 ObjectMapper 实例
        ObjectMapper objectMapper = new ObjectMapper();
        // 指定文件路径
        String filename = "MFT_HR_CORE_HQ_00071_" + DateUtils.getDate() + mftHrCoreHq00071ResList.size() + ".TXT";
        String filePath = "D:\\" + filename;
        File file = new File(filePath);
        // 写入txt文件
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
            for (MftHrCoreHq00071Res mftHrCoreHq00071Res : mftHrCoreHq00071ResList) {
                // 将每个MftHrCoreHq00071Res对象转换为JSON字符串
                String json = objectMapper.writeValueAsString(mftHrCoreHq00071Res);
                // 写入文件
                writer.write(json);
                writer.newLine(); // 添加换行符
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        Enterprisepension configData = enterprisepensionService.queryConfigData("PSFT_TO_CWJY");
        if (ObjectUtil.isNull(configData)) {
            return Result.failed("PSFT配置不存在,请配置后重试");
        }
        //上传
        SftpUtil.sftpUploadFile(configData.getIpAddress(), configData.getCPort(), configData.getUserid(),
                configData.getPassword(), configData.getFilePath(), filePath, configData.getFilePath() + "/" + filename);

        //清空本地文件
        FileUtil.cleanFile(filePath);

        updateWrapperList(ids);
        return Result.ok();
    }

    @Override
    public Result financeLanguageCompetence() {
        List<WsTaskLog> wsTaskLogList = wsTaskLogService.lambdaQuery().eq(WsTaskLog::getTablename, "A844").eq(WsTaskLog::getStatue, "0").list();
        List<Integer> ids = wsTaskLogList.stream().map(i -> Integer.parseInt(i.getPrimarykey())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(ids)) {
            return Result.ok("没有需要同步的数据");
        }
        List<MftHrCoreHq00072Res> mftHrCoreHq00072ResList = a844Service.selectByIds(ids);
        // 创建 ObjectMapper 实例
        ObjectMapper objectMapper = new ObjectMapper();
        // 指定文件路径
        String filename = "MFT_HR_CORE_HQ_00072_" + DateUtils.getDate() + mftHrCoreHq00072ResList.size() + ".TXT";
        String filePath = "D:\\" + filename;
        File file = new File(filePath);
        // 写入txt文件
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
            for (MftHrCoreHq00072Res mftHrCoreHq00072Res : mftHrCoreHq00072ResList) {
                // 将每个MftHrCoreHq00072Res对象转换为JSON字符串
                String json = objectMapper.writeValueAsString(mftHrCoreHq00072Res);
                // 写入文件
                writer.write(json);
                writer.newLine(); // 添加换行符
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        Enterprisepension configData = enterprisepensionService.queryConfigData("PSFT_TO_CWJY");
        if (ObjectUtil.isNull(configData)) {
            return Result.failed("PSFT配置不存在,请配置后重试");
        }
        //上传
        SftpUtil.sftpUploadFile(configData.getIpAddress(), configData.getCPort(), configData.getUserid(),
                configData.getPassword(), configData.getFilePath(), filePath, configData.getFilePath() + "/" + filename);
        //清空本地文件
        FileUtil.cleanFile(filePath);

        updateWrapperList(ids);
        return Result.ok();
    }

    @Override
    public Result financeOccupationalQualifications() {
        List<WsTaskLog> wsTaskLogList = wsTaskLogService.lambdaQuery().eq(WsTaskLog::getTablename, "A842").eq(WsTaskLog::getStatue, "0").list();
        List<Integer> ids = wsTaskLogList.stream().map(i -> Integer.parseInt(i.getPrimarykey())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(ids)) {
            return Result.ok("没有需要同步的数据");
        }

        List<MftHrCoreHq00069Res> mftHrCoreHq00069ResList = a842Service.selectByIds(ids);
        // 创建 ObjectMapper 实例
        ObjectMapper objectMapper = new ObjectMapper();
        // 指定文件路径
        String filename = "MFT_HR_CORE_HQ_00069_" + DateUtils.getDate() + mftHrCoreHq00069ResList.size() + ".TXT";
        String filePath = "D:\\" + filename;
        File file = new File(filePath);
        // 写入txt文件
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
            for (MftHrCoreHq00069Res mftHrCoreHq00069Res : mftHrCoreHq00069ResList) {
                // 将每个MftHrCoreHq00072Res对象转换为JSON字符串
                String json = objectMapper.writeValueAsString(mftHrCoreHq00069Res);
                // 写入文件
                writer.write(json);
                writer.newLine(); // 添加换行符
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        Enterprisepension configData = enterprisepensionService.queryConfigData("PSFT_TO_CWJY");
        if (ObjectUtil.isNull(configData)) {
            return Result.failed("PSFT配置不存在,请配置后重试");
        }
        //上传
        SftpUtil.sftpUploadFile(configData.getIpAddress(), configData.getCPort(), configData.getUserid(),
                configData.getPassword(), configData.getFilePath(), filePath, configData.getFilePath() + "/" + filename);
        //清空本地文件
        FileUtil.cleanFile(filePath);

        updateWrapperList(ids);
        return Result.ok();
    }

    public void updateWrapperList(List<Integer> ids) {
        //修改 WS_TASK_LOG状态
        UpdateWrapper<WsTaskLog> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("primaryKey", ids);

        // 设置要更新的字段
        WsTaskLog updateTaskLog = new WsTaskLog();
        updateTaskLog.setStatue("1");
//        updateTaskLog.setSynctime(DateUtils.getNowDate());
        // 执行批量更新
        wsTaskLogService.update(updateTaskLog, updateWrapper);
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值