package com.chinaweal.aiccs.schedule;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.XML;
import com.chinaweal.aiccs.utils.TypeConversionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chinaweal.aiccs.aicbizqy.entity.datamove.*;
import com.chinaweal.aiccs.aicbizqy.mapper.datamove.*;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSAbnList;
import com.chinaweal.aiccs.aiccs.abnormal.entity.datamove.*;
import com.chinaweal.aiccs.aiccs.abnormal.mapper.datamove.*;
import com.chinaweal.aiccs.aiccs.abnormal.service.TSAbnListService;
import com.chinaweal.aiccs.aicepsqy.entity.datamove.*;
import com.chinaweal.aiccs.aicepsqy.mapper.datamove.*;
import com.chinaweal.aiccs.crgs.entity.EMoveIn;
import com.chinaweal.aiccs.crgs.mapper.EMoveInMapper;
import com.chinaweal.aiccs.aiccs.abnormal.mapper.FileUploadRecordMapper;
import com.chinaweal.aiccs.aiccs.abnormal.entity.FileUploadRecord;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.InputStream;
import java.io.ByteArrayInputStream;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.util.*;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.time.LocalDate;
import java.time.ZoneId;
import java.text.SimpleDateFormat;
import java.util.Date;
import cn.hutool.json.JSONUtil;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * 迁入省局数据定时任务
 * 功能：查询需要迁入的企业，下载ZIP文件，解析XML数据并插入到对应表
 *
 * @author Claude
 */
@Component
@ConditionalOnProperty(prefix = "scheduling", name = "enable", havingValue = "true")
@Slf4j
public class MoveInDataSchedule {

    @Autowired
    private EMoveInMapper eMoveInMapper;

    @Autowired
    private FileUploadRecordMapper fileUploadRecordMapper;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private EBaseInfoDataMoveMapper eBaseInfoMapper;

    // 主要企业信息表Mapper
    @Autowired
    private EBaseInfoDataMoveMapperAiccs eBaseInfoMapperAiccs;
    @Autowired
    private EAlterRecoderDataMoveMapperAiccs eAlterRecoderMapperAiccs;
    @Autowired
    private EImPermitDataMoveMapperAiccs eImPermitMapperAiccs;
    @Autowired
    private EOtSpotcheckDataMoveMapperAiccs eOtSpotcheckMapperAiccs;
    @Autowired
    private EPubSpotcheckDataMoveMapperAiccs ePubSpotcheckMapperAiccs;
    @Autowired
    private DrRaninsresDataMoveMapperAiccs drRaninsresMapperAiccs;
    @Autowired
    private AoOpAnomalyDataMoveMapperAiccs aoOpAnomalyMapperAiccs;
    @Autowired
    private AoOpaDetailDataMoveMapperAiccs aoOpaDetailMapperAiccs;
    @Autowired
    private AoOpAnomalyInvDataMoveMapperAiccs aoOpAnomalyInvMapperAiccs;
    @Autowired
    private AnBaseinfoDataMoveMapperAiccs anBaseinfoMapperAiccs;
    @Autowired
    private EImInvestmentDataMoveMapperAiccs eImInvestmentMapperAiccs;
    @Autowired
    private EImInvupdateDataMoveMapperAiccs eImInvupdateMapperAiccs;
    @Autowired
    private CaseCreInformationDataMoveMapperAiccs caseCreInformationMapperAiccs;
    @Autowired
    private EImIppldgDataMoveMapperAiccs eImIppldgMapperAiccs;
    @Autowired
    private EImCaseDataMoveMapperAiccs eImCaseMapperAiccs;
    @Autowired
    private EImInvsraltDataMoveMapperAiccs eImInvsraltMapperAiccs;
    @Autowired
    private ELiIlldishonestyDataMoveMapperAiccs eLiIlldishonestyMapperAiccs;
    @Autowired
    private ELiIlldisdetailDataMoveMapperAiccs eLiIlldisdetailMapperAiccs;
    @Autowired
    private CasePubNbaseinfoDataMoveMapperAiccs casePubNbaseinfoMapperAiccs;
    @Autowired
    private EOtNpermitDataMoveMapperAiccs eOtNpermitMapperAiccs;
    @Autowired
    private EOtNcaseDataMoveMapperAiccs eOtNcaseMapperAiccs;

    // AN相关表Mapper
    @Autowired
    private AnSubcapitalDataMoveMapperAiccs anSubcapitalMapperAiccs;
    @Autowired
    private AnForinvestmentDataMoveMapperAiccs anForinvestmentMapperAiccs;
    @Autowired
    private AnWebsiteinfoDataMoveMapperAiccs anWebsiteinfoMapperAiccs;
    @Autowired
    private AnAlterstockinfoDataMoveMapperAiccs anAlterstockinfoMapperAiccs;
    @Autowired
    private AnForguaranteeinfoDataMoveMapperAiccs anForguaranteeinfoMapperAiccs;
    @Autowired
    private AnUpdateinfoDataMoveMapperAiccs anUpdateinfoMapperAiccs;
    @Autowired
    private AnSupBaseinfoDataMoveMapperAiccs anSupBaseinfoMapperAiccs;
    @Autowired
    private AnSocsecinfoDataMoveMapperAiccs anSocsecinfoMapperAiccs;

    // 其他关联表Mapper
    @Autowired
    private EImPrmtaltDataMoveMapperAiccs eImPrmtaltMapperAiccs;
    @Autowired
    private EOtNprmtaltDataMoveMapperAiccs eOtNprmtaltMapperAiccs;
    @Autowired
    private EImInvprodetailDataMoveMapperAiccs eImInvprodetailMapperAiccs;
    @Autowired
    private EImInvactdetailDataMoveMapperAiccs eImInvactdetailMapperAiccs;
    @Autowired
    private EImIppldgaltDataMoveMapperAiccs eImIppldgaltMapperAiccs;
    @Autowired
    private EImCasaltDataMoveMapperAiccs eImCasaltMapperAiccs;
    @Autowired
    private CasePubNdocDataMoveMapperAiccs casePubNdocMapperAiccs;
    @Autowired
    private CasePubNalterDataMoveMapperAiccs casePubNalterMapperAiccs;
    @Autowired
    private EOtNcasaltDataMoveMapperAiccs eOtNcasaltMapperAiccs;
    @Autowired
    private TSAbnListService tsAbnListService;
    @Autowired
    private TREntBaseInfoTempMapper trEntBaseInfoTempMapper;
    @Autowired
    private CapitalModelMapper capitalModelMapper;
    @Autowired
    private AssetModelMapper assetModelMapper;
    @Autowired
    private PartyBuildInfoMapper partyBuildInfoMapper;
    @Autowired
    private SocialSecurityMapper socialSecurityMapper;
    @Autowired
    private IndividualReportMapper individualReportMapper;
    @Autowired
    private EntWebMapper entWebMapper;
    @Autowired
    private TaskInfoMapper taskInfoMapper;
    @Autowired
    private StockTransferMapper stockTransferMapper;
    @Autowired
    private TRGuarantyMapper trGuarantyMapper;
    @Autowired
    private InvestmentEntMapper investmentEntMapper;
    @Autowired
    private TrcorrectionsMapper trCorrectionsMapper;

    // 基础数据输入目录
//    private final String BASE_INPUT_DIR = "D:\\data";
    private final String BASE_INPUT_DIR = "/data/upload";
    @Value("${forest.variables.fileUpload.env}")
    private String env;
    @Value("${forest.variables.fileUpload.appform}")
    private String appform;
    @Value("${forest.variables.fileUpload.testUrl}")
    private String testUrl;
    @Value("${forest.variables.fileUpload.prodUrl}")
    private String prodUrl;
    @Value("${forest.variables.fileUpload.testDownloadUrl}")
    private String testDownloadUrl;
    @Value("${forest.variables.fileUpload.prodDownloadUrl}")
    private String prodDownloadUrl;
    @Value("${forest.variables.fileUpload.testMoveInRecordUrl}")
    private String testMoveInRecordUrl;
    @Value("${forest.variables.fileUpload.prodMoveInRecordUrl}")
    private String prodMoveInRecordUrl;
    @Value("${forest.variables.fileUpload.testQueryRegisterInfoUrl}")
    private String testQueryRegisterInfoUrl;
    @Value("${forest.variables.fileUpload.prodQueryRegisterInfoUrl}")
    private String prodQueryRegisterInfoUrl;
    @Value("${forest.variables.fileUpload.testDownloadRecordInfoUrl}")
    private String testDownloadRecordInfoUrl;
    @Value("${forest.variables.fileUpload.prodDownloadRecordInfoUrl}")
    private String prodDownloadRecordInfoUrl;

    /**
     * 定时任务方法 - 每天凌晨2点执行
     */
    @Scheduled(cron = "${scheduling.cron.moveInData}")
    public void executeMoveInData() {
        log.info("开始执行迁入省局数据定时任务...");

        try {
            // 第一步：查询需要迁入的企业
            List<EMoveIn> moveInList = queryMoveInEnterprises();
            log.info("查询到{}条需要迁入的企业记录", moveInList.size());

//            moveInList = null;
//            if (CollUtil.isEmpty(moveInList)) {
//                log.info("没有需要迁入的企业数据，任务结束");
//                return;
//            }

            // 第二步：遍历企业处理迁入数据
            int successCount = 0;
            int failureCount = 0;

            for (EMoveIn moveIn : moveInList) {
                try {
                    // 检查企业是否已经迁入成功
                    int movedInSuccessCount = fileUploadRecordMapper.countMoveInSuccessByPripid(moveIn.getPripid(),moveIn.getMinId());
                    if (movedInSuccessCount > 0) {
                        log.info("企业PRIPID={}已经迁入成功，跳过此次迁入处理", moveIn.getPripid());
                        continue;
                    }

                    // 第一阶段：查询企业基本信息
                    String entBaseInfo = queryEnterpriseBaseInfo(moveIn.getPripid());
                    if (entBaseInfo == null) {
                        log.error("企业PRIPID={}未查询到基本信息，跳过处理", moveIn.getPripid());
                        continue;
                    }

                    // 解析企业信息
                    String[] infoParts = entBaseInfo.split("\\|");
                    if (infoParts.length < 2) {
                        log.error("企业PRIPID={}基本信息格式错误，entBaseInfo={}", moveIn.getPripid(), entBaseInfo);
                        continue;
                    }
                    String uniscid = infoParts[0];
                    String entname = infoParts[1];

                    log.info("企业信息：PRIPID={}, UNISCID={}, ENTNAME={}", moveIn.getPripid(), uniscid, entname);

                    // 第一阶段成功：查询企业信息成功
                    String stage1SuccessMsg = String.format("企业%s查询基本信息成功，PRIPID=%s", uniscid, moveIn.getPripid());
                    String processRecord1 = "查询企业信息成功：" + stage1SuccessMsg;
                    recordFileUploadResult(moveIn.getPripid(), null, "Y", processRecord1, null, moveIn.getMinId());

                    // 第二阶段：下载ZIP文件
                    String currentDate = DateUtil.format(new Date(), "yyyyMMdd");
                    String zipFileName = uniscid + "-QYXYXX-" + currentDate + ".zip";
                    File zipFile = downloadZipFile(uniscid, zipFileName, currentDate, moveIn.getPripid(), moveIn.getMinId());

                    if (zipFile != null && zipFile.exists()) {
                        // 第二阶段成功：下载ZIP文件成功
                        String stage2SuccessMsg = String.format("企业%s下载ZIP文件成功：%s", uniscid, zipFile.getAbsolutePath());
                        String processRecord2 = "下载ZIP文件成功：" + stage2SuccessMsg;
                        recordFileUploadResult(moveIn.getPripid(), zipFile.getAbsolutePath(), "Y", processRecord2, null, moveIn.getMinId());

                        log.info("企业{}下载ZIP文件成功：{}", uniscid, zipFile.getAbsolutePath());

                        // 第三阶段：解析ZIP文件并插入数据
                        try {
                            // 解析ZIP文件
                            Map<String, List<?>> parsedDataMap = parseZipFile(zipFile, uniscid);
                            Map<String, Integer> recordCountMap = new HashMap<>();

                            if (!parsedDataMap.isEmpty()) {
                                // 将解析后的数据保存到独立的List集合中
                                Map<String, List<?>> tableDataLists = extractTableDataLists(parsedDataMap);
                                log.info("企业{}数据已保存到独立List集合中，共{}种数据类型", uniscid, tableDataLists.size());

                                // 统计各表数据量
                                for (Map.Entry<String, List<?>> entry : parsedDataMap.entrySet()) {
                                    recordCountMap.put(entry.getKey(), entry.getValue().size());
                                }

                                log.info("企业{}解析ZIP文件完成，包含{}种数据类型", uniscid, parsedDataMap.size());
                                log.info("企业{}各表数据统计：{}", uniscid, recordCountMap);

                                // 插入数据到对应表
                                boolean insertSuccess = insertDataToTables(parsedDataMap, uniscid);

                                if (insertSuccess) {
                                    // 第三阶段成功：数据插入成功
                                    String stage3SuccessMsg = String.format("企业%s数据插入成功，共处理%s种数据类型", uniscid, parsedDataMap.size());
                                    String processRecord3 = "数据插入成功：" + stage3SuccessMsg;

                                    // 构建对账参数JSON字符串
                                    // 对于迁入任务，moutareregorg 为迁出地区编号（从 moveIn 表的 Moutareregorg 字段获取）
                                    String moutareregorg = moveIn.getMoutareregorg() != null ? moveIn.getMoutareregorg() : "440000";
                                    // moveInProvince 为迁入省份，使用配置中的固定值
                                    // moveOutProvince 为迁出省份，使用 moutareregorg 作为迁出省份

                                    String reconciliationPar = buildReconciliationParams(uniscid, entname, recordCountMap, moutareregorg);

                                    // 记录第三阶段状态
                                    recordFileUploadResult(moveIn.getPripid(), zipFile.getAbsolutePath(), "Y", processRecord3, reconciliationPar, moveIn.getMinId());

                                    log.info("企业{}数据插入成功", uniscid);

                                    // 第四阶段：先调用下载对账接口，再调用上传对账接口
                                    try {
                                        // 先调用下载对账接口
                                        // moveInProvince 使用配置中的固定值 "440000"（广东省）
                                        // moveOutProvince 使用迁出地区编号 moutareregorg
                                        // 从 tableDataLists 中的 E_BASEINFO 表获取企业名称
                                        String entnameFromTableData = getEntnameFromTableDataLists(tableDataLists);
                                        String downloadApiEntname = entnameFromTableData.isEmpty() ? entname : entnameFromTableData;
                                        log.info("使用企业名称调用下载对账接口：从数据库获取={}, 从tableDataLists获取={}, 最终使用={}",
                                            entname, entnameFromTableData, downloadApiEntname);

                                        JSONObject downloadRecordResponse = callDownloadRecordInfoApi(uniscid, downloadApiEntname, "440000", moutareregorg, moutareregorg);

                                        QueryWrapper<FileUploadRecord> wrapper = new QueryWrapper<>();
                                        wrapper.eq("MIN_ID", moveIn.getMinId());
                                        List<FileUploadRecord> fileUploadRecordList = fileUploadRecordMapper.selectList(wrapper);
                                        FileUploadRecord fileUploadRecord = fileUploadRecordList.get(0);
                                        fileUploadRecord.setEntNamebf(downloadApiEntname);
                                        fileUploadRecordMapper.updateById(fileUploadRecord);

                                        if (downloadRecordResponse != null) {
                                            // 下载对账接口成功，现在调用上传对账接口
                                            try {
                                                callRecordInfoApi(uniscid, downloadApiEntname, recordCountMap, moutareregorg);

                                                // 两个接口都成功：对账流程完成
                                                String stage4SuccessMsg = String.format("企业%s数据对账成功，下载和上传对账接口都已完成", uniscid);
                                                String processRecord4 = "对账流程完成：" + stage4SuccessMsg;

                                                // 拼接两个JSON，用分隔符区分
                                                String combinedReconciliationPar = "DOWNLOAD_RECORD:" + downloadRecordResponse.toString() +
                                                    "|||UPLOAD_RECORD:" + reconciliationPar;

                                                // 记录第四阶段成功状态
                                                recordFileUploadResult(moveIn.getPripid(), zipFile.getAbsolutePath(), "Y", processRecord4, combinedReconciliationPar, moveIn.getMinId());

                                                log.info("企业{}对账流程完成（下载+上传都成功）", uniscid);
                                                successCount++;

                                                //第五阶段把获取的数据插到对应的数据库表中
                                                boolean flag = insertXt(tableDataLists,moveIn.getPripid());
                                                if (flag) {
                                                    // 第五阶段成功：数据插入到系统成功
                                                    String stage5SuccessMsg = String.format("企业%s数据插入到系统成功", uniscid);
                                                    String processRecord5 = "数据插入系统成功：" + stage5SuccessMsg;
                                                    recordFileUploadResult(moveIn.getPripid(), zipFile.getAbsolutePath(), "Y", processRecord5, combinedReconciliationPar, moveIn.getMinId());
                                                    log.info("企业{}第五阶段数据插入到系统成功", uniscid);
                                                } else {
                                                    // 第五阶段失败：数据插入到系统失败
                                                    String stage5FailedMsg = String.format("企业%s数据插入到系统失败", uniscid);
                                                    String processRecord5 = "数据插入系统失败：" + stage5FailedMsg;
                                                    recordFileUploadResult(moveIn.getPripid(), zipFile.getAbsolutePath(), "N", processRecord5, combinedReconciliationPar, moveIn.getMinId());
                                                    log.error("企业{}第五阶段数据插入到系统失败", uniscid);
                                                }
                                            } catch (Exception e) {
                                                // 上传对账接口失败
                                                String errorMsg = e.getMessage() != null && e.getMessage().length() <= 2000 ?
                                                    e.getMessage() : "上传对账接口调用失败，具体错误信息超过2000字符限制";
                                                String stage4FailedMsg = String.format("企业%s上传对账失败，错误：%s", uniscid, errorMsg);
                                                String processRecord4 = "上传对账接口失败：" + stage4FailedMsg;

                                                // 下载成功但上传失败，只记录下载的JSON
                                                String combinedReconciliationPar = "DOWNLOAD_RECORD:" + downloadRecordResponse.toString() +
                                                    "|||UPLOAD_RECORD:FAILED";

                                                // 记录第四阶段失败状态
                                                recordFileUploadResult(moveIn.getPripid(), zipFile.getAbsolutePath(), "N", processRecord4, combinedReconciliationPar, moveIn.getMinId());

                                                log.error("企业{}上传对账接口调用失败：{}", uniscid, e);
                                                failureCount++;
                                            }
                                        } else {
                                            // 下载对账接口失败，记录失败状态
                                            String stage4FailedMsg = String.format("企业%s下载对账接口失败，无法继续上传对账", uniscid);
                                            String processRecord4 = "下载对账接口失败：" + stage4FailedMsg;

                                            // 记录第四阶段失败状态
                                            recordFileUploadResult(moveIn.getPripid(), zipFile.getAbsolutePath(), "N", processRecord4, reconciliationPar, moveIn.getMinId());

                                            log.error("企业{}下载对账接口失败", uniscid);
                                            failureCount++;
                                        }
                                    } catch (Exception e) {
                                        // 下载对账接口调用异常
                                        String errorMsg = e.getMessage() != null && e.getMessage().length() <= 2000 ?
                                            e.getMessage() : "下载对账接口调用异常，具体错误信息超过2000字符限制";
                                        String stage4FailedMsg = String.format("企业%s下载对账接口异常，错误：%s", uniscid, errorMsg);
                                        String processRecord4 = "下载对账接口异常：" + stage4FailedMsg;

                                        // 记录第四阶段失败状态
                                        recordFileUploadResult(moveIn.getPripid(), zipFile.getAbsolutePath(), "N", processRecord4, reconciliationPar, moveIn.getMinId());

                                        log.error("企业{}下载对账接口调用异常：{}", uniscid, e);
                                        failureCount++;
                                    }
                                } else {
                                    // 第三阶段失败：数据插入失败
                                    String stage3FailedMsg = String.format("企业%s数据插入失败", uniscid);
                                    String processRecord3 = "数据插入失败：" + stage3FailedMsg;

                                    // 记录第三阶段失败状态
                                    recordFileUploadResult(moveIn.getPripid(), zipFile.getAbsolutePath(), "N", processRecord3, null, moveIn.getMinId());

                                    log.error("企业{}数据插入失败", uniscid);
                                    failureCount++;
                                }


                            } else {
                                // 第三阶段失败：ZIP文件解析失败或无数据
                                String stage3FailedMsg = String.format("企业%sZIP文件解析失败或无数据", uniscid);
                                String processRecord3 = "数据解析失败：" + stage3FailedMsg;

                                // 记录第三阶段失败状态
                                recordFileUploadResult(moveIn.getPripid(), zipFile.getAbsolutePath(), "N", processRecord3, null, moveIn.getMinId());

                                log.error("企业{}ZIP文件解析失败或无数据", uniscid);
                                failureCount++;
                            }

                        } catch (Exception e) {
                            // 第三阶段失败：解析或插入数据时发生异常
                            String errorMsg = e.getMessage() != null && e.getMessage().length() <= 2000 ?
                                e.getMessage() : "数据处理失败，具体错误信息超过2000字符限制";
                            String stage3FailedMsg = String.format("企业%s数据处理失败，错误：%s", uniscid, errorMsg);
                            String processRecord3 = "数据处理异常：" + stage3FailedMsg;

                            // 记录第三阶段失败状态
                            recordFileUploadResult(moveIn.getPripid(), zipFile.getAbsolutePath(), "N", processRecord3, null, moveIn.getMinId());

                            log.error("企业{}解析或插入数据时发生错误：{}", uniscid, e);
                            failureCount++;
                        }
                    } else {
                        // 第二阶段失败：下载ZIP文件失败
                        String stage2FailedMsg = String.format("企业%s下载ZIP文件失败：%s", uniscid, zipFileName);
                        String processRecord2 = "下载ZIP文件失败：" + stage2FailedMsg;

                        String failedPath = buildEnterpriseInputDir(uniscid, currentDate) + File.separator + zipFileName;

                        // 记录第二阶段失败状态
                        recordFileUploadResult(moveIn.getPripid(), failedPath, "N", processRecord2, null, moveIn.getMinId());

                        log.error("企业{}下载ZIP文件失败", uniscid);
                        failureCount++;
                    }

                } catch (Exception e) {
                    // 记录异常失败状态
                    String errorMsg = e.getMessage() != null && e.getMessage().length() <= 2000 ?
                        e.getMessage() : "数据处理失败，具体错误信息超过2000字符限制";
                    String processRecord = String.format("异常处理失败：企业PRIPID=%s数据处理失败，错误：%s", moveIn.getPripid(), errorMsg);

                    // 记录异常失败状态
                    recordFileUploadResult(moveIn.getPripid(), null, "N", processRecord, null, moveIn.getMinId());

                    failureCount++;
                    log.error("处理企业PRIPID={}时发生错误", moveIn.getPripid(), e);
                }
            }

            log.info("迁入数据任务执行完成，成功处理{}家企业，失败{}家", successCount, failureCount);

        } catch (Exception e) {
            log.error("迁入省局数据定时任务执行失败", e);
        }
    }


