package com.reyun.saas.security.service;


import com.reyun.saas.security.authentication.SecurityUser;
import com.reyun.saas.mob.user.dao.MenuRightMapper;
import com.reyun.saas.mob.user.dao.RoleMapper;
import com.reyun.saas.mob.user.domain.MenuRight;
import com.reyun.saas.mob.user.domain.Role;
import com.reyun.saas.mob.user.dto.LoginUserDTO;
import com.reyun.saas.mob.user.dto.user.UserDTO;
import com.reyun.saas.mob.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

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

@Component("securityUserService")
public class SecurityUserService implements UserDetailsService {
    @Autowired
    private UserService userService;
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private MenuRightMapper menuRightMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        UserDTO userDTO = userService.getRolesByUsername(username);
        if (null != userDTO){
            if(0L == userDTO.getRootParent()) {
                this.getAdminPermission(userDTO);
            }
            SecurityUser securityUser = new SecurityUser(LoginUserDTO.user2LoginUserDTO(userDTO));
            return securityUser;
        } else {
            throw new UsernameNotFoundException(username + " 用户不存在!");
        }
    }

    /**
     * 为管理员赋所有权限
     * @param userDTO
     * @return
     */
    private UserDTO getAdminPermission(UserDTO userDTO) {
        List<Role> roles = roleMapper.selectAll();
        List<MenuRight> menuRights = menuRightMapper.selectAll();
        userDTO.setRoles(roles);
        userDTO.setMenus(menuRights);
        return userDTO;
    }
}
