package yem.base.common.module.sso;

import kd.bos.login.thirdauth.ThirdSSOAuthHandler;
import kd.bos.login.thirdauth.UserAuthResult;
import kd.bos.login.thirdauth.UserProperType;

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

/**
 * @author zhouc
 * @date 2023/10/9 11:28
 * @className OtherSysSSOAuth
 * @description
 */
public class OtherSysSSOAuth implements ThirdSSOAuthHandler {

    private static String ERROR_USER = "errorUser";

    private static String SYS_INDEX_URL = "http://39.98.69.61:22248/ierp/login.html";

    private static String SYS_Loc_URL = "http://localhost:8080/ierp/login.html";

    /**
     * @return void
     * @Author zb
     * @Description 该方法是用户没有登录的时候插件需要转移到正确的登录地址
     * @Date 15:10 2022/2/21
     * @Param [request, response, s]
     **/
    @Override
    public void callTrdSSOLogin(HttpServletRequest request, HttpServletResponse response, String s) {
        //用户需要登录的地址
        String loginUrl = SYS_INDEX_URL;
        try {
            response.sendRedirect(loginUrl);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * @return kd.bos.login.thirdauth.UserAuthResult
     * @Author zb
     * @Description 该方法实现第三发插件认证及认证结果的返回
     * @Date 15:10 2022/2/21
     * @Param [httpServletRequest, httpServletResponse]
     **/
    @Override
    public UserAuthResult getTrdSSOAuth(HttpServletRequest request, HttpServletResponse response) {
        //此处code为第三方系统提供的相关鉴权码，如果需要接收其他参数也可自行获取
        String code = request.getParameter("code");
        UserAuthResult result = new UserAuthResult();
        result.setSucess(false);
        //这里编写自己的登录逻辑，判断是否登陆成功，并填写正确的返回类型和返回值
        try {
            String userName = "";
            //测试直接进入通道，此处为方便测试编写的，传入这个code就直接给set一个用户名登录进去了，正式一定记得注释掉
            if ("001".equals(code)) {
                userName = "18791337254";
                result.setUserType(UserProperType.Mobile);
                result.setUser(userName);
                result.setSucess(true);
            }else {
                String requestURL = request.getRequestURL().toString();
                if (requestURL.contains("http://localhost") || requestURL.contains("http://127.0.0.1")) {
                    response.sendRedirect(SYS_Loc_URL);
                } else{
                    response.sendRedirect(SYS_INDEX_URL);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}
