package com.vote.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vctgo.common.core.text.Convert;
import com.vctgo.common.core.utils.ServletUtils;
import com.vctgo.common.mybatisplus.constant.MybatisPageConstants;
import com.vctgo.system.api.RemoteBranchKindergartenService;
import com.vctgo.system.api.RemotePlatformUserService;
import com.vctgo.system.api.RemoteSysProvinceService;
import com.vctgo.system.api.domain.SysPlatformUser;
import com.vctgo.system.api.domain.SysProvince;
import com.vctgo.system.api.domain.dto.SysBranchKindergartenDto;
import com.vote.system.domain.*;
import com.vote.system.domain.dto.VoteEvaluationTasksDto;
import com.vote.system.domain.vo.*;
import com.vote.system.mapper.*;
import com.vote.system.service.VoteEvaluationTasksService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author MacBook
 * @description 针对表【vote_evaluation_tasks(评选任务表)】的数据库操作Service实现
 * @createDate 2024-08-22 10:03:45
 */
@Service
public class VoteEvaluationTasksServiceImpl extends ServiceImpl<VoteEvaluationTasksMapper, VoteEvaluationTasks> implements VoteEvaluationTasksService {

    @Autowired
    private VoteEvaluationTasksMapper voteEvaluationTasksMapper;

    @Autowired
    private VoteEventRegistrationWorkScoresMapper voteEventRegistrationWorkScoresMapper;

    @Autowired
    private VoteEventEvaluationRoundsMapper voteEventEvaluationRoundsMapper;

    @Autowired
    private VoteEventCompetitionZonesMapper voteEventCompetitionZonesMapper;

    @Autowired
    private VoteSubmissionMapper voteSubmissionMapper;

    @Autowired
    private VoteRegistrationsMapper voteRegistrationsMapper;

    @Autowired
    private RemotePlatformUserService remotePlatformUserService;

    @Autowired
    private RemoteSysProvinceService remoteSysProvinceService;

    @Autowired
    private RemoteBranchKindergartenService remoteBranchKindergartenService;

    /**
     * 统计数量
     *
     * @param voteEvaluationTasksDto
     * @return
     */
    @Override
    public VoteEvaluationTasksCountVo getStatistics(VoteEvaluationTasksDto voteEvaluationTasksDto) {
        VoteEvaluationTasksCountVo evaluationTasksVo = new VoteEvaluationTasksCountVo();

        // 构建查询条件
        LambdaQueryWrapper<VoteSubmission> submissionWrapper = new LambdaQueryWrapper<>();
        submissionWrapper.eq(VoteSubmission::getEventId, voteEvaluationTasksDto.getEventId()).eq(VoteSubmission::getWorkSettingsId, voteEvaluationTasksDto.getWorkSettingsId());
        List<VoteSubmission> submissions = voteSubmissionMapper.selectList(submissionWrapper);
        evaluationTasksVo.setSubMissionCount(submissions.size()); // 作品数

        // 统计已完成的总分数
        BigDecimal totalScore = BigDecimal.ZERO; // 使用 BigDecimal 来处理可能的浮点数运算

        if (!submissions.isEmpty()) {
            // 从 submissions 中提取出所有的 submissionId
            List<Long> submissionIds = submissions.stream().map(VoteSubmission::getId).collect(Collectors.toList());

            // 创建查询包装器，用于查询 VoteEventRegistrationWorkScores 表
            LambdaQueryWrapper<VoteEventRegistrationWorkScores> scoresWrapper = new LambdaQueryWrapper<>();
            scoresWrapper.in(VoteEventRegistrationWorkScores::getSubmissionId, submissionIds);

            // 执行查询，获取所有与 submissionIds 相关的评分记录
            List<VoteEventRegistrationWorkScores> workScores = voteEventRegistrationWorkScoresMapper.selectList(scoresWrapper);

            // 统计所有已完成的评分记录的总分数
            totalScore = workScores.stream().filter(scores -> scores.getScore() != null && scores.getScore().compareTo(BigDecimal.ZERO) > 0).map(VoteEventRegistrationWorkScores::getScore).reduce(BigDecimal.ZERO, BigDecimal::add); // 计算总分数
        }
        evaluationTasksVo.setFinishedCount(totalScore);

        // 评审专家数量
        VoteEventEvaluationRounds evaluationRounds = voteEventEvaluationRoundsMapper.selectById(voteEvaluationTasksDto.getRoundId());
        String[] judgeIds = evaluationRounds.getJudges().split(",");
        evaluationTasksVo.setJudgesCount(judgeIds.length);

        // 统计已完成评审的专家数
        int finishedJudgesCount = 0;
        if (judgeIds.length > 0) {
            LambdaQueryWrapper<VoteEvaluationTasks> tasksWrapper = new LambdaQueryWrapper<>();
            tasksWrapper.in(VoteEvaluationTasks::getJudgeId, Arrays.asList(judgeIds)).eq(VoteEvaluationTasks::getStatus, 1);
            List<Long> submissionIds = voteEvaluationTasksMapper.selectList(tasksWrapper).stream().map(VoteEvaluationTasks::getSubmissionId).collect(Collectors.toList());
             //过滤掉不是该活动 该类型 该轮次的作品
            LambdaQueryWrapper<VoteSubmission> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(VoteSubmission::getEventId, voteEvaluationTasksDto.getEventId())
                    .eq(VoteSubmission::getWorkSettingsId, voteEvaluationTasksDto.getWorkSettingsId())
                    .eq(VoteSubmission::getRoundId, voteEvaluationTasksDto.getRoundId())
                    .in(VoteSubmission::getId, submissionIds);
            finishedJudgesCount = voteSubmissionMapper.selectList(wrapper).size();

        }
        evaluationTasksVo.setFinishedJudgesCount(finishedJudgesCount);
        return evaluationTasksVo;
    }


