package shop.alien.store.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import shop.alien.entity.store.LifeSysUserRole;
import shop.alien.mapper.LifeSysUserRoleMapper;
import shop.alien.store.service.LifeSysUserRoleService;

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

/**
 * 用户角色关联表 服务实现类
 *
 * @author system
 * @since 2025-01-XX
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional
public class LifeSysUserRoleServiceImpl extends ServiceImpl<LifeSysUserRoleMapper, LifeSysUserRole> implements LifeSysUserRoleService {

    private final LifeSysUserRoleMapper lifeSysUserRoleMapper;

    @Override
    public boolean assignRoles(Integer userId, List<Long> roleIds) {
        if (userId == null) {
            log.error("用户ID不能为空");
            return false;
        }
        if (roleIds == null || roleIds.isEmpty()) {
            log.warn("角色ID列表为空，无需分配");
            return true;
        }

        // 先移除用户的所有角色
        LambdaQueryWrapper<LifeSysUserRole> deleteWrapper = new LambdaQueryWrapper<>();
        deleteWrapper.eq(LifeSysUserRole::getUserId, userId);
        lifeSysUserRoleMapper.delete(deleteWrapper);

        // 批量分配新角色
        for (Long roleId : roleIds) {
            if (roleId != null) {
                // 检查是否已存在该关联关系
                LambdaQueryWrapper<LifeSysUserRole> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(LifeSysUserRole::getUserId, userId)
                        .eq(LifeSysUserRole::getRoleId, roleId);
                LifeSysUserRole existing = lifeSysUserRoleMapper.selectOne(queryWrapper);
                if (existing == null) {
                    // 创建新的关联关系
                    LifeSysUserRole userRole = new LifeSysUserRole();
                    userRole.setUserId(userId);
                    userRole.setRoleId(roleId);
                    lifeSysUserRoleMapper.insert(userRole);
                }
            }
        }
        return true;
    }

    /**
     * 移除用户的所有角色
     *
     * @param userId 用户ID
     * @return boolean
     */
    public boolean removeAllRoles(Integer userId) {
        if (userId == null) {
            log.error("用户ID不能为空");
            return false;
        }

        LambdaQueryWrapper<LifeSysUserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LifeSysUserRole::getUserId, userId);
        int result = lifeSysUserRoleMapper.delete(queryWrapper);
        return result >= 0; // 即使没有记录也返回true
    }

    @Override
    public List<Long> getRoleIdsByUserId(Integer userId) {
        if (userId == null) {
            log.warn("用户ID为空，无法查询角色");
            return new ArrayList<>();
        }
        LambdaQueryWrapper<LifeSysUserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LifeSysUserRole::getUserId, userId);
        List<LifeSysUserRole> userRoles = lifeSysUserRoleMapper.selectList(queryWrapper);
        return userRoles.stream()
                .map(LifeSysUserRole::getRoleId)
                .collect(Collectors.toList());
    }

    @Override
    public boolean addRole(Integer userId, Long roleId) {
        if (userId == null) {
            log.error("用户ID不能为空");
            return false;
        }
        if (roleId == null) {
            log.error("角色ID不能为空");
            return false;
        }

        // 检查是否已存在该关联关系
        LambdaQueryWrapper<LifeSysUserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LifeSysUserRole::getUserId, userId)
                .eq(LifeSysUserRole::getRoleId, roleId);
        LifeSysUserRole existing = lifeSysUserRoleMapper.selectOne(queryWrapper);
        if (existing != null) {
            log.warn("用户ID={}已拥有角色ID={}，无需重复添加", userId, roleId);
            return true;
        }

        // 创建新的关联关系
        LifeSysUserRole userRole = new LifeSysUserRole();
        userRole.setUserId(userId);
        userRole.setRoleId(roleId);
        int result = lifeSysUserRoleMapper.insert(userRole);
        return result > 0;
    }

    @Override
    public boolean removeRole(Integer userId, Long roleId) {
        if (userId == null) {
            log.error("用户ID不能为空");
            return false;
        }
        if (roleId == null) {
            log.error("角色ID不能为空");
            return false;
        }

        LambdaQueryWrapper<LifeSysUserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LifeSysUserRole::getUserId, userId)
                .eq(LifeSysUserRole::getRoleId, roleId);
        int result = lifeSysUserRoleMapper.delete(queryWrapper);
        return result > 0;
    }
}

