package org.dromara.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.redis.utils.RedisUtils;
import org.dromara.system.domain.GameAthlete;
import org.dromara.system.domain.GameEvent;
import org.dromara.system.domain.bo.GameEventBo;
import org.dromara.system.domain.constant.GameEventConstant;
import org.dromara.system.domain.vo.GameEventVo;
import org.dromara.system.domain.vo.SysDictDataVo;
import org.dromara.system.mapper.GameEventMapper;
import org.dromara.system.service.IGameEventService;
import org.dromara.system.service.ISysDictTypeService;
import org.springframework.stereotype.Service;
import org.dromara.system.domain.bo.GameEventProjectBo;
import org.dromara.system.domain.vo.GameEventProjectVo;
import org.dromara.system.domain.GameEventProject;
import org.dromara.system.mapper.GameEventProjectMapper;
import org.dromara.system.service.IGameEventProjectService;

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

/**
 * 赛事项目Service业务层处理
 *
 * @author zlt
 * @date 2025-07-30
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class GameEventProjectServiceImpl implements IGameEventProjectService {

    private final GameEventProjectMapper baseMapper;
    private final GameEventMapper gameEventMapper;
    private final ISysDictTypeService sysDictTypeService;

    /**
     * 查询赛事项目
     *
     * @param projectId 主键
     * @return 赛事项目
     */
    @Override
    public GameEventProjectVo queryById(Long projectId) {
        GameEventProjectVo vo = baseMapper.selectVoById(projectId);
        vo.setRefereeGroups(JSONUtil.toList(vo.getRefereeGroup(), String.class));
        return vo;
    }

    /**
     * 分页查询赛事项目列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 赛事项目分页列表
     */
    @Override
    public TableDataInfo<GameEventProjectVo> queryPageList(GameEventProjectBo bo, PageQuery pageQuery) {
        if (bo.getEventId() == null) {
            Object cacheObject = RedisUtils.getCacheObject(GameEventConstant.DEFAULT_EVENT_ID);
            if (cacheObject instanceof Integer) {
                bo.setEventId(((Integer) cacheObject).longValue());  // 显式转换为 Long 类型
            } else if (cacheObject instanceof Long) {
                bo.setEventId((Long) cacheObject);
            }
        }
        LambdaQueryWrapper<GameEventProject> lqw = buildQueryWrapper(bo);
        Page<GameEventProjectVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);

        // 使用 forEach 直接修改原对象
        result.getRecords()
            .forEach(vo -> {
            Optional.ofNullable(vo.getEventId())
                .filter(ObjectUtil::isNotEmpty)
                .ifPresent(eventId -> {
                    GameEvent gameEvent = gameEventMapper.selectById(eventId);
                    if (gameEvent != null) {
                        vo.setEventName(gameEvent.getEventName());
                    }
                });

            Optional.ofNullable(vo.getRefereeGroup())
                .filter(ObjectUtil::isNotEmpty)
                .ifPresent(refereeIdStr -> {
                    List<String> refereeList = JSONUtil.toList(refereeIdStr.toString(), String.class);
                    vo.setRefereeGroups(refereeList);
                });
        });

        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的赛事项目列表
     *
     * @param bo 查询条件
     * @return 赛事项目列表
     */
    @Override
    public List<GameEventProjectVo> queryList(GameEventProjectBo bo) {
        if (bo.getEventId() == null) {
            Object cacheObject = RedisUtils.getCacheObject(GameEventConstant.DEFAULT_EVENT_ID);
            if (cacheObject instanceof Integer) {
                bo.setEventId(((Integer) cacheObject).longValue());  // 显式转换为 Long 类型
            } else if (cacheObject instanceof Long) {
                bo.setEventId((Long) cacheObject);
            }
        }
        LambdaQueryWrapper<GameEventProject> lqw = buildQueryWrapper(bo);
        List<GameEventProjectVo> list = baseMapper.selectVoList(lqw);
        list.forEach(vo -> {
            Optional.ofNullable(vo.getEventId())
                .filter(ObjectUtil::isNotEmpty)
                .ifPresent(eventId -> {
                    GameEvent gameEvent = gameEventMapper.selectById(eventId);
                    if (gameEvent != null) {
                        vo.setEventName(gameEvent.getEventName());
                    }
                });

            Optional.ofNullable(vo.getRefereeGroup())
                .filter(ObjectUtil::isNotEmpty)
                .ifPresent(refereeIdStr -> {
                    List<String> refereeList = JSONUtil.toList(refereeIdStr.toString(), String.class);
                    vo.setRefereeGroups(refereeList);
                });
        });
        return list;
    }

    private LambdaQueryWrapper<GameEventProject> buildQueryWrapper(GameEventProjectBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<GameEventProject> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(GameEventProject::getProjectId);
        lqw.eq(bo.getEventId() != null, GameEventProject::getEventId, bo.getEventId());
        // 通过名称模糊查询
        Optional.ofNullable(bo.getEventName())
            .ifPresent(eventName->{
                List<GameEvent> gameEvents = gameEventMapper.selectList(
                    Wrappers.lambdaQuery(GameEvent.class)
                        .like(GameEvent::getEventName, bo.getEventName())
                        .select(GameEvent::getEventId)
                );
                if(CollectionUtils.isNotEmpty(gameEvents)){
                    List<Long> ids = gameEvents.stream()
                        .map(GameEvent::getEventId)
                        .collect(Collectors.toList());
                    lqw.in(GameEventProject::getEventId, ids);
                }else{
                    lqw.apply("1=0");
                }
            });
        lqw.like(StringUtils.isNotBlank(bo.getProjectName()), GameEventProject::getProjectName, bo.getProjectName());
        lqw.eq(StringUtils.isNotBlank(bo.getProjectType()), GameEventProject::getProjectType, bo.getProjectType());
        lqw.eq(StringUtils.isNotBlank(bo.getGroupType()), GameEventProject::getGroupType, bo.getGroupType());
        lqw.eq(bo.getStartTime() != null, GameEventProject::getStartTime, bo.getStartTime());
        lqw.eq(StringUtils.isNotBlank(bo.getOrderType()), GameEventProject::getOrderType, bo.getOrderType());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), GameEventProject::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增赛事项目
     *
     * @param bo 赛事项目
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(GameEventProjectBo bo) {
        if (bo.getEventId() == null) {
            Object cacheObject = RedisUtils.getCacheObject(GameEventConstant.DEFAULT_EVENT_ID);
            if (cacheObject instanceof Integer) {
                bo.setEventId(((Integer) cacheObject).longValue());  // 显式转换为 Long 类型
            } else if (cacheObject instanceof Long) {
                bo.setEventId((Long) cacheObject);
            }
        }
        GameEventProject add = MapstructUtils.convert(bo, GameEventProject.class);
        validEntityBeforeSave(add);
        if (CollectionUtils.isNotEmpty(bo.getRefereeGroups())) {
            add.setRefereeGroup(JSONUtil.toJsonStr(bo.getRefereeGroups()));
        }
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setProjectId(add.getProjectId());
        }
        return flag;
    }

    /**
     * 修改赛事项目
     *
     * @param bo 赛事项目
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(GameEventProjectBo bo) {
        if (bo.getEventId() == null) {
            Object cacheObject = RedisUtils.getCacheObject(GameEventConstant.DEFAULT_EVENT_ID);
            if (cacheObject instanceof Integer) {
                bo.setEventId(((Integer) cacheObject).longValue());  // 显式转换为 Long 类型
            } else if (cacheObject instanceof Long) {
                bo.setEventId((Long) cacheObject);
            }
        }
        GameEventProject update = MapstructUtils.convert(bo, GameEventProject.class);
        if (CollectionUtils.isNotEmpty(bo.getRefereeGroups())) {
            update.setRefereeGroup(JSONUtil.toJsonStr(bo.getRefereeGroups()));
        }
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(GameEventProject entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除赛事项目信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public List<GameEventProjectVo> listProjectsByEventIdAndProjectIndex(Long eventId, String[] projectIds) {
        return this.baseMapper.selectVoList(
            new LambdaQueryWrapper<GameEventProject>()
                .eq(GameEventProject::getEventId, eventId)
                .in(GameEventProject::getProjectId, projectIds)
        );
    }

    @Override
    public Long countEventProject() {
        return this.baseMapper.selectCount(
            Wrappers.lambdaQuery(GameEventProject.class)
        );
    }


    /**
     * 获取excel动态表头
     *
     * @return
     */
    @Override
    public Map<String, List<String>> mapProjectTypeAndProject(Long eventId) {
        // Object cacheId = RedisUtils.getCacheObject(GameEventConstant.DEFAULT_EVENT_ID);
        // Long defaultEventId = Long.valueOf(cacheId.toString());
        List<GameEventProject> list = baseMapper.selectList(
            Wrappers.lambdaQuery(GameEventProject.class)
                .eq(GameEventProject::getEventId, eventId)
                .select(GameEventProject::getProjectType, GameEventProject::getProjectName)
        );

        // 从字典中获取项目类型映射：projectType (dictValue) -> dictLabel
        List<SysDictDataVo> projectTypeDictList = sysDictTypeService.selectDictDataByType("game_project_type");

        // 构建 dictValue -> dictLabel 的映射，便于快速查找
        Map<String, String> dictMap = projectTypeDictList.stream()
            .collect(Collectors.toMap(SysDictDataVo::getDictValue, SysDictDataVo::getDictLabel));

        // 遍历项目列表，将每个项目的 projectType 转换为对应的中文 label，并以 projectName 为 key 构建结果 map
        Map<String, List<String>> result = new HashMap<>();
        for (GameEventProject project : list) {
            String projectType = project.getProjectType();
            String projectName = project.getProjectName();
            String label = dictMap.getOrDefault(projectType, projectType); // 如果字典中没有，使用原值
            // 将项目名添加到对应类型的列表中
            result.computeIfAbsent(label, k -> new ArrayList<String>()).add(projectName);
        }

        return result;
    }
}
