package org.springblade.modules.martial.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.modules.martial.excel.ScheduleExportExcel;
import org.springblade.modules.martial.excel.ScheduleExportExcel2;
import org.springblade.modules.martial.mapper.MartialScheduleGroupMapper;
import org.springblade.modules.martial.pojo.entity.MartialProject;
import org.springblade.modules.martial.pojo.vo.ScheduleGroupDetailVO;
import org.springblade.modules.martial.service.IMartialProjectService;
import org.springblade.modules.martial.service.IScheduleExportService;
import org.springframework.stereotype.Service;

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

@Slf4j
@Service
@RequiredArgsConstructor
public class ScheduleExportServiceImpl implements IScheduleExportService {

    private final MartialScheduleGroupMapper scheduleGroupMapper;
    private final IMartialProjectService projectService;

    @Override
    public List<ScheduleExportExcel> exportSchedule(Long competitionId) {
        List<ScheduleExportExcel> exportList = new ArrayList<>();

        List<ScheduleGroupDetailVO> details = scheduleGroupMapper.selectScheduleGroupDetails(competitionId);

        if (details.isEmpty()) {
            return exportList;
        }

        Map<Long, List<ScheduleGroupDetailVO>> groupMap = details.stream()
            .collect(Collectors.groupingBy(ScheduleGroupDetailVO::getGroupId));

        List<Long> sortedGroupIds = details.stream()
            .collect(Collectors.toMap(
                ScheduleGroupDetailVO::getGroupId,
                d -> d.getDisplayOrder() != null ? d.getDisplayOrder() : 999,
                (a, b) -> a
            ))
            .entrySet().stream()
            .sorted(Map.Entry.comparingByValue())
            .map(Map.Entry::getKey)
            .collect(Collectors.toList());

        for (Long groupId : sortedGroupIds) {
            List<ScheduleGroupDetailVO> groupDetails = groupMap.get(groupId);
            if (groupDetails == null || groupDetails.isEmpty()) {
                continue;
            }

            ScheduleGroupDetailVO firstDetail = groupDetails.get(0);

            List<ScheduleGroupDetailVO> participants = groupDetails.stream()
                .filter(d -> d.getParticipantId() != null)
                .sorted(Comparator.comparing(d -> d.getPerformanceOrder() != null ? d.getPerformanceOrder() : 999))
                .collect(Collectors.toList());

            if (participants.isEmpty()) {
                ScheduleExportExcel excel = new ScheduleExportExcel();
                excel.setScheduleDate(firstDetail.getScheduleDate() != null ? firstDetail.getScheduleDate() : "");
                excel.setTimeSlot(firstDetail.getTimeSlot());
                excel.setVenueName(firstDetail.getVenueName());
                excel.setProjectName(firstDetail.getGroupName());
                excel.setCategory(firstDetail.getCategory());
                excel.setStatus("completed".equals(firstDetail.getScheduleStatus()) ? "已完成" : "草稿");
                exportList.add(excel);
            } else {
                for (ScheduleGroupDetailVO detail : participants) {
                    ScheduleExportExcel excel = new ScheduleExportExcel();
                    excel.setScheduleDate(detail.getScheduleDate() != null ? detail.getScheduleDate() : "");
                    excel.setTimeSlot(detail.getTimeSlot());
                    excel.setVenueName(detail.getVenueName());
                    excel.setProjectName(detail.getGroupName());
                    excel.setCategory(detail.getCategory());
                    excel.setAthleteName(detail.getPlayerName());
                    excel.setTeamName(detail.getOrganization());
                    excel.setSortOrder(detail.getPerformanceOrder());
                    excel.setStatus(detail.getCheckInStatus() != null ? detail.getCheckInStatus() : "未签到");
                    exportList.add(excel);
                }
            }
        }

        return exportList;
    }

    @Override
    public List<ScheduleExportExcel2> exportScheduleTemplate2(Long competitionId, Long venueId) {
        List<ScheduleExportExcel2> exportList = new ArrayList<>();
        List<ScheduleGroupDetailVO> details = scheduleGroupMapper.selectScheduleGroupDetails(competitionId);
        
        if (details.isEmpty()) {
            return exportList;
        }
        
        if (venueId != null) {
            details = details.stream().filter(d -> venueId.equals(d.getVenueId())).collect(Collectors.toList());
        }
        
        Map<Long, List<ScheduleGroupDetailVO>> groupMap = details.stream()
            .collect(Collectors.groupingBy(ScheduleGroupDetailVO::getGroupId));
        
        List<Long> sortedGroupIds = details.stream()
            .collect(Collectors.toMap(
                ScheduleGroupDetailVO::getGroupId, 
                d -> d.getDisplayOrder() != null ? d.getDisplayOrder() : 999, 
                (a, b) -> a))
            .entrySet().stream()
            .sorted(Map.Entry.comparingByValue())
            .map(Map.Entry::getKey)
            .collect(Collectors.toList());
        
        int sequenceNo = 1;
        int tableNoBase = 1101;
        
        for (Long groupId : sortedGroupIds) {
            List<ScheduleGroupDetailVO> groupDetails = groupMap.get(groupId);
            if (groupDetails == null || groupDetails.isEmpty()) continue;
            
            ScheduleGroupDetailVO firstDetail = groupDetails.get(0);
            long participantCount = groupDetails.stream().filter(d -> d.getParticipantId() != null).count();
            int durationMinutes = (int) (participantCount * 4);
            
            ScheduleExportExcel2 excel = new ScheduleExportExcel2();
            excel.setSequenceNo(sequenceNo++);
            excel.setProjectName(firstDetail.getGroupName());
            excel.setParticipantCount((int) participantCount);
            excel.setGroupCount(1);
            excel.setDurationMinutes(durationMinutes);
            excel.setTableNo(String.valueOf(tableNoBase++));
            exportList.add(excel);
        }
        
        return exportList;
    }
}
