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

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.io.Serializable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.aegis.common.core.domain.entity.SysUser;
import com.aegis.common.exception.ServiceException;
import com.aegis.common.utils.SecurityUtils;
import com.aegis.common.utils.StringUtils;
import com.aegis.emergency.duty.constant.DutyShiftMemberRole;
import com.aegis.emergency.duty.domain.DutyShiftMember;
import com.aegis.emergency.duty.mapper.DutyShiftMemberMapper;
import com.aegis.emergency.duty.service.DutyShiftMemberService;
import com.aegis.system.service.ISysUserService;

/**
 * 排班成员Service业务层处理
 * 
 * @author aegis
 */
@Service
public class DutyShiftMemberServiceImpl extends ServiceImpl<DutyShiftMemberMapper, DutyShiftMember> implements DutyShiftMemberService {

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询排班成员列表
     * 
     * @param condition 成员信息
     * @return 成员集合
     */
    @Override
    public List<DutyShiftMember> listByCondition(DutyShiftMember condition) {
        LambdaQueryWrapper<DutyShiftMember> wrapper = new LambdaQueryWrapper<>();
        if (condition != null) {
            if (condition.getShiftId() != null) {
                wrapper.eq(DutyShiftMember::getShiftId, condition.getShiftId());
            }
            if (condition.getUserId() != null) {
                wrapper.eq(DutyShiftMember::getUserId, condition.getUserId());
            }
            if (StringUtils.isNotEmpty(condition.getRole())) {
                wrapper.eq(DutyShiftMember::getRole, condition.getRole());
            }
        }
        wrapper.orderByAsc(DutyShiftMember::getShiftId);
        wrapper.orderByAsc(DutyShiftMember::getUserId);
        List<DutyShiftMember> members = super.list(wrapper);
        enrichMemberNames(members);
        return members;
    }

    @Override
    public List<DutyShiftMember> listByShiftIds(List<Long> shiftIds) {
        if (shiftIds == null || shiftIds.isEmpty()) {
            return Collections.emptyList();
        }
        LambdaQueryWrapper<DutyShiftMember> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(DutyShiftMember::getShiftId, shiftIds);
        List<DutyShiftMember> members = super.list(wrapper);
        enrichMemberNames(members);
        return members;
    }

    @Override
    public DutyShiftMember getById(Serializable id) {
        if (id == null) {
            throw new ServiceException("成员ID不能为空");
        }
        DutyShiftMember member = super.getById(id);
        if (member == null) {
            throw new ServiceException("成员不存在");
        }
        enrichMemberNames(Collections.singletonList(member));
        return member;
    }

    @Override
    @Transactional
    public boolean save(DutyShiftMember member) {
        if (member == null) {
            throw new ServiceException("成员信息不能为空");
        }
        if (member.getShiftId() == null) {
            throw new ServiceException("排班ID不能为空");
        }
        if (member.getUserId() == null) {
            throw new ServiceException("用户ID不能为空");
        }
        if (StringUtils.isEmpty(member.getRole())) {
            throw new ServiceException("成员角色不能为空");
        }
        
        // 验证角色
        if (DutyShiftMemberRole.fromCode(member.getRole()) == null) {
            throw new ServiceException("成员角色无效，可选值：leader-组长，member-成员");
        }
        
        // 如果添加的是组长，检查该排班是否已有组长
        if (DutyShiftMemberRole.LEADER.getCode().equals(member.getRole())) {
            LambdaQueryWrapper<DutyShiftMember> leaderWrapper = new LambdaQueryWrapper<>();
            leaderWrapper.eq(DutyShiftMember::getShiftId, member.getShiftId());
            leaderWrapper.eq(DutyShiftMember::getRole, DutyShiftMemberRole.LEADER.getCode());
            DutyShiftMember existingLeader = super.getOne(leaderWrapper, false);
            if (existingLeader != null) {
                throw new ServiceException("该排班已存在组长，不能重复添加");
            }
        }
        
        // 检查是否已存在（唯一约束：shift_id + user_id）
        LambdaQueryWrapper<DutyShiftMember> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DutyShiftMember::getShiftId, member.getShiftId());
        wrapper.eq(DutyShiftMember::getUserId, member.getUserId());
        DutyShiftMember existing = super.getOne(wrapper, false);
        if (existing != null) {
            throw new ServiceException("该用户已在此排班中，不能重复添加");
        }
        
        String operator = SecurityUtils.getUsername();
        member.setCreateBy(operator);
        member.setCreateTime(new Date());
        member.setUpdateBy(operator);
        member.setUpdateTime(new Date());
        
