
package com.tmerclub.cloud.rbac.feign;

import cn.hutool.core.collection.CollUtil;
import com.tmerclub.cloud.api.rbac.dto.UserRoleDTO;
import com.tmerclub.cloud.api.rbac.feign.UserRoleFeignClient;
import com.tmerclub.cloud.auth.manager.TokenStore;
import com.tmerclub.cloud.common.cache.constant.CacheNames;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.rbac.mapper.UserRoleMapper;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author tmerclub
 * @date 2020/7/15
 */
@DubboService
public class UserRoleFeignController implements UserRoleFeignClient {

    private static final Logger logger = LoggerFactory.getLogger(UserRoleFeignController.class);

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private TokenStore tokenStore;

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = CacheNames.MENU_ID_LIST_KEY, key = "#userRoleDTO.userId")
    public void saveByUserIdAndSysType(UserRoleDTO userRoleDTO) {

        if (CollUtil.isEmpty(userRoleDTO.getRoleIds())) {
            ServerResponseEntity.success();
            return;
        }
        //保存用户与角色关系
        userRoleMapper.insertUserAndUserRole(userRoleDTO.getUserId(), userRoleDTO.getRoleIds());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = CacheNames.MENU_ID_LIST_KEY, key = "#userRoleDTO.userId")
    public void updateByUserIdAndSysType(UserRoleDTO userRoleDTO) {
        // 不管权限具体有没有发生变动，都直接删除token缓存
        tokenStore.deleteUserToken();
        //先删除用户与角色关系
        userRoleMapper.deleteByUserId(userRoleDTO.getUserId());
        if (CollUtil.isEmpty(userRoleDTO.getRoleIds())) {
            ServerResponseEntity.success();
            return;
        }
        //保存用户与角色关系
        userRoleMapper.insertUserAndUserRole(userRoleDTO.getUserId(), userRoleDTO.getRoleIds());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = CacheNames.MENU_ID_LIST_KEY, key = "#userId")
    public void deleteByUserIdAndSysType(Long userId) {
        userRoleMapper.deleteByUserId(userId);
    }

    @Override
    public ServerResponseEntity<List<Long>> getRoleIds(Long userId) {
        return ServerResponseEntity.success(userRoleMapper.getRoleIds(userId));
    }
}
