package com.uas.platform.b2b.support;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.util.CollectionUtils;

import com.uas.platform.b2b.model.ResourceItem;
import com.uas.platform.b2b.model.Role;
import com.uas.platform.b2b.service.UserService;
import com.uas.platform.core.model.Constant;

/**
 * 获得用户验证信息
 * 
 * @author yingp
 * 
 * @since 2016年8月31日上午10:55:13
 *        <p>
 *        切换到单点登录
 *        </p>
 */
@Deprecated
public class CustomUserDetailsService implements UserDetailsService {

	private ThreadLocal<User> currentUser = new ThreadLocal<User>();

	@Autowired
	private UserService userService;

	static final String TEL_REGEXP = "^((\\(\\d{3}\\))|(\\d{3}\\-))?(13|15|17|18)\\d{9}$";

	static final String UU_REGEXP = "^\\d{4,}$";

	private static String EMAIL_SIGN = "@";

	/**
	 * @param username
	 * @return
	 * @throws UsernameNotFoundException
	 * @throws DataAccessException
	 */
	@Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
		try {
			com.uas.platform.b2b.model.User userinfo = null;
			// 邮箱登录
			if (username.contains(EMAIL_SIGN)) {
				userinfo = userService.findUserByUserEmail(username);
				// 手机号登录
			} else if (username.matches(TEL_REGEXP)) {
				userinfo = userService.findUserByUserTel(username);
			} else if (username.matches(UU_REGEXP)) {
				userinfo = userService.findUserByUserUU(Long.parseLong(username));
			}
			Collection<GrantedAuthority> array = getGrantedAuthorities(userinfo);
			User user = new User(String.valueOf(userinfo.getUserUU()), userinfo.getUserPwd(), true, true, true, true, array);
			currentUser.set(user);
			return user;
		} catch (Exception e) {
			throw new UsernameNotFoundException(username + " 不存在的账号!");
		}
	}

	private Set<GrantedAuthority> getGrantedAuthorities(com.uas.platform.b2b.model.User user) {
		Set<GrantedAuthority> authSet = new HashSet<GrantedAuthority>();
		Set<Role> roles = user.getRoles();
		if (!CollectionUtils.isEmpty(roles)) {
			for (Role role : roles) {
				// 超级账号
				if (role.isSys()) {
					user.setIssys(Constant.YES);
					break;
				}
				Set<ResourceItem> resourceItems = role.getResourceItems();
				if (!CollectionUtils.isEmpty(resourceItems)) {
					for (ResourceItem res : resourceItems) {
						authSet.add(new SimpleGrantedAuthority(res.getName()));
					}
				}
			}
		}
		return authSet;
	}
}