package com.cool.store.service.impl;

import com.cool.store.entity.EnterpriseUserDO;
import com.cool.store.entity.SysRoleDO;
import com.cool.store.enums.Role;
import com.cool.store.enums.RoleSourceEnum;
import com.cool.store.enums.UserRoleEnum;
import com.cool.store.mapper.SysRoleMapper;
import com.cool.store.service.SysRoleService;
import com.cool.store.service.UserAuthMappingService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 角色service
 * @author wxp
 */
@Slf4j
@Service
public class SysRoleServiceImpl implements SysRoleService {

    @Resource
    private SysRoleMapper sysRoleMapper;

    @Resource
    private UserAuthMappingService userAuthMappingService;

    @Override
    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()));
    }

    @Override
    public Map<String, Long> getXfsgRoles() {
        List<String> xfsgRoleNames = Arrays.stream(UserRoleEnum.values())
                .map(UserRoleEnum::getDesc)
                .collect(Collectors.toList());
        List<SysRoleDO> sysRoleDOList = sysRoleMapper.getRolesByNamesAndSource(xfsgRoleNames, RoleSourceEnum.CREATE.getCode());
        Map<String, Long> sysRoleDOMap = sysRoleDOList.stream().collect(Collectors.toMap(k -> k.getRoleName(), v -> v.getId(), (k1, k2) -> k1));
        return sysRoleDOMap;
    }

    @Override
    public String getUserIdByRegionIdWithRolePriority(Long regionId, List<UserRoleEnum> roleList) {
        if(CollectionUtils.isEmpty(roleList)){
            return null;
        }
        for(UserRoleEnum roleEnum: roleList){
            EnterpriseUserDO enterpriseUserDO = userAuthMappingService.getUserByRoleEnumAndRegionId(roleEnum, regionId);
            if(enterpriseUserDO != null){
                return enterpriseUserDO.getUserId();
            }
        }
        return null;
    }


}
