package com.qmth.qrzk.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
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 com.qmth.qrzk.repository.user.model.Role;
import com.qmth.qrzk.repository.user.model.User;
import com.qmth.qrzk.repository.user.service.IRoleService;
import com.qmth.qrzk.repository.utils.Consts;

@Component
public class UserLoginService implements UserDetailsService{
	
	private static Logger log = Logger.getLogger(UserLoginService.class);

	@javax.annotation.Resource(name="userDaoImpl")
	private LoginDao loginDao;
	
	@Autowired
	@Qualifier("roleServiceImpl")
	private IRoleService roleService;
	
	public User getUserByUsername(String username){
		return (User)loginDao.getLoginUserByUsername(username);
	}
	
	@Override
	public UserDetails loadUserByUsername(String username){
		log.info("开始加载用户[" + username + "]个人信息...");
		UserDetails ud = null;
		
		boolean accountNonExpired = true;  
        boolean credentialsNonExpired = true;  
        boolean accountNonLocked = true;  
        
        if(username.equals("superadmin")){
        	Collection<GrantedAuthority> superAuths = new LinkedList<GrantedAuthority>();
        	superAuths.add(new SimpleGrantedAuthority("9999"));
        	ud = new org.springframework.security.core.userdetails.User(username, 
            		"qmth87863577", 
            		true, 
            		accountNonExpired, 
            		credentialsNonExpired, 
            		accountNonLocked,
            		superAuths);
        }else{
        	LoginUser user = null;
        	try{
	        	user = loginDao.getLoginUserByUsername(username);
        	}catch(Exception e){
        		log.error("加载用户[" + username + "]个人信息系统异常：" + e.getMessage(),e);
        		throw new UsernameNotFoundException(e.getMessage());
        	}
    		if(user == null){
    			log.warn("加载用户[" + username + "]个人信息失败：用户不存在！");
    			throw new UsernameNotFoundException("用户不存在");
    		}
    		try{
	    		Collection<GrantedAuthority> auths = getAuthorities(user);
	    		ud = new org.springframework.security.core.userdetails.User(username, 
	    				user.getPassword(), 
	    				user.isEnabled(), 
	            		accountNonExpired, 
	            		credentialsNonExpired, 
	            		accountNonLocked,
	            		auths);
        	}catch(Exception e){
        		log.error("加载用户[" + username + "]个人信息Spring验证模块异常：" + e.getMessage(),e);
        		throw new UsernameNotFoundException(e.getMessage());
        	}
    		
        }
        log.info("加载用户[" + username + "]个人信息成功.");
		return ud;
	}
	
	/**
	 * 查询用户角色，spring security授权用
	 * @param user
	 * @return
	 */
	protected Collection<GrantedAuthority> getAuthorities(LoginUser user) {
		
		List<Role> roles = new ArrayList<Role>();
		boolean isQuesAuditor = false;
		boolean isQuesInputer =false;
		if(user instanceof User){ 
			roles = roleService.getRolesByUserId(((User) user).getId());
			isQuesAuditor = roleService.isQuesAuditor(((User) user).getId());
			isQuesInputer = roleService.isQuesInputer(((User) user).getId());
		}
		
		Collection<GrantedAuthority> auths = new LinkedList<GrantedAuthority>();
		for(Role role : roles){
			auths.add(new SimpleGrantedAuthority(role.getCode()));
		}
		if(isQuesAuditor){
			auths.add(new SimpleGrantedAuthority(Consts.UserRoleCodes.QUES_AUDITOR));
		}
		if(isQuesInputer){
			auths.add(new SimpleGrantedAuthority(Consts.UserRoleCodes.QUES_INPUTER));
		}
		return auths;
	}
	
//	public Set<Resource> getLoginUserResources(LoginUser user){
//		return user.getResources();
//	}
}
