package com.vote.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vctgo.common.core.domain.R;
import com.vctgo.common.core.web.domain.AjaxResult;
import com.vctgo.system.api.RemotePlatformUserService;
import com.vctgo.system.api.domain.SysPlatformUser;
import com.vote.system.domain.*;
import com.vote.system.domain.dto.VoteEventWorkSettingsDto;
import com.vote.system.domain.vo.VoteEventWorkSettingsVo;
import com.vote.system.mapper.*;
import com.vote.system.service.VoteEventWorkSettingsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author MacBook
 * @description 针对表【vote_event_work_settings(活动作品设置表)】的数据库操作Service实现
 * @createDate 2024-08-12 18:20:26
 */
@Service
public class VoteEventWorkSettingsServiceImpl extends ServiceImpl<VoteEventWorkSettingsMapper, VoteEventWorkSettings>
        implements VoteEventWorkSettingsService {


    @Autowired
    private VoteEventEvaluationRoundsMapper voteEventEvaluationRoundsMapper;//评选轮数

    @Autowired
    private VoteEventWorkSettingsMapper voteEventWorkSettingsMapper;//作品设置

    @Autowired
    private VoteWorkTypesMapper voteWorkTypesMapper;//作品类型

    @Autowired
    private VoteRuleMapper voteRuleMapper;// 规则表

    @Autowired
    private VoteEventsMapper voteEventsMapper;

    @Autowired
    private VoteEventAwardsMapper voteEventAwardsMapper;//奖品

    @Autowired
    private RemotePlatformUserService remotePlatformUserService;


    /**
     * 查询活动作品设置及其关联数据
     *
     * @param id
     * @return
     */
    @Override
    public VoteEventWorkSettingsVo getEventWorkSettings(Long id) {
        VoteEventWorkSettingsVo workSettingsVo = new VoteEventWorkSettingsVo();
        // 查询与事件相关的所有作品类型
        LambdaQueryWrapper<VoteEventWorkSettings> workSettingsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        workSettingsLambdaQueryWrapper.eq(VoteEventWorkSettings::getEventId, id);
        List<VoteEventWorkSettings> eventWorkSettings = voteEventWorkSettingsMapper.selectList(workSettingsLambdaQueryWrapper);
        VoteEvents voteEvents = voteEventsMapper.selectById(id);
        if (eventWorkSettings == null || eventWorkSettings.isEmpty()) {
            workSettingsVo.setName(voteEvents.getName());
            workSettingsVo.setId(voteEvents.getId());
            return workSettingsVo;
        }
        workSettingsVo.setName(voteEvents.getName());
        workSettingsVo.setId(voteEvents.getId());
        // 定义并初始化工作类型映射
        final Map<Long, VoteWorkTypes> workTypesMap;
        Set<Long> workTypeIds = eventWorkSettings.stream()
                .map(VoteEventWorkSettings::getWorkTypeId)
                .filter(Objects::nonNull)  // 确保工作类型ID不为空
                .collect(Collectors.toSet());

        if (!workTypeIds.isEmpty()) {
            List<VoteWorkTypes> workTypesList = voteWorkTypesMapper.selectBatchIds(workTypeIds);
            workTypesMap = (workTypesList != null) ?
                    workTypesList.stream()
                            .collect(Collectors.toMap(VoteWorkTypes::getId, workType -> workType)) :
                    Collections.emptyMap();
        } else {
            workTypesMap = Collections.emptyMap();
        }

        // 批量查询评选轮数
        List<VoteEventEvaluationRounds> evaluationRounds = getVoteEventEvaluationRounds(id);
        if (evaluationRounds == null) {
            evaluationRounds = Collections.emptyList(); // 如果查询结果为空，设置为空列表
        }

        // 设置工作设置详情
        List<VoteEventEvaluationRounds> finalEvaluationRounds = evaluationRounds;
        List<VoteEventWorkSettings> voteEventWorkSettings = eventWorkSettings.stream()
                .map(workSettings -> {
                    // 添加工作类型名称
                    if (workSettings.getAlias() != null && !workSettings.getAlias().isEmpty()) {
                        VoteWorkTypes workTypes = workTypesMap.get(workSettings.getWorkTypeId());
                        if (workTypes != null) {
                            workSettings.setWorkTypeName(workTypes.getName());
                        }
                    }

                    // 设置评选轮数及规则、专家名
                    if (!finalEvaluationRounds.isEmpty()) {
                        setEvaluationRoundsDetails(finalEvaluationRounds, workSettings);
                    } else {
                        // 如果评选轮数为空，设置评选轮数为空
                        workSettings.setVoteEventEvaluationRounds(null); // 评选轮数为空但字段存在
                        System.out.println("No evaluation rounds found for eventId: " + id);
                    }

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

        workSettingsVo.setVoteEventWorkSettingsList(voteEventWorkSettings);
        return workSettingsVo;
    }


    @Override
    @Transactional
    public Long saveWorkType(VoteEventWorkSettings voteEventWorkSettings) {
        VoteWorkTypes workTypes = new VoteWorkTypes();
        workTypes.setName(voteEventWorkSettings.getWorkTypeName());
        voteWorkTypesMapper.insert(workTypes);
        voteEventWorkSettings.setWorkTypeId(workTypes.getId());
        return voteEventWorkSettings.getId();
    }

    @Override
    public Map<String, String> getJudges() {
        Map<String, String> map = new HashMap<>();
        R<List<SysPlatformUser>> listR = remotePlatformUserService.processExpertList();
        listR.getData().forEach(user -> {
            map.put(String.valueOf(user.getUserId()), user.getNickName());
        });
        return map;
    }

    /**
     * 编辑
     *
     * @return
     */
    @Override
    @Transactional
    public AjaxResult editWorkSettings(VoteEventWorkSettingsDto workSettingsDto) {

        // 检查输入参数是否为null
        if (workSettingsDto == null) {
            throw new IllegalArgumentException("暂未关联任何活动");
        }
        if (workSettingsDto.getAlias() == null || workSettingsDto.getAlias().isEmpty()) {
            return AjaxResult.error("类型别称不允许为空");
        }

        if (workSettingsDto.getId() == null) {
            // 插入新的记录
            voteEventWorkSettingsMapper.insert(workSettingsDto);
        } else {
            // 更新现有记录
            voteEventWorkSettingsMapper.updateById(workSettingsDto);
        }

        // 获取当前的 roundsId
        VoteEventWorkSettings existingWorkSettings = voteEventWorkSettingsMapper.selectById(workSettingsDto.getId());
        if (existingWorkSettings == null) {
            throw new RuntimeException("无法找到现有的作品设置");
        }

        extracted(existingWorkSettings.getRoundsId());//删除评选轮次 以及 轮次下的奖项

        // 准备插入新的记录
        List<VoteEventAwards> awardsList = new ArrayList<>();
        List<VoteEventEvaluationRounds> evaluationRoundsList = new ArrayList<>();
        StringBuilder roundsIdBuilder = new StringBuilder();
        if (workSettingsDto.getEvaluationRounds() != null && !workSettingsDto.getEvaluationRounds().isEmpty()) {
            for (VoteEventEvaluationRounds round : workSettingsDto.getEvaluationRounds()) {
                if (round == null) {
                    continue; // 忽略空的轮次对象
                }

                if ("award".equals(round.getType().toString())) {
                    if (round.getVoteEventAwardsList() != null && !round.getVoteEventAwardsList().isEmpty()) {
                        StringBuilder awardsIdStrBuilder = new StringBuilder();
                        for (VoteEventAwards award : round.getVoteEventAwardsList()) {
                            if (award != null) {
                                award.setEventId(workSettingsDto.getEventId());
                                awardsList.add(award);

                                // 插入新的奖项记录并获取主键
                                voteEventAwardsMapper.insert(award);
                                awardsIdStrBuilder.append(award.getId()).append(",");
                            }
                        }
                        // 移除最后一个逗号
                        if (awardsIdStrBuilder.length() > 0) {
                            awardsIdStrBuilder.setLength(awardsIdStrBuilder.length() - 1);
                        }
                        round.setAwards(awardsIdStrBuilder.toString());
                    }
                }

                // 封装评选轮次
                round.setEventId(workSettingsDto.getEventId());
                evaluationRoundsList.add(round);

                // 插入新的评选轮次记录并获取主键
                voteEventEvaluationRoundsMapper.insert(round);
                roundsIdBuilder.append(round.getId()).append(",");
            }

            // 移除最后一个逗号
            if (roundsIdBuilder.length() > 0) {
                roundsIdBuilder.setLength(roundsIdBuilder.length() - 1);
            }

            // 更新 workSettings 的 roundsId 和 awards 字段
            workSettingsDto.setRoundsId(roundsIdBuilder.toString());
            voteEventWorkSettingsMapper.updateById(workSettingsDto);
        }
        return AjaxResult.success(workSettingsDto.getId());

    }

    private void extracted(String existingRoundsIdStr) {
        // 删除当前的评选轮次记录
        if (existingRoundsIdStr != null && !existingRoundsIdStr.isEmpty()) {
            Set<Integer> existingRoundIds = Arrays.stream(existingRoundsIdStr.split(","))
                    .map(Integer::parseInt)
                    .collect(Collectors.toSet());
            if (!existingRoundIds.isEmpty()) {
                // 首先，删除相关的奖项
                for (Integer roundId : existingRoundIds) {
                    VoteEventEvaluationRounds round = voteEventEvaluationRoundsMapper.selectById(roundId);
                    if (round != null && round.getAwards() != null && !round.getAwards().isEmpty()) {
                        Set<Integer> existingAwardIds = Arrays.stream(round.getAwards().split(","))
                                .map(Integer::parseInt)
                                .collect(Collectors.toSet());
                        if (!existingAwardIds.isEmpty()) {
                            voteEventAwardsMapper.deleteBatchIds(existingAwardIds);
                        }
                    }
                }
                // 删除评选轮次记录
                voteEventEvaluationRoundsMapper.deleteBatchIds(existingRoundIds);
            }
        }
    }

    /**
     * 物理删除
     *
     * @param id
     * @return
     */
    @Override
    @Transactional
    public int deleteWorkSettings(Long id) {
        VoteEventWorkSettings eventWorkSettings = voteEventWorkSettingsMapper.selectById(id);
        if (eventWorkSettings == null) {
            throw new RuntimeException("暂无作品设置数据");
        }
        this.extracted(eventWorkSettings.getRoundsId());
        return voteEventWorkSettingsMapper.deleteById(id);
    }

    /**
     * 根据id查询活动类型别称
     *
     * @param id
     * @return
     */
    @Override
    public Map<Long, String> getWorkSettingsList(Long id) {
        LambdaQueryWrapper<VoteEventWorkSettings> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(VoteEventWorkSettings::getEventId, id);
        Map<Long, String> map = new HashMap<>();
        List<VoteEventWorkSettings> settings = voteEventWorkSettingsMapper.selectList(wrapper);
        if (settings == null || settings.isEmpty()) {
            return Collections.emptyMap();
        }
        settings.forEach(setting -> {
            map.put(setting.getId(), setting.getAlias());
        });
        return map;
    }


    // 获取评选轮数及规则、专家名
    private List<VoteEventEvaluationRounds> getVoteEventEvaluationRounds(Long eventId) {
        return voteEventEvaluationRoundsMapper.selectList(
                new LambdaQueryWrapper<VoteEventEvaluationRounds>().eq(VoteEventEvaluationRounds::getEventId, eventId)
        );
    }


    // 设置评选轮数的详细信息
    private void setEvaluationRoundsDetails(List<VoteEventEvaluationRounds> rounds, VoteEventWorkSettings workSettings) {
        if (workSettings == null || rounds == null || rounds.isEmpty()) {
            return; // 如果输入参数无效，直接返回
        }

        Set<Long> roundsId = Optional.ofNullable(workSettings.getRoundsId())
                .map(ids -> Arrays.stream(ids.split(","))
                        .filter(id -> !id.trim().isEmpty()) // 过滤掉空字符串
                        .map(Long::parseLong)
                        .collect(Collectors.toSet()))
                .orElse(Collections.emptySet());

        if (roundsId.isEmpty()) {
            return; // 如果没有有效的轮次ID，直接返回
        }

        Map<String, String> stringMap = getJudges();

        // 过滤出需要的评选轮数
        List<VoteEventEvaluationRounds> filteredRounds = rounds.stream()
                .filter(round -> roundsId.contains(round.getId()))
                .collect(Collectors.toList());

        if (filteredRounds.isEmpty()) {
            return; // 如果过滤后的轮次为空，直接返回
        }

        // 批量查询所有评奖对象
        List<VoteEventAwards> allEventAwards = voteEventAwardsMapper.selectList(new LambdaQueryWrapper<>());

        // 批量查询所有评分规则名称
        Map<Long, String> ruleNamesMap = getRuleNamesMap(filteredRounds);

        // 设置详细信息
        filteredRounds.forEach(round -> {
            if ("award".equals(round.getType()) && round.getAwards() != null) {
                Set<Long> awardIds = Optional.of(round.getAwards())
                        .map(ids -> Arrays.stream(ids.split(","))
                                .filter(id -> !id.trim().isEmpty()) // 过滤掉空字符串
                                .map(Long::parseLong)
                                .collect(Collectors.toSet()))
                        .orElse(Collections.emptySet());
                // 过滤出该轮次相关的评奖对象
                List<VoteEventAwards> eventAwardsList = allEventAwards.stream()
                        .filter(award -> awardIds.contains(award.getId()))
                        .collect(Collectors.toList());
                round.setVoteEventAwardsList(eventAwardsList);
            }

            // 设置基础信息
            round.setRuleName(ruleNamesMap.get(round.getScoringRuleId()));

            // 查询评审专家姓名
            String judgesNames = getJudgesNamesMap(round.getJudges(), stringMap);
            round.setJudgesName(judgesNames);
        });

        // 将处理后的评选轮数列表设置到工作设置中
        workSettings.setVoteEventEvaluationRounds(filteredRounds);
    }

    // 批量查询所有评分规则名称
    private Map<Long, String> getRuleNamesMap(List<VoteEventEvaluationRounds> rounds) {
        Set<Long> ruleIds = rounds.stream()
                .map(VoteEventEvaluationRounds::getScoringRuleId)
                .collect(Collectors.toSet());
        if (ruleIds.isEmpty()) {
            return Collections.emptyMap();
        }
        List<VoteRule> scoringRules = voteRuleMapper.selectBatchIds(ruleIds);
        return scoringRules.stream()
                .collect(Collectors.toMap(VoteRule::getRuleId, VoteRule::getName));
    }

    // 批量查询所有评审专家姓名
    private String getJudgesNamesMap(String judgesId, Map<String, String> stringMap) {
        if (judgesId.isEmpty()){
            return "暂未分配专家";
        }
        Set<String> judgesIdSet = Arrays.stream(judgesId.split(","))
                .collect(Collectors.toSet());

        return stringMap.entrySet().stream()
                .filter(entry -> judgesIdSet.contains(entry.getKey()))
                .map(Map.Entry::getValue)
                .collect(Collectors.joining(","));
    }
}




