package com.vote.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.vctgo.common.core.exception.ServiceException;
import com.vctgo.common.core.text.Convert;
import com.vctgo.common.core.utils.JwtUtils;
import com.vctgo.common.core.utils.ServletUtils;
import com.vctgo.common.core.utils.StrUtils;
import com.vctgo.common.mybatisplus.constant.MybatisPageConstants;
import com.vctgo.common.security.utils.SecurityUtils;
import com.vctgo.system.api.RemoteFileService;
import com.vctgo.system.api.domain.FileInfo;
import com.vctgo.system.api.domain.dto.VoteExpertWorkingPlatformDto;
import com.vctgo.system.api.domain.dto.VoteSubmissionItemVo;
import com.vctgo.system.api.domain.vo.VoteExpertSubmissionCountVo;
import com.vctgo.system.api.domain.vo.VoteExpertSubmissionVo;
import com.vctgo.system.api.factory.RemoteClassSettingFallbackFactory;
import com.vote.system.domain.*;
import com.vote.system.domain.pojo.GroupedData;
import com.vote.system.domain.vo.VoteExpertWorkingPlatformVo;
import com.vctgo.system.api.domain.vo.VoteFileVo;
import com.vote.system.domain.vo.VoteSubmissionVo;
import com.vote.system.mapper.*;
import com.vote.system.service.VoteExpertWorkingPlatformService;
import com.vote.system.util.DataEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.vote.system.util.ConstantUtils.*;

/**
 * @author feng
 * @date 2024/8/29
 */
@Service
public class VoteExpertWorkingPlatformServiceImpl implements VoteExpertWorkingPlatformService {

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

    @Autowired
    private VoteEvaluationTasksMapper voteEvaluationTasksMapper;

    @Autowired
    private VoteSubmissionMapper voteSubmissionMapper;

    @Autowired
    private VoteEventsMapper voteEventsMapper;

    @Autowired
    private VoteJudgesVisibleFieldsMapper voteJudgesVisibleFieldsMapper;

    @Autowired
    private VoteWorkTypesMapper voteWorkTypesMapper;

    @Autowired
    private VoteEventWorkSettingsMapper voteEventWorkSettingsMapper;

    @Autowired
    private VoteEventRegistrationWorkScoresMapper voteEventRegistrationWorkScoresMapper;

    @Autowired
    private VoteScoringItemMapper voteScoringItemMapper;

    @Autowired
    private VoteOrganizersMapper voteOrganizersMapper;

    @Autowired
    private VoteEventEvaluationRoundsMapper voteEventEvaluationRoundsMapper;

    @Autowired
    private VoteSubmissionItemMapper voteSubmissionItemMapper;

    @Autowired
    private RemoteFileService remoteFileService;

    @Autowired
    private DataEncoder dataEncoder;


