package com.cool.store.dao;

import com.cool.store.entity.SysRoleDO;
import com.cool.store.enums.Role;
import com.cool.store.mapper.EnterpriseUserRoleMapper;
import com.cool.store.mapper.SysRoleMapper;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author zhangnan
 * @date 2022-04-14 18:38
 */
@Repository
public class EnterpriseUserRoleDao {

    @Resource
    private EnterpriseUserRoleMapper enterpriseUserRoleMapper;
    @Resource
    private SysRoleMapper sysRoleMapper;

    /**
     * 根据角色id查询用户id列表
     * @param roleIds
     * @return
     */
    public List<String> selectUserIdsByRoleIdList( List<Long> roleIds) {
        if( CollectionUtils.isEmpty(roleIds)) {
            return Lists.newArrayList();
        }
        return enterpriseUserRoleMapper.selectUserIdsByRoleIdList(roleIds);
    }

    public List<String> selectUserIdsByRole( Role role) {
        if(Objects.isNull(role)) {
            return Lists.newArrayList();
        }
        return enterpriseUserRoleMapper.selectUserIdsByRoleIdList( Arrays.asList(Long.valueOf(role.getId())));
    }

    public List<String> getUserIdsByRoleIds( List<String> roleIds, List<String> userIds){
        if(CollectionUtils.isEmpty(roleIds) || CollectionUtils.isEmpty(userIds)){
            return Lists.newArrayList();
        }
        return enterpriseUserRoleMapper.getUserIdsByRoleIds(roleIds, userIds);
    }

    public List<Long> getUserRoleIds( String userId){
        if(StringUtils.isAnyBlank(userId)){
            return Lists.newArrayList();
        }
        return enterpriseUserRoleMapper.getUserRoleIds(userId);
    }

    public Boolean checkIsAdmin( String userId) {

        // 1.取出所有用户角色
        // 2.匹配是否有管理员角色
        List<SysRoleDO> sysRoleDOList = sysRoleMapper.listRoleByUserId(userId);
        return ListUtils.emptyIfNull(sysRoleDOList)
                .stream()
                .anyMatch(role-> StringUtils.equals(Role.MASTER.getRoleEnum(),role.getRoleEnum()));
    }

    public List<String> getUserIdsByRoleIdList( List<Long> roleIdList) {
        return enterpriseUserRoleMapper.getUserIdsByRoleIdList(roleIdList);
    }

}
