package com.palmnest.webapp.filter;

import com.palmnest.application.Constants;
import com.palmnest.model.User;
import com.palmnest.model.estateserve.VirtualAccount;
import com.palmnest.service.UserManager;
import com.palmnest.service.virtProject.manager.VirtualAccountManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

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

/**
 * @Author hxt
 * @Description TODO
 * @Date 2019/3/28 10:19
 **/
@Component
public class VirAccountAuthenticationProvider implements AuthenticationProvider {

	@Autowired
	private VirtualAccountManager virtualAccountManager;
	@Autowired
	private UserManager           userManager;

	/**
	 * 认证方法 ---- 自定义
	 *
	 * @param authentication
	 * @return
	 * @throws AuthenticationException
	 */
	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {

		String name     = authentication.getName();
		String password = authentication.getCredentials().toString();

		// 验证企业账号与密码是否正确;正确返回token;错误直接返回null
		// UsernamePasswordAuthenticationToken参数;
		// [1]查询到的用户(可以是字符串,可以是对象);
		// [2]查询的密码(字符串或对象);
		// [3]权限角色
		VirtualAccount virAccount = virtualAccountManager.getVirtualAccountByName(name);

		if (Objects.isNull(virAccount)) {
			throw new UsernameNotFoundException("virAccount '" + virAccount + "' not found...");
		} else if (Objects.equals(password, virAccount.getPassword())) {

			List<GrantedAuthority> roleList = new ArrayList<GrantedAuthority>();

			GrantedAuthority authority1 = new SimpleGrantedAuthority(Constants.ADMIN_ROLE);
			GrantedAuthority authority2 = new SimpleGrantedAuthority(Constants.USER_ROLE);

			roleList.add(authority1);
			roleList.add(authority2);

			// 此处构建企业账号对应的用户;并为其分配
			// 1-企业管理父菜单
			// 1-1 企业资料信息管理子菜单
			// 1-2 部门信息管理
			// 1-3 身份类型管理
			// 1-4 企业人员管理
			User virUser = userManager.createVirAccountUser(virAccount);

			return new UsernamePasswordAuthenticationToken(virUser, password, roleList);
		}

		return null;
	}

	@Override
	public boolean supports(Class<?> authentication) {
		return authentication.equals(UsernamePasswordAuthenticationToken.class);
	}
}
