package com.uas.platform.b2b.support;

import java.util.ArrayList;

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 com.uas.platform.b2b.service.UserService;

/**
 * 
 * 获得用户验证信息
 * 
 * @author yingp
 * @version 1.0
 * 
 */
public class CustomUserDetailsService implements UserDetailsService {

	public static final String ROLE_USER = "ROLE_USER";

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

	@Autowired
	private UserService userService;

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

	/**
	 * @param username
	 * @return
	 * @throws UsernameNotFoundException
	 * @throws DataAccessException
	 */
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
		try {
			com.uas.platform.b2b.model.User userinfo = null;
			if (username.contains("@")) { // 邮箱登录
				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));
			}
			ArrayList<GrantedAuthority> array = new ArrayList<GrantedAuthority>();
			array.add(new SimpleGrantedAuthority(ROLE_USER));
			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 + " 不存在的账号!");
		}
	}
}