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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.tool.api.R;
import org.springblade.modules.martial.pojo.dto.MiniScoreSubmitDTO;
import org.springblade.modules.martial.pojo.entity.MartialAthlete;
import org.springblade.modules.martial.pojo.entity.MartialJudge;
import org.springblade.modules.martial.pojo.entity.MartialScore;
import org.springblade.modules.martial.service.IMartialAthleteService;
import org.springblade.modules.martial.service.IMartialJudgeService;
import org.springblade.modules.martial.service.IMartialScoreService;
import org.springblade.modules.martial.service.IMiniScoringService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class MiniScoringServiceImpl implements IMiniScoringService {

    private final IMartialScoreService scoreService;
    private final IMartialJudgeService judgeService;
    private final IMartialAthleteService athleteService;

    @Override
    public R<String> submitScore(MiniScoreSubmitDTO dto) {
        MartialScore score = new MartialScore();
        
        score.setAthleteId(parseLong(dto.getAthleteId()));
        score.setJudgeId(parseLong(dto.getJudgeId()));
        score.setScore(dto.getScore());
        score.setProjectId(parseLong(dto.getProjectId()));
        score.setCompetitionId(parseLong(dto.getCompetitionId()));
        score.setVenueId(parseLong(dto.getVenueId()));
        score.setScheduleId(parseLong(dto.getScheduleId()));
        score.setNote(dto.getNote());
        score.setScoreTime(LocalDateTime.now());

        if (dto.getDeductions() != null && !dto.getDeductions().isEmpty()) {
            List<Long> deductionIds = dto.getDeductions().stream()
                .map(this::parseLong)
                .filter(id -> id != null)
                .collect(Collectors.toList());
            score.setDeductionItems(com.alibaba.fastjson.JSON.toJSONString(deductionIds));
        }

        Long judgeId = parseLong(dto.getJudgeId());
        if (judgeId != null) {
            MartialJudge judge = judgeService.getById(judgeId);
            if (judge != null) {
                score.setJudgeName(judge.getName());
            }
        }

        boolean success = scoreService.save(score);
        
        if (success) {
            Long athleteId = parseLong(dto.getAthleteId());
            Long projectId = parseLong(dto.getProjectId());
            Long venueId = parseLong(dto.getVenueId());
            if (athleteId != null && projectId != null) {
                updateAthleteTotalScore(athleteId, projectId, venueId);
            }
        }
        
        return success ? R.success("评分提交成功") : R.fail("评分提交失败");
    }

    private void updateAthleteTotalScore(Long athleteId, Long projectId, Long venueId) {
        // TODO: Implement score calculation logic
        // This will be extracted to a separate service in later refactoring
    }

    private Long parseLong(String str) {
        if (str == null || str.trim().isEmpty()) {
            return null;
        }
        try {
            return Long.parseLong(str);
        } catch (NumberFormatException e) {
            log.warn("Failed to parse long: {}", str);
            return null;
        }
    }
}
