package com.aegis.emergency.dispatch.service.impl;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import com.aegis.common.exception.ServiceException;
import com.aegis.common.utils.StringUtils;
import com.aegis.common.utils.SecurityUtils;
import com.aegis.emergency.dispatch.domain.DispatchTaskParticipant;
import com.aegis.emergency.dispatch.mapper.DispatchTaskParticipantMapper;
import com.aegis.emergency.dispatch.service.IDispatchTaskParticipantService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 调度任务参与方 Service 实现
 *
 * @author aegis
 */
@Service
public class DispatchTaskParticipantServiceImpl extends ServiceImpl<DispatchTaskParticipantMapper, DispatchTaskParticipant>
        implements IDispatchTaskParticipantService {

    @Override
    public List<DispatchTaskParticipant> listByTaskId(Long taskId) {
        if (taskId == null) {
            return Collections.emptyList();
        }
        return this.list(new LambdaQueryWrapper<DispatchTaskParticipant>()
            .eq(DispatchTaskParticipant::getTaskId, taskId)
            .eq(DispatchTaskParticipant::getDelFlag, "0"));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addParticipants(Long taskId, List<DispatchTaskParticipant> participants) {
        if (taskId == null) {
            throw new ServiceException("任务ID不能为空");
        }
        if (participants == null || participants.isEmpty()) {
            return;
        }

        // 去除 null 并填充任务ID与默认字段
        List<DispatchTaskParticipant> candidateList = participants.stream()
            .filter(p -> p != null && p.getPersonId() != null)
            .peek(p -> {
                p.setTaskId(taskId);
                if (StringUtils.isEmpty(p.getDelFlag())) {
                    p.setDelFlag("0");
                }
            })
            .collect(Collectors.toList());

        if (candidateList.isEmpty()) {
            return;
        }

        // 检查重复（同一人从同一队伍不可重复添加，但同一人可从不同队伍添加）
        // 检查每个候选参与方是否已存在（考虑 personId 和 teamId 的组合）
        for (DispatchTaskParticipant candidate : candidateList) {
            LambdaQueryWrapper<DispatchTaskParticipant> wrapper = new LambdaQueryWrapper<DispatchTaskParticipant>()
                .eq(DispatchTaskParticipant::getTaskId, taskId)
                .eq(DispatchTaskParticipant::getPersonId, candidate.getPersonId())
                .eq(DispatchTaskParticipant::getDelFlag, "0");
            
            // 如果候选参与方有 teamId，则检查相同 teamId 的记录
            // 如果候选参与方 teamId 为 null，则检查 teamId 也为 null 的记录
            if (candidate.getTeamId() != null) {
                wrapper.eq(DispatchTaskParticipant::getTeamId, candidate.getTeamId());
            } else {
                wrapper.isNull(DispatchTaskParticipant::getTeamId);
            }
            
            long count = this.count(wrapper);
            if (count > 0) {
                String duplicateInfo = candidate.getTeamId() != null 
                    ? String.format("personId=%d, teamId=%d", candidate.getPersonId(), candidate.getTeamId())
                    : String.format("personId=%d (专家)", candidate.getPersonId());
                throw new ServiceException("参与方已存在：" + duplicateInfo);
            }
        }

        String operator = SecurityUtils.getUsername();
        Date now = new Date();
        candidateList.forEach(participant -> {
            participant.setCreateBy(operator);
            participant.setCreateTime(now);
            participant.setUpdateBy(operator);
            participant.setUpdateTime(now);
        });

        this.saveBatch(candidateList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeParticipant(Long taskId, Long participantId) {
        if (taskId == null || participantId == null) {
            throw new ServiceException("任务ID和参与方ID不能为空");
        }
        DispatchTaskParticipant participant = this.getById(participantId);
        if (participant == null || !"0".equals(participant.getDelFlag())) {
            throw new ServiceException("参与方不存在");
        }
        if (!taskId.equals(participant.getTaskId())) {
            throw new ServiceException("参与方不属于该任务");
        }
        participant.setDelFlag("2");

        String operator = SecurityUtils.getUsername();
        participant.setUpdateBy(operator);
        participant.setUpdateTime(new Date());
        return this.updateById(participant);
    }
}