    /**
     * 查询需要迁入的企业（一周内的数据）
     */
    private List<EMoveIn> queryMoveInEnterprises() {
        QueryWrapper<EMoveIn> queryWrapper = new QueryWrapper<>();

        // 计算一周前的时间
        Date oneWeekAgo = DateUtil.offsetWeek(new Date(), -1);
        Timestamp oneWeekAgoTimestamp = new Timestamp(oneWeekAgo.getTime());

        // 查询S_EXT_DATATIME为一个星期内的数据
//        queryWrapper.ge("MOUTDATE", "6");
        queryWrapper.eq("MOVE_TYPE", 7);
//        queryWrapper.eq("PRIPID", "440126126012025103100478");
        return eMoveInMapper.selectList(queryWrapper);
    }

    /**
     * 查询企业基本信息
     * @param pripid 主体身份代码
     * @return 企业基本信息（格式：UNISCID|ENTNAME）
     */
    private String queryEnterpriseBaseInfo(String pripid) {
        try {
            QueryWrapper<EBaseInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("PRIPID", pripid);
            List<EBaseInfo> eBaseInfoList = eBaseInfoMapper.selectList(queryWrapper);

            if (CollUtil.isNotEmpty(eBaseInfoList)) {
                EBaseInfo eBaseInfo = eBaseInfoList.get(0);
                log.info("从 AICRI.E_BASEINFO 查询到企业信息：PRIPID={}, UNISCID={}, ENTNAME={}",
                    pripid, eBaseInfo.getUniscid(), eBaseInfo.getEntname());
                return eBaseInfo.getUniscid() + "|" + eBaseInfo.getEntname();
            } else {
                log.warn("未从 AICRI.E_BASEINFO 查询到企业信息，PRIPID={}", pripid);
                return null;
            }
        } catch (Exception e) {
            log.error("查询企业基本信息时发生错误，PRIPID={}", pripid, e);
            return null;
        }
    }

    /**
     * 从tableDataLists中的E_BASEINFO表获取企业名称
     * @param tableDataLists 解析后的数据列表
     * @return 企业名称，如果获取失败返回空字符串
     */
    private String getEntnameFromTableDataLists(Map<String, List<?>> tableDataLists) {
        try {
            List<?> eBaseInfoList = tableDataLists.get("E_BASEINFO");
            if (eBaseInfoList != null && !eBaseInfoList.isEmpty()) {
                // 取第一条记录
                Object firstRecord = eBaseInfoList.get(0);
                if (firstRecord instanceof Map) {
                    Map<String, Object> dataMap = (Map<String, Object>) firstRecord;
                    Object entnameObj = dataMap.get("ENTNAME");
                    if (entnameObj != null) {
                        return entnameObj.toString();
                    }
                }
            }
            log.warn("从tableDataLists的E_BASEINFO表中未获取到企业名称");
            return "";
        } catch (Exception e) {
            log.error("从tableDataLists的E_BASEINFO表获取企业名称时发生错误", e);
            return "";
        }
    }

    /**
     * 构建企业专用的输入目录路径
     * @param uniscid 企业统一社会信用代码
     * @param currentDate 当前日期
     * @return 企业专用目录路径
     */
    private String buildEnterpriseInputDir(String uniscid, String currentDate) {
        return BASE_INPUT_DIR + File.separator + "movein" + currentDate + File.separator + uniscid;
    }

