package com.ym.mec.auth.core.provider.service;

import java.util.ArrayList;
import java.util.List;

import com.ym.mec.auth.api.enums.UserLockFlag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
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.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import com.ym.mec.auth.api.dto.SysUserInfo;
import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.auth.api.enums.SysUserType;
import com.ym.mec.auth.config.constant.SecurityConstants;
import com.ym.mec.auth.service.SysUserService;
import com.ym.mec.common.security.AuthUser;

@Service
public class DefaultUserDetailsService implements UserDetailsService {

	@Autowired
	private PasswordEncoder passwordEncoder;

	@Autowired
	private SysUserService sysUserService;

	private final String BCRYPT = "{bcrypt}";

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		if (StringUtils.isBlank(username)) {
			return null;
		}

		SysUserInfo userInfo = null;

		if (StringUtils.startsWith(username, SecurityConstants.PHONE_PRINCIPAL_PREFIX)) {
			userInfo = sysUserService.queryUserInfoByPhone(StringUtils.substringAfter(username, SecurityConstants.PHONE_PRINCIPAL_PREFIX));
		} else if (StringUtils.startsWith(username, SecurityConstants.USERNAME_PRINCIPAL_PREFIX)) {
			userInfo = sysUserService.queryUserInfoByUsername(StringUtils.substringAfter(username, SecurityConstants.USERNAME_PRINCIPAL_PREFIX));
		} else {
			userInfo = sysUserService.queryUserInfoByUsername(username);
		}
		if (userInfo == null) {
			throw new UsernameNotFoundException("账户不存在");
		} else if (userInfo.getSysUser().getLockFlag() == UserLockFlag.NORMAL) {
			throw new LockedException("账户被锁定");
		}

		List<GrantedAuthority> authorities = null;

		SysUserType userType = userInfo.getSysUser().getUserType();

		if (userType == SysUserType.SYSTEM) {
			authorities = AuthorityUtils.createAuthorityList(userInfo.getPermissions());
		} else {
			authorities = new ArrayList<GrantedAuthority>();
			authorities.add(new SimpleGrantedAuthority(StringUtils.lowerCase(userType.name())));
		}

		SysUser sysUser = userInfo.getSysUser();

		return new AuthUser(sysUser.getId(), sysUser.getOrganId(), username, BCRYPT + sysUser.getPassword(), sysUser.getLockFlag() == UserLockFlag.NOACTIVATED,
				true, true, true, authorities);
	}

}