        return super.save(member);
    }

    @Override
    @Transactional
    public boolean updateById(DutyShiftMember member) {
        if (member == null || member.getId() == null) {
            throw new ServiceException("成员信息或ID不能为空");
        }
        
        // 检查成员是否存在
        DutyShiftMember existing = getById(member.getId());
        // getById已做校验, 此处无需重复判断
        
        // 验证角色（必填）
        if (StringUtils.isEmpty(member.getRole())) {
            throw new ServiceException("成员角色不能为空");
        }
        if (DutyShiftMemberRole.fromCode(member.getRole()) == null) {
            throw new ServiceException("成员角色无效，可选值：leader-组长，member-成员");
        }
        
        // 如果修改为组长，检查该排班是否已有其他组长
        // 需要确定目标排班ID（可能是新值或原值）
        Long targetShiftId = member.getShiftId() != null ? member.getShiftId() : existing.getShiftId();
        String targetRole = member.getRole();
        
        if (DutyShiftMemberRole.LEADER.getCode().equals(targetRole)) {
            LambdaQueryWrapper<DutyShiftMember> leaderWrapper = new LambdaQueryWrapper<>();
            leaderWrapper.eq(DutyShiftMember::getShiftId, targetShiftId);
            leaderWrapper.eq(DutyShiftMember::getRole, DutyShiftMemberRole.LEADER.getCode());
            leaderWrapper.ne(DutyShiftMember::getId, member.getId());
            DutyShiftMember existingLeader = super.getOne(leaderWrapper, false);
            if (existingLeader != null) {
                throw new ServiceException("该排班已存在其他组长，不能重复设置");
            }
        }
        
        // 如果修改了 shiftId 或 userId，需要检查唯一约束
        if ((member.getShiftId() != null && !member.getShiftId().equals(existing.getShiftId()))
                || (member.getUserId() != null && !member.getUserId().equals(existing.getUserId()))) {
            LambdaQueryWrapper<DutyShiftMember> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(DutyShiftMember::getShiftId, 
                    member.getShiftId() != null ? member.getShiftId() : existing.getShiftId());
            wrapper.eq(DutyShiftMember::getUserId, 
                    member.getUserId() != null ? member.getUserId() : existing.getUserId());
            wrapper.ne(DutyShiftMember::getId, member.getId());
            DutyShiftMember duplicate = super.getOne(wrapper, false);
            if (duplicate != null) {
                throw new ServiceException("该用户已在此排班中，不能重复添加");
            }
        }
        
        String operator = SecurityUtils.getUsername();
        member.setUpdateBy(operator);
        member.setUpdateTime(new Date());
        
        return super.updateById(member);
    }

    @Override
    @Transactional
    public boolean removeById(Serializable id) {
        if (id == null) {
            throw new ServiceException("成员ID不能为空");
        }
        
        getById(id); // triggers存在校验
        return super.removeById(id);
    }

    @Override
    @Transactional
    public boolean removeByIds(Collection<?> idList) {
        if (idList == null || idList.isEmpty()) {
            throw new ServiceException("成员ID数组不能为空");
        }
        boolean result = true;
        for (Object id : idList) {
            result &= removeById((Serializable) id);
        }
        return result;
    }

    /**
     * 根据排班ID删除所有成员
     * 
     * @param shiftId 排班ID
     * @return 结果
     */
    @Override
    @Transactional
    public int removeByShiftId(Long shiftId) {
        if (shiftId == null) {
            throw new ServiceException("排班ID不能为空");
        }
        
        LambdaQueryWrapper<DutyShiftMember> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DutyShiftMember::getShiftId, shiftId);
        return baseMapper.delete(wrapper);
    }

    /**
     * 批量填充成员的姓名信息
     * 
     * @param members 成员列表
     */
    private void enrichMemberNames(List<DutyShiftMember> members) {
        if (members == null || members.isEmpty()) {
            return;
        }
        
        // 收集所有唯一的用户ID
        Set<Long> userIds = members.stream()
            .map(DutyShiftMember::getUserId)
            .filter(userId -> userId != null)
            .collect(Collectors.toSet());
        
        if (userIds.isEmpty()) {
            return;
        }
        
        // 批量查询用户信息并构建映射
        List<SysUser> users = sysUserService.selectUsersByIds(new ArrayList<>(userIds));
        Map<Long, String> userNamesMap = users.stream()
            .filter(user -> user != null && user.getUserId() != null)
            .collect(Collectors.toMap(
                SysUser::getUserId,
                user -> user.getNickName() != null ? user.getNickName() : null,
                (existing, replacement) -> existing
            ));
        
        // 为每个成员设置姓名
        members.forEach(member -> {
            if (member.getUserId() != null) {
                member.setMemberName(userNamesMap.get(member.getUserId()));
            }
        });
    }
}