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.domain.R;
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.VoteEventCompetitionZones;
import com.vote.system.domain.VoteEventEvaluationRounds;
import com.vote.system.domain.VoteRegistrations;
import com.vote.system.domain.VoteSubmission;
import com.vote.system.domain.vo.VoteEventCompetitionZonesVo;
import com.vote.system.domain.vo.VoteSubmissionCountVo;
import com.vote.system.mapper.VoteEventEvaluationRoundsMapper;
import com.vote.system.mapper.VoteRegistrationsMapper;
import com.vote.system.mapper.VoteSubmissionMapper;
import com.vote.system.service.VoteEventCompetitionZonesService;
import com.vote.system.mapper.VoteEventCompetitionZonesMapper;
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;

import static com.vote.system.util.ConstantUtils.IS_DELETED_0;
import static com.vote.system.util.ConstantUtils.IS_DELETED_1;

/**
 * @author MacBook
 * @description 针对表【vote_event_competition_zones(活动赛区表)】的数据库操作Service实现
 * @createDate 2024-08-21 14:21:04
 */
@Service
public class VoteEventCompetitionZonesServiceImpl extends ServiceImpl<VoteEventCompetitionZonesMapper, VoteEventCompetitionZones>
        implements VoteEventCompetitionZonesService {

    @Autowired
    private VoteSubmissionMapper voteSubmissionMapper;

    @Autowired
    private VoteEventCompetitionZonesMapper voteEventCompetitionZonesMapper;

    @Autowired
    private VoteEventEvaluationRoundsMapper voteEventEvaluationRoundsMapper;

    @Autowired
    private VoteRegistrationsMapper voteRegistrationsMapper;

    @Autowired
    private RemoteBranchKindergartenService remoteBranchKindergartenService;//园区服务

    @Autowired
    private RemoteSysProvinceService remoteSysProvinceService;//省份服务

    @Autowired
    private RemotePlatformUserService remotePlatformUserService;//远程调用专家列表


    /**
     * 获取各省份下的作品数量
     *
     * @param voteSubmission
     * @return
     */
    @Override
    public List<VoteSubmissionCountVo> getSubmissionCount(VoteSubmission voteSubmission) {
        // 查询所有符合条件的作品
        LambdaQueryWrapper<VoteSubmission> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(VoteSubmission::getEventId, voteSubmission.getEventId())
                .eq(VoteSubmission::getWorkSettingsId, voteSubmission.getWorkSettingsId());
        List<VoteSubmission> submissions = voteSubmissionMapper.selectList(wrapper); // 所有作品

        // 获取所有省份
        List<SysProvince> provinces = remoteSysProvinceService.getProvince().getData();

        // 创建结果列表
        List<VoteSubmissionCountVo> result = new ArrayList<>();

        // 遍历每个省份，统计作品数量
        for (SysProvince province : provinces) {
            // 获取当前省份下的所有园区
            List<SysBranchKindergartenDto> kindergartens = remoteBranchKindergartenService
                    .get(province.getProvinceId(), null, null).getData();

            // 如果没有园区，则跳过
            if (kindergartens == null || kindergartens.isEmpty()) {
                continue;
            }

            // 获取当前省份下所有园区的ID列表
            Set<Long> kindergartenIds = kindergartens.stream()
                    .map(SysBranchKindergartenDto::getId)
                    .collect(Collectors.toSet());

            // 计算当前省份下的作品数量
            long submissionCount = submissions.stream()
                    .filter(submission -> kindergartenIds.contains(submission.getLocationId()))
                    .count();

            // 如果当前省份有作品，则添加到结果列表中
            if (submissionCount > 0) {
                VoteSubmissionCountVo countVo = new VoteSubmissionCountVo();
                countVo.setProvince(province.getProvince());
                countVo.setCount(submissionCount);
                result.add(countVo);
            }
        }

        return result;
    }

    /**
     * 删除赛区
     *
     * @param id
     * @return
     */
    @Override
    @Transactional
    public int deleteZones(Long id) {
        VoteEventCompetitionZones zones = new VoteEventCompetitionZones();
        zones.setId(id);
        zones.setIsDeleted(IS_DELETED_1);
        return voteEventCompetitionZonesMapper.updateById(zones);
    }


    /**
     * 分页查询 赛区列表
     *
     * @param voteEventCompetitionZones
     * @return
     */
    @Override
    public IPage<VoteEventCompetitionZonesVo> selectByPage(VoteEventCompetitionZones voteEventCompetitionZones) {
        // 分页参数
        long pageNum = Convert.toLong(ServletUtils.getParameterToInt(MybatisPageConstants.PAGE_NUM), 1L);
        long pageSize = Convert.toLong(ServletUtils.getParameterToInt(MybatisPageConstants.PAGE_SIZE), 10L);
        Page<VoteEventCompetitionZonesVo> page = new Page<>(pageNum, pageSize);
        // 参数校验
        if (voteEventCompetitionZones.getEventId() == null) {
            throw new RuntimeException("活动id不能为空！");
        }
        if (voteEventCompetitionZones.getWorkSettingsId() == null) {
            throw new RuntimeException("类型别称id不能为空！");
        }
        // 构建查询条件
        LambdaQueryWrapper<VoteEventCompetitionZones> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(VoteEventCompetitionZones::getEventId, voteEventCompetitionZones.getEventId());
        wrapper.eq(VoteEventCompetitionZones::getWorkSettingsId, voteEventCompetitionZones.getWorkSettingsId());
        wrapper.eq(VoteEventCompetitionZones::getIsDeleted, IS_DELETED_0);
        wrapper.orderByDesc(VoteEventCompetitionZones::getCreatedAt);
        List<VoteEventCompetitionZones> competitionZones = voteEventCompetitionZonesMapper.selectList(wrapper);
        // 获取所有省份信息，并将其放入 Map 中
        List<SysProvince> provinceList = remoteSysProvinceService.getProvince().getData();
        Map<String, String> provinceMap = provinceList.stream()
                .collect(Collectors.toMap(SysProvince::getProvinceId, SysProvince::getProvince));
        // 获取专家信息映射
        Map<String, String> stringMap = this.getJudges();
        // 处理查询结果并映射到 VO 对象
        List<VoteEventCompetitionZonesVo> zonesVoList = competitionZones.stream().map(item -> {
            VoteEventCompetitionZonesVo zonesVo = new VoteEventCompetitionZonesVo();
            zonesVo.setId(item.getId())
                    .setName(item.getName());

            // 配置专家
            if (item.getJudges() != null) {
                zonesVo.setJudges(getJudgesNamesMap(item.getJudges(), stringMap));
            } else {
                zonesVo.setJudges("暂未添加专家名单");
            }

            // 处理省份 ID，获取省份名称并拼接
            StringBuilder provincesBuilder = new StringBuilder();
            String[] provinceIds = item.getProvinces().split(",");
            for (String provinceId : provinceIds) {
                String provinceName = provinceMap.get(provinceId);
                if (provinceName != null) {
                    provincesBuilder.append(provinceName).append(",");
                }
            }

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

            zonesVo.setProvinces(provincesBuilder.toString());

            // 计算作品数和提交人数
            Long submissionCount = getCount(item.getProvinces(), voteEventCompetitionZones.getEventId(), voteEventCompetitionZones.getWorkSettingsId(), true);
            Long registrationsCount = getCount(item.getProvinces(), voteEventCompetitionZones.getEventId(), voteEventCompetitionZones.getWorkSettingsId(), false);
            zonesVo.setJudgesId(item.getJudges());
            zonesVo.setProvincesId(item.getProvinces());
            zonesVo.setSubmissionCount(submissionCount);
            zonesVo.setRegistrationsCount(registrationsCount);

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

        // 将结果封装到分页对象中
        Page<VoteEventCompetitionZonesVo> resultPage = new Page<>(pageNum, pageSize);
        resultPage.setRecords(zonesVoList);
        resultPage.setTotal(competitionZones.size());

        return resultPage;
    }

    @Override
    @Transactional
    public int addZones(VoteEventCompetitionZones voteEventCompetitionZones) {
        if (voteEventCompetitionZones.getProvinces() == null) {
            throw new RuntimeException("未添加省份，不可创建赛区");
        }
        return voteEventCompetitionZonesMapper.insert(voteEventCompetitionZones);

    }

    /**
     * 回显专家
     *
     * @param voteEventCompetitionZones
     * @return
     */
    @Override
    public List<Map<String, String>> showJudges(VoteEventCompetitionZones voteEventCompetitionZones) {
        VoteEventEvaluationRounds rounds = voteEventEvaluationRoundsMapper.selectById(voteEventCompetitionZones.getRoundId());
        Map<String, String> judges = getJudges();
        String[] split = rounds.getJudges().split(",");
        // 用于存放匹配的专家信息
        List<Map<String, String>> result = new ArrayList<>(); // 遍历split数组中的每个专家ID
        for (String judgeId : split) {
            if (judges.containsKey(judgeId)) {
                // 如果所有专家信息中包含这个ID的专家，封装成Map并加入结果列表
                Map<String, String> judgeInfo = new HashMap<>();
                judgeInfo.put(judgeId, judges.get(judgeId));
                result.add(judgeInfo);
            }
        } // 返回封装好的专家信息列表 return result;
        return result;
    }


    //远程获取专家
    private 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;
    }


    // 批量查询所有评审专家姓名
    private String getJudgesNamesMap(String judgesId, Map<String, String> stringMap) {
        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(","));
    }


    /**
     * 计算注册人数或作品数
     *
     * @param provinces      省份字符串
     * @param eventId        事件 ID
     * @param workSettingsId 工作设置 ID
     * @param isSubmission   是否计算作品数，true 为作品数，false 为注册人数
     * @return 计算结果
     */
    private Long getCount(String provinces, Long eventId, Long workSettingsId, boolean isSubmission) {
        // 选择对应的 Mapper 和对象类型
        LambdaQueryWrapper<?> wrapper;
        List<?> items;
        if (isSubmission) {
            wrapper = new LambdaQueryWrapper<VoteSubmission>()
                    .eq(VoteSubmission::getEventId, eventId)
                    .eq(VoteSubmission::getWorkSettingsId, workSettingsId);
            items = voteSubmissionMapper.selectList((LambdaQueryWrapper<VoteSubmission>) wrapper);
        } else {
            wrapper = new LambdaQueryWrapper<VoteRegistrations>()
                    .eq(VoteRegistrations::getEventId, eventId)
                    .eq(VoteRegistrations::getWorkSettingsId, workSettingsId);
            items = voteRegistrationsMapper.selectList((LambdaQueryWrapper<VoteRegistrations>) wrapper);
        }

        // 存储所有园区 ID 的 Set
        Set<Long> allKindergartenIds = new HashSet<>();

        // 省份字符串
        String[] split = provinces.split(",");
        for (String provinceId : split) {
            // 获取当前省份下的所有园区
            List<SysBranchKindergartenDto> kindergartens = remoteBranchKindergartenService
                    .get(provinceId, null, null).getData();
            // 如果没有园区，则跳过
            if (kindergartens != null && !kindergartens.isEmpty()) {
                // 添加当前省份下所有园区的 ID 到 Set 中
                allKindergartenIds.addAll(kindergartens.stream()
                        .map(SysBranchKindergartenDto::getId)
                        .collect(Collectors.toSet()));
            }
        }

        // 计算符合条件的数量
        return items.stream()
                .filter(item -> allKindergartenIds.contains(getLocationId(item)))
                .count();
    }

    /**
     * 获取对象的园区 ID
     *
     * @param item 对象
     * @return 园区 ID
     */
    private Long getLocationId(Object item) {
        if (item instanceof VoteSubmission) {
            return ((VoteSubmission) item).getLocationId();
        } else if (item instanceof VoteRegistrations) {
            return ((VoteRegistrations) item).getLocationId();
        }
        throw new IllegalArgumentException("Unsupported item type: " + item.getClass().getName());
    }


}




