package com.qy.sso.bamboocloud.filter.validate;

import com.kingdee.bos.sso.client.util.FilterUtil;
import com.kingdee.shr.base.syssetting.exception.SHRWebException;
import com.qy.sso.bamboocloud.validation.ZYPortalServiceTicketValidator;
import org.jasig.cas.client.Protocol;
import org.jasig.cas.client.proxy.ProxyGrantingTicketStorage;
import org.jasig.cas.client.proxy.ProxyGrantingTicketStorageImpl;
import org.jasig.cas.client.validation.*;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;

/**
 * @Description 竹云用户信息校验过滤器
 * @Date 2024/9/23 16:01
 * @Created by Heyuan
 */
public class ZYTicketValidationFilter extends Cas20ProxyReceivingTicketValidationFilter {
    //com.kingdee.shr.base.syssetting.web.filter.SHRTicketValidationFilter
    private String getTokenPath;//获取授权接口,相对地址
    private String getUserInfoPath;//获取用户信息接口,相对地址
    private String clientSecret;
    private String grantType;
    private String clientId;
    private String responseType;

    private boolean getServerNameFromRequest;
    private boolean getServerLoginUrlFromRequest;
    private String casServerUrlPrefix;
    private String acceptAnyProxy;
    private String allowedProxyChains;
    private String proxyCallbackUrl;
    private boolean renew;
    private String encoding;
    private Map<String, String> additionalParameters = new HashMap();
    private ProxyGrantingTicketStorage proxyGrantingTicketStorage = new ProxyGrantingTicketStorageImpl();


    public ZYTicketValidationFilter() {
        this(Protocol.ZY);
        //this.defaultServiceTicketValidatorClass = Cas20ServiceTicketValidator.class;
        this.defaultProxyTicketValidatorClass = Cas20ProxyTicketValidator.class;
    }

    protected ZYTicketValidationFilter(Protocol protocol) {
        super(protocol);
        this.proxyGrantingTicketStorage = new ProxyGrantingTicketStorageImpl();
    }

    /**
     * 校验成功
     *
     * @param request
     * @param response
     * @param assertion
     */
    protected void onSuccessfulValidation(HttpServletRequest request,
                                          HttpServletResponse response,
                                          Assertion assertion) {
        super.onSuccessfulValidation(request, response, assertion);
        try {
            //初始化会话数据
            this.initializeSessionData(request, response);
        } catch (SHRWebException var5) {
            throw new RuntimeException(var5);
        }
    }

    /**
     * 初始化会话数据
     *
     * @param request
     * @param response
     * @throws SHRWebException
     */
    private void initializeSessionData(HttpServletRequest request,
                                       HttpServletResponse response) throws SHRWebException {
        HttpSession session = request.getSession();
        try {
            if (session != null) {
                session.setAttribute("contextPath", request.getContextPath());
                session.setAttribute("sessionCreateTime", session.getCreationTime());
            } else {
                //重定向到登出页面
                response.sendRedirect("/shr/shr_loginout/logout.do");
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                if (session != null) {
                    //会话失效
                    session.invalidate();
                }
                //重定向到登出页面
                response.sendRedirect("/shr/shr_loginout/logout.do");
            } catch (IOException var6) {
                var6.printStackTrace();
            }
        }
    }


    /**
     * 获取身份校验器
     *
     * @return
     */
    protected TicketValidator getTicketValidator() {
        //Cas20ServiceTicketValidator
        ZYPortalServiceTicketValidator validator = new ZYPortalServiceTicketValidator();
        validator.setClientId(this.clientId);
        validator.setClientSecret(this.clientSecret);
        validator.setGrantType(this.grantType);
        validator.setResponseType(this.responseType);
        validator.setGetTokenPath(this.getTokenPath);
        validator.setGetUserInfoPath(this.getUserInfoPath);
        return validator;
    }

    /**
     *
     * @param request
     * @return
     */
    protected String retrieveTicketFromRequest(HttpServletRequest request) {
        try {
            if (FilterUtil.isUnFilter(request)) {
                return null;
            }
            this.constructLoginUrl(request);
            this.constructServerName(request);
            this.setTicketValidator(this.getTicketValidator());
        } catch (MalformedURLException var3) {
            var3.printStackTrace();
        }
        return super.retrieveTicketFromRequest(request);
    }

    /**
     * 构建登录地址
     *
     * @param request
     */
    private void constructLoginUrl(ServletRequest request) {
        if (this.getServerLoginUrlFromRequest) {
            try {
                URL contextURL = new URL(this.casServerUrlPrefix);
                URL destURL = new URL(contextURL.getProtocol(), request.getServerName(), request.getServerPort(), contextURL.getFile());
                this.casServerUrlPrefix = destURL.toString();
            } catch (MalformedURLException var4) {
                var4.printStackTrace();
            }
        }

    }

    /**
     * 构建服务地址   ip:port
     *
     * @param request
     * @return
     */
    private void constructServerName(ServletRequest request) {
        if (this.getServerNameFromRequest) {
            StringBuilder serverName = new StringBuilder();
            serverName.append(request.getServerName());
            serverName.append(":");
            serverName.append(request.getServerPort());
            this.setServerName(serverName.toString());
        }
    }


    public void setGetTokenPath(String getTokenPath) {
        this.getTokenPath = getTokenPath;
    }

    public void setGetUserInfo(String getUserInfoPath) {
        this.getUserInfoPath = getUserInfoPath;
    }

    public void setClientSecret(String clientSecret) {
        this.clientSecret = clientSecret;
    }

    public void setGrantType(String grantType) {
        this.grantType = grantType;
    }

    public void setClientId(String clientId) {
        this.clientId = clientId;
    }

    public void setResponseType(String responseType) {
        this.responseType = responseType;
    }

    public String getGetTokenPath() {
        return getTokenPath;
    }

    public String getGetUserInfoPath() {
        return getUserInfoPath;
    }

    public void setGetUserInfoPath(String getUserInfoPath) {
        this.getUserInfoPath = getUserInfoPath;
    }

    public String getClientSecret() {
        return clientSecret;
    }

    public String getGrantType() {
        return grantType;
    }

    public String getClientId() {
        return clientId;
    }

    public String getResponseType() {
        return responseType;
    }

    public final void setGetServerNameFromRequest(boolean getServerNameFromRequest) {
        this.getServerNameFromRequest = getServerNameFromRequest;
    }

    public final void setGetServerLoginUrlFromRequest(boolean getServerLoginUrlFromRequest) {
        this.getServerLoginUrlFromRequest = getServerLoginUrlFromRequest;
    }

    public final void setCasServerUrlPrefix(String casServerUrlPrefix) {
        this.casServerUrlPrefix = casServerUrlPrefix;
    }

    public final void setAcceptAnyProxy(String acceptAnyProxy) {
        this.acceptAnyProxy = acceptAnyProxy;
    }

    public final void setAllowedProxyChains(String allowedProxyChains) {
        this.allowedProxyChains = allowedProxyChains;
    }

    public final void setProxyCallbackUrl(String proxyCallbackUrl) {
        this.proxyCallbackUrl = proxyCallbackUrl;
    }

    public final void setRenew(boolean renew) {
        this.renew = renew;
    }

    public final void setEncoding(String encoding) {
        this.encoding = encoding;
    }
}