    /**
     * 专家平台 分页
     */
    @Override
    public IPage<VoteExpertWorkingPlatformVo> expertPlatformPage(String judgesId) {
        // 分页参数
        long pageNum = Convert.toLong(ServletUtils.getParameterToInt(MybatisPageConstants.PAGE_NUM), 1L);
        long pageSize = Convert.toLong(ServletUtils.getParameterToInt(MybatisPageConstants.PAGE_SIZE), 10L);
        // 获取该专家的所有评选作品
        List<Long> submissionIds = voteEvaluationTasksMapper.selectList(new LambdaQueryWrapper<VoteEvaluationTasks>().eq(VoteEvaluationTasks::getJudgeId, judgesId)).stream().map(VoteEvaluationTasks::getSubmissionId).collect(Collectors.toList());
        if (submissionIds.isEmpty()) {
            return null;
        }

        // 根据作品id查询作品
        List<VoteSubmission> submissions = voteSubmissionMapper.selectList(new LambdaQueryWrapper<VoteSubmission>().in(VoteSubmission::getId, submissionIds));

        // 获取所有需要的相关数据
        Set<Long> eventIds = submissions.stream().map(VoteSubmission::getEventId).collect(Collectors.toSet());
        Set<Long> roundIds = submissions.stream().map(VoteSubmission::getRoundId).collect(Collectors.toSet());
        Set<Long> workSettingsIds = submissions.stream().map(VoteSubmission::getWorkSettingsId).collect(Collectors.toSet());
        Map<Long, VoteEvents> eventMap = getFilteredEventMap(eventIds);
        Map<Long, VoteEventEvaluationRounds> roundMap = voteEventEvaluationRoundsMapper.selectBatchIds(roundIds).stream().collect(Collectors.toMap(VoteEventEvaluationRounds::getId, Function.identity()));
        Map<Long, VoteEventWorkSettings> workSettingsMap = voteEventWorkSettingsMapper.selectBatchIds(workSettingsIds).stream().collect(Collectors.toMap(VoteEventWorkSettings::getId, Function.identity()));
        Map<Long, VoteWorkTypes> workTypesMap = voteWorkTypesMapper.selectBatchIds(workSettingsMap.values().stream().map(VoteEventWorkSettings::getWorkTypeId).collect(Collectors.toSet())).stream().collect(Collectors.toMap(VoteWorkTypes::getId, Function.identity()));

        // 分组数据
        Map<Long, Map<Long, Map<Long, GroupedData>>> result = submissions.stream().collect(Collectors.groupingBy(VoteSubmission::getEventId, Collectors.groupingBy(VoteSubmission::getRoundId, Collectors.groupingBy(VoteSubmission::getWorkSettingsId, Collectors.collectingAndThen(Collectors.toList(), groupedSubmissions -> {
            GroupedData groupedData = new GroupedData();
            groupedSubmissions.forEach(item -> groupedData.add(item.getId(), item.getEventId(), item.getRoundId(), item.getWorkSettingsId()));
            return groupedData;
        })))));

        List<VoteExpertWorkingPlatformVo> voList = new ArrayList<>();
        result.forEach((eventId, roundMapByEvent) -> {
            VoteEvents event = eventMap.get(eventId);
            String eventName = event != null ? event.getName() : "未知活动";

            roundMapByEvent.forEach((roundId, workSettingsMapByRound) -> {
                VoteEventEvaluationRounds evaluationRounds = roundMap.get(roundId); // 修正此处
                String roundNumber = evaluationRounds != null ? String.valueOf(evaluationRounds.getRoundNumber()) : "未知轮次";
                Long ruleId = evaluationRounds != null ? evaluationRounds.getScoringRuleId() : null;

                workSettingsMapByRound.forEach((workSettingsId, groupedData) -> {
                    VoteEventWorkSettings workSettings = workSettingsMap.get(workSettingsId);
                    String aliasName = workSettings != null ? workSettings.getAlias() : "未知设置";
                    Long workTypeId = workSettings != null ? workSettings.getWorkTypeId() : null;
                    VoteWorkTypes workType = workTypeId != null ? workTypesMap.get(workTypeId) : null;
                    String workTypeName = workType != null ? workType.getName() : "未知类型";

                    int yetGradeCount = voteEvaluationTasksMapper.selectCount(new LambdaQueryWrapper<VoteEvaluationTasks>().in(VoteEvaluationTasks::getSubmissionId, groupedData.getSubmissionIds()).eq(VoteEvaluationTasks::getStatus, "1")).intValue();

                    VoteExpertWorkingPlatformVo platformVo = new VoteExpertWorkingPlatformVo();
                    platformVo.setEventId(eventId);
                    platformVo.setEventName(eventName);
                    platformVo.setRoundId(roundId);
                    platformVo.setRoundNumber(roundNumber);
                    platformVo.setRuleId(ruleId);
                    platformVo.setWorkSettingsId(workSettingsId);
                    platformVo.setAliasName(aliasName);
                    platformVo.setWorkTypeName(workTypeName);
                    platformVo.setGradeCount(groupedData.getCount());
                    platformVo.setYetGrade(yetGradeCount);
                    voList.add(platformVo);
                });
            });
        });
        // 分页结果
        Page<VoteExpertWorkingPlatformVo> page = new Page<>(pageNum, pageSize);
        int start = (int) ((pageNum - 1) * pageSize);
        int end = Math.min(start + (int) pageSize, voList.size());
        page.setRecords(voList.subList(start, end));
        page.setTotal(voList.size());

        return page;
    }


    /**
     * 评分规则
     */
    @Override
    public List<VoteScoringItem> getItem(Long ruleId) {
        LambdaQueryWrapper<VoteScoringItem> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(VoteScoringItem::getRuleId, ruleId);
        return voteScoringItemMapper.selectList(wrapper);
    }


