package com.ho.user.service.impl;


import com.ho.common.tools.exception.BaseResponseCode;
import com.ho.common.tools.exception.BusinessException;
import com.ho.user.entity.SysUserRole;
import com.ho.user.mapper.SysUserRoleMapper;
import com.ho.user.service.UserRoleService;
import com.ho.user.vo.req.UserRoleOperationReqVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 用户角色关联服务类
 */
@Service
public class UserRoleServiceImpl implements UserRoleService{

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Override
    public int removeByRoleId(Integer roleId) {
        return sysUserRoleMapper.removeByRoleId(roleId);
    }

    @Override
    public List<Integer> getRoleIdsByUserId(String userId) {
        return sysUserRoleMapper.getRoleIdsByUserId(userId);
    }



    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addUserRoleInfo(UserRoleOperationReqVO vo) {
        if(vo.getRoleIds()==null||vo.getRoleIds().isEmpty()){
            return;
        }
        Date createTime=new Date();
        List<SysUserRole> list=new ArrayList<>();

        for (Integer roleId:vo.getRoleIds()){
            SysUserRole sysUserRole=new SysUserRole();
           // sysUserRole.setId(snowflake.nextIdStr());
            sysUserRole.setCreateTime(createTime);
            sysUserRole.setUserId(vo.getUserId());
            sysUserRole.setRoleId(roleId);
            list.add(sysUserRole);
        }
        //将根目录的角色加进来,避免无法获取tree的根

        sysUserRoleMapper.removeByUserId(vo.getUserId());
        int count=sysUserRoleMapper.batchUserRole(list);
        if (count==0){
            throw new BusinessException(BaseResponseCode.OPERATION_ERRO);
        }
    }

    @Override
    public int removeByUserId(String userId) {

        return sysUserRoleMapper.removeByUserId(userId);
    }

    @Override
    public int removeByUserIds(List<String> userIds) {
       return sysUserRoleMapper.removeByUserIds(userIds);
    }

    @Override
    public List<String> getUserIdsByRoleIds(List<Integer> roleIds) {

        return sysUserRoleMapper.getUserIdsByRoleIds(roleIds);
    }
}
