package com.srs.framework.security.handle;


import com.srs.common.constant.Constants;
import com.srs.common.core.domain.model.LoginUser;
import com.srs.framework.config.properties.CasProperties;
import com.srs.framework.web.service.TokenService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

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

@Service
public class CasAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    protected final Log logger =   LogFactory.getLog(this.getClass());

    private RequestCache requestCache = new HttpSessionRequestCache();

    @Autowired
    private TokenService tokenService;

    @Autowired
    private CasProperties casProperties;

    /**
     * 令牌有效期（默认30分钟）
     */
    @Value("${token.expireTime}")
    private int expireTime;

//    @Override
//    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
//                                        Authentication authentication) throws ServletException, IOException {
//        String targetUrlParameter = getTargetUrlParameter();
//        String qqtype=request.getParameter("qqtype"); //判断是pc还是移动端请求
//        if (isAlwaysUseDefaultTargetUrl()
//                || (targetUrlParameter != null && StringUtils.hasText(request.getParameter(targetUrlParameter)))) {
//            requestCache.removeRequest(request, response);
//            super.onAuthenticationSuccess(request, response, authentication);
//            return;
//        }
//        clearAuthenticationAttributes(request);
//        LoginUser userDetails = (LoginUser) authentication.getPrincipal();
//        String token = tokenService.createToken(userDetails);
//        //往Cookie中设置token
//        Cookie casCookie = new Cookie(Constants.WEB_TOKEN_KEY, token);
//        casCookie.setMaxAge(expireTime * 600);
//        response.addCookie(casCookie);
//        response.setHeader("Access-Control-Allow-Origin","*");
//        response.setHeader("Access-Control-Allow-Methods","GET,POST,DELETE,PUT");
//        //Access-Control-Allow- Headers
//        casCookie.setPath("/");
//        casCookie.setDomain("gxsdxy.cn");
//        //设置后端认证成功标识
//        HttpSession httpSession = request.getSession();
//        httpSession.setAttribute(Constants.CAS_TOKEN, token);
//        //登录成功后跳转到前端登录页面
//        if(com.srs.common.utils.StringUtils.isNotNull(qqtype)){
//            String webindex="http://zhxg.gxsdxy.cn/hh/#/pages/index/index";
//            getRedirectStrategy().sendRedirect(request, response, casProperties.getWebUrl()+"?jwt="+token);
//        }else{
//            getRedirectStrategy().sendRedirect(request, response, casProperties.getWebUrl()+"?jwt="+token);
//        }
//    }

//    @Override
//    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
//                                        Authentication authentication) throws ServletException, IOException {
//        String targetUrlParameter = getTargetUrlParameter();
//        if (isAlwaysUseDefaultTargetUrl()
//                || (targetUrlParameter != null && StringUtils.hasText(request.getParameter(targetUrlParameter)))) {
//            requestCache.removeRequest(request, response);
//            super.onAuthenticationSuccess(request, response, authentication);
//            return;
//        }
//        clearAuthenticationAttributes(request);
//        LoginUser userDetails = (LoginUser) authentication.getPrincipal();
//        String token = tokenService.createToken(userDetails);
//        // 往Cookie中设置token
////        Cookie casCookie = new Cookie(Constants.WEB_TOKEN_KEY, token);
////        casCookie.setMaxAge(expireTime * 600);
////        response.addCookie(casCookie);
////        response.setHeader("Access-Control-Allow-Origin", "*");
////        response.setHeader("Access-Control-Allow-Methods", "GET,POST,DELETE,PUT");
////        // Access-Control-Allow-Headers
////        casCookie.setPath("/");
////        casCookie.setDomain("gxsdxy.cn");
//        // 设置后端认证成功标识
//        HttpSession httpSession = request.getSession();
//        httpSession.setAttribute(Constants.CAS_TOKEN, token);
//        // 登录成功后跳转到前端登录页面
//        if (isMobileDevice(request)) {
////            String webindex = "http://zhxg.gxsdxy.cn/wab/#/pages/index/index";
//            String waburl = casProperties.getWabUrl()+"?jwt="+ token;
//            getRedirectStrategy().sendRedirect(request, response, waburl);
//        } else {
//            String weburl = casProperties.getWebUrl() + "?jwt=" + token;
//            getRedirectStrategy().sendRedirect(request, response, weburl);
//        }
//    }

    @Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                    Authentication authentication) throws ServletException, IOException {
    String targetUrlParameter = getTargetUrlParameter();
    if (isAlwaysUseDefaultTargetUrl()
            || (targetUrlParameter != null && StringUtils.hasText(request.getParameter(targetUrlParameter)))) {
        requestCache.removeRequest(request, response);
        super.onAuthenticationSuccess(request, response, authentication);
        return;
    }
    clearAuthenticationAttributes(request);
    LoginUser userDetails = (LoginUser) authentication.getPrincipal();
    String token = tokenService.createToken(userDetails);

    // 设置后端认证成功标识
    HttpSession httpSession = request.getSession();
    httpSession.setAttribute(Constants.CAS_TOKEN, token);

    // 构造跳转 URL
    String redirectUrl;
    if (isMobileDevice(request)) {
        redirectUrl = casProperties.getWabUrl() + "?jwt=" + token;
    } else {
        redirectUrl = casProperties.getWebUrl() + "?jwt=" + token;
    }

    // 使用客户端 JS 跳转替代 sendRedirect
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter writer = response.getWriter();
    writer.write("<!DOCTYPE html>\n" +
                 "<html>\n" +
                 "<head>\n" +
                 "    <meta charset=\"UTF-8\">\n" +
                 "    <title>Redirecting...</title>\n" +
                 "    <script type=\"text/javascript\">\n" +
                 "        window.location.href = '" + redirectUrl + "';\n" +
                 "    </script>\n" +
                 "</head>\n" +
                 "<body>\n" +
                 "    <p>正在跳转，请稍候...</p>\n" +
                 "</body>\n" +
                 "</html>");
    writer.flush();
}


    private boolean isMobileDevice(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        if (userAgent == null) {
            return false;
        }
        return userAgent.matches("(?i).*\\b(mobi|android|iphone|ipad|ipod)\\b.*");
    }

}