    /**
     * 获取迁移数据路径
     * @param uniscid 企业统一社会信用代码
     * @param pripid 企业PRIPID
     * @param minId 企业MIN_ID
     * @return 最新的registerInfoFilePath，如果获取失败返回null
     */
    private String getMigrationDataPath(String uniscid, String pripid, String minId) {
        try {
            // 构建请求URL
            String queryUrl = "prod".equals(env) ? prodQueryRegisterInfoUrl : testQueryRegisterInfoUrl;

            // 构建请求参数
            Map<String, Object> requestParams = new HashMap<>();
            requestParams.put("appform", appform);
            requestParams.put("uniscid", uniscid);
            requestParams.put("moveInProvince", "440000");
            // uploadStartDate和uploadEndDate不传值

            // 构建请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            // 构建请求实体
            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestParams, headers);

            log.info("调用获取迁移数据路径接口：URL={}, 参数={}", queryUrl, requestParams);

            // 调用接口
            String response = restTemplate.postForObject(queryUrl, requestEntity, String.class);

            if (StrUtil.isNotEmpty(response)) {
                // 解析JSON响应
                JSONObject jsonResponse = new JSONObject(response);

                // 检查返回码
                if ("2000".equals(jsonResponse.getStr("resultCode"))) {
                    // 获取data数组
                    Object dataObj = jsonResponse.get("data");
                    if (dataObj instanceof cn.hutool.json.JSONArray) {
                        cn.hutool.json.JSONArray dataArray = (cn.hutool.json.JSONArray) dataObj;
                        log.info("调用获取迁移数据路径接口：所有路径={}", dataArray);
                        if (dataArray.size() > 0) {
                            // 取第一条记录（通常只有一个企业）
                            JSONObject enterpriseData = dataArray.getJSONObject(0);

                            // 获取registerInfoFiles数组
                            Object filesObj = enterpriseData.get("registerInfoFiles");
                            if (filesObj instanceof cn.hutool.json.JSONArray) {
                                cn.hutool.json.JSONArray filesArray = (cn.hutool.json.JSONArray) filesObj;

                                if (filesArray.size() > 0) {
                                    // 找到uploadTime最新的文件记录，只考虑registerInfoFileType为"1"的文件
                                    JSONObject latestFile = null;
                                    String latestUploadTime = "";

                                    for (int i = 0; i < filesArray.size(); i++) {
                                        JSONObject fileRecord = filesArray.getJSONObject(i);
                                        String uploadTime = fileRecord.getStr("uploadTime");
                                        String registerInfoFileType = fileRecord.getStr("registerInfoFileType");

                                        // 只处理registerInfoFileType为"1"的记录
                                        if ("1".equals(registerInfoFileType) && StrUtil.isNotEmpty(uploadTime) && uploadTime.compareTo(latestUploadTime) > 0) {
                                            latestFile = fileRecord;
                                            latestUploadTime = uploadTime;
                                        }
                                    }

                                    if (latestFile != null) {
                                        String registerInfoFilePath = latestFile.getStr("registerInfoFilePath");
                                        log.info("企业{}获取到最新迁移数据路径：{}, 上传时间：{}", uniscid, registerInfoFilePath, latestUploadTime);

                                        // 记录获取迁移数据路径成功
                                        String successMsg = String.format("企业%s获取迁移数据路径成功：路径=%s, 上传时间=%s", uniscid, registerInfoFilePath, latestUploadTime);
                                        String processRecord = "获取迁移数据路径成功：" + successMsg;
                                        recordFileUploadResult(pripid, registerInfoFilePath, "Y", processRecord, null, minId);

                                        return registerInfoFilePath;
                                    } else {
                                        // 没有找到文件记录
                                        log.warn("企业{}没有找到可用的迁移数据文件记录", uniscid);

                                        // 记录获取迁移数据路径失败
                                        String failMsg = String.format("企业%s获取迁移数据路径失败：没有找到可用的迁移数据文件记录", uniscid);
                                        String processRecord = "获取迁移数据路径失败：" + failMsg;
                                        recordFileUploadResult(pripid, null, "N", processRecord, null, minId);
                                    }
                                } else {
                                    // registerInfoFiles数组为空
                                    log.warn("企业{}registerInfoFiles数组为空", uniscid);

                                    // 记录获取迁移数据路径失败
                                    String failMsg = String.format("企业%s获取迁移数据路径失败：registerInfoFiles数组为空", uniscid);
                                    String processRecord = "获取迁移数据路径失败：" + failMsg;
                                    recordFileUploadResult(pripid, null, "N", processRecord, null, minId);
                                }
                            } else {
                                // registerInfoFiles不是JSONArray类型
                                log.warn("企业{}registerInfoFiles字段格式不正确", uniscid);

                                // 记录获取迁移数据路径失败
                                String failMsg = String.format("企业%s获取迁移数据路径失败：registerInfoFiles字段格式不正确", uniscid);
                                String processRecord = "获取迁移数据路径失败：" + failMsg;
                                recordFileUploadResult(pripid, null, "N", processRecord, null, minId);
                            }
                        } else {
                            // data数组为空
                            log.warn("企业{}获取迁移数据路径失败：返回的data数组为空", uniscid);

                            // 记录获取迁移数据路径失败
                            String failMsg = String.format("企业%s获取迁移数据路径失败：返回的data数组为空", uniscid);
                            String processRecord = "获取迁移数据路径失败：" + failMsg;
                            recordFileUploadResult(pripid, null, "N", processRecord, null, minId);
                        }
                    } else {
                        // data不是JSONArray类型
                        log.warn("企业{}获取迁移数据路径失败：返回的data字段格式不正确", uniscid);

                        // 记录获取迁移数据路径失败
                        String failMsg = String.format("企业%s获取迁移数据路径失败：返回的data字段格式不正确", uniscid);
                        String processRecord = "获取迁移数据路径失败：" + failMsg;
                        recordFileUploadResult(pripid, null, "N", processRecord, null, minId);
                    }
                }

                String errorMsg = jsonResponse.getStr("resultMsg") != null ? jsonResponse.getStr("resultMsg") : "未知错误";
                log.warn("企业{}获取迁移数据路径失败：{}", uniscid, errorMsg);

                // 记录获取迁移数据路径失败
                String failMsg = String.format("企业%s获取迁移数据路径失败：错误=%s", uniscid, errorMsg);
                String processRecord = "获取迁移数据路径失败：" + failMsg;
                recordFileUploadResult(pripid, null, "N", processRecord, null, minId);
            } else {
                log.error("企业{}获取迁移数据路径接口返回空响应", uniscid);

                // 记录获取迁移数据路径失败
                String failMsg = String.format("企业%s获取迁移数据路径失败：接口返回空响应", uniscid);
                String processRecord = "获取迁移数据路径失败：" + failMsg;
                recordFileUploadResult(pripid, null, "N", processRecord, null, minId);
            }

            return null;

        } catch (Exception e) {
            String errorMsg = e.getMessage() != null && e.getMessage().length() <= 2000 ? e.getMessage() : "获取迁移数据路径时发生异常，具体错误信息超过2000字符限制";
            log.error("企业{}获取迁移数据路径时发生错误：{}", uniscid, e);

            // 记录获取迁移数据路径失败
            String failMsg = String.format("企业%s获取迁移数据路径失败：异常=%s", uniscid, errorMsg);
            String processRecord = "获取迁移数据路径失败：" + failMsg;
            recordFileUploadResult(pripid, null, "N", processRecord, null, minId);

            return null;
        }
    }

    /**
     * 下载ZIP文件
     * @param uniscid 企业统一社会信用代码
     * @param zipFileName ZIP文件名
     * @param currentDate 当前日期
     * @param pripid 企业PRIPID
     * @param minId 企业MIN_ID
     * @return 下载的ZIP文件
     */
    private File downloadZipFile(String uniscid, String zipFileName, String currentDate, String pripid, String minId) {
        try {
            // 构建企业专用的输入目录
            String inputDir = buildEnterpriseInputDir(uniscid, currentDate);
            File enterpriseDir = new File(inputDir);
            if (!enterpriseDir.exists()) {
                enterpriseDir.mkdirs();
            }

            // 首先尝试从本地D:\data目录下载（开发环境）
            File localZipFile = new File(BASE_INPUT_DIR, zipFileName);
            if (localZipFile.exists()) {
                log.info("从本地目录下载ZIP文件：{}", localZipFile.getAbsolutePath());

                // 复制到企业专用目录
                File targetFile = new File(enterpriseDir, zipFileName);
                FileUtil.copy(localZipFile, targetFile, true);
                return targetFile;
            }

            // 本地文件不存在，先获取迁移数据路径
            log.info("本地文件不存在，开始获取迁移数据路径：企业={}", uniscid);

            String uploadFilePath = getMigrationDataPath(uniscid, pripid, minId);

            if (StrUtil.isEmpty(uploadFilePath)) {
                log.error("企业{}获取迁移数据路径失败，无法下载ZIP文件", uniscid);
                return null;
            }

            // 获取到uploadFilePath后，调用下载接口
            log.info("获取到迁移数据路径：{}，开始下载ZIP文件：企业={}, 文件={}", uploadFilePath, uniscid, zipFileName);

            // 构建下载URL
            String downloadUrl = "prod".equals(env) ? prodDownloadUrl : testDownloadUrl;

            // 构建POST请求参数JSON格式
            Map<String, Object> downloadParams = new HashMap<>();
            downloadParams.put("appform", appform);
            downloadParams.put("filePath", uploadFilePath);

            // 构建请求头
            HttpHeaders downloadHeaders = new HttpHeaders();
            downloadHeaders.setContentType(MediaType.APPLICATION_JSON);

            // 构建请求实体
            HttpEntity<Map<String, Object>> downloadRequestEntity = new HttpEntity<>(downloadParams, downloadHeaders);

            log.info("调用下载接口：URL={}, 参数={}", downloadUrl, downloadParams);

            // 调用下载接口（POST请求）
            byte[] fileBytes = restTemplate.postForObject(downloadUrl, downloadRequestEntity, byte[].class);

            if (fileBytes != null && fileBytes.length > 0) {
                // 保存ZIP文件
                File zipFile = new File(enterpriseDir, zipFileName);
                FileUtil.writeBytes(fileBytes, zipFile);

                log.info("企业{}下载ZIP文件成功，保存到：{}", uniscid, zipFile.getAbsolutePath());
                return zipFile;
            } else {
                log.error("企业{}下载ZIP文件失败，接口返回空数据", uniscid);
                return null;
            }

        } catch (Exception e) {
            log.error("企业{}下载ZIP文件时发生错误：{}", uniscid, e);
            return null;
        }
    }

    /**
     * 解析ZIP文件
     * @param zipFile ZIP文件
     * @param uniscid 企业统一社会信用代码
     * @return 解析后的数据Map
     */
    private Map<String, List<?>> parseZipFile(File zipFile, String uniscid) {
        Map<String, List<?>> parsedDataMap = new HashMap<>();

        try (ZipFile zip = new ZipFile(zipFile, StandardCharsets.UTF_8)) {
            Enumeration<? extends ZipEntry> entries = zip.entries();

            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                String entryName = entry.getName();

                // 只处理XML文件
                if (entryName.endsWith(".xml")) {
                    // 解析表名（去掉.xml后缀）
                    String tableName = entryName.substring(0, entryName.length() - 4).toUpperCase();

                    try (InputStream is = zip.getInputStream(entry)) {
                        // 使用IOUtils读取InputStream为字符串
                        String xmlContent = cn.hutool.core.io.IoUtil.read(is, StandardCharsets.UTF_8);

                        // 解析XML为对象列表
                        List<?> dataList = parseXmlToObjectList(xmlContent, tableName);

                        if (CollUtil.isNotEmpty(dataList)) {
                            parsedDataMap.put(tableName, dataList);
                            log.debug("企业{}解析XML文件{}，包含{}条记录", uniscid, entryName, dataList.size());
                        }
                    } catch (Exception e) {
                        log.error("企业{}解析XML文件{}时发生错误", uniscid, entryName, e);
                    }
                }
            }

            log.info("企业{}ZIP文件解析完成，共解析{}种数据类型", uniscid, parsedDataMap.size());
            return parsedDataMap;

        } catch (Exception e) {
            log.error("企业{}解析ZIP文件时发生错误", uniscid, e);
            return parsedDataMap;
        }
    }

    /**
     * 将XML转换为对象列表
     * @param xmlContent XML内容
     * @param tableName 表名
     * @return 对象列表
     */
    private List<?> parseXmlToObjectList(String xmlContent, String tableName) {
        List<Map<String, Object>> dataList = new ArrayList<>();

        try {
            log.debug("开始解析XML，表名={}，XML内容长度={}", tableName, xmlContent.length());

            // 打印XML内容的前1000个字符用于调试
            if (log.isDebugEnabled()) {
                String xmlPreview = xmlContent.length() > 1000 ?
                    xmlContent.substring(0, 1000) + "..." : xmlContent;
                log.debug("XML内容预览: {}", xmlPreview);
            }

            // 在hutool解析前进行XML结构分析
            analyzeXmlStructure(xmlContent, tableName);

            // 特别分析BUSEXCLIST字段的XML内容
            String busExclistPattern = "<BUSEXCLIST>(.*?)</BUSEXCLIST>";
            java.util.regex.Pattern pattern = java.util.regex.Pattern.compile(busExclistPattern);
            java.util.regex.Matcher matcher = pattern.matcher(xmlContent);

            if (matcher.find()) {
                String busExclistValue = matcher.group(1);
                log.warn("在原始XML中找到BUSEXCLIST值: '{}', 长度: {}", busExclistValue, busExclistValue.length());

                // 检查值中是否包含异常字符
                if (busExclistValue.contains(")") || busExclistValue.contains("(")) {
                    log.error("原始XML中BUSEXCLIST包含异常字符: '{}'", busExclistValue);
                }

                // 检查是否完整
                if (!busExclistValue.equals("400000105908626066")) {
                    log.error("原始XML中BUSEXCLIST值不完整，期望: 400000105908626066, 实际: '{}'", busExclistValue);
                }
            } else {
                log.error("在原始XML中未找到BUSEXCLIST字段");
                // 检查是否因为大小写问题
                String caseInsensitivePattern = "(?i)<BUSEXCLIST>(.*?)</BUSEXCLIST>";
                java.util.regex.Pattern ciPattern = java.util.regex.Pattern.compile(caseInsensitivePattern);
                java.util.regex.Matcher ciMatcher = ciPattern.matcher(xmlContent);
                if (ciMatcher.find()) {
                    log.warn("使用大小写不敏感匹配找到BUSEXCLIST: '{}'", ciMatcher.group(1));
                } else {
                    log.error("完全未找到BUSEXCLIST字段，检查XML结构");
                }
            }

            // 解析XML（使用hutool的XML.toJSONObject）
            JSONObject jsonObject = XML.toJSONObject(xmlContent);
            log.debug("XML解析完成，表名={}，JSON对象: {}", tableName, jsonObject.toString());

            // 获取rows节点下的数据
            if (jsonObject.containsKey("rows")) {
                Object rowsObj = jsonObject.get("rows");
                log.debug("表名{}的rows节点类型: {}", tableName, rowsObj.getClass().getSimpleName());

                if (rowsObj instanceof JSONObject) {
                    JSONObject rows = (JSONObject) rowsObj;

                    // 获取row数组或单个row的对象
                    Object rowData = rows.get("row");
                    if (rowData != null) {
                        if (rowData instanceof List) {
                            // 多个row
                            List<JSONObject> rowList = (List<JSONObject>) rowData;
                            log.debug("表名{}包含{}条记录", tableName, rowList.size());
                            for (int i = 0; i < rowList.size(); i++) {
                                JSONObject row = rowList.get(i);
                                Map<String, Object> dataMap = new HashMap<>();
                                for (String key : row.keySet()) {
                                    Object value = row.get(key);
                                    dataMap.put(key.toUpperCase(), value);

                                    // 特别关注BUSEXCLIST字段
                                    if ("BUSEXCLIST".equalsIgnoreCase(key)) {
                                        log.warn("表名{}第{}条记录的BUSEXCLIST: '{}'", tableName, i+1, value);

                                        // 检查是否包含异常字符
                                        if (value.toString().contains(")") || value.toString().contains("(")) {
                                            log.error("原始解析发现BUSEXCLIST包含异常字符: '{}'", value);
                                        }

                                        // 检查长度
                                        if (value.toString().length() < 18) {
                                            log.error("原始解析发现BUSEXCLIST长度异常: '{}', 长度: {}", value, value.toString().length());
                                        }
                                    }
                                }
                                dataList.add(dataMap);
                            }
                        } else if (rowData instanceof JSONObject) {
                            // 单个row
                            JSONObject row = (JSONObject) rowData;
                            Map<String, Object> dataMap = new HashMap<>();
                            for (String key : row.keySet()) {
                                Object value = row.get(key);
                                dataMap.put(key.toUpperCase(), value);

                                // 特别关注BUSEXCLIST字段
                                if ("BUSEXCLIST".equalsIgnoreCase(key)) {
                                    log.warn("表名{}的BUSEXCLIST: '{}'", tableName, value);

                                    // 检查是否包含异常字符
                                    if (value.toString().contains(")") || value.toString().contains("(")) {
                                        log.error("原始解析(单条)发现BUSEXCLIST包含异常字符: '{}'", value);
                                    }

                                    // 检查长度
                                    if (value.toString().length() < 18) {
                                        log.error("原始解析(单条)发现BUSEXCLIST长度异常: '{}', 长度: {}", value, value.toString().length());
                                    }
                                }
                            }
                            dataList.add(dataMap);
                        }
                    } else {
                        log.info("表名{}的rows节点中不存在row数据，可能是空数据集", tableName);
                    }
                } else if (rowsObj instanceof String) {
                    // 处理空字符串情况（正式环境的空XML：<rows/>）
                    String rowsStr = (String) rowsObj;
                    if (StrUtil.isEmpty(rowsStr)) {
                        log.info("表名{}的rows节点为空字符串，可能是空数据集（<rows/>格式）", tableName);
                    } else {
                        log.warn("表名{}的rows节点是非空字符串：{}，这可能是意外的数据格式", tableName, rowsStr);
                    }
                } else {
                    log.warn("表名{}的rows节点类型不是JSONObject或String，而是：{}",
                            tableName, rowsObj.getClass().getSimpleName());
                }
            } else {
                log.warn("XML中不包含rows节点，表名：{}", tableName);
            }

            log.debug("解析XML到对象列表，表名={}，数据量={}", tableName, dataList.size());
            return dataList;

        } catch (Exception e) {
            log.error("使用hutool解析XML失败，表名={}，尝试使用备用解析方法", tableName, e);
            // 使用备用解析方法
            return parseXmlToObjectListFallback(xmlContent, tableName);
        }
    }

    /**
     * 备用XML解析方法 - 使用标准DOM解析器
     * 当hutool解析失败时使用
     */
    private List<?> parseXmlToObjectListFallback(String xmlContent, String tableName) {
        List<Map<String, Object>> dataList = new ArrayList<>();

        try {
            log.debug("开始使用备用方法解析XML，表名={}", tableName);

            // 在备用解析前也进行XML结构分析
            analyzeXmlStructure(xmlContent, tableName);

            // 在备用解析前也分析一下原始XML中的BUSEXCLIST
            String busExclistPattern = "<BUSEXCLIST>(.*?)</BUSEXCLIST>";
            java.util.regex.Pattern pattern = java.util.regex.Pattern.compile(busExclistPattern);
            java.util.regex.Matcher matcher = pattern.matcher(xmlContent);

            if (matcher.find()) {
                String busExclistValue = matcher.group(1);
                log.warn("备用解析-在原始XML中找到BUSEXCLIST值: '{}', 长度: {}", busExclistValue, busExclistValue.length());
            }

            // 使用标准的DOM解析器
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(new ByteArrayInputStream(xmlContent.getBytes(StandardCharsets.UTF_8)));

            // 获取根节点
            Element root = document.getDocumentElement();
            log.debug("XML根节点: {}", root.getNodeName());

            // 查找rows节点
            NodeList rowsNodes = root.getElementsByTagName("rows");
            if (rowsNodes.getLength() == 0) {
                log.warn("XML中未找到rows节点，表名：{}", tableName);
                return dataList;
            }

            Element rowsElement = (Element) rowsNodes.item(0);

            // 查找所有row节点
            NodeList rowNodes = rowsElement.getElementsByTagName("row");
            log.debug("找到{}个row节点", rowNodes.getLength());

            for (int i = 0; i < rowNodes.getLength(); i++) {
                Element rowElement = (Element) rowNodes.item(i);
                Map<String, Object> dataMap = new HashMap<>();

                // 遍历row节点的所有子节点
                NodeList fieldNodes = rowElement.getChildNodes();
                for (int j = 0; j < fieldNodes.getLength(); j++) {
                    Node fieldNode = fieldNodes.item(j);

                    // 只处理元素节点
                    if (fieldNode.getNodeType() == Node.ELEMENT_NODE) {
                        String fieldName = fieldNode.getNodeName();
                        String fieldValue = fieldNode.getTextContent();

                        dataMap.put(fieldName.toUpperCase(), fieldValue);

                        // 特别关注BUSEXCLIST字段
                        if ("BUSEXCLIST".equalsIgnoreCase(fieldName)) {
                            log.warn("备用解析-表名{}第{}条记录的BUSEXCLIST: '{}'", tableName, i+1, fieldValue);

                            // 检查是否包含异常字符
                            if (fieldValue.contains(")") || fieldValue.contains("(")) {
                                log.error("备用解析发现BUSEXCLIST包含异常字符: '{}'", fieldValue);
                            }

                            // 检查长度
                            if (fieldValue.length() < 18) {
                                log.error("备用解析发现BUSEXCLIST长度异常: '{}', 长度: {}", fieldValue, fieldValue.length());
                            }
                        }
                    }
                }

                dataList.add(dataMap);
            }

            log.debug("备用XML解析完成，表名={}，数据量={}", tableName, dataList.size());
            return dataList;

        } catch (Exception e) {
            log.error("备用XML解析方法也失败，表名={}", tableName, e);
            return dataList;
        }
    }

    /**
     * 专门用于分析XML结构的方法
     * 帮助定位解析问题
     */
    private void analyzeXmlStructure(String xmlContent, String tableName) {
        try {
            log.warn("=== 开始分析XML结构，表名: {} ===", tableName);

            // 1. 检查XML基本结构
            log.warn("XML总长度: {}", xmlContent.length());

            // 2. 使用正则表达式查找所有的BUSEXCLIST相关内容
            java.util.regex.Pattern allBusPattern = java.util.regex.Pattern.compile("(<BUSEXCLIST>.*?</BUSEXCLIST>)");
            java.util.regex.Matcher allMatcher = allBusPattern.matcher(xmlContent);

            int matchCount = 0;
            while (allMatcher.find()) {
                matchCount++;
                String fullTag = allMatcher.group(1);
                log.warn("发现第{}个BUSEXCLIST标签: '{}'", matchCount, fullTag);
            }

            if (matchCount == 0) {
                log.error("未找到任何BUSEXCLIST标签");

                // 检查是否因为大小写问题
                String lowerXml = xmlContent.toLowerCase();
                if (lowerXml.contains("busexclist")) {
                    log.warn("发现小写的busexclist，检查大小写问题");
                    int index = lowerXml.indexOf("busexclist");
                    String context = xmlContent.substring(Math.max(0, index - 50), Math.min(xmlContent.length(), index + 100));
                    log.warn("busexclist附近的内容: '{}'", context);
                }
            }

            // 3. 检查row结构
            java.util.regex.Pattern rowPattern = java.util.regex.Pattern.compile("(<row>.*?</row>)");
            java.util.regex.Matcher rowMatcher = rowPattern.matcher(xmlContent);

            int rowCount = 0;
            while (rowMatcher.find()) {
                rowCount++;
                String rowContent = rowMatcher.group(1);
                log.warn("发现第{}个row: '{}'", rowCount, rowContent.length() > 200 ? rowContent.substring(0, 200) + "..." : rowContent);
            }

            // 4. 检查是否包含4000001这个可疑字符串
            if (xmlContent.contains("4000001)")) {
                log.error("发现可疑字符串'4000001)'在XML中");
                int index = xmlContent.indexOf("4000001)");
                String context = xmlContent.substring(Math.max(0, index - 100), Math.min(xmlContent.length(), index + 50));
                log.error("4000001)附近的上下文: '{}'", context);
            }

            // 5. 检查特殊字符
            if (xmlContent.contains(")") || xmlContent.contains("(")) {
                log.warn("XML中包含括号字符");
            }

            log.warn("=== XML结构分析完成 ===");

        } catch (Exception e) {
            log.error("XML结构分析失败", e);
        }
    }

    /**
     * 插入数据到对应表
     * @param dataMap 数据Map
     * @param uniscid 企业统一社会信用代码
     * @return 是否插入成功
     */
    private boolean insertDataToTables(Map<String, List<?>> dataMap, String uniscid) {
        try {
            int totalTables = dataMap.size();
            int successTables = 0;
            List<String> failedTables = new ArrayList<>();

            for (Map.Entry<String, List<?>> entry : dataMap.entrySet()) {
                String tableName = entry.getKey();
                List<?> dataList = entry.getValue();

                if (CollUtil.isEmpty(dataList)) {
                    continue;
                }

                boolean tableSuccess = insertDataToSingleTable(tableName, dataList, uniscid);
                if (tableSuccess) {
                    successTables++;
                } else {
                    failedTables.add(tableName);
                }
            }

            log.info("企业{}数据插入完成，总表数={}，成功表数={}", uniscid, totalTables, successTables);

            // 报告失败的表
            if (!failedTables.isEmpty()) {
                log.error("企业{}以下表插入失败: {}", uniscid, String.join(", ", failedTables));
            }

            return successTables == totalTables;

        } catch (Exception e) {
            log.error("企业{}插入数据到表时发生错误", uniscid, e);
            return false;
        }
    }

    /**
     * 插入数据到单个表
     * @param tableName 表名
     * @param dataList 数据列表
     * @param uniscid 企业统一社会信用代码
     * @return 是否插入成功
     */
    private boolean insertDataToSingleTable(String tableName, List<?> dataList, String uniscid) {
        try {
            boolean result = false;

            // 根据表名调用对应的Mapper插入数据
            switch (tableName) {
                case "E_BASEINFO":
                    result = insertOrUpdateEBaseInfo(dataList, uniscid);
                    break;
                case "E_ALTER_RECODER":
                    result = insertOrUpdateEAlterRecoder(dataList, uniscid);
                    break;
                case "E_IM_PERMIT":
                    result = insertOrUpdateEImPermit(dataList, uniscid);
                    break;
                case "E_OT_SPOTCHECK":
                    result = insertOrUpdateEOtSpotcheck(dataList, uniscid);
                    break;
                case "E_PUB_SPOTCHECK":
                    result = insertOrUpdateEPubSpotcheck(dataList, uniscid);
                    break;
                case "DR_RANINSRES":
                    result = insertOrUpdateDrRaninsres(dataList, uniscid);
                    break;
                case "AO_OPANOMALY":
                    result = insertOrUpdateAoOpAnomaly(dataList, uniscid);
                    break;
                case "AO_OPA_DETAIL":
                    result = insertOrUpdateAoOpaDetail(dataList, uniscid);
                    break;
                case "AO_OPANOMALY_INV":
                    result = insertOrUpdateAoOpAnomalyInv(dataList, uniscid);
                    break;
                case "AN_BASEINFO":
                    result = insertOrUpdateAnBaseinfo(dataList, uniscid);
                    break;
                case "E_IM_INVESTMENT":
                    result = insertOrUpdateEImInvestment(dataList, uniscid);
                    break;
                case "E_IM_INVUPDATE":
                    result = insertOrUpdateEImInvupdate(dataList, uniscid);
                    break;
                case "CASE_CRE_INFORMATION":
                    result = insertOrUpdateCaseCreInformation(dataList, uniscid);
                    break;
                case "E_IM_IPPLDG":
                    result = insertOrUpdateEImIppldg(dataList, uniscid);
                    break;
                case "E_IM_CASE":
                    result = insertOrUpdateEImCase(dataList, uniscid);
                    break;
                case "E_IM_INVSRALT":
                    result = insertOrUpdateEImInvsralt(dataList, uniscid);
                    break;
                case "E_LI_ILLDISHONESTY":
                    result = insertOrUpdateELiIlldishonesty(dataList, uniscid);
                    break;
                case "E_LI_ILLDISDETAIL":
                    result = insertOrUpdateELiIlldisdetail(dataList, uniscid);
                    break;
                case "CASE_PUB_NBASEINFO":
                    result = insertOrUpdateCasePubNbaseinfo(dataList, uniscid);
                    break;
                case "E_OT_NPERMIT":
                    result = insertOrUpdateEOtNpermit(dataList, uniscid);
                    break;
                case "E_OT_NCASE":
                    result = insertOrUpdateEOtNcase(dataList, uniscid);
                    break;
                case "AN_SUBCAPITAL":
                    result = insertOrUpdateAnSubcapital(dataList, uniscid);
                    break;
                case "AN_FORINVESTMENT":
                    result = insertOrUpdateAnForinvestment(dataList, uniscid);
                    break;
                case "AN_WEBSITEINFO":
                    result = insertOrUpdateAnWebsiteinfo(dataList, uniscid);
                    break;
                case "AN_ALTERSTOCKINFO":
                    result = insertOrUpdateAnAlterstockinfo(dataList, uniscid);
                    break;
                case "AN_FORGUARANTEEINFO":
                    result = insertOrUpdateAnForguaranteeinfo(dataList, uniscid);
                    break;
                case "AN_UPDATEINFO":
                    result = insertOrUpdateAnUpdateinfo(dataList, uniscid);
                    break;
                case "AN_SUP_BASEINFO":
                    result = insertOrUpdateAnSupBaseinfo(dataList, uniscid);
                    break;
                case "AN_SOCSECINFO":
                    result = insertOrUpdateAnSocsecinfo(dataList, uniscid);
                    break;
                case "E_IM_PRMTALT":
                    result = insertOrUpdateEImPrmtalt(dataList, uniscid);
                    break;
                case "E_OT_NPRMTALT":
                    result = insertOrUpdateEOtNprmtalt(dataList, uniscid);
                    break;
                case "E_IM_INVPRODETAIL":
                    result = insertOrUpdateEImInvprodetail(dataList, uniscid);
                    break;
                case "E_IM_INVACTDETAIL":
                    result = insertOrUpdateEImInvactdetail(dataList, uniscid);
                    break;
                case "E_IM_IPPLDGALT":
                    result = insertOrUpdateEImIppldgalt(dataList, uniscid);
                    break;
                case "E_IM_CASALT":
                    result = insertOrUpdateEImCasalt(dataList, uniscid);
                    break;
                case "CASE_PUB_NDOC":
                    result = insertOrUpdateCasePubNdoc(dataList, uniscid);
                    break;
                case "CASE_PUB_NALTER":
                    result = insertOrUpdateCasePubNalter(dataList, uniscid);
                    break;
                case "E_OT_NCASALT":
                    result = insertOrUpdateEOtNcasalt(dataList, uniscid);
                    break;
                default:
                    log.warn("企业{}未知表名：{}", uniscid, tableName);
                    return false;
            }

            if (result) {
                log.debug("企业{}表{}插入成功，数据量={}", uniscid, tableName, dataList.size());
            } else {
                log.error("企业{}表{}插入失败", uniscid, tableName);
            }

            return result;

        } catch (Exception e) {
            String errorMsg = e.getMessage() != null ? e.getMessage() : "未知错误";
            log.error("企业{}插入数据到表{}时发生错误: {}", uniscid, tableName, errorMsg, e);
            return false;
        }
    }

    // 各个表的插入或更新方法实现（每个方法都先查询再插入/更新）

    private boolean insertOrUpdateEBaseInfo(List<?> dataList, String uniscid) {
        try {
            for (Object obj : dataList) {
                Map<String, Object> dataMap = (Map<String, Object>) obj;
                EBaseInfoAiccs entity = mapToEntity(dataMap, EBaseInfoAiccs.class);
                if (entity != null) {
                    QueryWrapper<EBaseInfoAiccs> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("PRIPID", entity.getPripid());
                    EBaseInfoAiccs existing = eBaseInfoMapperAiccs.selectOne(queryWrapper);
                    if (existing != null) {
                        try {
                            eBaseInfoMapperAiccs.updateById(entity);
                        } catch (Exception updateEx) {
                            log.error("企业{}更新E_BASEINFO表记录失败，PRIPID={}: {}", uniscid, entity.getPripid(), updateEx.getMessage(), updateEx);
                            throw updateEx;
                        }
                    } else {
                        try {
                            eBaseInfoMapperAiccs.insert(entity);
                        } catch (Exception insertEx) {
                            log.error("企业{}插入E_BASEINFO表记录失败，PRIPID={}: {}", uniscid, entity.getPripid(), insertEx.getMessage(), insertEx);
                            throw insertEx;
                        }
                    }
                }
            }
            return true;
        } catch (Exception e) {
            String errorMsg = e.getMessage() != null ? e.getMessage() : "未知错误";
            log.error("插入E_BASEINFO表失败: {}", errorMsg, e);
            return false;
        }
    }

    private boolean insertOrUpdateEAlterRecoder(List<?> dataList, String uniscid) {
        try {
            for (Object obj : dataList) {
                Map<String, Object> dataMap = (Map<String, Object>) obj;
                EAlterRecoderAiccs entity = mapToEntity(dataMap, EAlterRecoderAiccs.class);
                if (entity != null) {
                    QueryWrapper<EAlterRecoderAiccs> queryWrapper = new QueryWrapper<>();
                    // 使用ALTID作为唯一标识查询
                    queryWrapper.eq("ALTID", entity.getAltid());
                    EAlterRecoderAiccs existing = eAlterRecoderMapperAiccs.selectOne(queryWrapper);
                    if (existing != null) {
                        try {
                            eAlterRecoderMapperAiccs.updateById(entity);
                        } catch (Exception updateEx) {
                            log.error("企业{}更新E_ALTER_RECODER表记录失败，ALTID={}: {}", uniscid, entity.getAltid(), updateEx.getMessage(), updateEx);
                            throw updateEx;
                        }
                    } else {
                        try {
                            eAlterRecoderMapperAiccs.insert(entity);
                        } catch (Exception insertEx) {
                            log.error("企业{}插入E_ALTER_RECODER表记录失败，ALTID={}: {}", uniscid, entity.getAltid(), insertEx.getMessage(), insertEx);
                            throw insertEx;
                        }
                    }
                }
            }
            return true;
        } catch (Exception e) {
            String errorMsg = e.getMessage() != null ? e.getMessage() : "未知错误";
            log.error("插入E_ALTER_RECODER表失败: {}", errorMsg, e);
            return false;
        }
    }

    // 以下是其他表的插入方法（每个方法都直接实现，不使用genericInsertOrUpdate）
    private boolean insertOrUpdateEImPermit(List<?> dataList, String uniscid) {
        try {
            for (Object obj : dataList) {
                Map<String, Object> dataMap = (Map<String, Object>) obj;
                EImPermitAiccs entity = mapToEntity(dataMap, EImPermitAiccs.class);
                if (entity != null) {
                    QueryWrapper<EImPermitAiccs> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("LICID", entity.getLicid());
                    EImPermitAiccs existing = eImPermitMapperAiccs.selectOne(queryWrapper);
                    if (existing != null) {
                        eImPermitMapperAiccs.updateById(entity);
                    } else {
                        eImPermitMapperAiccs.insert(entity);
                    }
                }
            }
            return true;
        } catch (Exception e) {
            log.error("插入E_IM_PERMIT表失败", e);
            return false;
        }
    }

    private boolean insertOrUpdateEOtSpotcheck(List<?> dataList, String uniscid) {
        try {
            for (Object obj : dataList) {
                Map<String, Object> dataMap = (Map<String, Object>) obj;
                EOtSpotcheckAiccs entity = mapToEntity(dataMap, EOtSpotcheckAiccs.class);
                if (entity != null) {
                    QueryWrapper<EOtSpotcheckAiccs> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("INSID", entity.getInsid());
                    EOtSpotcheckAiccs existing = eOtSpotcheckMapperAiccs.selectOne(queryWrapper);
                    if (existing != null) {
                        eOtSpotcheckMapperAiccs.updateById(entity);
                    } else {
                        eOtSpotcheckMapperAiccs.insert(entity);
                    }
                }
            }
            return true;
        } catch (Exception e) {
            log.error("插入E_OT_SPOTCHECK表失败", e);
            return false;
        }
    }

    private boolean insertOrUpdateEPubSpotcheck(List<?> dataList, String uniscid) {
        try {
            for (Object obj : dataList) {
                Map<String, Object> dataMap = (Map<String, Object>) obj;
                EPubSpotcheckAiccs entity = mapToEntity(dataMap, EPubSpotcheckAiccs.class);
                if (entity != null) {
                    QueryWrapper<EPubSpotcheckAiccs> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("INSID", entity.getInsid());
                    EPubSpotcheckAiccs existing = ePubSpotcheckMapperAiccs.selectOne(queryWrapper);
                    if (existing != null) {
                        ePubSpotcheckMapperAiccs.updateById(entity);
                    } else {
                        ePubSpotcheckMapperAiccs.insert(entity);
                    }
                }
            }
            return true;
        } catch (Exception e) {
            log.error("插入E_PUB_SPOTCHECK表失败", e);
            return false;
        }
    }

    private boolean insertOrUpdateDrRaninsres(List<?> dataList, String uniscid) {
        try {
            for (Object obj : dataList) {
                Map<String, Object> dataMap = (Map<String, Object>) obj;
                DrRaninsresAiccs entity = mapToEntity(dataMap, DrRaninsresAiccs.class);
                if (entity != null) {
                    QueryWrapper<DrRaninsresAiccs> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("CHECKRESID", entity.getCheckresid());
                    DrRaninsresAiccs existing = drRaninsresMapperAiccs.selectOne(queryWrapper);
                    if (existing != null) {
                        drRaninsresMapperAiccs.updateById(entity);
                    } else {
                        drRaninsresMapperAiccs.insert(entity);
                    }
                }
            }
            return true;
        } catch (Exception e) {
            log.error("插入DR_RANINSRES表失败", e);
            return false;
        }
    }

    private boolean insertOrUpdateAoOpAnomaly(List<?> dataList, String uniscid) {
        try {
            for (Object obj : dataList) {
                Map<String, Object> dataMap = (Map<String, Object>) obj;
                AoOpAnomalyAiccs entity = mapToEntity(dataMap, AoOpAnomalyAiccs.class);
                if (entity != null) {
                    QueryWrapper<AoOpAnomalyAiccs> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("busexclist", entity.getBusexclist());
                    AoOpAnomalyAiccs existing = aoOpAnomalyMapperAiccs.selectOne(queryWrapper);
                    if (existing != null) {
                        aoOpAnomalyMapperAiccs.updateById(entity);
                    } else {
                        aoOpAnomalyMapperAiccs.insert(entity);
                    }
                }
            }
            return true;
        } catch (Exception e) {
            log.error("插入AO_OPANOMALY表失败", e);
            return false;
        }
    }

    private boolean insertOrUpdateAoOpaDetail(List<?> dataList, String uniscid) {
        try {
            for (Object obj : dataList) {
                Map<String, Object> dataMap = (Map<String, Object>) obj;

                // 添加详细的调试日志：打印原始数据
                log.warn("处理AO_OPA_DETAIL数据，原始数据Map: {}", dataMap);

                // 特别关注BUSEXCLIST字段的解析结果
                Object busexclistObj = dataMap.get("BUSEXCLIST");
                if (busexclistObj != null) {
                    String busexclist = busexclistObj.toString();
                    log.warn("XML解析的BUSEXCLIST值: '{}', 长度: {}, 类型: {}",
                             busexclist, busexclist.length(), busexclistObj.getClass().getSimpleName());

                    // 检查是否是完整的ID
                    if (busexclist.length() < 18) { // 正常的ID应该比较长
                        log.error("BUSEXCLIST长度异常，可能解析不完整: '{}'", busexclist);
                    }
                } else {
                    log.error("BUSEXCLIST字段在Map中不存在，Map键: {}", dataMap.keySet());
                }

                AoOpaDetailAiccs entity = mapToEntity(dataMap, AoOpaDetailAiccs.class);
                if (entity != null) {
                    // 验证实体对象的BUSEXCLIST字段
                    if (entity.getBusexclist() != null) {
                        log.warn("实体对象BUSEXCLIST: '{}', 长度: {}",
                                 entity.getBusexclist(), entity.getBusexclist().length());

                        // 检查是否包含异常字符
                        if (entity.getBusexclist().contains(")")) {
                            log.error("发现异常字符：BUSEXCLIST包含 ')': '{}'", entity.getBusexclist());
                        }
                    } else {
                        log.error("实体对象的BUSEXCLIST为null");
                    }

                    QueryWrapper<AoOpaDetailAiccs> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("BUSEXCLIST", entity.getBusexclist());
                    AoOpaDetailAiccs existing = aoOpaDetailMapperAiccs.selectOne(queryWrapper);
                    if (existing != null) {
                        aoOpaDetailMapperAiccs.updateById(entity);
                    } else {
                        aoOpaDetailMapperAiccs.insert(entity);
                    }
                } else {
                    log.error("Map转实体对象失败，跳过该条记录");
                }
            }
            return true;
        } catch (Exception e) {
            log.error("插入AO_OPA_DETAIL表失败", e);
            return false;
        }
    }

    private boolean insertOrUpdateAoOpAnomalyInv(List<?> dataList, String uniscid) {
        try {
            for (Object obj : dataList) {
                Map<String, Object> dataMap = (Map<String, Object>) obj;
                AoOpAnomalyInvAiccs entity = mapToEntity(dataMap, AoOpAnomalyInvAiccs.class);
                if (entity != null) {
                    QueryWrapper<AoOpAnomalyInvAiccs> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("BLINVID", entity.getBlinvid());
                    AoOpAnomalyInvAiccs existing = aoOpAnomalyInvMapperAiccs.selectOne(queryWrapper);
                    if (existing != null) {
                        aoOpAnomalyInvMapperAiccs.updateById(entity);
                    } else {
                        aoOpAnomalyInvMapperAiccs.insert(entity);
                    }
                }
            }
            return true;
        } catch (Exception e) {
            log.error("插入AO_OPANOMALY_INV表失败", e);
            return false;
        }
    }

    private boolean insertOrUpdateAnBaseinfo(List<?> dataList, String uniscid) {
        try {
            for (Object obj : dataList) {
                Map<String, Object> dataMap = (Map<String, Object>) obj;
                AnBaseinfoAiccs entity = mapToEntity(dataMap, AnBaseinfoAiccs.class);
                if (entity != null) {
                    QueryWrapper<AnBaseinfoAiccs> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("ANCHEID", entity.getAncheid());
                    AnBaseinfoAiccs existing = anBaseinfoMapperAiccs.selectOne(queryWrapper);
                    if (existing != null) {
                        anBaseinfoMapperAiccs.updateById(entity);
                    } else {
                        anBaseinfoMapperAiccs.insert(entity);
                    }
                }
            }
            return true;
        } catch (Exception e) {
            log.error("插入AN_BASEINFO表失败", e);
            return false;
        }
    }

    private boolean insertOrUpdateEImInvestment(List<?> dataList, String uniscid) {
        try {
            for (Object obj : dataList) {
                Map<String, Object> dataMap = (Map<String, Object>) obj;
                EImInvestmentAiccs entity = mapToEntity(dataMap, EImInvestmentAiccs.class);
                if (entity != null) {
                    QueryWrapper<EImInvestmentAiccs> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("INVID", entity.getInvid());
                    EImInvestmentAiccs existing = eImInvestmentMapperAiccs.selectOne(queryWrapper);
                    if (existing != null) {
                        try {
                            eImInvestmentMapperAiccs.updateById(entity);
                        } catch (Exception updateEx) {
                            log.error("企业{}更新E_IM_INVESTMENT表记录失败，INVID={}: {}", uniscid, entity.getInvid(), updateEx.getMessage(), updateEx);
                            throw updateEx;
                        }
                    } else {
                        try {
                            eImInvestmentMapperAiccs.insert(entity);
                        } catch (Exception insertEx) {
                            log.error("企业{}插入E_IM_INVESTMENT表记录失败，INVID={}: {}", uniscid, entity.getInvid(), insertEx.getMessage(), insertEx);
                            throw insertEx;
                        }
                    }
                }
            }
            return true;
        } catch (Exception e) {
            String errorMsg = e.getMessage() != null ? e.getMessage() : "未知错误";
            log.error("插入E_IM_INVESTMENT表失败: {}", errorMsg, e);
            return false;
        }
    }

    private boolean insertOrUpdateEImInvupdate(List<?> dataList, String uniscid) {
        try {
            for (Object obj : dataList) {
                Map<String, Object> dataMap = (Map<String, Object>) obj;
                EImInvupdateAiccs entity = mapToEntity(dataMap, EImInvupdateAiccs.class);
                if (entity != null) {
                    QueryWrapper<EImInvupdateAiccs> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("INVUID", entity.getInvuid());
                    EImInvupdateAiccs existing = eImInvupdateMapperAiccs.selectOne(queryWrapper);
                    if (existing != null) {
                        try {
                            eImInvupdateMapperAiccs.updateById(entity);
                        } catch (Exception updateEx) {
                            log.error("企业{}更新E_IM_INVUPDATE表记录失败，INVUID={}: {}", uniscid, entity.getInvuid(), updateEx.getMessage(), updateEx);
                            throw updateEx;
                        }
                    } else {
                        try {
                            eImInvupdateMapperAiccs.insert(entity);
                        } catch (Exception insertEx) {
                            log.error("企业{}插入E_IM_INVUPDATE表记录失败，INVUID={}: {}", uniscid, entity.getInvuid(), insertEx.getMessage(), insertEx);
                            throw insertEx;
                        }
                    }
                }
            }
            return true;
        } catch (Exception e) {
            String errorMsg = e.getMessage() != null ? e.getMessage() : "未知错误";
            log.error("插入E_IM_INVUPDATE表失败: {}", errorMsg, e);
            return false;
        }
    }

    private boolean insertOrUpdateCaseCreInformation(List<?> dataList, String uniscid) {
        try {
            for (Object obj : dataList) {
                Map<String, Object> dataMap = (Map<String, Object>) obj;
                CaseCreInformationAiccs entity = mapToEntity(dataMap, CaseCreInformationAiccs.class);
                if (entity != null) {
                    QueryWrapper<CaseCreInformationAiccs> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("CASECREID", entity.getCasecreid());
                    CaseCreInformationAiccs existing = caseCreInformationMapperAiccs.selectOne(queryWrapper);
                    if (existing != null) {
                        try {
                            caseCreInformationMapperAiccs.updateById(entity);
                        } catch (Exception updateEx) {
                            log.error("企业{}更新CASE_CRE_INFORMATION表记录失败，CASECREID={}: {}", uniscid, entity.getCasecreid(), updateEx.getMessage(), updateEx);
                            throw updateEx;
                        }
                    } else {
                        try {
                            caseCreInformationMapperAiccs.insert(entity);
                        } catch (Exception insertEx) {
                            log.error("企业{}插入CASE_CRE_INFORMATION表记录失败，CASECREID={}: {}", uniscid, entity.getCasecreid(), insertEx.getMessage(), insertEx);
                            throw insertEx;
                        }
                    }
                }
            }
            return true;
        } catch (Exception e) {
            String errorMsg = e.getMessage() != null ? e.getMessage() : "未知错误";
            log.error("插入CASE_CRE_INFORMATION表失败: {}", errorMsg, e);
            return false;
        }
    }

    private boolean insertOrUpdateEImIppldg(List<?> dataList, String uniscid) {
        try {
            for (Object obj : dataList) {
                Map<String, Object> dataMap = (Map<String, Object>) obj;
                EImIppldgAiccs entity = mapToEntity(dataMap, EImIppldgAiccs.class);
                if (entity != null) {
                    QueryWrapper<EImIppldgAiccs> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("PLEID", entity.getPleid());
                    EImIppldgAiccs existing = eImIppldgMapperAiccs.selectOne(queryWrapper);
                    if (existing != null) {
                        eImIppldgMapperAiccs.updateById(entity);
                    } else {
                        eImIppldgMapperAiccs.insert(entity);
                    }
                }
            }
            return true;
        } catch (Exception e) {
            log.error("插入E_IM_IPPLDG表失败", e);
            return false;
        }
    }

    private boolean insertOrUpdateEImCase(List<?> dataList, String uniscid) {
        try {
            for (Object obj : dataList) {
                Map<String, Object> dataMap = (Map<String, Object>) obj;
                EImCaseAiccs entity = mapToEntity(dataMap, EImCaseAiccs.class);
                if (entity != null) {
                    QueryWrapper<EImCaseAiccs> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("CASEID", entity.getCaseid());
                    EImCaseAiccs existing = eImCaseMapperAiccs.selectOne(queryWrapper);
                    if (existing != null) {
                        eImCaseMapperAiccs.updateById(entity);
                    } else {
                        eImCaseMapperAiccs.insert(entity);
                    }
                }
            }
            return true;
        } catch (Exception e) {
            log.error("插入E_IM_CASE表失败", e);
            return false;
        }
    }

    private boolean insertOrUpdateEImInvsralt(List<?> dataList, String uniscid) {
        try {
            for (Object obj : dataList) {
                Map<String, Object> dataMap = (Map<String, Object>) obj;
                EImInvsraltAiccs entity = mapToEntity(dataMap, EImInvsraltAiccs.class);
                if (entity != null) {
                    QueryWrapper<EImInvsraltAiccs> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("INVALTID", entity.getInvaltid());
                    EImInvsraltAiccs existing = eImInvsraltMapperAiccs.selectOne(queryWrapper);
                    if (existing != null) {
                        eImInvsraltMapperAiccs.updateById(entity);
                    } else {
                        eImInvsraltMapperAiccs.insert(entity);
                    }
                }
            }
            return true;
        } catch (Exception e) {
            log.error("插入E_IM_INVSRALT表失败", e);
            return false;
        }
    }

    private boolean insertOrUpdateELiIlldishonesty(List<?> dataList, String uniscid) {
        try {
            for (Object obj : dataList) {
                Map<String, Object> dataMap = (Map<String, Object>) obj;
                ELiIlldishonestyAiccs entity = mapToEntity(dataMap, ELiIlldishonestyAiccs.class);
                if (entity != null) {
                    QueryWrapper<ELiIlldishonestyAiccs> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("ILLID", entity.getIllid());
                    ELiIlldishonestyAiccs existing = eLiIlldishonestyMapperAiccs.selectOne(queryWrapper);
                    if (existing != null) {
                        eLiIlldishonestyMapperAiccs.updateById(entity);
                    } else {
                        eLiIlldishonestyMapperAiccs.insert(entity);
                    }
                }
            }
            return true;
        } catch (Exception e) {
            log.error("插入E_LI_ILLDISHONESTY表失败", e);
            return false;
        }
    }

    private boolean insertOrUpdateELiIlldisdetail(List<?> dataList, String uniscid) {
        try {
            for (Object obj : dataList) {
                Map<String, Object> dataMap = (Map<String, Object>) obj;
                ELiIlldisdetailAiccs entity = mapToEntity(dataMap, ELiIlldisdetailAiccs.class);
                if (entity != null) {
                    QueryWrapper<ELiIlldisdetailAiccs> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("ILLID", entity.getIllid());
                    ELiIlldisdetailAiccs existing = eLiIlldisdetailMapperAiccs.selectOne(queryWrapper);
                    if (existing != null) {
                        eLiIlldisdetailMapperAiccs.updateById(entity);
                    } else {
                        eLiIlldisdetailMapperAiccs.insert(entity);
                    }
                }
            }
            return true;
        } catch (Exception e) {
            log.error("插入E_LI_ILLDISDETAIL表失败", e);
            return false;
        }
    }

    private boolean insertOrUpdateCasePubNbaseinfo(List<?> dataList, String uniscid) {
        try {
            for (Object obj : dataList) {
                Map<String, Object> dataMap = (Map<String, Object>) obj;
                CasePubNbaseinfoAiccs entity = mapToEntity(dataMap, CasePubNbaseinfoAiccs.class);
                if (entity != null) {
                    QueryWrapper<CasePubNbaseinfoAiccs> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("CASEID", entity.getCaseid());
                    CasePubNbaseinfoAiccs existing = casePubNbaseinfoMapperAiccs.selectOne(queryWrapper);
                    if (existing != null) {
                        casePubNbaseinfoMapperAiccs.updateById(entity);
                    } else {
                        casePubNbaseinfoMapperAiccs.insert(entity);
                    }
                }
            }
            return true;
        } catch (Exception e) {
            log.error("插入CASE_PUB_NBASEINFO表失败", e);
            return false;
        }
    }

    private boolean insertOrUpdateEOtNpermit(List<?> dataList, String uniscid) {
        try {
            for (Object obj : dataList) {
                Map<String, Object> dataMap = (Map<String, Object>) obj;
                EOtNpermitAiccs entity = mapToEntity(dataMap, EOtNpermitAiccs.class);
                if (entity != null) {
                    QueryWrapper<EOtNpermitAiccs> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("LICID", entity.getLicid());
                    EOtNpermitAiccs existing = eOtNpermitMapperAiccs.selectOne(queryWrapper);
                    if (existing != null) {
                        eOtNpermitMapperAiccs.updateById(entity);
                    } else {
                        eOtNpermitMapperAiccs.insert(entity);
                    }
                }
            }
            return true;
        } catch (Exception e) {
            log.error("插入E_OT_NPERMIT表失败", e);
            return false;
        }
    }

    private boolean insertOrUpdateEOtNcase(List<?> dataList, String uniscid) {
        try {
            for (Object obj : dataList) {
                Map<String, Object> dataMap = (Map<String, Object>) obj;
                EOtNcaseAiccs entity = mapToEntity(dataMap, EOtNcaseAiccs.class);
                if (entity != null) {
                    QueryWrapper<EOtNcaseAiccs> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("CASEID", entity.getCaseid());
                    EOtNcaseAiccs existing = eOtNcaseMapperAiccs.selectOne(queryWrapper);
                    if (existing != null) {
                        eOtNcaseMapperAiccs.updateById(entity);
                    } else {
                        eOtNcaseMapperAiccs.insert(entity);
                    }
                }
            }
            return true;
        } catch (Exception e) {
            log.error("插入E_OT_NCASE表失败", e);
            return false;
        }
    }
    private boolean insertOrUpdateAnSubcapital(List<?> dataList, String uniscid) {
        try {
            for (Object obj : dataList) {
                Map<String, Object> dataMap = (Map<String, Object>) obj;
                AnSubcapitalAiccs entity = mapToEntity(dataMap, AnSubcapitalAiccs.class);
                if (entity != null) {
                    QueryWrapper<AnSubcapitalAiccs> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("INVID", entity.getInvid());
                    AnSubcapitalAiccs existing = anSubcapitalMapperAiccs.selectOne(queryWrapper);
                    if (existing != null) {
                        anSubcapitalMapperAiccs.updateById(entity);
                    } else {
                        anSubcapitalMapperAiccs.insert(entity);
                    }
                }
            }
            return true;
        } catch (Exception e) {
            log.error("插入AN_SUBCAPITAL表失败", e);
            return false;
        }
    }

    private boolean insertOrUpdateAnForinvestment(List<?> dataList, String uniscid) {
        try {
            for (Object obj : dataList) {
                Map<String, Object> dataMap = (Map<String, Object>) obj;
                AnForinvestmentAiccs entity = mapToEntity(dataMap, AnForinvestmentAiccs.class);
                if (entity != null) {
                    QueryWrapper<AnForinvestmentAiccs> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("OUTINVID", entity.getOutinvid());
                    AnForinvestmentAiccs existing = anForinvestmentMapperAiccs.selectOne(queryWrapper);
                    if (existing != null) {
                        anForinvestmentMapperAiccs.updateById(entity);
                    } else {
                        anForinvestmentMapperAiccs.insert(entity);
                    }
                }
            }
            return true;
        } catch (Exception e) {
            log.error("插入AN_FORINVESTMENT表失败", e);
            return false;
        }
    }

    private boolean insertOrUpdateAnWebsiteinfo(List<?> dataList, String uniscid) {
        try {
            for (Object obj : dataList) {
                Map<String, Object> dataMap = (Map<String, Object>) obj;
                AnWebsiteinfoAiccs entity = mapToEntity(dataMap, AnWebsiteinfoAiccs.class);
                if (entity != null) {
                    QueryWrapper<AnWebsiteinfoAiccs> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("WEBID", entity.getWebid());
                    AnWebsiteinfoAiccs existing = anWebsiteinfoMapperAiccs.selectOne(queryWrapper);
                    if (existing != null) {
                        anWebsiteinfoMapperAiccs.updateById(entity);
                    } else {
                        anWebsiteinfoMapperAiccs.insert(entity);
                    }
                }
            }
            return true;
        } catch (Exception e) {
            log.error("插入AN_WEBSITEINFO表失败", e);
            return false;
        }
    }

    private boolean insertOrUpdateAnAlterstockinfo(List<?> dataList, String uniscid) {
        try {
            for (Object obj : dataList) {
                Map<String, Object> dataMap = (Map<String, Object>) obj;
                AnAlterstockinfoAiccs entity = mapToEntity(dataMap, AnAlterstockinfoAiccs.class);
                if (entity != null) {
                    QueryWrapper<AnAlterstockinfoAiccs> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("INVALTID", entity.getInvaltid());
                    AnAlterstockinfoAiccs existing = anAlterstockinfoMapperAiccs.selectOne(queryWrapper);
                    if (existing != null) {
                        anAlterstockinfoMapperAiccs.updateById(entity);
                    } else {
                        anAlterstockinfoMapperAiccs.insert(entity);
                    }
                }
            }
            return true;
        } catch (Exception e) {
            log.error("插入AN_ALTERSTOCKINFO表失败", e);
            return false;
        }
    }

    private boolean insertOrUpdateAnForguaranteeinfo(List<?> dataList, String uniscid) {
        try {
            for (Object obj : dataList) {
                Map<String, Object> dataMap = (Map<String, Object>) obj;
                AnForguaranteeinfoAiccs entity = mapToEntity(dataMap, AnForguaranteeinfoAiccs.class);
                if (entity != null) {
                    QueryWrapper<AnForguaranteeinfoAiccs> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("MOREID", entity.getMoreid());
                    AnForguaranteeinfoAiccs existing = anForguaranteeinfoMapperAiccs.selectOne(queryWrapper);
                    if (existing != null) {
                        anForguaranteeinfoMapperAiccs.updateById(entity);
                    } else {
                        anForguaranteeinfoMapperAiccs.insert(entity);
                    }
                }
            }
            return true;
        } catch (Exception e) {
            log.error("插入AN_FORGUARANTEEINFO表失败", e);
            return false;
        }
    }

    private boolean insertOrUpdateAnUpdateinfo(List<?> dataList, String uniscid) {
        try {
            for (Object obj : dataList) {
                Map<String, Object> dataMap = (Map<String, Object>) obj;
                AnUpdateinfoAiccs entity = mapToEntity(dataMap, AnUpdateinfoAiccs.class);
                if (entity != null) {
                    QueryWrapper<AnUpdateinfoAiccs> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("ANCHEUID", entity.getAncheuid());
                    AnUpdateinfoAiccs existing = anUpdateinfoMapperAiccs.selectOne(queryWrapper);
                    if (existing != null) {
                        anUpdateinfoMapperAiccs.updateById(entity);
                    } else {
                        anUpdateinfoMapperAiccs.insert(entity);
                    }
                }
            }
            return true;
        } catch (Exception e) {
            log.error("插入AN_UPDATEINFO表失败", e);
            return false;
        }
    }

    private boolean insertOrUpdateAnSupBaseinfo(List<?> dataList, String uniscid) {
        try {
            for (Object obj : dataList) {
                Map<String, Object> dataMap = (Map<String, Object>) obj;
                AnSupBaseinfoAiccs entity = mapToEntity(dataMap, AnSupBaseinfoAiccs.class);
                if (entity != null) {
                    QueryWrapper<AnSupBaseinfoAiccs> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("ANCHEID", entity.getAncheid());
                    AnSupBaseinfoAiccs existing = anSupBaseinfoMapperAiccs.selectOne(queryWrapper);
                    if (existing != null) {
                        anSupBaseinfoMapperAiccs.updateById(entity);
                    } else {
                        anSupBaseinfoMapperAiccs.insert(entity);
                    }
                }
            }
            return true;
        } catch (Exception e) {
            log.error("插入AN_SUP_BASEINFO表失败", e);
            return false;
        }
    }

    private boolean insertOrUpdateAnSocsecinfo(List<?> dataList, String uniscid) {
        try {
            for (Object obj : dataList) {
                Map<String, Object> dataMap = (Map<String, Object>) obj;
                AnSocsecinfoAiccs entity = mapToEntity(dataMap, AnSocsecinfoAiccs.class);
                if (entity != null) {
                    QueryWrapper<AnSocsecinfoAiccs> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("SOSEID", entity.getSoseid());
                    AnSocsecinfoAiccs existing = anSocsecinfoMapperAiccs.selectOne(queryWrapper);
                    if (existing != null) {
                        anSocsecinfoMapperAiccs.updateById(entity);
                    } else {
                        anSocsecinfoMapperAiccs.insert(entity);
                    }
                }
            }
            return true;
        } catch (Exception e) {
            log.error("插入AN_SOCSECINFO表失败", e);
            return false;
        }
    }

    private boolean insertOrUpdateEImPrmtalt(List<?> dataList, String uniscid) {
        try {
            for (Object obj : dataList) {
                Map<String, Object> dataMap = (Map<String, Object>) obj;
                EImPrmtaltAiccs entity = mapToEntity(dataMap, EImPrmtaltAiccs.class);
                if (entity != null) {
                    QueryWrapper<EImPrmtaltAiccs> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("LICALTID", entity.getLicaltid());
                    EImPrmtaltAiccs existing = eImPrmtaltMapperAiccs.selectOne(queryWrapper);
                    if (existing != null) {
                        eImPrmtaltMapperAiccs.updateById(entity);
                    } else {
                        eImPrmtaltMapperAiccs.insert(entity);
                    }
                }
            }
            return true;
        } catch (Exception e) {
            log.error("插入E_IM_PRMTALT表失败", e);
            return false;
        }
    }

    private boolean insertOrUpdateEOtNprmtalt(List<?> dataList, String uniscid) {
        try {
            for (Object obj : dataList) {
                Map<String, Object> dataMap = (Map<String, Object>) obj;
                EOtNprmtaltAiccs entity = mapToEntity(dataMap, EOtNprmtaltAiccs.class);
                if (entity != null) {
                    QueryWrapper<EOtNprmtaltAiccs> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("LICALTID", entity.getLicaltid());
                    EOtNprmtaltAiccs existing = eOtNprmtaltMapperAiccs.selectOne(queryWrapper);
                    if (existing != null) {
                        eOtNprmtaltMapperAiccs.updateById(entity);
                    } else {
                        eOtNprmtaltMapperAiccs.insert(entity);
                    }
                }
            }
            return true;
        } catch (Exception e) {
            log.error("插入E_OT_NPRMTALT表失败", e);
            return false;
        }
    }

    private boolean insertOrUpdateEImInvprodetail(List<?> dataList, String uniscid) {
        try {
            for (Object obj : dataList) {
                Map<String, Object> dataMap = (Map<String, Object>) obj;
                EImInvprodetailAiccs entity = mapToEntity(dataMap, EImInvprodetailAiccs.class);
                if (entity != null) {
                    QueryWrapper<EImInvprodetailAiccs> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("INVID", entity.getInvid());
                    EImInvprodetailAiccs existing = eImInvprodetailMapperAiccs.selectOne(queryWrapper);
                    if (existing != null) {
                        eImInvprodetailMapperAiccs.updateById(entity);
                    } else {
                        eImInvprodetailMapperAiccs.insert(entity);
                    }
                }
            }
            return true;
        } catch (Exception e) {
            log.error("插入E_IM_INVPRODETAIL表失败", e);
            return false;
        }
    }

    private boolean insertOrUpdateEImInvactdetail(List<?> dataList, String uniscid) {
        try {
            for (Object obj : dataList) {
                Map<String, Object> dataMap = (Map<String, Object>) obj;
                EImInvactdetailAiccs entity = mapToEntity(dataMap, EImInvactdetailAiccs.class);
                if (entity != null) {
                    QueryWrapper<EImInvactdetailAiccs> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("PAIDID", entity.getPaidid());
                    EImInvactdetailAiccs existing = eImInvactdetailMapperAiccs.selectOne(queryWrapper);
                    if (existing != null) {
                        eImInvactdetailMapperAiccs.updateById(entity);
                    } else {
                        eImInvactdetailMapperAiccs.insert(entity);
                    }
                }
            }
            return true;
        } catch (Exception e) {
            log.error("插入E_IM_INVACTDETAIL表失败", e);
            return false;
        }
    }

    private boolean insertOrUpdateEImIppldgalt(List<?> dataList, String uniscid) {
        try {
            for (Object obj : dataList) {
                Map<String, Object> dataMap = (Map<String, Object>) obj;
                EImIppldgaltAiccs entity = mapToEntity(dataMap, EImIppldgaltAiccs.class);
                if (entity != null) {
                    QueryWrapper<EImIppldgaltAiccs> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("PLEALTID", entity.getPlealtid());
                    EImIppldgaltAiccs existing = eImIppldgaltMapperAiccs.selectOne(queryWrapper);
                    if (existing != null) {
                        eImIppldgaltMapperAiccs.updateById(entity);
                    } else {
                        eImIppldgaltMapperAiccs.insert(entity);
                    }
                }
            }
            return true;
        } catch (Exception e) {
            log.error("插入E_IM_IPPLDGALT表失败", e);
            return false;
        }
    }

    private boolean insertOrUpdateEImCasalt(List<?> dataList, String uniscid) {
        try {
            for (Object obj : dataList) {
                Map<String, Object> dataMap = (Map<String, Object>) obj;
                EImCasaltAiccs entity = mapToEntity(dataMap, EImCasaltAiccs.class);
                if (entity != null) {
                    QueryWrapper<EImCasaltAiccs> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("CASEALTID", entity.getCasealtid());
                    EImCasaltAiccs existing = eImCasaltMapperAiccs.selectOne(queryWrapper);
                    if (existing != null) {
                        eImCasaltMapperAiccs.updateById(entity);
                    } else {
                        eImCasaltMapperAiccs.insert(entity);
                    }
                }
            }
            return true;
        } catch (Exception e) {
            log.error("插入E_IM_CASALT表失败", e);
            return false;
        }
    }

    private boolean insertOrUpdateCasePubNdoc(List<?> dataList, String uniscid) {
        try {
            for (Object obj : dataList) {
                Map<String, Object> dataMap = (Map<String, Object>) obj;
                CasePubNdocAiccs entity = mapToEntity(dataMap, CasePubNdocAiccs.class);
                if (entity != null) {
                    QueryWrapper<CasePubNdocAiccs> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("CASEDECBOOKID", entity.getCasedecbookid());
                    CasePubNdocAiccs existing = casePubNdocMapperAiccs.selectOne(queryWrapper);
                    if (existing != null) {
                        casePubNdocMapperAiccs.updateById(entity);
                    } else {
                        casePubNdocMapperAiccs.insert(entity);
                    }
                }
            }
            return true;
        } catch (Exception e) {
            log.error("插入CASE_PUB_NDOC表失败", e);
            return false;
        }
    }

    private boolean insertOrUpdateCasePubNalter(List<?> dataList, String uniscid) {
        try {
            for (Object obj : dataList) {
                Map<String, Object> dataMap = (Map<String, Object>) obj;
                CasePubNalterAiccs entity = mapToEntity(dataMap, CasePubNalterAiccs.class);
                if (entity != null) {
                    QueryWrapper<CasePubNalterAiccs> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("CASEALTID", entity.getCasealtid());
                    CasePubNalterAiccs existing = casePubNalterMapperAiccs.selectOne(queryWrapper);
                    if (existing != null) {
                        casePubNalterMapperAiccs.updateById(entity);
                    } else {
                        casePubNalterMapperAiccs.insert(entity);
                    }
                }
            }
            return true;
        } catch (Exception e) {
            log.error("插入CASE_PUB_NALTER表失败", e);
            return false;
        }
    }

    private boolean insertOrUpdateEOtNcasalt(List<?> dataList, String uniscid) {
        try {
            for (Object obj : dataList) {
                Map<String, Object> dataMap = (Map<String, Object>) obj;
                EOtNcasaltAiccs entity = mapToEntity(dataMap, EOtNcasaltAiccs.class);
                if (entity != null) {
                    QueryWrapper<EOtNcasaltAiccs> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("CASEALTID", entity.getCasealtid());
                    EOtNcasaltAiccs existing = eOtNcasaltMapperAiccs.selectOne(queryWrapper);
                    if (existing != null) {
                        eOtNcasaltMapperAiccs.updateById(entity);
                    } else {
                        eOtNcasaltMapperAiccs.insert(entity);
                    }
                }
            }
            return true;
        } catch (Exception e) {
            log.error("插入E_OT_NCASALT表失败", e);
            return false;
        }
    }

    /**
     * 通用的插入或更新方法
     */
    private <T> boolean genericInsertOrUpdate(List<?> dataList, com.baomidou.mybatisplus.core.mapper.BaseMapper<T> mapper, String idField) {
        try {
            // 使用反射获取泛型类型
            Class<T> entityClass = getEntityClassFromMapper(mapper);

            for (Object obj : dataList) {
                Map<String, Object> dataMap = (Map<String, Object>) obj;
                T entity = mapToEntity(dataMap, entityClass);
                if (entity != null) {
                    // 使用反射获取ID字段的值
                    Object idValue = getFieldValue(entity, idField);

                    // 检查ID字段是否存在
                    if (idField == null || "null".equals(idField)) {
                        log.warn("实体类 {} 的 ID 字段不存在或为 null，跳过处理", entity.getClass().getSimpleName());
                        continue;
                    }

                    if (idValue != null) {
                        T existing = selectById(mapper, idField, idValue);
                        if (existing != null) {
                            updateById(mapper, entity, idField);
                            log.debug("实体类 {} ID={} 更新成功", entity.getClass().getSimpleName(), idValue);
                        } else {
                            insert(mapper, entity);
                            log.debug("实体类 {} ID={} 插入成功", entity.getClass().getSimpleName(), idValue);
                        }
                    } else {
                        // ID 字段值为空，直接插入
                        insert(mapper, entity);
                        log.debug("实体类 {} ID 字段为空，直接插入", entity.getClass().getSimpleName());
                    }
                }
            }
            return true;
        } catch (Exception e) {
            log.error("通用插入或更新失败", e);
            return false;
        }
    }

    // 通用的数据库操作方法
    private <T> T selectById(com.baomidou.mybatisplus.core.mapper.BaseMapper<T> mapper, String idField, Object idValue) {
        try {
            QueryWrapper<T> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(idField, idValue);
            return mapper.selectOne(queryWrapper);
        } catch (Exception e) {
            log.debug("查询失败", e);
            return null;
        }
    }

    private <T> void updateById(com.baomidou.mybatisplus.core.mapper.BaseMapper<T> mapper, T entity, String idField) {
        try {
            // 使用 update 方法 + Where 条件，而不是 updateById
            // 这样不需要 @TableId 注解
            QueryWrapper<T> updateWrapper = new QueryWrapper<>();
            // 获取 ID 字段值
            Object idValue = getFieldValue(entity, idField);
            if (idValue != null) {
                updateWrapper.eq(idField, idValue);
                mapper.update(entity, updateWrapper);
                log.debug("使用 Where 条件更新成功，字段={}, 值={}", idField, idValue);
            } else {
                log.warn("无法获取 ID 字段值，更新失败");
            }
        } catch (Exception e) {
            log.error("更新失败", e);
            throw e;
        }
    }

    private <T> void insert(com.baomidou.mybatisplus.core.mapper.BaseMapper<T> mapper, T entity) {
        try {
            mapper.insert(entity);
        } catch (Exception e) {
            log.error("插入失败", e);
            throw e;
        }
    }

    private Class<?> getEntityClass(com.baomidou.mybatisplus.core.mapper.BaseMapper<?> mapper) {
        // 根据mapper的类型返回对应的实体类
        // 这是一个简化实现，实际项目中可以通过更复杂的反射机制获取
        if (mapper instanceof EBaseInfoDataMoveMapper) {
            return EBaseInfo.class;
        } else if (mapper instanceof EAlterRecoderDataMoveMapper) {
            return EAlterRecoder.class;
        } else if (mapper instanceof EImPermitDataMoveMapper) {
            return EImPermit.class;
        } else if (mapper instanceof EOtSpotcheckDataMoveMapper) {
            return EOtSpotcheck.class;
        } else if (mapper instanceof EPubSpotcheckDataMoveMapper) {
            return EPubSpotcheck.class;
        } else if (mapper instanceof DrRaninsresDataMoveMapper) {
            return DrRaninsres.class;
        } else if (mapper instanceof AoOpAnomalyDataMoveMapper) {
            return AoOpAnomaly.class;
        } else if (mapper instanceof AoOpaDetailDataMoveMapper) {
            return AoOpaDetail.class;
        } else if (mapper instanceof AoOpAnomalyInvDataMoveMapper) {
            return AoOpAnomalyInv.class;
        } else if (mapper instanceof AnBaseinfoDataMoveMapper) {
            return AnBaseinfo.class;
        } else if (mapper instanceof EImInvestmentDataMoveMapper) {
            return EImInvestment.class;
        } else if (mapper instanceof EImInvupdateDataMoveMapper) {
            return EImInvupdate.class;
        } else if (mapper instanceof CaseCreInformationDataMoveMapper) {
            return CaseCreInformation.class;
        } else if (mapper instanceof EImIppldgDataMoveMapper) {
            return EImIppldg.class;
        } else if (mapper instanceof EImCaseDataMoveMapper) {
            return EImCase.class;
        } else if (mapper instanceof EImInvsraltDataMoveMapper) {
            return EImInvsralt.class;
        } else if (mapper instanceof ELiIlldishonestyDataMoveMapper) {
            return ELiIlldishonesty.class;
        } else if (mapper instanceof ELiIlldisdetailDataMoveMapper) {
            return ELiIlldisdetail.class;
        } else if (mapper instanceof CasePubNbaseinfoDataMoveMapper) {
            return CasePubNbaseinfo.class;
        } else if (mapper instanceof EOtNpermitDataMoveMapper) {
            return EOtNpermit.class;
        } else if (mapper instanceof EOtNcaseDataMoveMapper) {
            return EOtNcase.class;
        } else if (mapper instanceof AnSubcapitalDataMoveMapper) {
            return AnSubcapital.class;
        } else if (mapper instanceof AnForinvestmentDataMoveMapper) {
            return AnForinvestment.class;
        } else if (mapper instanceof AnWebsiteinfoDataMoveMapper) {
            return AnWebsiteinfo.class;
        } else if (mapper instanceof AnAlterstockinfoDataMoveMapper) {
            return AnAlterstockinfo.class;
        } else if (mapper instanceof AnForguaranteeinfoDataMoveMapper) {
            return AnForguaranteeinfo.class;
        } else if (mapper instanceof AnUpdateinfoDataMoveMapper) {
            return AnUpdateinfo.class;
        } else if (mapper instanceof AnSupBaseinfoDataMoveMapper) {
            return AnSupBaseinfo.class;
        } else if (mapper instanceof AnSocsecinfoDataMoveMapper) {
            return AnSocsecinfo.class;
        } else if (mapper instanceof EImPrmtaltDataMoveMapper) {
            return EImPrmtalt.class;
        } else if (mapper instanceof EOtNprmtaltDataMoveMapper) {
            return EOtNprmtalt.class;
        } else if (mapper instanceof EImInvprodetailDataMoveMapper) {
            return EImInvprodetail.class;
        } else if (mapper instanceof EImInvactdetailDataMoveMapper) {
            return EImInvactdetail.class;
        } else if (mapper instanceof EImIppldgaltDataMoveMapper) {
            return EImIppldgalt.class;
        } else if (mapper instanceof EImCasaltDataMoveMapper) {
            return EImCasalt.class;
        } else if (mapper instanceof CasePubNdocDataMoveMapper) {
            return CasePubNdoc.class;
        } else if (mapper instanceof CasePubNalterDataMoveMapper) {
            return CasePubNalter.class;
        } else if (mapper instanceof EOtNcasaltDataMoveMapper) {
            return EOtNcasalt.class;
        } else {
            throw new IllegalArgumentException("未知的Mapper类型：" + mapper.getClass().getName());
        }
    }

    /**
     * 使用反射从Mapper中获取实体类类型（处理Spring代理对象）
     */
    private <T> Class<T> getEntityClassFromMapper(com.baomidou.mybatisplus.core.mapper.BaseMapper<T> mapper) {
        try {
            // 方案1：尝试从getGenericInterfaces获取泛型类型
            java.lang.reflect.Type[] genericInterfaces = mapper.getClass().getGenericInterfaces();

            for (java.lang.reflect.Type genericType : genericInterfaces) {
                if (genericType instanceof java.lang.reflect.ParameterizedType) {
                    java.lang.reflect.ParameterizedType paramType = (java.lang.reflect.ParameterizedType) genericType;
                    if (paramType.getRawType() instanceof Class) {
                        Class<?> rawClass = (Class<?>) paramType.getRawType();
                        if (rawClass.getName().contains("BaseMapper")) {
                            java.lang.reflect.Type[] typeArguments = paramType.getActualTypeArguments();
                            if (typeArguments != null && typeArguments.length > 0) {
                                java.lang.reflect.Type typeArg = typeArguments[0];
                                if (typeArg instanceof Class) {
                                    return (Class<T>) typeArg;
                                }
                            }
                        }
                    }
                }
            }

            // 方案2：如果方案1失败，从Mapper类名推断实体类名
            Class<?> mapperClass = mapper.getClass();
            String mapperClassName = mapperClass.getName();

            // 从类名中提取实体类名
            // 例如：EBaseInfoDataMoveMapperAiccs -> EBaseInfoAiccs
            String entityClassName = extractEntityClassNameFromMapper(mapperClassName);
            if (entityClassName != null) {
                try {
                    Class<?> entityClass = Class.forName(entityClassName);
                    return (Class<T>) entityClass;
                } catch (ClassNotFoundException e) {
                    log.error("通过类名推断的实体类不存在：{}", entityClassName, e);
                }
            }

            // 方案3：方案1和2都失败，回退到旧的getEntityClass方法
            log.warn("反射和类名推断都无法获取实体类，回退到getEntityClass方法：{}", mapperClassName);
            Class<?> entityClass = getEntityClass(mapper);
            return (Class<T>) entityClass;

        } catch (Exception e) {
            log.error("通过反射获取Mapper实体类失败：{}", mapper.getClass().getName(), e);
            // 抛出异常，让调用者知道问题
            if (e instanceof IllegalArgumentException) {
                throw e;
            }
            throw new IllegalArgumentException("无法获取Mapper的实体类类型：" + mapper.getClass().getName(), e);
        }
    }

    /**
     * 从Mapper类名推断实体类名
     * 例如：EBaseInfoDataMoveMapperAiccs -> EBaseInfoAiccs
     */
    private String extractEntityClassNameFromMapper(String mapperClassName) {
        // 处理AICCS Mapper：EBaseInfoDataMoveMapperAiccs -> EBaseInfoAiccs
        if (mapperClassName.contains("DataMoveMapperAiccs")) {
            // 提取类名部分
            int lastDot = mapperClassName.lastIndexOf('.');
            String simpleClassName = mapperClassName.substring(lastDot + 1);

            // 移除后缀：EBaseInfoDataMoveMapperAiccs -> EBaseInfo
            String prefix = simpleClassName.replace("DataMoveMapperAiccs", "");

            // 添加Aiccs后缀：EBaseInfo -> EBaseInfoAiccs
            return "com.chinaweal.aiccs.aiccs.abnormal.entity.datamove." + prefix + "Aiccs";
        }

        // 处理原始Mapper：EBaseInfoDataMoveMapper -> EBaseInfo
        if (mapperClassName.contains("DataMoveMapper") && !mapperClassName.contains("Aiccs")) {
            int lastDot = mapperClassName.lastIndexOf('.');
            String simpleClassName = mapperClassName.substring(lastDot + 1);

            String prefix = simpleClassName.replace("DataMoveMapper", "");
            return "com.chinaweal.aiccs.aicbiz.entity.datamove." + prefix;
        }

        return null;
    }

    /**
     * 将Map转换为实体对象
     */
    private <T> T mapToEntity(Map<String, Object> dataMap, Class<T> entityClass) {
        try {
            T entity = entityClass.newInstance();
            log.debug("开始将Map转换为实体对象: {}", entityClass.getSimpleName());

            for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
                String fieldName = entry.getKey();
                Object value = entry.getValue();

                // 如果值为空，跳过
                if (value == null) {
                    log.debug("字段 {} 的值为空，跳过", fieldName);
                    continue;
                }

                log.debug("处理字段: {}, 原始值: '{}', 类型: {}",
                         fieldName, value, value.getClass().getSimpleName());

                try {
                    // 先尝试直接匹配（可能已经是小写）
                    Field field = entityClass.getDeclaredField(fieldName);
                    field.setAccessible(true);
                    // 进行类型转换
                    Object convertedValue = convertValue(field.getType(), value);
                    field.set(entity, convertedValue);
                    log.debug("直接匹配成功: {} = '{}'", fieldName, convertedValue);
                } catch (NoSuchFieldException e) {
                    // 如果直接匹配失败，尝试转换为驼峰命名
                    try {
                        String camelCaseName = toCamelCase(fieldName);
                        Field field = entityClass.getDeclaredField(camelCaseName);
                        field.setAccessible(true);
                        // 进行类型转换
                        Object convertedValue = convertValue(field.getType(), value);
                        field.set(entity, convertedValue);
                        log.debug("驼峰匹配成功: {} -> {} = '{}'", fieldName, camelCaseName, convertedValue);
                    } catch (NoSuchFieldException e2) {
                        // 忽略不存在的字段
                        log.debug("字段 {} 在实体类 {} 中不存在", fieldName, entityClass.getSimpleName());
                    }
                } catch (Exception e) {
                    log.error("设置字段 {} 时发生错误: {}", fieldName, e.getMessage(), e);
                    // 继续处理其他字段
                }
            }

            log.debug("Map转实体对象完成: {}", entityClass.getSimpleName());
            return entity;
        } catch (Exception e) {
            log.error("Map转实体对象失败", e);
            return null;
        }
    }

    /**
     * 将值转换为目标类型
     */
    /**
     * 将值转换为目标类型 - 使用通用转换工具类
     */
    private Object convertValue(Class<?> targetType, Object value) {
        return TypeConversionUtils.convertValue(value, targetType);
    }

    /**
     * 解析日期字符串为 java.util.Date
     * 支持多种日期格式
     */
    private Date parseDate(String dateStr) {
        if (dateStr == null || dateStr.trim().isEmpty()) {
            return null;
        }

        // 常见的日期格式
        String[] formats = {
            "yyyy-MM-dd HH:mm:ss",
            "yyyy-MM-dd HH:mm",
            "yyyy-MM-dd",
            "yyyy/MM/dd HH:mm:ss",
            "yyyy/MM/dd HH:mm",
            "yyyy/MM/dd",
            "yyyy.MM.dd HH:mm:ss",
            "yyyy.MM.dd",
            "yyyy年MM月dd日",
            "yyyyMMdd",
            "yyyyMMddHHmmss"
        };

        for (String format : formats) {
            try {
                return new SimpleDateFormat(format).parse(dateStr);
            } catch (Exception e) {
                // 尝试下一个格式
            }
        }

        log.debug("无法解析日期字符串: {}", dateStr);
        return null;
    }

    /**
     * 将下划线分隔的字符串转换为驼峰命名
     */
    private String toCamelCase(String str) {
        if (str == null || str.isEmpty()) {
            return str;
        }
        StringBuilder result = new StringBuilder();
        boolean nextUpperCase = false;
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (ch == '_') {
                nextUpperCase = true;
            } else {
                if (nextUpperCase) {
                    result.append(Character.toUpperCase(ch));
                    nextUpperCase = false;
                } else {
                    result.append(Character.toLowerCase(ch));
                }
            }
        }
        return result.toString();
    }

    /**
     * 获取字段值
     */
    private Object getFieldValue(Object obj, String fieldName) {
        try {
            // 如果字段名为null，返回null
            if (fieldName == null) {
                return null;
            }

            // 先尝试直接匹配
            try {
                Field field = obj.getClass().getDeclaredField(fieldName);
                field.setAccessible(true);
                Object value = field.get(obj);
                // 如果字段名本身是"null"字符串，返回null（这表示字段未找到）
                return "null".equals(fieldName) ? null : value;
            } catch (NoSuchFieldException e) {
                // 如果直接匹配失败，尝试转换为驼峰命名
                String camelCaseName = toCamelCase(fieldName);
                Field field = obj.getClass().getDeclaredField(camelCaseName);
                field.setAccessible(true);
                Object value = field.get(obj);
                // 如果字段名本身是"null"字符串，返回null（这表示字段未找到）
                return "null".equals(fieldName) ? null : value;
            }
        } catch (Exception e) {
            log.debug("获取字段 {} 的值失败，字段不存在", fieldName);
            return null;
        }
    }

    /**
     * 记录文件上传结果
     */
    private boolean recordFileUploadResult(String pripid, String filePath, String isSuccess, String processRecord, String reconciliationPar, String minId) {
        try {
            // 查询企业基本信息
            String entBaseInfo = queryEnterpriseBaseInfo(pripid);
            if (entBaseInfo == null) {
                log.error("无法查询企业基本信息，无法记录文件上传结果，PRIPID={}, 文件路径={}", pripid, filePath);
                return false;
            }

            // 解析企业信息
            String[] infoParts = entBaseInfo.split("\\|");
            String uniscid = infoParts[0];
            String entname = infoParts[1];

            // 创建上传记录
            FileUploadRecord uploadRecord = new FileUploadRecord();
            uploadRecord.setId(UUID.randomUUID().toString().replace("-", ""));
            uploadRecord.setPripid(pripid);
            uploadRecord.setUniscid(uniscid);
            uploadRecord.setEntname(entname);
            uploadRecord.setRegno(null);
            uploadRecord.setUploadDir(filePath);
            uploadRecord.setMigrationType(2); // 数据迁入
            uploadRecord.setProcessRecord(processRecord);
            uploadRecord.setReconciliationPar(reconciliationPar);
            uploadRecord.setMinId(minId);

            Timestamp currentTime = new Timestamp(System.currentTimeMillis());
            uploadRecord.setCreateTime(currentTime);
            uploadRecord.setUpdateTime(currentTime);
            uploadRecord.setIsyn(isSuccess);

            QueryWrapper<FileUploadRecord> wrapper = new QueryWrapper<>();
            wrapper.eq("MIN_ID", minId);
            List<FileUploadRecord> fileUploadRecordList = fileUploadRecordMapper.selectList(wrapper);

            if (CollUtil.isNotEmpty(fileUploadRecordList)) {
                uploadRecord.setId(fileUploadRecordList.get(0).getId());
                fileUploadRecordMapper.updateById(uploadRecord);
                return true;
            } else {
                int result = fileUploadRecordMapper.insert(uploadRecord);
                if (result > 0) {
                    log.info("记录文件上传{}成功：PRIPID={}, UNISCID={}, 文件路径={}, 流程记录={}",
                            "Y".equals(isSuccess) ? "成功" : "失败", pripid, uniscid, filePath, processRecord);
                    return true;
                } else {
                    log.error("记录文件上传结果失败：PRIPID={}, 文件路径={}", pripid, filePath);
                    return false;
                }
            }

        } catch (Exception e) {
            log.error("记录文件上传结果时发生错误，PRIPID={}, 文件路径={}", pripid, filePath, e);
            return false;
        }
    }

    /**
     * 构建对账参数JSON字符串
     */
    private String buildReconciliationParams(String uniscid, String entname, Map<String, Integer> recordCountMap, String moutareregorg) {
        try {
            Map<String, Object> recordData = new HashMap<>();
            recordData.put("appform", appform);
            recordData.put("uniscid", uniscid);
            recordData.put("entname", entname);
            recordData.put("moveInProvince", "440000");  // 迁入省份
            String minOrg = "";
            if (moutareregorg != null && moutareregorg.length() >= 2) {
                minOrg = moutareregorg.substring(0, 2) + "0000";
            }
            recordData.put("moveOutProvince", minOrg);  // 迁出省份

            recordData.put("eBaseinfo", recordCountMap.getOrDefault("E_BASEINFO", 0));
            recordData.put("eAlterRecoder", recordCountMap.getOrDefault("E_ALTER_RECODER", 0));
            recordData.put("ePubSpotcheck", recordCountMap.getOrDefault("E_PUB_SPOTCHECK", 0));
            recordData.put("drRaninsres", recordCountMap.getOrDefault("DR_RANINSRES", 0));
            recordData.put("aoOpAnomaly", recordCountMap.getOrDefault("AO_OPANOMALY", 0));
            recordData.put("aoOpaDetail", recordCountMap.getOrDefault("AO_OPA_DETAIL", 0));
            recordData.put("aoOpAnomalyInv", recordCountMap.getOrDefault("AO_OPANOMALY_INV", 0));
            recordData.put("anBaseinfo", recordCountMap.getOrDefault("AN_BASEINFO", 0));
            recordData.put("anSubcapital", recordCountMap.getOrDefault("AN_SUBCAPITAL", 0));
            recordData.put("anForinvestment", recordCountMap.getOrDefault("AN_FORINVESTMENT", 0));
            recordData.put("anWebsiteinfo", recordCountMap.getOrDefault("AN_WEBSITEINFO", 0));
            recordData.put("anAlterstockinfo", recordCountMap.getOrDefault("AN_ALTERSTOCKINFO", 0));
            recordData.put("anForguaranteeinfo", recordCountMap.getOrDefault("AN_FORGUARANTEEINFO", 0));
            recordData.put("anUpdateinfo", recordCountMap.getOrDefault("AN_UPDATEINFO", 0));
            recordData.put("anSupBaseinfo", recordCountMap.getOrDefault("AN_SUP_BASEINFO", 0));
            recordData.put("anSocsecinfo", recordCountMap.getOrDefault("AN_SOCSECINFO", 0));
            recordData.put("eImPermit", recordCountMap.getOrDefault("E_IM_PERMIT", 0));
            recordData.put("eImPrmtalt", recordCountMap.getOrDefault("E_IM_PRMTALT", 0));
            recordData.put("eImInvestment", recordCountMap.getOrDefault("E_IM_INVESTMENT", 0));
            recordData.put("eImInvprodetail", recordCountMap.getOrDefault("E_IM_INVPRODETAIL", 0));
            recordData.put("eImInvactdetail", recordCountMap.getOrDefault("E_IM_INVACTDETAIL", 0));
            recordData.put("eImInvupdate", recordCountMap.getOrDefault("E_IM_INVUPDATE", 0));
            recordData.put("eImIppldg", recordCountMap.getOrDefault("E_IM_IPPLDG", 0));
            recordData.put("eImIppldgalt", recordCountMap.getOrDefault("E_IM_IPPLDGALT", 0));
            recordData.put("eImCase", recordCountMap.getOrDefault("E_IM_CASE", 0));
            recordData.put("eImCasalt", recordCountMap.getOrDefault("E_IM_CASALT", 0));
            recordData.put("eImInvsralt", recordCountMap.getOrDefault("E_IM_INVSRALT", 0));
            recordData.put("eLiIlldishonesty", recordCountMap.getOrDefault("E_LI_ILLDISHONESTY", 0));
            recordData.put("eLiIlldisdetail", recordCountMap.getOrDefault("E_LI_ILLDISDETAIL", 0));
            recordData.put("casePubNbaseinfo", recordCountMap.getOrDefault("CASE_PUB_NBASEINFO", 0));
            recordData.put("casePubNdoc", recordCountMap.getOrDefault("CASE_PUB_NDOC", 0));
            recordData.put("casePubNalter", recordCountMap.getOrDefault("CASE_PUB_NALTER", 0));
            recordData.put("eOtNpermit", recordCountMap.getOrDefault("E_OT_NPERMIT", 0));
            recordData.put("eOtNprmtalt", recordCountMap.getOrDefault("E_OT_NPRMTALT", 0));
            recordData.put("eOtNcase", recordCountMap.getOrDefault("E_OT_NCASE", 0));
            recordData.put("eOtNcasalt", recordCountMap.getOrDefault("E_OT_NCASALT", 0));
            recordData.put("eOtSpotcheck", recordCountMap.getOrDefault("E_OT_SPOTCHECK", 0));
            recordData.put("caseCreInformation", recordCountMap.getOrDefault("CASE_CRE_INFORMATION", 0));


            // 序列化后，打印完整JSON（这行必须加！）
            String jsonParams = JSONUtil.toJsonStr(recordData);
            log.info("发送给对账接口的完整JSON参数：{}", jsonParams); // 重点看这个日志中的 aoOpanomaly

            return new JSONObject(recordData).toString();


        } catch (Exception e) {
            log.error("构建对账参数JSON时发生错误.", e);
            return "{}";
        }
    }

    /**
     * 调用下载对账接口
     * @param uniscid 企业统一社会信用代码
     * @param entname 企业名称
     * @param moveInProvince 迁入省份
     * @param moveOutProvince 迁出省份
     * @param moutareregorg 迁出地区编号
     * @return 下载对账接口返回的JSON数据，失败返回null
     */
    private JSONObject callDownloadRecordInfoApi(String uniscid, String entname, String moveInProvince, String moveOutProvince, String moutareregorg) {
        try {
            // 根据环境选择下载对账接口地址
            String downloadRecordUrl = "prod".equals(env) ? prodDownloadRecordInfoUrl : testDownloadRecordInfoUrl;

            log.info("开始调用下载对账接口：企业={}, 企业名={}, 接口地址={}", uniscid, entname, downloadRecordUrl);

            // 构建请求参数
            Map<String, Object> requestParams = new HashMap<>();
            requestParams.put("appform", appform);
            requestParams.put("uniscid", uniscid);
            requestParams.put("moveInProvince", moveInProvince);
            String minOrg = "";
            if (moveOutProvince != null && moveOutProvince.length() >= 2) {
                 minOrg = moveOutProvince.substring(0, 2) + "0000";

            }
            requestParams.put("moveOutProvince", minOrg);
            String pinyin = getPinyin(minOrg);
            requestParams.put("province", pinyin); // 固定值为"shandong"
            requestParams.put("entname", entname);

            // 构建请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            // 构建请求实体
            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestParams, headers);

            log.info("调用下载对账接口：URL={}, 参数={}", downloadRecordUrl, requestParams);

            // 调用接口
            String response = restTemplate.postForObject(downloadRecordUrl, requestEntity, String.class);

            if (StrUtil.isNotEmpty(response)) {
                // 解析JSON响应
                JSONObject jsonResponse = new JSONObject(response);

                // 检查返回码
                if ("2000".equals(jsonResponse.getStr("resultCode"))) {
                    log.info("企业{}下载对账接口调用成功：{}", uniscid, jsonResponse.getStr("resultMsg"));
                    return jsonResponse;
                } else {
                    log.warn("企业{}下载对账接口调用失败：{}", uniscid, jsonResponse.getStr("resultMsg"));
                    return null;
                }
            } else {
                log.error("企业{}下载对账接口返回空响应", uniscid);
                return null;
            }

        } catch (Exception e) {
            String errorMsg = e.getMessage() != null && e.getMessage().length() <= 2000 ? e.getMessage() : "下载对账接口调用异常，具体错误信息超过2000字符限制";
            log.error("企业{}调用下载对账接口时发生错误：{}", uniscid, errorMsg);
            return null;
        }
    }

    /**
     * 调用对账接口
     */
    private void callRecordInfoApi(String uniscid, String entname, Map<String, Integer> recordCountMap, String moutareregorg) {
        try {
            // 根据环境选择对账接口地址
            String recordUrl = "prod".equals(env) ? prodMoveInRecordUrl : testMoveInRecordUrl;

            log.info("开始调用上传对账接口：企业={}, 企业名={}, 对账地址={}", uniscid, entname, recordUrl);

            // 构建对账接口参数
            Map<String, Object> recordData = new HashMap<>();
            recordData.put("appform", appform);
            recordData.put("uniscid", uniscid);
            recordData.put("entname", entname);
            recordData.put("moveInProvince", "440000");  // 迁入省份就是我们自己省份固定的

            if (moutareregorg != null && moutareregorg.length() >= 2) {
                recordData.put("moveOutProvince", moutareregorg.substring(0, 2) + "0000");  // 迁出省份
            }else {
                recordData.put("moveOutProvince", "");
            }
            // 设置各表的数量
            recordData.put("eBaseinfo", String.valueOf(recordCountMap.getOrDefault("E_BASEINFO", 0)));
            recordData.put("eAlterRecoder", String.valueOf(recordCountMap.getOrDefault("E_ALTER_RECODER", 0)));
            recordData.put("ePubSpotcheck", String.valueOf(recordCountMap.getOrDefault("E_PUB_SPOTCHECK", 0)));
            recordData.put("drRaninsres", String.valueOf(recordCountMap.getOrDefault("DR_RANINSRES", 0)));
            recordData.put("aoOpanomaly", String.valueOf(recordCountMap.getOrDefault("AO_OPANOMALY", 0)));
            recordData.put("aoOpaDetail", String.valueOf(recordCountMap.getOrDefault("AO_OPA_DETAIL", 0)));
            recordData.put("aoOpanomalyInv", String.valueOf(recordCountMap.getOrDefault("AO_OPANOMALY_INV", 0)));
            recordData.put("anBaseinfo", String.valueOf(recordCountMap.getOrDefault("AN_BASEINFO", 0)));
            recordData.put("anSubcapital", String.valueOf(recordCountMap.getOrDefault("AN_SUBCAPITAL", 0)));
            recordData.put("anForinvestment", String.valueOf(recordCountMap.getOrDefault("AN_FORINVESTMENT", 0)));
            recordData.put("anWebsiteinfo", String.valueOf(recordCountMap.getOrDefault("AN_WEBSITEINFO", 0)));
            recordData.put("anAlterstockinfo", String.valueOf(recordCountMap.getOrDefault("AN_ALTERSTOCKINFO", 0)));
            recordData.put("anForguaranteeinfo", String.valueOf(recordCountMap.getOrDefault("AN_FORGUARANTEEINFO", 0)));
            recordData.put("anUpdateinfo", String.valueOf(recordCountMap.getOrDefault("AN_UPDATEINFO", 0)));
            recordData.put("anSupBaseinfo", String.valueOf(recordCountMap.getOrDefault("AN_SUP_BASEINFO", 0)));
            recordData.put("anSocsecinfo", String.valueOf(recordCountMap.getOrDefault("AN_SOCSECINFO", 0)));
            recordData.put("eImPermit", String.valueOf(recordCountMap.getOrDefault("E_IM_PERMIT", 0)));
            recordData.put("eImPrmtalt", String.valueOf(recordCountMap.getOrDefault("E_IM_PRMTALT", 0)));
            recordData.put("eImInvestment", String.valueOf(recordCountMap.getOrDefault("E_IM_INVESTMENT", 0)));
            recordData.put("eImInvprodetail", String.valueOf(recordCountMap.getOrDefault("E_IM_INVPRODETAIL", 0)));
            recordData.put("eImInvactdetail", String.valueOf(recordCountMap.getOrDefault("E_IM_INVACTDETAIL", 0)));
            recordData.put("eImInvupdate", String.valueOf(recordCountMap.getOrDefault("E_IM_INVUPDATE", 0)));
            recordData.put("eImIppldg", String.valueOf(recordCountMap.getOrDefault("E_IM_IPPLDG", 0)));
            recordData.put("eImIppldgalt", String.valueOf(recordCountMap.getOrDefault("E_IM_IPPLDGALT", 0)));
            recordData.put("eImCase", String.valueOf(recordCountMap.getOrDefault("E_IM_CASE", 0)));
            recordData.put("eImCasalt", String.valueOf(recordCountMap.getOrDefault("E_IM_CASALT", 0)));
            recordData.put("eImInvsralt", String.valueOf(recordCountMap.getOrDefault("E_IM_INVSRALT", 0)));
            recordData.put("eLiIlldishonesty", String.valueOf(recordCountMap.getOrDefault("E_LI_ILLDISHONESTY", 0)));
            recordData.put("eLiIlldisdetail", String.valueOf(recordCountMap.getOrDefault("E_LI_ILLDISDETAIL", 0)));
            recordData.put("casePubNbaseinfo", String.valueOf(recordCountMap.getOrDefault("CASE_PUB_NBASEINFO", 0)));
            recordData.put("casePubNdoc", String.valueOf(recordCountMap.getOrDefault("CASE_PUB_NDOC", 0)));
            recordData.put("casePubNalter", String.valueOf(recordCountMap.getOrDefault("CASE_PUB_NALTER", 0)));
            recordData.put("eOtNpermit", String.valueOf(recordCountMap.getOrDefault("E_OT_NPERMIT", 0)));
            recordData.put("eOtNprmtalt", String.valueOf(recordCountMap.getOrDefault("E_OT_NPRMTALT", 0)));
            recordData.put("eOtNcase", String.valueOf(recordCountMap.getOrDefault("E_OT_NCASE", 0)));
            recordData.put("eOtNcasalt", String.valueOf(recordCountMap.getOrDefault("E_OT_NCASALT", 0)));
            recordData.put("eOtSpotcheck", String.valueOf(recordCountMap.getOrDefault("E_OT_SPOTCHECK", 0)));
            recordData.put("caseCreInformation", String.valueOf(recordCountMap.getOrDefault("CASE_CRE_INFORMATION", 0)));
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            // 创建HttpEntity
            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(recordData, headers);

            // 使用RestTemplate调用对账接口
            String response = restTemplate.postForObject(recordUrl, requestEntity, String.class);

            log.info("上传对账接口响应：企业={}, 企业名={}, 响应内容={}", uniscid, entname, response);

        } catch (Exception e) {
            log.error("调用上传对账接口时发生异常：企业={}, 企业名={}", uniscid, entname, e);
            throw e;
        }
    }

    /**
     * 将解析后的数据保存到独立的List集合中
     * 以表名为key，对应的List集合为值
     * @param parsedDataMap 解析后的数据Map
     * @return 包含所有表数据的Map
     */
    private Map<String, List<?>> extractTableDataLists(Map<String, List<?>> parsedDataMap) {
        Map<String, List<?>> tableDataLists = new HashMap<>();

        // 遍历解析后的数据，为每个表创建独立的List集合
        for (Map.Entry<String, List<?>> entry : parsedDataMap.entrySet()) {
            String tableName = entry.getKey();
            List<?> dataList = entry.getValue();

            // 将数据保存到独立的List集合中
            tableDataLists.put(tableName, dataList);

            log.debug("表 {} 的数据已保存到独立List集合中，数据量: {}", tableName, dataList.size());
        }

        log.info("所有表数据已保存到独立List集合中，共 {} 种表", tableDataLists.size());
        return tableDataLists;
    }

    private boolean insertXt(Map<String, List<?>> tableDataLists, String pripid) {

        boolean result = false;
        String tableName = "unknown"; // 初始化变量，避免未初始化异常

        try {
            if (!tableDataLists.isEmpty()) {
                tableName = tableDataLists.keySet().iterator().next();

                // ================================================================
                // 第一部分：处理企业经营异常名录数据（原有逻辑保持不变）
                // ================================================================

                //获取企业经营异常名录信息AO_OPANOMALY
//                List<?> aoOpAnomalyDataList = tableDataLists.get("AO_OPANOMALY");
//                if (aoOpAnomalyDataList != null && !aoOpAnomalyDataList.isEmpty()) {
//                    for (Object obj : aoOpAnomalyDataList) {
//                        Map<String, Object> dataMap = (Map<String, Object>) obj;
//                        AoOpAnomalyAiccs ao = mapToEntity(dataMap, AoOpAnomalyAiccs.class);
//                        if (ao != null) {
//                            TSAbnList tsAbnList = new TSAbnList();
//                            tsAbnList.setAbnlistid(ao.getBusexclist());
//                            tsAbnList.setPripid(ao.getPripid());
//                            tsAbnList.setEntname(ao.getEntname());
//                            tsAbnList.setUniscid(ao.getUniscid());
//                            tsAbnList.setRegno(ao.getRegno());
//                            tsAbnList.setLerep(ao.getLerep());
//                            tsAbnList.setCerno(ao.getCerno());
//                            tsAbnList.setCertype(ao.getCertype());
//                            tsAbnList.setSpecause(ao.getSpecause());
//                            tsAbnList.setSpecauseCn(ao.getSpecauseCn());
//                            // 如果ao.getAbntime()可能为null，需要先判断避免空指针
//                            Date abnTimeDate = ao.getAbntime();
//                            LocalDate abnTimeLocalDate = null;
//                            if (abnTimeDate != null) {
//                                // 将Date转换为LocalDate
//                                abnTimeLocalDate = abnTimeDate.toInstant()
//                                        .atZone(ZoneId.systemDefault()) // 转换为系统默认时区的ZonedDateTime
//                                        .toLocalDate(); // 提取LocalDate（仅日期部分）
//                            }
//                            tsAbnList.setAbntime(abnTimeLocalDate);
//                            tsAbnList.setDecorg(ao.getDecorg());
//                            tsAbnList.setIntoDecorg(ao.getDecorgCn());
//                            TSAbnList tsAbnList1 = tsAbnListService.queryByAbnlistid(ao.getBusexclist());
//                            if (tsAbnList1 != null) {
//                                // 使用查询出的对象作为更新对象
//                                tsAbnList1.setAbnlistid(tsAbnList.getAbnlistid());
//                                tsAbnList1.setPripid(tsAbnList.getPripid());
//                                tsAbnList1.setEntname(tsAbnList.getEntname());
//                                tsAbnList1.setUniscid(tsAbnList.getUniscid());
//                                tsAbnList1.setRegno(tsAbnList.getRegno());
//                                tsAbnList1.setLerep(tsAbnList.getLerep());
//                                tsAbnList1.setCerno(tsAbnList.getCerno());
//                                tsAbnList1.setCertype(tsAbnList.getCertype());
//                                tsAbnList1.setSpecause(tsAbnList.getSpecause());
//                                tsAbnList1.setSpecauseCn(tsAbnList.getSpecauseCn());
//                                tsAbnList1.setAbntime(tsAbnList.getAbntime());
//                                tsAbnList1.setDecorg(tsAbnList.getDecorg());
//                                tsAbnList1.setIntoDecorg(tsAbnList.getIntoDecorg());
//                                tsAbnListService.updateById(tsAbnList1);
//                            } else {
//                                tsAbnListService.save(tsAbnList);
//                            }
//                        }
//                    }
//                }
//
//                //企业经营异常名录详细信息AO_OPA_DETAIL
//                List<?> aoOpaDetailDataList = tableDataLists.get("AO_OPA_DETAIL");
//                if (aoOpaDetailDataList != null && !aoOpaDetailDataList.isEmpty()) {
//                    for (Object obj : aoOpaDetailDataList) {
//                        Map<String, Object> dataMap = (Map<String, Object>) obj;
//                        AoOpaDetailAiccs ao = mapToEntity(dataMap, AoOpaDetailAiccs.class);
//                        if (ao != null) {
//                            TSAbnList tsAbnList = new TSAbnList();
//                            tsAbnList.setAbnlistid(ao.getBusexclist());
//                            tsAbnList.setPripid(ao.getPripid());
//                            tsAbnList.setEntname(ao.getEntname());
//                            tsAbnList.setUniscid(ao.getUniscid());
//                            tsAbnList.setRegno(ao.getRegno());
//                            tsAbnList.setLerep(ao.getLerep());
//                            tsAbnList.setCerno(ao.getCerno());
//                            tsAbnList.setCertype(ao.getCertype());
//                            tsAbnList.setSpecause(ao.getSpecause());
//                            tsAbnList.setSpecauseCn(ao.getSpecauseCn());
//                            // 如果ao.getAbntime()可能为null，需要先判断避免空指针
//                            Date abnTimeDate = ao.getAbntime();
//                            LocalDate abnTimeLocalDate = null;
//                            if (abnTimeDate != null) {
//                                // 将Date转换为LocalDate
//                                abnTimeLocalDate = abnTimeDate.toInstant()
//                                        .atZone(ZoneId.systemDefault()) // 转换为系统默认时区的ZonedDateTime
//                                        .toLocalDate(); // 提取LocalDate（仅日期部分）
//                            }
//                            tsAbnList.setAbntime(abnTimeLocalDate);
//                            tsAbnList.setDecorg(ao.getDecorg());
//                            tsAbnList.setIntoDecorg(ao.getDecorgCn());
//                            tsAbnList.setOperatestatus(ao.getIsmove());
//                            tsAbnList.setRemexcpres(ao.getRemexcpres());
//                            tsAbnList.setRemexcpresCn(ao.getRemexcpresCn());
//                            Date abnremTimeDate = ao.getRemdate();
//                            LocalDate abnremTimeLocalDate = null;
//                            if (abnremTimeDate != null) {
//                                // 将Date转换为LocalDate
//                                abnremTimeLocalDate = abnremTimeDate.toInstant()
//                                        .atZone(ZoneId.systemDefault()) // 转换为系统默认时区的ZonedDateTime
//                                        .toLocalDate(); // 提取LocalDate（仅日期部分）
//                            }
//                            tsAbnList.setRemdate(abnremTimeLocalDate);
//                            tsAbnList.setReDecorg(ao.getRedecorg());
//                            tsAbnList.setRemDecorgCn(ao.getRedecorgCn());
//                            TSAbnList tsAbnList1 = tsAbnListService.queryByAbnlistid(ao.getBusexclist());
//                            if (tsAbnList1 != null) {
//                                // 使用查询出的对象作为更新对象
//                                tsAbnList1.setAbnlistid(tsAbnList.getAbnlistid());
//                                tsAbnList1.setPripid(tsAbnList.getPripid());
//                                tsAbnList1.setEntname(tsAbnList.getEntname());
//                                tsAbnList1.setUniscid(tsAbnList.getUniscid());
//                                tsAbnList1.setRegno(tsAbnList.getRegno());
//                                tsAbnList1.setLerep(tsAbnList.getLerep());
//                                tsAbnList1.setCerno(tsAbnList.getCerno());
//                                tsAbnList1.setCertype(tsAbnList.getCertype());
//                                tsAbnList1.setSpecause(tsAbnList.getSpecause());
//                                tsAbnList1.setSpecauseCn(tsAbnList.getSpecauseCn());
//                                tsAbnList1.setAbntime(tsAbnList.getAbntime());
//                                tsAbnList1.setDecorg(tsAbnList.getDecorg());
//                                tsAbnList1.setIntoDecorg(tsAbnList.getIntoDecorg());
//                                tsAbnList1.setOperatestatus(tsAbnList.getOperatestatus());
//                                tsAbnList1.setRemexcpres(tsAbnList.getRemexcpres());
//                                tsAbnList1.setRemexcpresCn(tsAbnList.getRemexcpresCn());
//                                tsAbnList1.setRemdate(tsAbnList.getRemdate());
//                                tsAbnList1.setReDecorg(tsAbnList.getReDecorg());
//                                tsAbnList1.setRemDecorgCn(tsAbnList.getRemDecorgCn());
//                                tsAbnListService.updateById(tsAbnList1);
//                            } else {
//                                tsAbnListService.save(tsAbnList);
//                            }
//                        }
//                    }
//                }
//
//                //企业经营异常名录股东信息AO_OPANOMALY_INV
//                List<?> aoOpAnomalyInvDataList = tableDataLists.get("AO_OPANOMALY_INV");
//                if (aoOpAnomalyInvDataList != null && !aoOpAnomalyInvDataList.isEmpty()) {
//                    for (Object obj : aoOpAnomalyInvDataList) {
//                        Map<String, Object> dataMap = (Map<String, Object>) obj;
//                        AoOpAnomalyInvAiccs ao = mapToEntity(dataMap, AoOpAnomalyInvAiccs.class);
//                        if (ao != null) {
//                            // TODO: 实现AO_OPANOMALY_INV的插入逻辑
//                            log.debug("处理企业经营异常名录股东信息AO_OPANOMALY_INV，ID={}", ao.getBlinvid());
//                        }
//                    }
//                }

                // ================================================================
                // 第二部分：处理年报数据（新增按ANCHEID分组逻辑）
                // ================================================================

                // 年报表名列表（主表和8张分表）
                List<String> annualReportTables = Arrays.asList(
                    "AN_BASEINFO",           // 企业年报基本信息表（主表）
                    "AN_ALTERSTOCKINFO",     // 股东及出资变更信息表
                    "AN_FORGUARANTEEINFO",   // 对外担保信息表
                    "AN_FORINVESTMENT",      // 对外投资信息表
                    "AN_SOCSECINFO",         // 社保信息表
                    "AN_SUBCAPITAL",         // 股东及出资信息表
                    "AN_SUP_BASEINFO",       // 年报企业补充信息表
                    "AN_UPDATEINFO",         // 年报修改记录表
                    "AN_WEBSITEINFO"         // 网站或网店信息表
                );

                // 检查是否有年报数据
                boolean hasAnnualReportData = false;
                for (String tableNameKey : annualReportTables) {
                    if (tableDataLists.containsKey(tableNameKey)) {
                        hasAnnualReportData = true;
                        break;
                    }
                }

                if (hasAnnualReportData) {
                    log.info("开始处理年报数据，共{}张表", annualReportTables.size());

                    // 按ANCHEID分组
                    Map<String, Map<String, List<?>>> groupedAnnualReportData = groupAnnualReportDataByAncheid(tableDataLists, annualReportTables);

                    log.info("年报数据按ANCHEID分组完成，共{}组", groupedAnnualReportData.size());

                    // 处理每一组数据
                    for (Map.Entry<String, Map<String, List<?>>> groupEntry : groupedAnnualReportData.entrySet()) {
                        String ancheid = groupEntry.getKey();
                        Map<String, List<?>> tableDataMap = groupEntry.getValue();

                        log.debug("开始处理年报数据组，ANCHEID={}", ancheid);

                        // 插入这一组的数据到数据库
                        boolean groupInsertSuccess = insertAnnualReportGroup(ancheid, tableDataMap,pripid);
                        if (!groupInsertSuccess) {
                            log.error("年报数据组插入失败，ANCHEID={}", ancheid);
                        }
                    }

                    log.info("年报数据处理完成，共处理{}组数据", groupedAnnualReportData.size());
                }

                result = true;
                return result;

            }
        }catch (Exception e) {
            log.error("数据插入到系统失败，tableName={}", tableName, e);
            result = false;
            return result;
        }
        return result;

    }

    /**
     * 按ANCHEID将年报数据分组
     * @param tableDataLists 原始数据列表
     * @param annualReportTables 年报表名列表
     * @return 按ANCHEID分组的年报数据
     */
    private Map<String, Map<String, List<?>>> groupAnnualReportDataByAncheid(Map<String, List<?>> tableDataLists, List<String> annualReportTables) {
        // Map<ANCHEID, Map<表名, List<数据>>>
        Map<String, Map<String, List<?>>> groupedData = new HashMap<>();

        for (String tableName : annualReportTables) {
            List<?> tableDataList = tableDataLists.get(tableName);
            if (tableDataList == null || tableDataList.isEmpty()) {
                continue;
            }

            log.debug("处理年报表{}，数据量={}", tableName, tableDataList.size());

            // 遍历该表的所有数据
            for (Object obj : tableDataList) {
                Map<String, Object> dataMap = (Map<String, Object>) obj;

                // 获取ANCHEID（所有年报表都有这个字段）
                Object ancheidObj = dataMap.get("ANCHEID");
                String ancheid = null;
                if (ancheidObj instanceof String) {
                    ancheid = (String) ancheidObj;
                } else if (ancheidObj instanceof Long) {
                    ancheid = String.valueOf(ancheidObj);
                } else if (ancheidObj != null) {
                    ancheid = ancheidObj.toString();
                }

                if (StrUtil.isBlank(ancheid)) {
                    log.warn("表{}中某条数据的ANCHEID为空，跳过处理", tableName);
                    continue;
                }

                // 如果该ANCHEID的组不存在，创建它
                if (!groupedData.containsKey(ancheid)) {
                    groupedData.put(ancheid, new HashMap<>());
                }

                // 将数据添加到对应的组和表中
                Map<String, List<?>> groupMap = groupedData.get(ancheid);
                if (!groupMap.containsKey(tableName)) {
                    groupMap.put(tableName, new ArrayList<>());
                }
                ((List<Object>) groupMap.get(tableName)).add(obj);
            }
        }

        return groupedData;
    }

    /**
     * 插入一组年报数据（包含主表和分表数据）
     *
     * @param ancheid      年报ID
     * @param tableDataMap 该组的数据（表名->数据列表）
     * @param pripid
     * @return 是否插入成功
     */
    private boolean insertAnnualReportGroup(String ancheid, Map<String, List<?>> tableDataMap, String pripid) {
        try {
            log.debug("开始插入年报数据组，ANCHEID={}, 表数量={}", ancheid, tableDataMap.size());

            QueryWrapper<EBaseInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("PRIPID", pripid);
            List<EBaseInfo> eBaseInfoList = eBaseInfoMapper.selectList(queryWrapper);
            AnSupBaseinfoAiccs anSupBaseinfoAiccs = null;
            List<?> anSupBaseinfo = tableDataMap.get("AN_SUP_BASEINFO");
            if (anSupBaseinfo != null) {
                for (Object obj : anSupBaseinfo) {
                    Map<String, Object> dataMap = (Map<String, Object>) obj;
                     anSupBaseinfoAiccs = mapToEntity(dataMap, AnSupBaseinfoAiccs.class);
                }
            }

            String ancheidnew = "";
            String reportYear = "";
            String regno = "";
            // 首先处理主表（AN_BASEINFO）
            List<?> baseInfoList = tableDataMap.get("AN_BASEINFO");
            if (baseInfoList != null && !baseInfoList.isEmpty()) {
                // 处理主表数据
                for (Object obj : baseInfoList) {
                    Map<String, Object> dataMap = (Map<String, Object>) obj;
                    AnBaseinfoAiccs baseInfo = mapToEntity(dataMap, AnBaseinfoAiccs.class);
                    if (baseInfo != null) {
                        TREntBaseInfoTemp trEntBaseInfoTemp1 = trEntBaseInfoTempMapper.selectByEntityNoAndReportYear(pripid,baseInfo.getAncheyear());
                        if (trEntBaseInfoTemp1 == null) {
                            ancheidnew = UUID.randomUUID().toString();
                        }else {
                            ancheidnew = trEntBaseInfoTemp1.getEntId();
                        }
                        TREntBaseInfoTemp trEntBaseInfoTemp = new TREntBaseInfoTemp();
                        trEntBaseInfoTemp.setEntId(ancheidnew);
                        trEntBaseInfoTemp.setEntityNo(pripid);
                        trEntBaseInfoTemp.setRegistNo(baseInfo.getRegno());
                        regno = baseInfo.getRegno();
                        trEntBaseInfoTemp.setEntName(baseInfo.getEntname());
                        trEntBaseInfoTemp.setIssueDeptID("440000");
                        trEntBaseInfoTemp.setEmpNumber(baseInfo.getEmpnum());
                        trEntBaseInfoTemp.setEntPhone(baseInfo.getTel());
                        trEntBaseInfoTemp.setEntAddress(baseInfo.getAddr());
                        trEntBaseInfoTemp.setEntZip(baseInfo.getPostalcode());
                        trEntBaseInfoTemp.setEntEmail(baseInfo.getEmail());
                        trEntBaseInfoTemp.setEntState(baseInfo.getBusst());
                        trEntBaseInfoTemp.setIsWeb("1");
                        trEntBaseInfoTemp.setIsInveInfo("1");
                        trEntBaseInfoTemp.setRegistDate(
                                baseInfo.getAnchedate() != null ? baseInfo.getAnchedate() : new Date()
                        );
                        // 根据 anType 字段值设置 EntType
                        String anType = baseInfo.getAntype(); // 假设获取 anType 的方法名
                        String entType = "1"; // 默认值
                        if ("10".equals(anType)) {
                            entType = "1";
                        } else if ("20".equals(anType)) {
                            entType = "2";
                        } else if ("30".equals(anType)) {
                            entType = "3";
                        } else if ("11".equals(anType)) {
                            entType = "6";
                        } else if ("21".equals(anType)) {
                            entType = "7";
                        } else if ("31".equals(anType)) {
                            entType = "8";
                        }
                        trEntBaseInfoTemp.setEntType(entType);
                        trEntBaseInfoTemp.setReportYear(baseInfo.getAncheyear());
                        reportYear = baseInfo.getAncheyear();
                        trEntBaseInfoTemp.setIsTransferStock("2");
                        trEntBaseInfoTemp.setEmpNumberIsShow(baseInfo.getEmpnumdis());
                        trEntBaseInfoTemp.setOnAiccips("");
                        trEntBaseInfoTemp.setRelations(baseInfo.getDependententname());
                        trEntBaseInfoTemp.setRelationsIsShow("2");
                        trEntBaseInfoTemp.setIssync("wA");
                        trEntBaseInfoTemp.setOrgId(eBaseInfoList != null && !eBaseInfoList.isEmpty() ? eBaseInfoList.get(0).getRegorg() : null);
                        trEntBaseInfoTemp.setEntityType(baseInfo.getEnttype());
                        trEntBaseInfoTemp.setSubEntityType(baseInfo.getEnttype());
                        if (anSupBaseinfoAiccs != null) {
                            trEntBaseInfoTemp.setMainBusiact(anSupBaseinfoAiccs.getMainbusiact());
                            trEntBaseInfoTemp.setWomEmpNum(anSupBaseinfoAiccs.getWomempnum());
                            trEntBaseInfoTemp.setHoldingsMsg(anSupBaseinfoAiccs.getHoldingsmsg());
                            trEntBaseInfoTemp.setWomEmpNumWhether(anSupBaseinfoAiccs.getWomempnumdis());
                            trEntBaseInfoTemp.setHoldingsMsgWhether(anSupBaseinfoAiccs.getHoldingsmsgdis());
                        }

                        trEntBaseInfoTemp.setIsSocialSecurity("2");
                        trEntBaseInfoTemp.setBelongEnterprise(null);
                        trEntBaseInfoTemp.setIsGuarantee("2");
                        trEntBaseInfoTemp.setIp(null);
                        trEntBaseInfoTemp.setIsPc(null);
                        trEntBaseInfoTemp.setImstAndMac(null);

                        if (trEntBaseInfoTemp1 != null) {
                            trEntBaseInfoTempMapper.updateDynamicTable(trEntBaseInfoTemp);
                        }else {
                            trEntBaseInfoTempMapper.deleteByTREntBaseInfoId(ancheidnew,reportYear);
                            trEntBaseInfoTempMapper.deleteByTREntBaseInfoIdzs(ancheidnew,reportYear);
                            trEntBaseInfoTempMapper.insertTREntBaseInfo(trEntBaseInfoTemp);
                            trEntBaseInfoTempMapper.insertTREntBaseInfozs(trEntBaseInfoTemp);
                        }

                        //资产信息
                        AssetModel assetModel = new AssetModel();
                        assetModel.setAssetId(ancheidnew);
                        assetModel.setEntId(ancheidnew);  // r.ANCHEID as entid
                        assetModel.setAssetsTotalAmount(baseInfo.getAssgro()); // r.ASSGRO as AssetsTotalAmount
                        assetModel.setAssetsIsShow(baseInfo.getAssgrodIs());   // r.ASSGRODIS as AssetsIsShow
                        assetModel.setLiabilitiesAmount(baseInfo.getLiagro()); // r.LIAGRO as LiabilitiesAmount
                        assetModel.setLiabilitiesIsShow(baseInfo.getLiagrodIs()); // r.LIAGRODIS as LiabilitiesIsShow
                        assetModel.setSalesAmount(baseInfo.getVendinc()); // r.VENDINC as SalesAmount
                        assetModel.setSalesIsShow(baseInfo.getVendincdis()); // r.VENDINCDIS as SalesIsShow
                        assetModel.setBusinessAmount(baseInfo.getMaibusinc()); // r.MAIBUSINC as BusinessAmount
                        assetModel.setBusinessIsShow(baseInfo.getMaibusincdis()); // r.MAIBUSINCDIS as BusinessIsShow
                        assetModel.setProfitsAmount(baseInfo.getProgro()); // r.PROGRO as ProfitsAmount
                        assetModel.setProfitsIsShow(baseInfo.getProgrodIs()); // r.PROGRODIS as ProfitsIsShow
                        assetModel.setNetProfitAmount(baseInfo.getNetinc()); // r.NETINC as NetProfitAmount
                        assetModel.setNetProfitIsShow(baseInfo.getNetincdis()); // r.NETINCDIS as NetProfitIsShow
                        assetModel.setTaxAmount(baseInfo.getRatgro()); // r.RATGRO as TaxAmount
                        assetModel.setTaxIsShow(baseInfo.getRatgrodIs()); // r.RATGRODIS as TaxIsShow
                        assetModel.setEquityAmount(baseInfo.getTotequ()); // r.TOTEQU as EquityAmount
                        assetModel.setEquityIsShow(baseInfo.getTotequdis()); // r.TOTEQUDIS as EquityIsShow
                        assetModel.setReportYear(baseInfo.getAncheyear()); // r.ANCHEYEAR as reportyear
                        assetModel.setCoinid(null); // null as coinid
                        assetModel.setEntityNo(pripid);

                        AssetModel assetModel1 = assetModelMapper.selectAssetModelByEntityNoAndReportYear(pripid,baseInfo.getAncheyear());

                        if (assetModel1 != null) {
                            assetModel.setAssetId(assetModel1.getAssetId());
                            assetModel.setEntId(assetModel1.getEntId());
                            assetModelMapper.updateAssetModelByEntityNoAndReportYear(assetModel,pripid,baseInfo.getAncheyear());
                        }else {
                            assetModelMapper.deleteByAssetModelId(ancheidnew,reportYear);
                            assetModelMapper.deleteByAssetModelIdzs(ancheidnew,reportYear);
                            assetModelMapper.insertToAssetModel(assetModel);
                            assetModelMapper.insertToAssetModelzs(assetModel);
                        }


                        //党建信息
                        PartyBuildInfoModel partyBuildInfoModel = new PartyBuildInfoModel();

                        // 1. 映射AN_BASEINFO表字段（对应SQL查询别名）
                        partyBuildInfoModel.setEntId(ancheidnew); // r.ANCHEID as entID
                        partyBuildInfoModel.setPartyId(ancheidnew); // r.ANCHEID as partyid
                        partyBuildInfoModel.setNumParM(baseInfo.getNumparm()); // r.NUMPARM as NUMPARM
                        partyBuildInfoModel.setParIns(baseInfo.getParins()); // r.PARINS as PARINS
                        partyBuildInfoModel.setResParMSign(baseInfo.getResparmsign()); // r.RESPARMSIGN as RESPARMSIGN
                        partyBuildInfoModel.setResParSecSign(baseInfo.getResparsecsign()); // r.RESPARSECSIGN as RESPARSECSIGN
                        partyBuildInfoModel.setReportYear(baseInfo.getAncheyear()); // r.ANCHEYEAR as reportyear
                        partyBuildInfoModel.setNumParMIsShow("2"); // '2' as NUMPARMisshow
                        partyBuildInfoModel.setParInsIsShow("2"); // '2' as PARINSisshow
                        partyBuildInfoModel.setResParMSignIsShow("2"); // '2' as RESPARMSIGNisshow
                        partyBuildInfoModel.setResParSecSignIsShow("2"); // '2' as RESPARSECSIGNisshow
                        partyBuildInfoModel.setEntityNo(pripid); // 此处entityNoParam为传入的参数（替换SQL中的?）

                        PartyBuildInfoModel partyBuildInfoModel1 = partyBuildInfoMapper.selectPartyBuildByEntityNoAndReportYear(pripid,baseInfo.getAncheyear());

                        if (partyBuildInfoModel1 != null) {
                            partyBuildInfoModel.setPartyId(partyBuildInfoModel1.getPartyId());
                            partyBuildInfoModel.setEntId(partyBuildInfoModel1.getEntId());
                            partyBuildInfoMapper.updatePartyBuildByEntityNoAndReportYear(partyBuildInfoModel1,pripid,baseInfo.getAncheyear());
                        }else {
                            partyBuildInfoMapper.deleteByPartyBuildId(ancheidnew,reportYear);
                            partyBuildInfoMapper.deleteByPartyBuildIdzs(ancheidnew,reportYear);
                            partyBuildInfoMapper.insertPartyBuildInfo(partyBuildInfoModel);
                            partyBuildInfoMapper.insertPartyBuildInfozs(partyBuildInfoModel);
                        }

                        //个体信息
                        IndividualReportModel individualReportModel = new IndividualReportModel();
                        // 基础字段映射（来自AN_BASEINFO）
                        individualReportModel.setEntId(ancheidnew); // r.ANCHEID as entid
                        individualReportModel.setIndividualID(ancheidnew); // r.ANCHEID as IndividualID

                        individualReportModel.setUserName(""); // '' as username
                        individualReportModel.setScope(""); // '' as Scope
                        individualReportModel.setIsPartyMember(""); // '' as IsPartyMember
                        individualReportModel.setIsPartyCommittee(""); // '' as IsPartyCommittee
                        individualReportModel.setEmpNumber(null); // '' as EmpNumber（数值类型用null匹配空字符串）
                        individualReportModel.setPartyMemberNum(null); // '' as PartyMemberNum
                        individualReportModel.setPartyIsShow(""); // '' as PartyIsShow
                        individualReportModel.setTotalFunds(null); // '' as TotalFunds（金额类型用null匹配）
                        individualReportModel.setOutputAmount(null); // '' as OutputAmount
                        individualReportModel.setOutputIsShow(""); // '' as OutputIsShow
                        individualReportModel.setSalesAmount(null); // '' as SalesAmount
                        individualReportModel.setSalesIsShow(""); // '' as SalesIsShow
                        individualReportModel.setRetailAmount(null); // '' as RetailAmount
                        individualReportModel.setRetailIsShow(""); // '' as RetailIsShow
                        individualReportModel.setMarkupMode(""); // '' as MarkupMode
                        individualReportModel.setReportIsShow(""); // '' as reportIsShow
                        individualReportModel.setEntNameissame(""); // '' as entNameissame
                        individualReportModel.setUserissame(""); // '' as userissame
                        individualReportModel.setMarkupModeissame(""); // '' as markupModeissame
                        individualReportModel.setScopeissame(""); // '' as scopeissame
                        individualReportModel.setAddressissame(""); // '' as addressissame
                        individualReportModel.setColGraNum(null); // '' as ColGraNum
                        individualReportModel.setRetSolNum(null); // '' as RetSolNum
                        individualReportModel.setDisPerNum(null); // '' as DisPerNum
                        individualReportModel.setUneNum(null); // '' as UneNum
                        individualReportModel.setRatGro(null); // '' as RatGro
                        individualReportModel.setRatGroIsShow(""); // '' as RatGroIsShow
                        individualReportModel.setCoinid(""); // '' as coinid

                        individualReportModel.setGraduatesNum(baseInfo.getColgranum()); // r.COLGRANUM as GraduatesNum
                        individualReportModel.setSoldiersNum(baseInfo.getRetsolnum()); // r.RETSOLNUM as SoldiersNum
                        individualReportModel.setDisabilityNum(baseInfo.getDispersnum()); // r.DISPERNUM as DisabilityNum
                        individualReportModel.setUnemploymentNum(baseInfo.getUnenum()); // r.UNENUM as UnemploymentNum

                        individualReportModel.setGraduatesIsShow(null); // null as GraduatesIsShow
                        individualReportModel.setSoldiersIsShow(null); // null as SoldiersIsShow
                        individualReportModel.setDisabilityIsShow(null); // null as DisabilityIsShow
                        individualReportModel.setUnemploymentIsShow(null); // null as UnemploymentIsShow

                        individualReportModel.setReportYear(baseInfo.getAncheyear()); // r.ANCHEYEAR as reportyear

                        if (trEntBaseInfoTemp1 != null) {
                            IndividualReportModel individualReportModel1 = individualReportMapper.selectIndividualByEntityNoAndReportYear(trEntBaseInfoTemp1.getEntId(),baseInfo.getAncheyear());

                            if (individualReportModel1 != null) {
                                individualReportModel.setEntId(individualReportModel1.getEntId());
                                individualReportModel.setIndividualID(individualReportModel1.getIndividualID());
                                individualReportMapper.updateIndividualByEntityNoAndReportYear(individualReportModel,individualReportModel1.getEntId(),reportYear);
                            }else {
                                individualReportMapper.deleteByIndividualId(ancheidnew,reportYear);
                                individualReportMapper.deleteByIndividualIdzs(ancheidnew,reportYear);
                                individualReportMapper.insertIndividualReport(individualReportModel);
                                individualReportMapper.insertIndividualReportzs(individualReportModel);
                            }
                        }else {
                            individualReportMapper.deleteByIndividualId(ancheidnew,reportYear);
                            individualReportMapper.deleteByIndividualIdzs(ancheidnew,reportYear);
                            individualReportMapper.insertIndividualReport(individualReportModel);
                            individualReportMapper.insertIndividualReportzs(individualReportModel);
                        }

                        //插入任务表
                        TaskInfoModel taskInfoModel = new TaskInfoModel();
                        taskInfoModel.setTaskInfoId(UUID.randomUUID().toString());
                        taskInfoModel.setRegistNo(baseInfo.getRegno()); // r.REGNO as registNo
                        taskInfoModel.setEntId(ancheidnew); // r.ANCHEID as entID
                        taskInfoModel.setEntName(baseInfo.getEntname()); // r.ENTNAME as EntName
                        taskInfoModel.setEntityType(baseInfo.getEnttype()); // r.ENTTYPE as entityType
                        taskInfoModel.setSubEntityType(baseInfo.getEnttype()); // r.ENTTYPE as subEntityType

                        Date anchorDate = baseInfo.getAnchedate();
                        Date registerDate = (anchorDate != null) ? anchorDate : new Date();
                        Date auditDate = (anchorDate != null) ? anchorDate : new Date();
                        taskInfoModel.setRegisterDate(registerDate); // 适配case逻辑的登记日期

                        // 格式化日期为数据库可识别的字符串格式 (YYYY-MM-DD HH:mm:ss)
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        taskInfoModel.setAuditDate(auditDate != null ? dateFormat.format(auditDate) : dateFormat.format(new Date())); // SQL中AuditDate映射为VARCHAR，需转为字符串

                        taskInfoModel.setTaskType("00"); // '00' as TaskType
                        taskInfoModel.setAuditState("00"); // 00 as AuditState（SQL中数字00映射为字符串）
                        taskInfoModel.setTaskNo("3"); // 3 as TaskNo（SQL中数字3映射为字符串）
                        taskInfoModel.setIssync("wA"); // 'wA' as issync
                        taskInfoModel.setOrgId(eBaseInfoList != null && !eBaseInfoList.isEmpty() ? eBaseInfoList.get(0).getRegorg() : null); // e.regorg as OrgID
                        taskInfoModel.setEntityNo(pripid);

                        if (trEntBaseInfoTemp1 != null) {
                            taskInfoMapper.deleteTaskInfoByEntId(trEntBaseInfoTemp1.getEntId());
                            taskInfoModel.setEntId(trEntBaseInfoTemp1.getEntId());
                            taskInfoMapper.insertTaskInfo(taskInfoModel);

                        }else {
                            taskInfoMapper.deleteTaskInfoByEntId(ancheidnew);
                            taskInfoMapper.insertTaskInfo(taskInfoModel);
                        }

                        log.debug("插入或更新企业年报基本信息，ANCHEID={}", ancheid);
                    }
                }
            } else {
                log.warn("年报数据组{}中缺少主表AN_BASEINFO数据", ancheid);
            }

            // 处理分表数据
            List<String> subTables = Arrays.asList(
                "AN_ALTERSTOCKINFO",
                "AN_FORGUARANTEEINFO",
                "AN_FORINVESTMENT",
                "AN_SOCSECINFO",
                "AN_SUBCAPITAL",
                "AN_SUP_BASEINFO",
                "AN_UPDATEINFO",
                "AN_WEBSITEINFO"
            );

            for (String subTable : subTables) {
                List<?> subTableDataList = tableDataMap.get(subTable);
                if (subTableDataList != null && !subTableDataList.isEmpty()) {
                    log.debug("处理分表{}，数据量={}", subTable, subTableDataList.size());

                    for (Object obj : subTableDataList) {
                        Map<String, Object> dataMap = (Map<String, Object>) obj;

                        // 根据不同的分表，选择对应的实体类
                        switch (subTable) {
                            case "AN_ALTERSTOCKINFO":
                                AnAlterstockinfoAiccs alterStockInfo = mapToEntity(dataMap, AnAlterstockinfoAiccs.class);
                                if (alterStockInfo != null) {
                                    StockTransferModel stockTransferModel = new StockTransferModel();
                                    stockTransferModel.setStockId(alterStockInfo.getInvaltid());
                                    stockTransferModel.setEntId(ancheidnew);
                                    stockTransferModel.setEntityNo(pripid);
                                    stockTransferModel.setInv(alterStockInfo.getInv());
                                    stockTransferModel.setAmPr(alterStockInfo.getTransampr() != null ? String.valueOf(alterStockInfo.getTransampr()) : "");
                                    stockTransferModel.setTransAmPr(alterStockInfo.getTransamaft() != null ? String.valueOf(alterStockInfo.getTransamaft()) : "");
                                    stockTransferModel.setTransferDate(alterStockInfo.getAltdate());
                                    stockTransferModel.setIsShow("0");
                                    StockTransferModel stockTransferModel1 = stockTransferMapper.selectByStockId(alterStockInfo.getInvaltid());

                                    if (stockTransferModel1 != null) {
                                        String entid = stockTransferModel1.getEntId();
                                        stockTransferMapper.deleteByStockId(alterStockInfo.getInvaltid());
                                        stockTransferMapper.deleteByStockIdzs(alterStockInfo.getInvaltid());
                                        stockTransferModel.setEntId(entid);
                                        stockTransferMapper.addStockTransferInfo(stockTransferModel);
                                        stockTransferMapper.addStockTransferInfozs(stockTransferModel);
                                    }else {
                                        stockTransferMapper.deleteByStockId(alterStockInfo.getInvaltid());
                                        stockTransferMapper.deleteByStockIdzs(alterStockInfo.getInvaltid());
                                        stockTransferMapper.addStockTransferInfo(stockTransferModel);
                                        stockTransferMapper.addStockTransferInfozs(stockTransferModel);
                                    }
                                    // TODO: 实现AN_ALTERSTOCKINFO的插入或更新逻辑
                                    log.debug("插入或更新股权变更信息，ANCHEID={}", ancheid);
                                }
                                break;
                            case "AN_FORGUARANTEEINFO":
                                AnForguaranteeinfoAiccs forGuaranteeInfo = mapToEntity(dataMap, AnForguaranteeinfoAiccs.class);
                                if (forGuaranteeInfo != null) {
                                    TRGuarantyModel tguarantyModel = new TRGuarantyModel();
                                    tguarantyModel.setGaId(forGuaranteeInfo.getMoreid());
                                    tguarantyModel.setEntityNo(pripid);
                                    tguarantyModel.setEntId(ancheidnew);
                                    tguarantyModel.setCreditorName(forGuaranteeInfo.getMore());
                                    tguarantyModel.setDebtorName(forGuaranteeInfo.getMortgagor());
                                    tguarantyModel.setPriClaSecKind(forGuaranteeInfo.getPriclaseckind());
                                    tguarantyModel.setPriClaSecAm(forGuaranteeInfo.getPriclasecam());
                                    tguarantyModel.setPefPerFrom(forGuaranteeInfo.getPefperform());
                                    tguarantyModel.setPefPerTo(forGuaranteeInfo.getPefperto());
                                    tguarantyModel.setGuaranperiod(forGuaranteeInfo.getGuaranperiod());
                                    tguarantyModel.setRage(forGuaranteeInfo.getGatype());
                                    tguarantyModel.setIsShowStatus(forGuaranteeInfo.getMoredis());
                                    tguarantyModel.setIsShow("0");
                                    TRGuarantyModel trGuarantyModel1 = trGuarantyMapper.selectByGaId(tguarantyModel.getGaId());
                                    if (trGuarantyModel1 != null) {
                                        String entid = trGuarantyModel1.getEntId();
                                        trGuarantyMapper.deleteByGaId(tguarantyModel.getGaId());
                                        trGuarantyMapper.deleteByGaIdzs(tguarantyModel.getGaId());
                                        tguarantyModel.setEntId(entid);
                                        trGuarantyMapper.addTRGuarantyInfo(tguarantyModel);
                                        trGuarantyMapper.addTRGuarantyInfozs(tguarantyModel);
                                    }else {
                                        trGuarantyMapper.deleteByGaId(tguarantyModel.getGaId());
                                        trGuarantyMapper.deleteByGaIdzs(tguarantyModel.getGaId());
                                        trGuarantyMapper.addTRGuarantyInfo(tguarantyModel);
                                        trGuarantyMapper.addTRGuarantyInfozs(tguarantyModel);
                                    }

                                    // TODO: 实现AN_FORGUARANTEEINFO的插入或更新逻辑
                                    log.debug("插入或更新对外担保信息，ANCHEID={}", ancheid);
                                }
                                break;
                            case "AN_FORINVESTMENT":
                                AnForinvestmentAiccs forInvestment = mapToEntity(dataMap, AnForinvestmentAiccs.class);
                                if (forInvestment != null) {
                                    InvestmentEntModel investmentEntModel = new InvestmentEntModel();
                                    investmentEntModel.setInvestmentId(forInvestment.getOutinvid());
                                    investmentEntModel.setEntityNo(pripid);
                                    investmentEntModel.setEntId(ancheidnew);
                                    investmentEntModel.setInveName(forInvestment.getEntname());
                                    investmentEntModel.setInveRegistNo(forInvestment.getUniscid());
                                    investmentEntModel.setIsShow("0");
                                    InvestmentEntModel investmentEntModel1 = investmentEntMapper.selectByInvestmentId(forInvestment.getOutinvid());

                                    if (investmentEntModel1 != null) {
                                        String entid = investmentEntModel1.getEntId();
                                        investmentEntMapper.deleteByInvestmentId(investmentEntModel.getInvestmentId());
                                        investmentEntMapper.deleteByInvestmentIdzs(investmentEntModel.getInvestmentId());
                                        investmentEntModel.setEntId(entid);
                                        investmentEntMapper.insertInvestment(investmentEntModel);
                                        investmentEntMapper.insertInvestmentzs(investmentEntModel);
                                    }else {
                                        investmentEntMapper.deleteByInvestmentId(investmentEntModel.getInvestmentId());
                                        investmentEntMapper.deleteByInvestmentIdzs(investmentEntModel.getInvestmentId());
                                        investmentEntMapper.insertInvestment(investmentEntModel);
                                        investmentEntMapper.insertInvestmentzs(investmentEntModel);
                                    }

                                    // TODO: 实现AN_FORINVESTMENT的插入或更新逻辑
                                    log.debug("插入或更新对外投资信息，ANCHEID={}", ancheid);
                                }
                                break;
                            case "AN_SOCSECINFO":
                                AnSocsecinfoAiccs socSecInfo = mapToEntity(dataMap, AnSocsecinfoAiccs.class);
                                if (socSecInfo != null) {
                                    SocialSecurityModel socialSecurityModel = new SocialSecurityModel();
                                    // 1. 映射AN_SOCSECINFO表字段（对应SQL查询别名）
                                    socialSecurityModel.setSocialSecurityId(ancheidnew); // r.SOSEID as socialSecurityId
                                    socialSecurityModel.setEntId(ancheidnew); // r.ANCHEID as EntID
                                    socialSecurityModel.setTownNum(socSecInfo.getSo110()); // r.SO110 as townNum
                                    socialSecurityModel.setUnemploymentNum(socSecInfo.getSo210()); // r.SO210 as unemploymentNum
                                    socialSecurityModel.setMedicalNum(socSecInfo.getSo310()); // r.SO310 as medicalNum
                                    socialSecurityModel.setInjuryNum(socSecInfo.getSo410()); // r.SO410 as injuryNum
                                    socialSecurityModel.setBirthNum(socSecInfo.getSo510()); // r.SO510 as birthNum

                                    // 工资总额相关字段
                                    socialSecurityModel.setTOTALWAGES_SO110(socSecInfo.getTotalwagesSo110()); // r.TOTALWAGES_SO110
                                    socialSecurityModel.setTOTALWAGES_SO210(socSecInfo.getTotalwagesSo210()); // r.TOTALWAGES_SO210
                                    socialSecurityModel.setTOTALWAGES_SO310(socSecInfo.getTotalwagesSo310()); // r.TOTALWAGES_SO310
                                    socialSecurityModel.setTOTALWAGES_SO510(socSecInfo.getTotalwagesSo510()); // r.TOTALWAGES_SO510
                                    socialSecurityModel.setTotalWagesWhether(socSecInfo.getTotalwagesdis()); // r.TOTALWAGESDIS

                                    // 缴费总额相关字段
                                    socialSecurityModel.setTOTALPAYMENT_SO110(socSecInfo.getTotalpaymentSo110()); // r.TOTALPAYMENT_SO110
                                    socialSecurityModel.setTOTALPAYMENT_SO210(socSecInfo.getTotalpaymentSo210()); // r.TOTALPAYMENT_SO210
                                    socialSecurityModel.setTOTALPAYMENT_SO310(socSecInfo.getTotalpaymentSo310()); // r.TOTALPAYMENT_SO310
                                    socialSecurityModel.setTOTALPAYMENT_SO410(socSecInfo.getTotalpaymentSo410()); // r.TOTALPAYMENT_SO410
                                    socialSecurityModel.setTOTALPAYMENT_SO510(socSecInfo.getTotalpaymentSo510()); // r.TOTALPAYMENT_SO510
                                    socialSecurityModel.setTotalPaymentWhether(socSecInfo.getTotalpaymentdis()); // r.TOTALPAYMENTDIS

                                    // 未缴社保相关字段
                                    socialSecurityModel.setUNPAIDSOCIALINS_SO110(socSecInfo.getUnpaidsocialinsSo110()); // r.UNPAIDSOCIALINS_SO110
                                    socialSecurityModel.setUNPAIDSOCIALINS_SO210(socSecInfo.getUnpaidsocialinsSo210()); // r.UNPAIDSOCIALINS_SO210
                                    socialSecurityModel.setUNPAIDSOCIALINS_SO310(socSecInfo.getUnpaidsocialinsSo310()); // r.UNPAIDSOCIALINS_SO310
                                    socialSecurityModel.setUNPAIDSOCIALINS_SO410(socSecInfo.getUnpaidsocialinsSo410()); // r.UNPAIDSOCIALINS_SO410
                                    socialSecurityModel.setUNPAIDSOCIALINS_SO510(socSecInfo.getUnpaidsocialinsSo510()); // r.UNPAIDSOCIALINS_SO510
                                    socialSecurityModel.setUnpaidSocialinsWhether(socSecInfo.getUnpaidsocialinsdis()); // r.UNPAIDSOCIALINSDIS

                                    // 2. 映射AN_BASEINFO表关联字段（需从关联查询中获取AN_BASEINFO实体，假设为anBaseInfo）
                                    socialSecurityModel.setReportYear(reportYear); // e.ANCHEYEAR as reportyear
                                    socialSecurityModel.setRegNo(regno != null ? regno : ""); // e.REGNO as regno

                                    // 3. 映射常量和系统时间字段
                                    socialSecurityModel.setDstate("0"); // '0' as dstate
                                    socialSecurityModel.setCreateDate(new Date()); // getdate() AS createDate
                                    socialSecurityModel.setUpdateDate(new Date()); // getdate() as updatedate
                                    socialSecurityModel.setEntityNo(pripid);

                                    SocialSecurityModel socialSecurityModel1 = socialSecurityMapper.selectSocialSecurityByEntityNoAndReportYear(pripid, reportYear);
                                    if (socialSecurityModel1 != null) {
                                        socialSecurityMapper.deleteBySocialSecurityId(ancheidnew,reportYear);
                                        socialSecurityMapper.deleteBySocialSecurityIdzs(ancheidnew,reportYear);
                                        socialSecurityModel.setEntId(socialSecurityModel1.getEntId());
                                        socialSecurityModel.setSocialSecurityId(socialSecurityModel1.getSocialSecurityId());
                                        socialSecurityMapper.updateSocialSecurityByEntityNoAndReportYear(socialSecurityModel,pripid,reportYear);
                                    }else {

                                        socialSecurityMapper.insertSocialSecurityModel(socialSecurityModel);
                                        socialSecurityMapper.insertSocialSecurityModelzs(socialSecurityModel);
                                    }

                                    log.debug("插入或更新社保信息，ANCHEID={}", ancheid);
                                }
                                break;
                            case "AN_SUBCAPITAL":
                                AnSubcapitalAiccs subcapital = mapToEntity(dataMap, AnSubcapitalAiccs.class);
                                if (subcapital != null) {
                                    CapitalModel capitalModel = new CapitalModel();
                                    capitalModel.setCapId(subcapital.getInvid());
                                    capitalModel.setUserName(subcapital.getInvname());
                                    capitalModel.setCapShould(subcapital.getLisubconam());
                                    capitalModel.setCapReal(subcapital.getLiacconam()); // 对应r.LIACCONAM
                                    capitalModel.setCapShouldDate(subcapital.getSubcondate()); // 对应r.SUBCONDATE
                                    capitalModel.setCapDate(subcapital.getAccondate()); // 对应r.ACCONDATE
                                    // 2. 处理认缴出资方式转换（对应SQL中的case when逻辑）
                                    String subconform = subcapital.getSubconform();
                                    if (subconform != null) {
                                        switch (subconform) {
                                            case "1":
                                                capitalModel.setCapShouldType("C");
                                                break;
                                            case "2":
                                                capitalModel.setCapShouldType("P");
                                                break;
                                            case "3":
                                                capitalModel.setCapShouldType("I");
                                                break;
                                            case "4":
                                                capitalModel.setCapShouldType("D");
                                                break;
                                            case "6":
                                                capitalModel.setCapShouldType("L");
                                                break;
                                            case "7":
                                                capitalModel.setCapShouldType("S");
                                                break;
                                            case "8":
                                            case "9":
                                                capitalModel.setCapShouldType("O");
                                                break;
                                            default:
                                                capitalModel.setCapShouldType(subconform); // 保留原始值
                                        }
                                    }

                                    // 3. 处理实缴出资方式转换（对应SQL中的case when逻辑）
                                    String acconform = subcapital.getAcconform();
                                    if (acconform != null) {
                                        switch (acconform) {
                                            case "1":
                                                capitalModel.setCapType("C");
                                                break;
                                            case "2":
                                                capitalModel.setCapType("P");
                                                break;
                                            case "3":
                                                capitalModel.setCapType("I");
                                                break;
                                            case "4":
                                                capitalModel.setCapType("D");
                                                break;
                                            case "6":
                                                capitalModel.setCapType("L");
                                                break;
                                            case "7":
                                                capitalModel.setCapType("S");
                                                break;
                                            case "8":
                                            case "9":
                                                capitalModel.setCapType("O");
                                                break;
                                            default:
                                                capitalModel.setCapType(acconform); // 保留原始值
                                        }
                                    }

                                    capitalModel.setIsShow("1"); // 对应SQL中的'1' as isshow
                                    capitalModel.setEntId(ancheidnew);
                                    capitalModel.setReportYear(reportYear);
                                    capitalModel.setEntityNo(pripid);

                                    // 示例：先查询是否存在，存在则更新，不存在则插入
                                    CapitalModel existCapital = capitalModelMapper.selectCapitalModelByCapId(subcapital.getInvid(),reportYear);
                                    if (existCapital != null) {
                                        String entid = existCapital.getEntId();
                                        capitalModelMapper.deleteCapitalModelByCapId(subcapital.getInvid(),reportYear);
                                        capitalModelMapper.deleteCapitalModelByCapIdzs(subcapital.getInvid(),reportYear);
                                        capitalModel.setEntId(entid);
                                        capitalModelMapper.insertDynamicTable(capitalModel);
                                        capitalModelMapper.insertDynamicTablezs(capitalModel);
                                    } else {
                                        capitalModelMapper.insertDynamicTable(capitalModel);
                                        capitalModelMapper.insertDynamicTablezs(capitalModel);
                                    }

                                    log.debug("插入或更新股东及出资信息，ANCHEID={}", ancheid);
                                }
                                break;
                            case "AN_SUP_BASEINFO":
                                AnSupBaseinfoAiccs supBaseInfo = mapToEntity(dataMap, AnSupBaseinfoAiccs.class);
                                if (supBaseInfo != null) {
                                    // TODO: 实现AN_SUP_BASEINFO的插入或更新逻辑
                                    log.debug("插入或更新年报企业补充信息，ANCHEID={}", ancheid);
                                }
                                break;
                            case "AN_UPDATEINFO":
                                AnUpdateinfoAiccs updateInfo = mapToEntity(dataMap, AnUpdateinfoAiccs.class);
                                if (updateInfo != null) {
                                    TrcorrectionsModel trcorrectionsModel = new TrcorrectionsModel();
                                    trcorrectionsModel.setCorrectionsid(updateInfo.getAncheuid());
                                    trcorrectionsModel.setEntid(ancheidnew);
                                    trcorrectionsModel.setReportYear(reportYear);
                                    trcorrectionsModel.setSubitem(updateInfo.getAlitem());
                                    trcorrectionsModel.setCorrectionsbefore(updateInfo.getAltbe());
                                    trcorrectionsModel.setCorrectionsafter(updateInfo.getAltaf());
                                    trcorrectionsModel.setEntityno(pripid);
                                    trcorrectionsModel.setIsshow("0");
                                    TrcorrectionsModel trcorrectionsModel1 = trCorrectionsMapper.selectByPrimaryKey(trcorrectionsModel.getCorrectionsid(),trcorrectionsModel.getReportYear());

                                    if (trcorrectionsModel1 != null) {
                                        String entid = trcorrectionsModel1.getEntid();
                                        trCorrectionsMapper.deleteByPrimaryKey(trcorrectionsModel.getCorrectionsid(),trcorrectionsModel.getReportYear());
                                        trCorrectionsMapper.deleteByPrimaryKeyzs(trcorrectionsModel.getCorrectionsid(),trcorrectionsModel.getReportYear());
                                        trcorrectionsModel1.setEntid(entid);
                                        trCorrectionsMapper.insertDynamic(trcorrectionsModel);
                                        trCorrectionsMapper.insertDynamiczs(trcorrectionsModel);
                                    }else {
                                        trCorrectionsMapper.deleteByPrimaryKey(ancheidnew,trcorrectionsModel.getReportYear());
                                        trCorrectionsMapper.deleteByPrimaryKeyzs(ancheidnew,trcorrectionsModel.getReportYear());
                                        trCorrectionsMapper.insertDynamic(trcorrectionsModel);
                                        trCorrectionsMapper.insertDynamiczs(trcorrectionsModel);
                                    }

                                    // TODO: 实现AN_UPDATEINFO的插入或更新逻辑
                                    log.debug("插入或更新年报修改记录，ANCHEID={}", ancheid);
                                }
                                break;
                            case "AN_WEBSITEINFO":
                                AnWebsiteinfoAiccs websiteInfo = mapToEntity(dataMap, AnWebsiteinfoAiccs.class);
                                if (websiteInfo != null) {

                                    EntWebModel entWebModel = new EntWebModel();
                                    // 1. 映射AN_WEBSITEINFO表字段（对应SQL查询别名）
                                    entWebModel.setWebId(websiteInfo.getWebid()); // r.WEBID as WebID
                                    entWebModel.setEntId(ancheidnew); // r.ANCHEID as EntID
                                    entWebModel.setWebType(websiteInfo.getWebtype()); // r.WEBTYPE as WebType
                                    entWebModel.setWebName(websiteInfo.getWebsitname()); // r.WEBSITNAME as WebName
                                    entWebModel.setWebUrl(websiteInfo.getWebsite()); // r.WEBSITE as WebUrl
                                    // 2. 映射常量字段
                                    entWebModel.setIsShow("0"); // '0' as isshow（注意实体类字段是isShow，SQL别名是isshow，保持一致）
                                    entWebModel.setEntityNo(pripid); // 此处entityNoParam为传入的参数
                                    EntWebModel entWebModel1 = entWebMapper.selectEntWebModelByWebId(websiteInfo.getWebid());

                                    if (entWebModel1 != null) {
                                        String entid = entWebModel1.getEntId();
                                        entWebMapper.deleteEntWebModelByWebId(websiteInfo.getWebid());
                                        entWebMapper.deleteEntWebModelByWebIdzs(websiteInfo.getWebid());
                                        entWebModel.setEntId(entid);
                                        entWebMapper.insertWeb(entWebModel);
                                        entWebMapper.insertWebzs(entWebModel);
                                    }else {
                                        entWebMapper.deleteEntWebModelByWebId(websiteInfo.getWebid());
                                        entWebMapper.deleteEntWebModelByWebIdzs(websiteInfo.getWebid());
                                        entWebMapper.insertWeb(entWebModel);
                                        entWebMapper.insertWebzs(entWebModel);
                                    }
                                    log.debug("插入或更新网站或网店信息，ANCHEID={}", ancheid);
                                }
                                break;
                            default:
                                log.warn("未处理的分表：{}", subTable);
                        }
                    }
                }
            }

            log.debug("年报数据组插入完成，ANCHEID={}", ancheid);



            return true;

        } catch (Exception e) {
            log.error("插入年报数据组失败，ANCHEID={}", ancheid, e);
            return false;
        }
    }

    /**
     * 通过行政区划代码获取拼音
     */
    public  String getPinyin(String areaCode) {
        switch(areaCode) {
            case "110000": return "beijing";
            case "120000": return "tianjin";
            case "130000": return "hebei";
            case "140000": return "shanxi";
            case "150000": return "neimenggu";
            case "210000": return "liaoning";
            case "220000": return "jilin";
            case "230000": return "heilongjiang";
            case "310000": return "shanghai";
            case "320000": return "jiangsu";
            case "330000": return "zhejiang";
            case "340000": return "anhui";
            case "350000": return "fujian";
            case "360000": return "jiangxi";
            case "370000": return "shandong";
            case "410000": return "henan";
            case "420000": return "hubei";
            case "430000": return "hunan";
            case "440000": return "guangdong";
            case "450000": return "guangxi";
            case "460000": return "hainan";
            case "500000": return "chongqing";
            case "510000": return "sichuan";
            case "520000": return "guizhou";
            case "530000": return "yunnan";
            case "540000": return "xizang";
            case "610000": return "shaxi";
            case "620000": return "gansu";
            case "630000": return "qinghai";
            case "640000": return "ningxia";
            case "650000": return "xinjiang";
            case "710000": return "taiwan";
            case "810000": return "xianggang";
            case "820000": return "aomen";
            default: return null;
        }
    }


    /**
     * 工具方法：获取表的计数，为空则返回"0"（确保非空字符串）
     * @param recordCountMap 计数Map
     * @param key 表名键
     * @return 非空的计数字符串
     */
    private String getCountValue(Map<String, Integer> recordCountMap, String key) {
        // 双重校验：Map为空 → 返回0；key不存在/值为null → 返回0；否则返回实际值
        if (recordCountMap == null) {
            return "0";
        }
        Integer count = recordCountMap.get(key);
        return count == null ? "0" : String.valueOf(count);
    }

}
