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.domain.Team;
import com.aegis.resource.team.mapper.ResourceTeamMapper;
import com.aegis.resource.team.service.IResourceTeamService;
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 ResourceTeamServiceImpl extends ServiceImpl<ResourceTeamMapper, Team> implements IResourceTeamService {

    private static final String STATUS_AVAILABLE = "available";
    private static final String DEL_FLAG_NORMAL = "0";
    private static final String DEL_FLAG_DELETED = "2";

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean save(Team team) {
        if (team == null) {
            throw new ServiceException("队伍信息不能为空");
        }
        ensureTeamNameUnique(team.getTeamName(), null);
        String operator = SecurityUtils.getUsername();
        Date now = new Date();
        team.setCreateBy(operator);
        team.setCreateTime(now);
        team.setUpdateBy(operator);
        team.setUpdateTime(now);
        team.setStatus(StringUtils.isEmpty(team.getStatus()) ? STATUS_AVAILABLE : team.getStatus());
        team.setDelFlag(DEL_FLAG_NORMAL);
        return super.save(team);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateById(Team team) {
        if (team == null || team.getId() == null) {
            throw new ServiceException("队伍ID不能为空");
        }
        Team existing = super.getById(team.getId());
        if (existing == null || DEL_FLAG_DELETED.equals(existing.getDelFlag())) {
            throw new ServiceException("队伍不存在或已删除");
        }
        ensureTeamNameUnique(team.getTeamName(), team.getId());
        team.setUpdateBy(SecurityUtils.getUsername());
        team.setUpdateTime(new Date());
        return super.updateById(team);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeById(Serializable id) {
        if (id == null) {
            throw new ServiceException("队伍ID不能为空");
        }
        Team team = super.getById(id);
        if (team == null || DEL_FLAG_DELETED.equals(team.getDelFlag())) {
            throw new ServiceException("队伍不存在或已删除");
        }
        team.setDelFlag(DEL_FLAG_DELETED);
        team.setUpdateBy(SecurityUtils.getUsername());
        team.setUpdateTime(new Date());
        return super.updateById(team);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeByIds(Collection<?> idList) {
        if (idList == null || idList.isEmpty()) {
            return false;
        }
        boolean allSuccess = true;
        for (Object idObj : idList) {
            if (idObj == null) {
                continue;
            }
            Long id = (Long) idObj;
            Team team = super.getById(id);
            if (team == null || DEL_FLAG_DELETED.equals(team.getDelFlag())) {
                continue;
            }
            team.setDelFlag(DEL_FLAG_DELETED);
            team.setUpdateBy(SecurityUtils.getUsername());
            team.setUpdateTime(new Date());
            allSuccess &= super.updateById(team);
        }
        return allSuccess;
    }

    @Override
    public Team getById(Serializable id) {
        Team team = super.getById(id);
        if (team != null && DEL_FLAG_DELETED.equals(team.getDelFlag())) {
            return null;
        }
        return team;
    }

    private LambdaQueryWrapper<Team> buildConditionWrapper(Team condition) {
        LambdaQueryWrapper<Team> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Team::getDelFlag, DEL_FLAG_NORMAL);
        if (condition == null) {
            return wrapper;
        }
        wrapper.like(StringUtils.isNotBlank(condition.getTeamName()), Team::getTeamName, condition.getTeamName());
        wrapper.like(StringUtils.isNotBlank(condition.getBelongOrgName()), Team::getBelongOrgName, condition.getBelongOrgName());
        wrapper.eq(StringUtils.isNotBlank(condition.getTeamType()), Team::getTeamType, condition.getTeamType());
        wrapper.eq(StringUtils.isNotBlank(condition.getBelongOrgType()), Team::getBelongOrgType, condition.getBelongOrgType());
        wrapper.eq(StringUtils.isNotBlank(condition.getExternalFlag()), Team::getExternalFlag, condition.getExternalFlag());
        wrapper.eq(StringUtils.isNotBlank(condition.getStatus()), Team::getStatus, condition.getStatus());
        return wrapper;
    }

    private void ensureTeamNameUnique(String teamName, Long currentId) {
        if (StringUtils.isEmpty(teamName)) {
            return;
        }
        LambdaQueryWrapper<Team> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Team::getTeamName, teamName)
            .eq(Team::getDelFlag, DEL_FLAG_NORMAL);
        if (currentId != null) {
            wrapper.ne(Team::getId, currentId);
        }
        long exists = count(wrapper);
        if (exists > 0) {
            throw new ServiceException("队伍名称已存在：" + teamName);
        }
    }
}