package com.qiaoba.module.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.qiaoba.api.system.entity.SysUserRole;
import com.qiaoba.api.auth.entity.dto.RoleDto;
import com.qiaoba.common.base.constant.BaseConstant;
import com.qiaoba.common.base.enums.BaseEnum;
import com.qiaoba.module.system.mapper.SysUserRoleMapper;
import com.qiaoba.module.system.service.SysUserRoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

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

/**
 * 用户角色关联 服务层实现
 *
 * @author ailanyin
 * @version 1.0
 * @since 2023/5/10 13:03
 */
@Service
@RequiredArgsConstructor
public class SysUserRoleServiceImpl implements SysUserRoleService {

    private final SysUserRoleMapper sysUserRoleMapper;

    @Override
    public void insertBatch(List<SysUserRole> list) {
        Db.saveBatch(list);
    }

    @Override
    public void deleteByUserId(String userId) {
        sysUserRoleMapper.delete(createWrapper(userId));
    }

    @Override
    public void deleteByUserIds(List<String> userIds) {
        sysUserRoleMapper.deleteByUserIds(userIds);
    }

    @Override
    public void deleteByRoleIdAndUserIds(String roleId, List<String> userIds) {
        sysUserRoleMapper.deleteByRoleIdAndUserIds(roleId, userIds);
    }

    @Override
    public List<String> selectRoleIdsByUserId(String userId, String status) {
        return sysUserRoleMapper.selectRoleIdsByUserId(userId, status);
    }

    @Override
    public List<RoleDto> selectRoleDtoByUserId(String userId, String status) {
        return sysUserRoleMapper.selectRoleDtoByUserId(userId, status);
    }

    @Override
    public void insertAuthUsers(String roleId, List<String> userIds) {
        List<SysUserRole> list = new ArrayList<>();
        for (String userId : userIds) {
            list.add(new SysUserRole(userId, roleId));
        }
        Db.saveBatch(list);
    }

    @Override
    public String selectRoleGroup(String userId) {
        List<RoleDto> list = selectRoleDtoByUserId(userId, BaseEnum.NORMAL.getCode());
        List<String> names = list.stream().map(RoleDto::getRoleName).collect(Collectors.toList());
        return CollUtil.isNotEmpty(list) ? StrUtil.join(BaseConstant.LINE_JOIN_STR, names) : StrUtil.EMPTY;
    }

    private QueryWrapper<SysUserRole> createWrapper(String userId) {
        QueryWrapper<SysUserRole> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(SysUserRole::getUserId, userId);
        return wrapper;
    }
}
