package com.keao.edu.auth.core.provider.service;

import com.keao.edu.auth.api.dto.AuthUser;
import com.keao.edu.auth.api.dto.SysUserInfo;
import com.keao.edu.auth.api.entity.SysUser;
import com.keao.edu.auth.api.util.SecurityConstants;
import com.keao.edu.auth.service.SysUserService;
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.stereotype.Service;

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

@Service
public class DefaultUserDetailsService implements UserDetailsService {

	@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() == 9) {
			throw new LockedException("账户被锁定");
		}

		List<GrantedAuthority> authorities = null;

		String userType = userInfo.getSysUser().getUserType();
		String[] roles = userType.split(",");

		if (userType.contains("SYSTEM")) {
			authorities = AuthorityUtils.createAuthorityList(userInfo.getPermissions());
		}

		if (authorities == null) {
			authorities = new ArrayList<>();
		}
		
		authorities.add(new SimpleGrantedAuthority(StringUtils.lowerCase(userType)));

		for (String role : roles) {
			authorities.add(new SimpleGrantedAuthority(StringUtils.lowerCase(role)));
		}

		SysUser sysUser = userInfo.getSysUser();

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

}