    /**
     * 活动内容
     */
    @Override
    public VoteEvents getEventDetails(Long eventId) {
        VoteEvents voteEvents = voteEventsMapper.selectById(eventId);
        VoteOrganizers voteOrganizers = voteOrganizersMapper.selectById(voteEvents.getOrganizerId());
        voteEvents.setOrganizersName(voteOrganizers.getName());
        return voteEvents;
    }


    /**
     * 专家作品清单
     */
    @Override
    public List<VoteExpertSubmissionVo> expertPlatformDetail(Long eventId, Long workSettingsId, Long roundId, String status, HttpServletRequest request) {
        String token = SecurityUtils.getToken(request);
        if (!StrUtils.isNotEmpty(token)) {
            throw new ServiceException("请重新登录！");
        }
        String userId = JwtUtils.getUserId(token);
        // 查询符合条件的作品列表
        LambdaQueryWrapper<VoteSubmission> submissionWrapper = new LambdaQueryWrapper<>();
        submissionWrapper.eq(VoteSubmission::getEventId, eventId).eq(VoteSubmission::getWorkSettingsId, workSettingsId).eq(VoteSubmission::getRoundId, roundId);
        List<VoteSubmission> submissions = voteSubmissionMapper.selectList(submissionWrapper);
        List<Long> validSubmissionIds;
        LambdaQueryWrapper<VoteEvaluationTasks> tasksWrapper = new LambdaQueryWrapper<>();
        tasksWrapper.eq(VoteEvaluationTasks::getJudgeId, userId);
        if ("0".equals(status) || "1".equals(status)) {
            tasksWrapper.eq(VoteEvaluationTasks::getStatus, Integer.parseInt(status)); // 根据 status 过滤 tasks
            validSubmissionIds = voteEvaluationTasksMapper.selectList(tasksWrapper).stream().map(VoteEvaluationTasks::getSubmissionId).collect(Collectors.toList());
        } else if ("2".equals(status)) {
            validSubmissionIds = voteEvaluationTasksMapper.selectList(tasksWrapper).stream().map(VoteEvaluationTasks::getSubmissionId).collect(Collectors.toList());
        } else {
            throw new IllegalArgumentException("无效的状态值: " + status);
        }
        // 过滤 VoteSubmission 列表，只保留 tasks 表中符合条件的记录
        return submissions.stream().filter(item -> validSubmissionIds.contains(item.getId())).map(item -> {
            VoteExpertSubmissionVo submissionVo = new VoteExpertSubmissionVo();
            submissionVo.setSubmissionName(item.getName()).setSubmissionId(item.getId()).setWorkTypeName(voteEventWorkSettingsMapper.selectById(workSettingsId).getAlias());
            // 处理评分逻辑
            LambdaQueryWrapper<VoteEventRegistrationWorkScores> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(VoteEventRegistrationWorkScores::getSubmissionId, item.getId());
            VoteEventRegistrationWorkScores scores = voteEventRegistrationWorkScoresMapper.selectOne(queryWrapper);

            // 设置评分，如果没有找到对应的记录则评分为 0
            if (scores != null) {
                submissionVo.setScore(scores.getScore());
            } else {
                submissionVo.setScore(BigDecimal.ZERO);
            }

            return submissionVo;
        }).collect(Collectors.toList());
    }


