package com.dxhy.admin.sys.service.impl;

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

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dxhy.admin.sys.dao.SysUserRoleDao;
import com.dxhy.admin.sys.entity.SysRoleEntity;
import com.dxhy.admin.sys.entity.SysUserRoleEntity;
import com.dxhy.admin.sys.service.SysUserRoleService;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.utils.Aops;

/**
 * 用户与角色对应关系
 *
 * @author jiaohongyang
 */
@Service("sysUserRoleService")
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleDao, SysUserRoleEntity>
    implements SysUserRoleService {
    @Override
    public void saveOrUpdate(Long userId, List<Long> roleIdList) {
        DynamicContextHolder.push(DbConstant.BASICS_WRITE);
        Aops.getSelf(this).insertUserRole(userId, roleIdList);

    }

    @Transactional(rollbackFor = Exception.class)
    public void insertUserRole(Long userId, List<Long> roleIdList) {
        List<SysUserRoleEntity> userRoleList = new ArrayList<>();
        // 先删除用户与角色关系
        this.remove(new QueryWrapper<SysUserRoleEntity>().eq("user_id", userId));

        if (roleIdList == null || roleIdList.size() == 0) {
            return;
        }
        // 保存用户与角色关系
        for (Long roleId : roleIdList) {
            SysUserRoleEntity sysUserRoleEntity = new SysUserRoleEntity();
            sysUserRoleEntity.setUserId(userId);
            sysUserRoleEntity.setRoleId(roleId);
            userRoleList.add(sysUserRoleEntity);
        }
        this.saveOrUpdateBatch(userRoleList);
    }

    @Override
    public List<Long> queryRoleIdList(Long userId) {
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        return baseMapper.queryRoleIdList(userId);
    }

    @Override
    public int deleteBatch(Long roleIds) {
        DynamicContextHolder.push(DbConstant.BASICS_WRITE);
        return Aops.getSelf(this).deleteUserRole(roleIds);
    }

    @Transactional(rollbackFor = Exception.class)
    public int deleteUserRole(Long roleIds) {
        return baseMapper.deleteById(roleIds);
    }

    @Override
    public List<SysRoleEntity> queryRole(Long userId) {
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        return baseMapper.queryRole(userId);
    }

    @Override
    public void delete(Long userId) {
        DynamicContextHolder.push(DbConstant.BASICS_WRITE);
        Aops.getSelf(this).deleteUser(userId);
    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteUser(Long userId) {
        baseMapper.delete(new QueryWrapper<SysUserRoleEntity>().eq("user_id", userId));
    }
}
