package com.qmth.teachcloud.cas.util.supwisdom;

import com.qmth.teachcloud.cas.util.supwisdom.utils.Base64Utils;
import com.qmth.teachcloud.cas.util.supwisdom.utils.BooleanUtils;
import com.qmth.teachcloud.cas.util.supwisdom.utils.HttpRequestUtils;
import com.qmth.teachcloud.cas.util.supwisdom.utils.StringUtils;
import com.qmth.teachcloud.exchange.common.contant.SystemConstant;
import com.qmth.teachcloud.exchange.common.util.ServletUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class CasUtils {
    /**
     * 判断是否已经登录过
     */
    public static boolean isLogin(HttpSession session) {
        Object isLogin = session.getAttribute(Constants.LOGIN_KEY);
        return BooleanUtils.toBoolean(String.valueOf(isLogin));
    }

    /**
     * 获取TargetUrl
     */
    public static String getTargetUrl() {
        HttpServletRequest request = ServletUtil.getRequest();
        String basePath = SystemConstant.getBasePath();

        // 获取请求中的targetUrl
        String targetUrl = request.getParameter(Constants.TARGET_URL_KEY);

        if (StringUtils.isEmpty(targetUrl)) {
            // 若不存在，则使用默认页面作为targetUrl
            targetUrl = basePath + Constants.DEF_TARGET_URI;
        } else {
            // 判断target是否编码
            if (targetUrl.startsWith(Constants.BASE64_PREFIX)) {
                targetUrl = targetUrl.substring(Constants.BASE64_PREFIX.length());
                targetUrl = Base64Utils.decodeBase64Str(targetUrl);
            }
        }
        return targetUrl;
    }

    /**
     * 判断票据是否存在
     */
    public static boolean hasTicket() {
        HttpServletRequest request = ServletUtil.getRequest();
        Object ticket = request.getParameter(Constants.TICKET_KEY);

        // System.out.println("ticket = " + ticket);
        return ticket != null && !StringUtils.isEmpty(String.valueOf(ticket));
    }

    public static String getURLEncodeServiceUrl()
            throws UnsupportedEncodingException {
        // 编码成系统可识别的加密串
        String targetUrl = getTargetUrl();
        String base64TargetUrl = Base64Utils.encodeBase64Str(targetUrl);
        String serviceUrlRoot = SystemConstant.getBasePath() + Constants.SSO_LOGIN_URI;
        String serviceUrl = serviceUrlRoot + SystemConstant.GET_UNKNOWN + Constants.TARGET_URL_KEY + SystemConstant.GET_EQUAL + Constants.BASE64_PREFIX + base64TargetUrl;
        return URLEncoder.encode(serviceUrl, SystemConstant.CHARSET_NAME);
    }

    /**
     * 获取Cas登录Url 登录成功后返回票据
     */
    public static String getLoginUrl() throws UnsupportedEncodingException {
        String encodeServiceUrl = getURLEncodeServiceUrl();
        return Constants.CAS_LOGIN_URL + SystemConstant.GET_UNKNOWN + SystemConstant.SERVICE_KEY + SystemConstant.GET_EQUAL + encodeServiceUrl;
    }

    /**
     * 获取校验票据Url
     */
    public static String getServiceValidateUrl() throws UnsupportedEncodingException {
        HttpServletRequest request = ServletUtil.getRequest();
        String encodeServiceUrl = getURLEncodeServiceUrl();
        Object ticket = request.getParameter(Constants.TICKET_KEY);
        return Constants.CAS_VALIDATE_URL + SystemConstant.GET_UNKNOWN + Constants.TICKET_KEY
                + SystemConstant.GET_EQUAL + ticket + SystemConstant.GET_SYMBOL + SystemConstant.SERVICE_KEY + SystemConstant.GET_EQUAL
                + encodeServiceUrl;
    }

    public static LoginUser getLoginUser() throws IOException {
        String serviceValidateUrl = getServiceValidateUrl();
        String casUserInfoXml = HttpRequestUtils.doGet(serviceValidateUrl);
        casUserInfoXml = "<?xml version=\"1.0\" encoding=\"UTF8\"?>" + casUserInfoXml;
        return new LoginUser(casUserInfoXml);
    }

    /**
     * 获取登出地址
     */
    public static String getLogoutUrl() throws UnsupportedEncodingException {
        // 获取本次请求的根Path
        String loginUrlRoot = SystemConstant.getBasePath() + Constants.SSO_LOGIN_URI;
        String encodeLoginUrlRoot = URLEncoder.encode(loginUrlRoot, SystemConstant.CHARSET_NAME);
        return Constants.CAS_LOGOUT_URL + SystemConstant.GET_UNKNOWN + SystemConstant.SERVICE_KEY + SystemConstant.GET_EQUAL + encodeLoginUrlRoot;
    }

    /**
     * 集成失败页
     */
    public static String getErrorUrl() throws UnsupportedEncodingException {
        return Constants.SSO_ERROR_URI;
    }

    /**
     * 写入单页面登录判断标志
     */
    public static void login(LoginUser loginUser, HttpSession session) {
        session.setAttribute(Constants.LOGIN_KEY, true);
        session.setAttribute(Constants.LOGIN_USER_KEY, loginUser);
    }

    /**
     * 移出单页面登录判断标志
     */
    public static void logout(HttpSession session) {
        session.removeAttribute(Constants.LOGIN_KEY);
        session.removeAttribute(Constants.LOGIN_USER_KEY);
    }
}