    /**
     * 作品统计
     */
    @Override
    public VoteExpertSubmissionCountVo expertPlatformCount(Long eventId, Long workSettingsId, Long roundId, HttpServletRequest request) {
        // 获取 Token 并校验
        String token = SecurityUtils.getToken(request);
        if (!StrUtils.isNotEmpty(token)) {
            throw new ServiceException("请重新登录！");
        }
        String userId = JwtUtils.getUserId(token);
        VoteExpertSubmissionCountVo submissionCount = new VoteExpertSubmissionCountVo();

        // 获取所有 submissions
        LambdaQueryWrapper<VoteSubmission> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(VoteSubmission::getEventId, eventId).eq(VoteSubmission::getWorkSettingsId, workSettingsId).eq(VoteSubmission::getRoundId, roundId);
        List<VoteSubmission> submissions = voteSubmissionMapper.selectList(wrapper);

        // 如果没有 submissions，直接返回 0
        if (submissions.isEmpty()) {
            submissionCount.setYetGrade(0);
            submissionCount.setUnGrade(0);
            submissionCount.setGradeCount(0);
            return submissionCount;
        }

        List<Long> submissionIds = submissions.stream().map(VoteSubmission::getId).collect(Collectors.toList());

        // 通过 JudgeId 和 submissionIds 进行查询，并按 status 分组
        LambdaQueryWrapper<VoteEvaluationTasks> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(VoteEvaluationTasks::getJudgeId, userId).in(VoteEvaluationTasks::getSubmissionId, submissionIds);

        // 查询出所有符合条件的记录，并按 status 分组统计
        Map<Integer, Long> statusCountMap = voteEvaluationTasksMapper.selectList(queryWrapper).stream().collect(Collectors.groupingBy(VoteEvaluationTasks::getStatus, Collectors.counting()));

        // 获取 status 为 "1" 和 "0" 的数量
        int countStatus1 = statusCountMap.getOrDefault(1, 0L).intValue();
        int countStatus0 = statusCountMap.getOrDefault(0, 0L).intValue();

        // 填充统计结果
        submissionCount.setYetGrade(countStatus1);    // 已评分数量
        submissionCount.setUnGrade(countStatus0);     // 未评分数量
        submissionCount.setGradeCount(countStatus1 + countStatus0); // 总的作品数量

        return submissionCount;
    }


    /**
     * 作品详情
     */
    @Override
    public VoteSubmission expertPlatformSubmissionDetails(Long eventId, Long workSettingsId, Long roundId, Long submissionId) {
        try {
            // 创建查询包装器以获取可见字段配置
            LambdaQueryWrapper<VoteJudgesVisibleFields> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(VoteJudgesVisibleFields::getEventId, eventId)
                    .eq(VoteJudgesVisibleFields::getWorkSettingsId, workSettingsId)
                    .eq(VoteJudgesVisibleFields::getRoundId, roundId);

            // 获取可见字段配置
            VoteJudgesVisibleFields selectOne = voteJudgesVisibleFieldsMapper.selectOne(wrapper);
            if (selectOne == null) {
                // 如果未找到可见字段配置，记录警告日志并返回null
                log.warn("未找到可见字段配置，eventId={}, workSettingsId={}, roundId={}", eventId, workSettingsId, roundId);
                return null;
            }

            // 解析可见字段的JSON字符串，确定哪些字段是可见的
            String visibleFieldsJson = selectOne.getVisibleFields();
            Set<String> visibleFields = parseVisibleFieldsJson(visibleFieldsJson);

            // 根据主键从数据库中获取VoteSubmission
            VoteSubmission voteSubmission = voteSubmissionMapper.selectById(submissionId);
            if (voteSubmission == null) {
                log.warn("未找到提交记录，submissionId={}", submissionId);
                return null;
            }
            voteSubmission.setFile(voteSubmission.getFile() + "," + voteSubmission.getImages() + "," + voteSubmission.getVideo());
            // 获取文件信息并进行分类处理
            List<FileInfo> fileInfoList = remoteFileService.selectUrlByIds(voteSubmission.getFile()).getData();
            // 需要剔除的字段集合
            Set<String> excludeFields = new HashSet<>();
            excludeFields.add("isDeleted");
            excludeFields.add("updateById");
            excludeFields.add("updateAt");
            excludeFields.add("file");
            excludeFields.add("images");
            excludeFields.add("video");
            // 创建一个新的VoteSubmission对象，仅包含可见字段
            VoteSubmission submission = filterVoteSubmissionFields(voteSubmission, visibleFields, excludeFields);
            List<VoteFileVo> imageFiles = new ArrayList<>();
            List<VoteFileVo> videoFiles = new ArrayList<>();
            List<VoteFileVo> documentFiles = new ArrayList<>();

            for (FileInfo fileInfo : fileInfoList) {
                VoteFileVo fileVo = new VoteFileVo();
                fileVo.setFileName(fileInfo.getFileName());
                fileVo.setFileUrl(fileInfo.getFileUrl()); // 设置文件URL
                // 根据 fileType 来判断文件类型
                String fileType = fileInfo.getFileType();
                switch (fileType) {
                    case "1":  // 文件
                        documentFiles.add(fileVo);
                        break;
                    case "2":  // 图片类型
                        imageFiles.add(fileVo);
                        break;
                    case "3":  // 视频类型
                        videoFiles.add(fileVo);
                        break;
                    default:
                        // 未知类型处理（可选）
                        log.warn("未知文件类型: {}", fileType);
                        break;
                }
            }


            // 处理班龄段描述
            if (submission.getAgeSegment() == null || submission.getAgeSegment().isEmpty()) {
                submission.setAgeSegment("暂无设置");
            } else {
                String ageSegmentDescription = Arrays.stream(submission.getAgeSegment().split(","))
                        .map(code -> AGE_SEGMENT_MAP.getOrDefault(code, "未知"))
                        .collect(Collectors.joining(","));
                submission.setAgeSegment(ageSegmentDescription);
            }

            // 处理创作类型描述
            if (submission.getCreateType() == null || submission.getCreateType().isEmpty()) {
                submission.setCreateType("暂无设置");
            } else {
                String createTypeDesc = "0".equals(submission.getCreateType()) ? "个人创作" : "团队创作";
                submission.setCreateType(createTypeDesc);
            }
            submission.setImageFiles(imageFiles);
            submission.setDocumentFiles(documentFiles);
            submission.setVideoFiles(videoFiles);
            return submission;
        } catch (Exception e) {
            // 捕获任何异常并记录错误日志
            log.error("处理专家平台提交详情时发生异常，eventId={}, workSettingsId={}, roundId={}, submissionId={}", eventId, workSettingsId, roundId, submissionId, e);
            return null;
        }
    }

