package com.yifu.cloud.plus.v1.yifu.auth.util;

import org.jasig.cas.client.authentication.AttributePrincipal;
import org.jasig.cas.client.util.AbstractCasFilter;
import org.jasig.cas.client.validation.Assertion;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.logging.Logger;

public class LoginUtils {

	private static final Logger LOG = Logger.getLogger(LoginUtils.class.getName());
	/**
	 * 登录
	 *
	 * @author licancan
	 * @param server cas服务端获取tgt地址
	 * @param username 用户名
	 * @param password 密码
	 * @param service 需要跳转的应用地址
	 * @return {@link String}
	 */
	public static String getTicket(final String server, final String username, final String password, final String service) {
		//重定向
		return getServiceTicket(server, getTicketGrantingTicket(server, username, password), service);
	}

	/**
	 * 获取ST
	 *
	 * @author licancan
	 * @param server cas服务端获取tgt地址
	 * @param ticketGrantingTicket tgt
	 * @param service 需要跳转的应用地址
	 * @return {@link String}
	 */
	private static String getServiceTicket(final String server, final String ticketGrantingTicket, final String service) {
		if (ticketGrantingTicket == null){
			return null;
		}

		try {
			RestTemplate restTemplate = new RestTemplate();
			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
			MultiValueMap<String,Object> wholeForm = new LinkedMultiValueMap<>();
			wholeForm.add("service",service);
			HttpEntity<MultiValueMap<String,Object>> entity = new HttpEntity<>(wholeForm,headers);
			ResponseEntity<String> obj = restTemplate.exchange(server + "/" + ticketGrantingTicket, HttpMethod.POST, entity, String.class);

			if (obj.getStatusCode().value() == 200) {
				LOG.info("Successful service ticket request: " + obj.getBody());
				return obj.getBody();
			} else {
				LOG.warning("Invalid response code (" + obj.getStatusCode().value() + ") from CAS server!");
				LOG.info("Response (1k): " + obj.getBody());
			}
		} catch (Exception e) {
			LOG.warning(e.getMessage());
		}
		return null;
	}

	/**
	 * 获取 TGT
	 *
	 * @author licancan
	 * @param server cas服务端获取tgt地址
	 * @param username 用户名
	 * @param password 密码
	 * @return {@link String}
	 */
	private static String getTicketGrantingTicket(final String server, final String username, final String password) {

		try {
			RestTemplate restTemplate = new RestTemplate();
			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
			MultiValueMap<String,Object> wholeForm = new LinkedMultiValueMap<>();
			wholeForm.add("username",username);
			wholeForm.add("password",password);
			HttpEntity<MultiValueMap<String,Object>> entity = new HttpEntity<>(wholeForm,headers);
			ResponseEntity<String> obj = restTemplate.exchange(server, HttpMethod.POST, entity, String.class);
			if (obj.getStatusCode().value() == 201) {
				LOG.info("Successful ticket granting ticket request: " + obj.getBody());
				return obj.getBody();
			} else {
				LOG.warning("Invalid response code (" + obj.getStatusCode().value() + ") from CAS server!");
				LOG.info("Response (1k): " + obj.getBody());
			}
		} catch (Exception e) {
			LOG.warning(e.getMessage());
		}
		return null;
	}


    //从cas中获取用户名
	public static String getAccountNameFromCas(HttpServletRequest request) {
		Assertion assertion = (Assertion) request.getSession().getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);
		if (assertion != null) {
			AttributePrincipal principal = assertion.getPrincipal();
			return principal.getName();
		} else {
			return null;
		}
	}

	public static void main(final String[] args) {
		final String server = "http://192.168.1.62:8443/cas/v1/tickets";
		final String username = "zhangfei2";
		final String password = "123456";
		final String service = "http://127.0.0.1:8888/login";
		LOG.info(getTicket(server, username, password, service));
	}
}