    /**
     * 评选任务分页查询
     *
     * @param voteEvaluationTasksDto
     * @return
     */
    @Override
    public IPage<VoteJudgeTaskInfoVo> selectPage(VoteEvaluationTasksDto voteEvaluationTasksDto) {
        //分页参数
        long pageNum = Convert.toLong(ServletUtils.getParameterToInt(MybatisPageConstants.PAGE_NUM), 1L);
        long pageSize = Convert.toLong(ServletUtils.getParameterToInt(MybatisPageConstants.PAGE_SIZE), 10L);
        Page<VoteJudgeTaskInfoVo> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<VoteEventCompetitionZones> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(VoteEventCompetitionZones::getEventId, voteEvaluationTasksDto.getEventId())
                .eq(VoteEventCompetitionZones::getWorkSettingsId, voteEvaluationTasksDto.getWorkSettingsId())
                .eq(VoteEventCompetitionZones::getRoundId, voteEvaluationTasksDto.getRoundId())
                .eq(VoteEventCompetitionZones::getStatus, "1");
        List<VoteEventCompetitionZones> zones = voteEventCompetitionZonesMapper.selectList(wrapper);
        //获取所有作品id
        LambdaQueryWrapper<VoteSubmission> submissionWrapper = new LambdaQueryWrapper<>();
        submissionWrapper.eq(VoteSubmission::getEventId, voteEvaluationTasksDto.getEventId())
                .eq(VoteSubmission::getWorkSettingsId, voteEvaluationTasksDto.getWorkSettingsId())
                .eq(VoteSubmission::getRoundId, voteEvaluationTasksDto.getRoundId());
        List<Long> submissionIds = voteSubmissionMapper.selectList(submissionWrapper).stream().map(VoteSubmission::getId).collect(Collectors.toList());
        String[] judgeIds = zones.stream()
                .map(VoteEventCompetitionZones::getJudges)
                .filter(Objects::nonNull) // 避免空值
                .flatMap(judges -> Arrays.stream(judges.split(","))) // 分割每个 judge 字符串
                .toArray(String[]::new);
        // 获取专家数据和省份数据，避免频繁调用服务
        List<SysPlatformUser> users = Optional.ofNullable(remotePlatformUserService.processExpertList().getData()).orElse(Collections.emptyList());
        List<SysProvince> provinces = Optional.ofNullable(remoteSysProvinceService.getProvince().getData()).orElse(Collections.emptyList());
        // 初始化返回的结果集
        List<VoteJudgeTaskInfoVo> judgeTaskInfoList = new ArrayList<>();

        // 遍历每个专家ID，获取任务数、已完成数、专家名称及赛区信息
        for (String judgeId : judgeIds) {
            if (judgeId == null || judgeId.trim().isEmpty()) {
                continue; // 跳过空的专家ID
            }

            VoteJudgeTaskInfoVo judgeTaskInfo = new VoteJudgeTaskInfoVo();

            // 获取专家名称，设置默认值
            String judgeName = users.stream().filter(user -> judgeId.equals(user.getUserId().toString())).map(SysPlatformUser::getNickName).findFirst().orElse("未知专家");

            // 计算任务数和已完成任务数
            int taskCount = calculateTaskCount(new String[]{judgeId}, submissionIds, false);
            int doneTaskCount = calculateTaskCount(new String[]{judgeId}, submissionIds, true);

            // 查询专家所在的赛区及相关省份，并设置默认值
            Map<String, String> zonesAndProvinces = findZoneNamesAndProvincesByJudgeId(judgeId);
            String provinceNames = getProvinceNames(zonesAndProvinces.get("provinces"), provinces);

            // 填充信息到结果对象
            judgeTaskInfo.setJudgeName(judgeName);
            judgeTaskInfo.setJudgeId(Long.valueOf(judgeId));
            judgeTaskInfo.setTaskCount(taskCount);
            judgeTaskInfo.setDoneTaskCount(doneTaskCount);
            judgeTaskInfo.setUndoneCount(taskCount - doneTaskCount);
            judgeTaskInfo.setZonesName(Optional.ofNullable(zonesAndProvinces.get("zoneNames")).orElse("未知赛区"));
            judgeTaskInfo.setProvince(Optional.ofNullable(provinceNames).orElse("未知省份"));

            // 加入结果集
            judgeTaskInfoList.add(judgeTaskInfo);
        }
        page.setRecords(judgeTaskInfoList);
        page.setTotal(judgeTaskInfoList.size());

        return page;
    }

