package com.uas.platform.b2b.openapi.controller;

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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.uas.platform.b2b.model.AccessToken;
import com.uas.platform.b2b.model.Enterprise;
import com.uas.platform.b2b.model.ResourceItem;
import com.uas.platform.b2b.model.Role;
import com.uas.platform.b2b.model.User;
import com.uas.platform.b2b.openapi.support.ErrorUtils;
import com.uas.platform.b2b.service.AccessTokenService;
import com.uas.platform.b2b.service.EnterpriseService;
import com.uas.platform.b2b.service.UserService;
import com.uas.platform.b2b.support.SystemSession;
import com.uas.platform.b2b.support.TrustedAuthenticationToken;
import com.uas.platform.core.exception.SystemError;
import com.uas.platform.core.model.Constant;
import com.uas.platform.core.util.AgentUtils;

/**
 * 认证信息跳转界面
 * 
 * @author yingp
 *
 */
@SuppressWarnings("deprecation")
@RequestMapping("/openapi")
@Controller
public class AuthedWebPageController {

	@Autowired
	private EnterpriseService enterpriseService;

	@Autowired
	private UserService userService;

	@Autowired
	private AccessTokenService accessTokenService;

	/**
	 * 用token信息自动登录并打开web页面
	 * 
	 * @param request
	 * @param response
	 * @param access_token
	 * @param redirect_page
	 * @throws IOException
	 */
	@RequestMapping(value = "/webpage", method = RequestMethod.GET)
	public void getWebPageAccessToken(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "access_token", required = true) String access_token,
			@RequestParam(value = "redirect_page", required = true) String redirect_page) throws IOException {
		AccessToken token = accessTokenService.findOne(access_token);
		if (token != null) {
			Enterprise enterprise = enterpriseService.findByEnUU(token.getEnUU());
			if (enterprise != null) {
				// 将企业信息、用户信息写入SystemSession
				User user = userService.findUserByUserUU(token.getUserUU());
				if (user != null) {
					user.setEnterprise(enterprise);
					user.setIp(AgentUtils.getIp(request));
					SystemSession.setUser(user);
					Collection<GrantedAuthority> array = getGrantedAuthorities(user);
					TrustedAuthenticationToken authenticate = new TrustedAuthenticationToken(user.getUserUU(), array);
					SecurityContextHolder.getContext().setAuthentication(authenticate);
					request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
							SecurityContextHolder.getContext());
					request.getSession().setAttribute("user", user);
					response.sendRedirect(redirect_page);
				}
			}
			throw new SystemError(ErrorUtils.EN_NOT_FOUND);
		}
		throw new SystemError(ErrorUtils.ACCESS_TOKEN_EXPIRES);
	}

	private Set<GrantedAuthority> getGrantedAuthorities(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;
	}

}
