package com.shr.filter;

import com.alibaba.fastjson.JSON;
import com.eetrust.security.plugin.MessageConstants;
import com.eetrust.security.plugin.SIDPlugin;
import com.shr.common.response.RestResponse;
import com.shr.utils.StringUtil;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Inori
 */
@WebServlet(urlPatterns = "/*")
public class VerifyTicketServlet extends HttpServlet {
    private static final long serialVersionUID = 4300219912599669959L;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) {
        String ticket = request.getParameter("ticket");
        if (StringUtil.isEmpty(ticket)) {
            this.writeResponse(response, "单点登录缺少登录票据[ticket]信息!");
            return;
        }

        // 认证服务器地址
        String authServerIp = "10.10.12.1:80";

        // 认证服务器端口
        String authServerPort = "80";

        // 业务系统编码
        String authAppCode = "OASys";

        SIDPlugin sid = new SIDPlugin(authServerIp, Integer.parseInt(authServerPort));
        int result = sid.Security_VerifyTicket(authAppCode, ticket);
        if (result == MessageConstants.SECURITY_SERVICE_SUCCESS) {
            // 票据验证成功, 获取用户唯一标识
            String passport = sid.getPassport();
            this.writeResponse(response, "单点登录成功! 用户唯一标识: " + passport);
        } else {
            // 认证失败, 获取错误编码
            String errorCode = sid.getErrorCode();

            // 认证失败, 获取错误信息
            String errorMsg = sid.getErrorMsg();
            this.writeResponse(response, "单点登录失败! 错误编码: " + errorCode + ", 错误信息: " + errorMsg);
        }
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    private void writeResponse(HttpServletResponse httpServletResponse, String message) {
        httpServletResponse.setHeader("Cache-Control", "no-store, max-age=0, no-cache, must-revalidate");
        httpServletResponse.addHeader("Cache-Control", "post-check=0, pre-check=0");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json;charset=UTF-8");

        RestResponse resp = RestResponse.fail(message).setCode(RestResponse.CODE_TOKEN_NOTFOUND);
        try (PrintWriter printWriter = httpServletResponse.getWriter()) {
            printWriter.write(JSON.toJSONString(resp));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