    /**
     * 查询详情
     *
     * @param voteEvaluationTasksDto
     * @return
     */
    @Override
    public IPage<VoteTasksScoresVo> getDetail(VoteEvaluationTasksDto voteEvaluationTasksDto) {
        // 分页参数
        long pageNum = Convert.toLong(ServletUtils.getParameterToInt(MybatisPageConstants.PAGE_NUM), 1L);
        long pageSize = Convert.toLong(ServletUtils.getParameterToInt(MybatisPageConstants.PAGE_SIZE), 10L);
        Page<VoteTasksScoresVo> page = new Page<>(pageNum, pageSize);

        // 查询评估任务
        LambdaQueryWrapper<VoteEvaluationTasks> taskWrapper = new LambdaQueryWrapper<>();
        taskWrapper.eq(VoteEvaluationTasks::getJudgeId, voteEvaluationTasksDto.getJudgeId());
        if ("1".equals(voteEvaluationTasksDto.getType())) {
            taskWrapper.eq(VoteEvaluationTasks::getStatus, "0");
        } else if ("2".equals(voteEvaluationTasksDto.getType())) {
            taskWrapper.eq(VoteEvaluationTasks::getStatus, "1");
        }
        List<VoteEvaluationTasks> tasks = voteEvaluationTasksMapper.selectList(taskWrapper);

        if (tasks.isEmpty()) {
            return page.setRecords(Collections.emptyList()).setTotal(0);
        }

        // 获取所有相关的提交信息
        List<Long> submissionIds = tasks.stream().map(VoteEvaluationTasks::getSubmissionId).collect(Collectors.toList());
        LambdaQueryWrapper<VoteSubmission> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(VoteSubmission::getId, submissionIds)
                .eq(VoteSubmission::getEventId, voteEvaluationTasksDto.getEventId())
                .eq(VoteSubmission::getWorkSettingsId, voteEvaluationTasksDto.getWorkSettingsId())
                .eq(VoteSubmission::getRoundId, voteEvaluationTasksDto.getRoundId());
        List<VoteSubmission> submissions = voteSubmissionMapper.selectList(wrapper);

        // 获取所有相关的评分信息
        List<Long> eventIds = submissions.stream().map(VoteSubmission::getEventId).distinct().collect(Collectors.toList());
        List<VoteEventRegistrationWorkScores> scoresList = voteEventRegistrationWorkScoresMapper.selectList(new LambdaQueryWrapper<VoteEventRegistrationWorkScores>().in(VoteEventRegistrationWorkScores::getSubmissionId, submissionIds).in(VoteEventRegistrationWorkScores::getEventId, eventIds).eq(VoteEventRegistrationWorkScores::getJudgeId, voteEvaluationTasksDto.getJudgeId()));

        // 获取所有相关的幼儿园信息
        List<Long> locationIds = submissions.stream().map(VoteSubmission::getLocationId).distinct().collect(Collectors.toList());
        Map<Long, SysBranchKindergartenDto> branchMap = getBranchMap(locationIds);

        // 处理任务和评分数据
        Map<String, VoteEventRegistrationWorkScores> scoresMap = scoresList.stream().collect(Collectors.toMap(score -> score.getSubmissionId() + "-" + score.getEventId(), Function.identity()));

        List<VoteTasksScoresVo> scoresVos = tasks.stream().map(item -> {
            VoteTasksScoresVo scoresVo = new VoteTasksScoresVo();

            // 获取 submission，如果找不到则字段为 null 而不是返回 null
            VoteSubmission submission = submissions.stream()
                    .filter(sub -> sub.getId().equals(item.getSubmissionId()))
                    .findFirst()
                    .orElse(null);

            // 无论 submission 是否为空，都设置对应的字段
            if (submission != null) {
                scoresVo.setSubmissionName(submission.getName())
                        .setCommitName(submission.getCommitName());
            } else {
                return null;
            }

            // 获取幼儿园信息，如果找不到则设置为 null
            SysBranchKindergartenDto data = branchMap.get(submission.getLocationId());
            scoresVo.setLocationName(data != null ? data.getKindergartenName() : null);

            // 获取评分信息，如果找不到则设置为 null
            VoteEventRegistrationWorkScores scores = scoresMap.get(submission.getId() + "-" + submission.getEventId());
            if (scores != null) {
                scoresVo.setScoresTime(scores.getCreatedAt())
                        .setScore(scores.getScore());
            } else {
                scoresVo.setScoresTime(null)
                        .setScore(null);
            }

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

        List<VoteTasksScoresVo> collect = scoresVos.stream().filter(Objects::nonNull).collect(Collectors.toList());
        // 设置分页结果
        page.setRecords(collect);
        page.setTotal(collect.size());

        return page;
    }

    /**
     * 查询评选任务
     */
    @Override
    public IPage<VoteTasksIssueVo> tasksIssue(VoteEvaluationTasksDto voteEvaluationTasksDto) {
        // 构建分页参数
        long pageNum = Convert.toLong(ServletUtils.getParameterToInt(MybatisPageConstants.PAGE_NUM), 1L);
        long pageSize = Convert.toLong(ServletUtils.getParameterToInt(MybatisPageConstants.PAGE_SIZE), 10L);
        // 构建查询条件
        LambdaQueryWrapper<VoteEventCompetitionZones> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(VoteEventCompetitionZones::getEventId, voteEvaluationTasksDto.getEventId()).eq(VoteEventCompetitionZones::getRoundId, voteEvaluationTasksDto.getRoundId()).eq(VoteEventCompetitionZones::getWorkSettingsId, voteEvaluationTasksDto.getWorkSettingsId()).orderByDesc(VoteEventCompetitionZones::getCreatedAt);
        List<VoteEventCompetitionZones> competitionZones = voteEventCompetitionZonesMapper.selectList(wrapper);
        // 调用获取所有省份
        List<SysProvince> provinces = remoteSysProvinceService.getProvince().getData();
        // 构建返回集合
        List<VoteTasksIssueVo> issueVos = new ArrayList<>();
        if (competitionZones != null && !competitionZones.isEmpty()) {
            for (VoteEventCompetitionZones zone : competitionZones) {
                try {
                    // 初始化并设置 issueVo 对象的属性
                    VoteTasksIssueVo issueVo = new VoteTasksIssueVo();
                    issueVo.setZonesName(zone.getName())
                            .setProvince(getProvinceNames(zone.getProvinces(), provinces))
                            .setZonesId(zone.getId())
                            .setStatus(zone.getStatus());

                    // 提取和处理省份 ID
                    String[] provinceIds = zone.getProvinces() != null ? zone.getProvinces().split(",") : new String[0];

                    // 如果 provinceIds 非空，则根据省份 ID 查询 userIds
                    List<Long> userIds = new ArrayList<>();
                    if (provinceIds.length > 0) {
                        userIds = voteRegistrationsMapper.selectList(
                                        new LambdaQueryWrapper<VoteRegistrations>()
                                                .in(VoteRegistrations::getProvinceId, provinceIds)
                                ).stream()
                                .map(VoteRegistrations::getUid)
                                .collect(Collectors.toList());
                    }
                    // 初始化作品计数
                    int submissionCount = 0;
                    if (!userIds.isEmpty()) {
                        // 只有当 userIds 非空时才查询作品数
                        submissionCount = Math.toIntExact(voteSubmissionMapper.selectCount(
                                new LambdaQueryWrapper<VoteSubmission>()
                                        .in(VoteSubmission::getUserId, userIds)
                                        .eq(VoteSubmission::getEventId, voteEvaluationTasksDto.getEventId())
                                        .eq(VoteSubmission::getWorkSettingsId, voteEvaluationTasksDto.getWorkSettingsId())
                                        .eq(VoteSubmission::getRoundId, voteEvaluationTasksDto.getRoundId())
                        ));
                    }
                    // 处理评委并计算每个评委的平均作品数
                    String[] judgesIds = zone.getJudges() != null ? zone.getJudges().split(",") : new String[0];
                    int judgesCount = judgesIds.length;
                    int avgSubmissionsPerJudge = (judgesCount > 0) ? submissionCount / judgesCount : 0;
                    // 安全地设置额外的参数
                    issueVo.setSubmissionCount(Math.max(submissionCount, 0)) // 确保作品数为非负值
                            .setJudgesCount(judgesCount)
                            .setAvg(Math.max(avgSubmissionsPerJudge, 0)); // 确保平均值为非负值
                    // 将 issueVo 添加到结果列表
                    issueVos.add(issueVo);
                } catch (Exception e) {
                    // 处理任何异常并记录错误日志
                    log.error("处理 zone 时出错: " + zone.getId(), e);
                    // 可以选择继续处理下一个 zone，或者在关键错误时重新抛出异常
                }
            }
        }

        // 分页
        Page<VoteTasksIssueVo> page = new Page<>(pageNum, pageSize);
        page.setRecords(issueVos.stream().skip((pageNum - 1) * pageSize).limit(pageSize).collect(Collectors.toList()));
        page.setTotal(issueVos.size());
        return page;
    }


    // 获取幼儿园信息的辅助方法
    private Map<Long, SysBranchKindergartenDto> getBranchMap(List<Long> locationIds) {
        ExecutorService executorService = Executors.newFixedThreadPool(10); // 设置适当的线程池大小
        Map<Long, SysBranchKindergartenDto> branchMap = new HashMap<>();

        // 等待所有异步操作完成
        CompletableFuture.allOf(locationIds.stream().map(locationId -> CompletableFuture.supplyAsync(() -> {
            // 执行单个查询
            return remoteBranchKindergartenService.getById(locationId).getData();
        }, executorService).thenAccept(data -> {
            if (data != null) {
                synchronized (branchMap) {
                    branchMap.put(locationId, data);
                }
            }
        })).toArray(CompletableFuture[]::new)).join();

        executorService.shutdown();
        return branchMap;
    }

    // 获取任务数和已完成数
    private int calculateTaskCount(String[] judgeIds, List<Long> submissionIds, boolean includeJudgeCondition) {
        if (judgeIds == null || judgeIds.length == 0 || submissionIds == null || submissionIds.isEmpty()) {
            return 0; // 如果 judgeIds 或 submissionIds 为空，直接返回 0
        }
        LambdaQueryWrapper<VoteEvaluationTasks> queryWrapper = new LambdaQueryWrapper<>();
        // 根据专家ID查询
        queryWrapper.in(VoteEvaluationTasks::getJudgeId, Arrays.asList(judgeIds));

        // 根据 submissionIds 查询
        queryWrapper.in(VoteEvaluationTasks::getSubmissionId, submissionIds);

        // 如果需要根据任务状态查询，添加相应的条件
        if (includeJudgeCondition) {
            queryWrapper.eq(VoteEvaluationTasks::getStatus, 1); // 1表示已完成
        }

        // 使用 Long 类型来获取 count 的值，并将其安全地转换为 int
        Long count = voteEvaluationTasksMapper.selectCount(queryWrapper);
        return Optional.ofNullable(count).orElse(0L).intValue();
    }


    //获取赛区名 和 相关的省份
    public Map<String, String> findZoneNamesAndProvincesByJudgeId(String judgeId) {
        if (judgeId == null || judgeId.trim().isEmpty()) {
            // 如果 judgeId 为空，返回空的 Map
            return Collections.emptyMap();
        }

        LambdaQueryWrapper<VoteEventCompetitionZones> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(VoteEventCompetitionZones::getJudges, "," + judgeId + ",").or().like(VoteEventCompetitionZones::getJudges, judgeId + ",").or().like(VoteEventCompetitionZones::getJudges, "," + judgeId).or().eq(VoteEventCompetitionZones::getJudges, judgeId);

        List<VoteEventCompetitionZones> zones = Optional.ofNullable(voteEventCompetitionZonesMapper.selectList(queryWrapper)).orElse(Collections.emptyList());

        // 提取 name 字段和 provinces 字段，并用逗号拼接成一个字符串
        String zoneNames = zones.stream().map(VoteEventCompetitionZones::getName).filter(Objects::nonNull).collect(Collectors.joining(","));

        String provinces = zones.stream().map(VoteEventCompetitionZones::getProvinces).filter(Objects::nonNull).collect(Collectors.joining(","));

        Map<String, String> result = new HashMap<>();
        result.put("zoneNames", zoneNames.isEmpty() ? "暂未分配赛区" : zoneNames);
        result.put("provinces", provinces.isEmpty() ? "" : provinces);

        return result;
    }

    //根据省份编号获取省份名
    private String getProvinceNames(String provinceIds, List<SysProvince> allProvinces) {
        if (provinceIds == null || provinceIds.isEmpty()) {
            return "暂无省份"; // 如果 provinceIds 为空，返回默认值
        }

        List<String> provinceIdList = Arrays.asList(provinceIds.split(","));
        return allProvinces.stream().filter(province -> provinceIdList.contains(province.getProvinceId())).map(SysProvince::getProvince).collect(Collectors.joining(","));
    }

    /**
     * 发布评选任务
     */
    @Override
    @Transactional
    public int releaseTask(VoteEvaluationTasksDto voteEvaluationTasksDto) {
        // 构建查询条件
        LambdaQueryWrapper<VoteSubmission> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(VoteSubmission::getEventId, voteEvaluationTasksDto.getEventId())
                .eq(VoteSubmission::getWorkSettingsId, voteEvaluationTasksDto.getWorkSettingsId())
                .eq(VoteSubmission::getRoundId, voteEvaluationTasksDto.getRoundId());
        List<VoteSubmission> voteSubmissions = voteSubmissionMapper.selectList(wrapper);
        if (voteSubmissions == null || voteSubmissions.isEmpty()) {
            throw new RuntimeException("该赛区下暂无作品，分配失败");
        }
        //收集主键
        List<Long> submissionIds = voteSubmissions.stream()
                .map(VoteSubmission::getId)
                .collect(Collectors.toList());

        // 获取专家id数组
        VoteEventCompetitionZones competitionZones = voteEventCompetitionZonesMapper.selectById(voteEvaluationTasksDto.getZonesId());
        String judges = competitionZones.getJudges();
        if (judges == null || judges.isEmpty()) {
            throw new RuntimeException("该赛区下暂未分配专家，分配失败");
        }
        String[] split = judges.split(",");
        List<String> judgeIds = Arrays.asList(split);
        // 结果集，存储每个专家分配到的作品ID
        Map<String, List<Long>> assignmentMap = new HashMap<>();
        // 初始化结果集
        for (String judgeId : judgeIds) {
            assignmentMap.put(judgeId, new ArrayList<>());
        }
        // 平均分配作品
        int judgeCount = judgeIds.size();
        int submissionCount = submissionIds.size();
        int baseCount = submissionCount / judgeCount;  // 每个专家最少分到的作品数量
        int remainder = submissionCount % judgeCount;  // 不能平均分配的剩余作品数量
        // 迭代分配
        Iterator<Long> submissionIterator = submissionIds.iterator();
        for (String judgeId : judgeIds) {
            // 为当前专家分配baseCount个作品
            List<Long> assignedSubmissions = assignmentMap.get(judgeId);
            for (int i = 0; i < baseCount && submissionIterator.hasNext(); i++) {
                assignedSubmissions.add(submissionIterator.next());
            }
        }
        // 在所有作品并未平均分配的情况下，随机分配剩余作品
        if (remainder > 0) {
            Random random = new Random();
            for (int i = 0; i < remainder && submissionIterator.hasNext(); i++) {
                String randomJudgeId = judgeIds.get(random.nextInt(judgeCount));
                assignmentMap.get(randomJudgeId).add(submissionIterator.next());
            }
        }
        List<VoteEvaluationTasks> tasksToInsert = getVoteEvaluationTasks(assignmentMap);
        // 批量插入任务到数据库
        if (!tasksToInsert.isEmpty()) {
            int i = voteEvaluationTasksMapper.insertBatch(tasksToInsert);
            //修改作品评选状态 为评选中

            if (i > 0) {
                VoteEventCompetitionZones zones = new VoteEventCompetitionZones();
                zones.setId(voteEvaluationTasksDto.getZonesId()).setStatus("1");
                voteEventCompetitionZonesMapper.updateById(zones);
                return i;
            }
        }
        throw new RuntimeException("分配失败");
    }


    //构建插入任务
    private List<VoteEvaluationTasks> getVoteEvaluationTasks(Map<String, List<Long>> assignmentMap) {
        List<VoteEvaluationTasks> tasksToInsert = new ArrayList<>();
        for (Map.Entry<String, List<Long>> entry : assignmentMap.entrySet()) {
            String judgeId = entry.getKey();
            List<Long> submissions = entry.getValue();
            for (Long submissionId : submissions) {
                // 创建任务对象
                VoteEvaluationTasks task = new VoteEvaluationTasks();
                task.setJudgeId(judgeId);
                task.setSubmissionId(submissionId);
                tasksToInsert.add(task);
            }
        }
        return tasksToInsert;
    }
}




