package com.ningdatech.carapi.sys.convert;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import com.google.common.collect.Lists;
import com.ningdatech.carapi.sys.entity.Role;
import com.ningdatech.carapi.sys.entity.UserRole;
import com.ningdatech.carapi.sys.entity.dto.UserQueryDTO;
import com.ningdatech.carapi.sys.entity.vo.UserInfoVO;

import cn.hutool.core.collection.CollUtil;

/**
 * @Classname UserRoleConverter
 * @Description
 * @Date 2022/10/9 10:30
 * @Created by PoffyZhang
 */
public class UserRoleConverter {

    public static UserInfoVO convert(UserInfoVO user, List<Role> roles) {
        if(Objects.isNull(user) || Objects.isNull(user.getId())){
            return user;
        }
        if(CollUtil.isNotEmpty(roles)){
            roles.forEach(role -> {
                if(user.getRole().equals(role.getId())){
                    user.setRoleName(role.getName());
                }
            });
        }
        return user;
    }

    public static UserInfoVO convert(UserInfoVO user, List<UserRole> userRoles, List<Role> roles) {
        if(Objects.isNull(user) || Objects.isNull(user.getId())){
            return user;
        }
        if(CollUtil.isNotEmpty(userRoles) && CollUtil.isNotEmpty(roles)){
            List<String> roleNames = Lists.newArrayList();
            roles.forEach(role -> {
                userRoles.forEach(userRole -> {
                    if(userRole.getRoleId().equals(role.getId()) &&
                            userRole.getUserId().equals(user.getId())){
                        roleNames.add(role.getName());
                        user.setRole(role.getId());
                    }
                });
            });
            user.setRoleName(roleNames.stream().collect(Collectors.joining(",")));
        }
        return user;
    }

    public static UserQueryDTO convert(UserQueryDTO user, List<UserRole> userRoles, List<Role> roles) {
        if(Objects.isNull(user) || Objects.isNull(user.getId())){
            return user;
        }
        if(CollUtil.isNotEmpty(userRoles) && CollUtil.isNotEmpty(roles)){
            List<String> roleNames = Lists.newArrayList();
            roles.forEach(role -> {
                userRoles.forEach(userRole -> {
                    if(userRole.getRoleId().equals(role.getId()) &&
                            userRole.getUserId().equals(user.getId())){
                        roleNames.add(role.getName());
                        user.setRole(role.getId());
                    }
                });
            });
            user.setRoleName(roleNames.stream().collect(Collectors.joining(",")));
        }
        return user;
    }
}