    // 用于存储班龄段代码到描述的映射
    private static final Map<String, String> AGE_SEGMENT_MAP = new HashMap<>();

    static {
        AGE_SEGMENT_MAP.put(XIAO_BAN_CODE, XIAO_BAN_DESC);
        AGE_SEGMENT_MAP.put(ZHONG_BAN_CODE, ZHONG_BAN_DESC);
        AGE_SEGMENT_MAP.put(DA_BAN_CODE, DA_BAN_DESC);
    }

    /**
     * 专家评分
     */
    @Override
    @Transactional
    public int expertScoring(String encode, HttpServletRequest request) {
        // 获取 Token 并校验
        String token = SecurityUtils.getToken(request);
        if (!StrUtils.isNotEmpty(token)) {
            throw new ServiceException("请重新登录！");
        }
        String userId = JwtUtils.getUserId(token);
        try {
            VoteExpertWorkingPlatformDto decode = dataEncoder.decode(encode);
            //校验是否重复评分
            LambdaQueryWrapper<VoteEventRegistrationWorkScores> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(VoteEventRegistrationWorkScores::getSubmissionId, decode.getSubmissionId()).eq(VoteEventRegistrationWorkScores::getEventId, decode.getEventId()).eq(VoteEventRegistrationWorkScores::getWorkSettingsId, decode.getWorkSettingsId()).eq(VoteEventRegistrationWorkScores::getJudgeId, userId);
            List<VoteEventRegistrationWorkScores> scoresList = voteEventRegistrationWorkScoresMapper.selectList(queryWrapper);
            if (!scoresList.isEmpty()) {
                throw new ServiceException("该作品已经评分，不可重复评分");
            }
            //计算总分
            int totalScore = 0;
            List<VoteSubmissionItem> itemList = new ArrayList<>();
            for (VoteSubmissionItemVo item : decode.getItemList()) {
                //参数校验
                if (item.getScore() == null) {
                    throw new ServiceException("请完成全部评分后提交");
                }
                VoteScoringItem scoringItem = voteScoringItemMapper.selectById(item.getItemId());
                Double score = scoringItem.getScore();
                Integer itemScore = item.getScore();
                if (itemScore < 0 || itemScore > score) {
                    throw new ServiceException("该" + scoringItem.getScoring() + "评分分数必须在 0 到" + score + "之间");
                }
                VoteSubmissionItem voteSubmissionItem = new VoteSubmissionItem();
                voteSubmissionItem.setItemId(item.getItemId()).setScore(item.getScore()).setSubmissionId(item.getSubmissionId());
                totalScore += item.getScore();
                itemList.add(voteSubmissionItem);
            }
            int i = voteSubmissionItemMapper.insertBatch(itemList);
            if (i > 0) {
                voteEvaluationTasksMapper.updateBySubmissionId(decode.getSubmissionId(), userId);
                //根据作品id 修改评分表总分
                LambdaUpdateWrapper<VoteEventRegistrationWorkScores> wrapper = new LambdaUpdateWrapper<>();
                wrapper.eq(VoteEventRegistrationWorkScores::getSubmissionId, decode.getSubmissionId());
                List<VoteEventRegistrationWorkScores> workScores = voteEventRegistrationWorkScoresMapper.selectList(wrapper);
                VoteEventRegistrationWorkScores scores = new VoteEventRegistrationWorkScores();
                scores.setScore(BigDecimal.valueOf(totalScore)).setEventId(decode.getEventId()).setWorkSettingsId(decode.getWorkSettingsId()).setSubmissionId(decode.getSubmissionId()).setJudgeId(Long.valueOf(decode.getJudgesId()));
                if (workScores != null) {
                    return voteEventRegistrationWorkScoresMapper.insert(scores);
                } else {
                    return voteEventRegistrationWorkScoresMapper.update(scores, wrapper);
                }
            }
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        throw new RuntimeException("评分失败");
    }


    // 解析JSON字符串，将其转换为可见字段名称的集合
    private Set<String> parseVisibleFieldsJson(String visibleFieldsJson) {
        try {
            // 使用JSON解析库将JSON字符串转换为Set集合，包含可见字段名称
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.readValue(visibleFieldsJson, new TypeReference<Set<String>>() {
            });
        } catch (JsonProcessingException e) {
            // 捕获异常并记录错误日志，返回空集合以保证继续执行
            log.error("解析可见字段JSON时发生异常", e);
            return Collections.emptySet();
        }
    }

    // 将snake_case转换为CamelCase（驼峰命名）
    private String convertSnakeToCamel(String snakeCase) {
        try {
            StringBuilder result = new StringBuilder();
            boolean nextUpperCase = false;
            for (char c : snakeCase.toCharArray()) {
                if (c == '_') {
                    nextUpperCase = true;
                } else {
                    result.append(nextUpperCase ? Character.toUpperCase(c) : c);
                    nextUpperCase = false;
                }
            }
            return result.toString();
        } catch (Exception e) {
            // 捕获异常并记录错误日志，返回原始字段名以保证继续执行
            log.error("转换字段名时发生异常，字段名={}", snakeCase, e);
            return snakeCase;
        }
    }

    // 根据可见字段集合动态地过滤VoteSubmission对象中的字段
    private VoteSubmission filterVoteSubmissionFields(VoteSubmission voteSubmission, Set<String> visibleFields, Set<String> excludeFields) {
        VoteSubmission filteredSubmission = new VoteSubmission();
        for (String field : visibleFields) {
            // 如果字段属于剔除字段集，则跳过
            if (excludeFields.contains(field)) {
                continue;
            }
            try {
                // 将字段从snake_case转换为CamelCase
                String camelCaseField = convertSnakeToCamel(field);
                // 通过反射获取并设置相应的字段值
                Field voteField = VoteSubmission.class.getDeclaredField(camelCaseField);
                voteField.setAccessible(true);
                Field filteredField = VoteSubmission.class.getDeclaredField(camelCaseField);
                filteredField.setAccessible(true);
                filteredField.set(filteredSubmission, voteField.get(voteSubmission));
            } catch (NoSuchFieldException | IllegalAccessException e) {
                // 捕获字段未找到或无法访问的异常，并记录错误日志，但继续处理下一个字段
                log.error("处理字段时发生异常，字段名={}", field, e);
            } catch (Exception e) {
                // 捕获其他任何异常，并记录错误日志，但继续处理下一个字段
                log.error("未知错误，字段名={}", field, e);
            }
        }
        return filteredSubmission;
    }

    public Map<Long, VoteEvents> getFilteredEventMap(Set<Long> eventIds) {
        if (eventIds == null || eventIds.isEmpty()) {
            return Collections.emptyMap(); // 如果 eventIds 为空，返回空的 Map
        }
        // 创建查询条件
        LambdaQueryWrapper<VoteEvents> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(VoteEvents::getId, eventIds); // 根据 eventId 查询
        queryWrapper.eq(VoteEvents::getStatus, "0");
        // 执行查询并转换为 Map
        return voteEventsMapper.selectList(queryWrapper).stream().collect(Collectors.toMap(VoteEvents::getId, Function.identity()));
    }
}
