package org.jeecg.modules.cas.util;

import com.alibaba.fastjson.JSONObject;
import org.jasig.cas.client.authentication.AuthenticationRedirectStrategy;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class CustomAuthRedirectStrategy implements AuthenticationRedirectStrategy {
    private final int vueRedirectCasStatus = 479;
    private final String vueRedirectCasText = "重定向CAS登录";

    @Override
    public void redirect(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String s) throws IOException {
        httpServletResponse.setHeader("content-type", "text/html;charset=UTF-8");
        httpServletResponse.setHeader("Access-control-Allow-Origin", "*");
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "*");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", "*");
        httpServletResponse.setCharacterEncoding("UTF-8");
        PrintWriter out = httpServletResponse.getWriter();
        httpServletResponse.setStatus(vueRedirectCasStatus);
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("status", vueRedirectCasStatus);
        jsonObject.put("message", vueRedirectCasText);
        String res = jsonObject.toJSONString();
        out.write(res);
    }
}
