package com.lesingle.creation.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lesingle.creation.dto.judge.CreateJudgeDTO;
import com.lesingle.creation.dto.judge.UpdateJudgeDTO;
import com.lesingle.creation.entity.Contest;
import com.lesingle.creation.entity.ContestJudge;
import com.lesingle.creation.common.exception.BusinessException;
import com.lesingle.creation.mapper.ContestJudgeMapper;
import com.lesingle.creation.mapper.ContestMapper;
import com.lesingle.creation.service.ContestJudgeService;
import com.lesingle.creation.vo.judge.JudgeVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 竞赛评委服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ContestJudgeServiceImpl implements ContestJudgeService {

    private final ContestJudgeMapper contestJudgeMapper;
    private final ContestMapper contestMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JudgeVO create(CreateJudgeDTO dto, Long creatorId) {
        // 验证活动是否存在
        Contest contest = contestMapper.selectById(dto.getContestId());
        if (contest == null) {
            throw new BusinessException("活动不存在");
        }

        ContestJudge judge = new ContestJudge();
        judge.setContestId(dto.getContestId());
        judge.setTenantId(contest.getTenantId());
        judge.setJudgeName(dto.getJudgeName());
        judge.setTitle(dto.getTitle());
        judge.setOrganization(dto.getOrganization());
        judge.setPhone(dto.getPhone());
        judge.setEmail(dto.getEmail());
        judge.setSpecialty(dto.getSpecialty());
        judge.setWeight(dto.getWeight());
        judge.setStatus("1"); // 1-活跃
        judge.setValidState(1);
        if (creatorId != null) {
            judge.setCreateBy(creatorId.toString());
        }

        contestJudgeMapper.insert(judge);
        log.info("创建评委成功，ID={}", judge.getId());

        return convertToVO(judge);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JudgeVO update(Long id, UpdateJudgeDTO dto) {
        ContestJudge judge = contestJudgeMapper.selectById(id);
        if (judge == null) {
            throw new BusinessException("评委不存在");
        }

        if (dto.getJudgeName() != null) {
            judge.setJudgeName(dto.getJudgeName());
        }
        if (dto.getTitle() != null) {
            judge.setTitle(dto.getTitle());
        }
        if (dto.getOrganization() != null) {
            judge.setOrganization(dto.getOrganization());
        }
        if (dto.getPhone() != null) {
            judge.setPhone(dto.getPhone());
        }
        if (dto.getEmail() != null) {
            judge.setEmail(dto.getEmail());
        }
        if (dto.getSpecialty() != null) {
            judge.setSpecialty(dto.getSpecialty());
        }
        if (dto.getStatus() != null) {
            judge.setStatus(dto.getStatus().toString());
        }

        contestJudgeMapper.updateById(judge);
        log.info("更新评委成功，ID={}", id);

        return convertToVO(judge);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        ContestJudge judge = contestJudgeMapper.selectById(id);
        if (judge == null) {
            throw new BusinessException("评委不存在");
        }

        judge.setDeleted(1);
        contestJudgeMapper.updateById(judge);
        log.info("删除评委成功，ID={}", id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchDelete(List<Long> ids) {
        for (Long id : ids) {
            ContestJudge judge = contestJudgeMapper.selectById(id);
            if (judge != null) {
                judge.setDeleted(1);
                contestJudgeMapper.updateById(judge);
            }
        }
        log.info("批量删除评委成功，删除数量={}", ids.size());
    }

    @Override
    public JudgeVO freeze(Long id) {
        ContestJudge judge = contestJudgeMapper.selectById(id);
        if (judge == null) {
            throw new BusinessException("评委不存在");
        }

        judge.setStatus("2"); // 2-不活跃
        contestJudgeMapper.updateById(judge);
        log.info("冻结评委成功，ID={}", id);

        return convertToVO(judge);
    }

    @Override
    public JudgeVO unfreeze(Long id) {
        ContestJudge judge = contestJudgeMapper.selectById(id);
        if (judge == null) {
            throw new BusinessException("评委不存在");
        }

        judge.setStatus("1"); // 1-活跃
        contestJudgeMapper.updateById(judge);
        log.info("解冻评委成功，ID={}", id);

        return convertToVO(judge);
    }

    @Override
    public JudgeVO getDetail(Long id) {
        ContestJudge judge = contestJudgeMapper.selectById(id);
        if (judge == null) {
            throw new BusinessException("评委不存在");
        }
        return convertToVO(judge);
    }

    @Override
    public List<JudgeVO> listByContest(Long contestId) {
        List<ContestJudge> judges = contestJudgeMapper.selectList(new LambdaQueryWrapper<ContestJudge>()
                .eq(ContestJudge::getContestId, contestId)
                .eq(ContestJudge::getValidState, 1)
                .eq(ContestJudge::getDeleted, 0)
                .orderByDesc(ContestJudge::getCreateTime));

        return judges.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    // ========== 转换方法 ==========

    private JudgeVO convertToVO(ContestJudge judge) {
        JudgeVO vo = new JudgeVO();
        vo.setId(judge.getId());
        vo.setContestId(judge.getContestId());
        vo.setJudgeId(judge.getJudgeId());
        vo.setJudgeName(judge.getJudgeName());
        vo.setTitle(judge.getTitle());
        vo.setOrganization(judge.getOrganization());
        vo.setPhone(judge.getPhone());
        vo.setEmail(judge.getEmail());
        vo.setSpecialty(judge.getSpecialty());
        vo.setStatus(judge.getStatus() != null ? Integer.parseInt(judge.getStatus()) : 1);
        vo.setValidState(judge.getValidState());

        // 获取活动名称
        Contest contest = contestMapper.selectById(judge.getContestId());
        if (contest != null) {
            vo.setContestName(contest.getContestName());
        }

        return vo;
    }
}
