package com.aegis.resource.team.service.impl;

import com.aegis.common.exception.ServiceException;
import com.aegis.common.utils.SecurityUtils;
import com.aegis.common.utils.StringUtils;
import com.aegis.resource.team.constant.TeamMemberStatus;
import com.aegis.resource.team.domain.Team;
import com.aegis.resource.team.domain.TeamMember;
import com.aegis.resource.team.mapper.ResourceTeamMapper;
import com.aegis.resource.team.mapper.ResourceTeamMemberMapper;
import com.aegis.resource.team.service.IResourceTeamMemberService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 队伍成员Service业务层处理
 *
 * <p>对齐MyBatis-Plus风格，复用通用CRUD，并在必要位置添加业务校验。</p>
 *
 * @author aegis
 */
@Service
public class ResourceTeamMemberServiceImpl extends ServiceImpl<ResourceTeamMemberMapper, TeamMember>
        implements IResourceTeamMemberService {

    private final ResourceTeamMapper teamMapper;

    public ResourceTeamMemberServiceImpl(ResourceTeamMapper teamMapper) {
        this.teamMapper = teamMapper;
    }

    @Override
    public List<TeamMember> listByCondition(TeamMember condition) {
        LambdaQueryWrapper<TeamMember> wrapper = buildConditionWrapper(condition);
        wrapper.orderByDesc(TeamMember::getCreateTime);
        return list(wrapper);
    }

    @Override
    public List<TeamMember> listByTeamId(Long teamId) {
        return list(new LambdaQueryWrapper<TeamMember>().eq(TeamMember::getTeamId, teamId));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean save(TeamMember entity) {
        validateTeamExists(entity.getTeamId());
        if (StringUtils.isEmpty(entity.getStatus())) {
            entity.setStatus(TeamMemberStatus.ACTIVE);
        }
        String operator = SecurityUtils.getUsername();
        Date now = new Date();
        entity.setCreateBy(operator);
        entity.setCreateTime(now);
        entity.setUpdateBy(operator);
        entity.setUpdateTime(now);
        return super.save(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateById(TeamMember entity) {
        if (entity.getId() == null) {
            throw new ServiceException("成员ID不能为空");
        }
        TeamMember existing = super.getById(entity.getId());
        if (existing == null) {
            throw new ServiceException("成员不存在或已删除");
        }
        Long targetTeamId = entity.getTeamId() != null ? entity.getTeamId() : existing.getTeamId();
        validateTeamExists(targetTeamId);
        entity.setTeamId(targetTeamId);
        entity.setUpdateBy(SecurityUtils.getUsername());
        entity.setUpdateTime(new Date());
        return super.updateById(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeById(Serializable id) {
        return super.removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeByIds(Collection<?> idList) {
        return super.removeByIds(idList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeByTeamId(Long teamId) {
        if (teamId == null) {
            return false;
        }
        return remove(new LambdaQueryWrapper<TeamMember>().eq(TeamMember::getTeamId, teamId));
    }

    private LambdaQueryWrapper<TeamMember> buildConditionWrapper(TeamMember condition) {
        LambdaQueryWrapper<TeamMember> wrapper = new LambdaQueryWrapper<>();
        if (condition == null) {
            return wrapper;
        }
        wrapper.eq(condition.getTeamId() != null, TeamMember::getTeamId, condition.getTeamId());
        wrapper.eq(condition.getUserId() != null, TeamMember::getUserId, condition.getUserId());
        wrapper.like(StringUtils.isNotBlank(condition.getMemberName()), TeamMember::getMemberName, condition.getMemberName());
        wrapper.like(StringUtils.isNotBlank(condition.getMemberCode()), TeamMember::getMemberCode, condition.getMemberCode());
        wrapper.eq(StringUtils.isNotBlank(condition.getStatus()), TeamMember::getStatus, condition.getStatus());
        wrapper.eq(StringUtils.isNotBlank(condition.getPosition()), TeamMember::getPosition, condition.getPosition());
        wrapper.eq(StringUtils.isNotBlank(condition.getSpecialty()), TeamMember::getSpecialty, condition.getSpecialty());
        return wrapper;
    }

    private void validateTeamExists(Long teamId) {
        if (teamId == null) {
            throw new ServiceException("队伍ID不能为空");
        }
        Team team = teamMapper.selectById(teamId);
        if (team == null) {
            throw new ServiceException("队伍不存在");
        }
    }
}