package com.shr.controller;

import com.kingdee.shr.sso.client.ltpa.LtpaTokenManager;
import com.shr.config.ThreadLocalConfig;
import com.shr.utils.StringUtil;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @author Lnori
 */
@RestController
@RequestMapping("/api")
public class EasController {

    @GetMapping(value = "/eas/ssoLogin")
    public void easSsoLogin(HttpServletResponse response) throws IOException {
        //从EAS服务器上下载     server\profiles\server(1...n)\config\portalConfig\LtpaToken.properties
        File file2 = new File("src/main/resources/LtpaToken.properties");
        String configPath = file2.getAbsolutePath();

        //要跳转的url '//'代表首页
        String redirectTo = "//";
        //调用LtpaTokenManager,根据密钥生成用户令牌
        /*String ssoUsername = ThreadLocalConfig.get().get("ssoUsername").toString();
        if (StringUtil.isBlank(ssoUsername)) {
            return;
        }*/
        String ssoUsername = "administrator";
        String password = LtpaTokenManager.generate(ssoUsername, LtpaTokenManager.getDefaultLtpaConfig()).toString();
        System.out.println("password: " + password);

        //生成EAS单点登录地址
        String url = "http://172.16.1.67:8090/portal/index2sso.jsp?username=" + ssoUsername + "&password=" + password + "&redirectTo=" + redirectTo + "&isNotCheckRelogin=true";
        //验证Token
        LtpaTokenManager.isValid(password);
        System.out.println(url);

        response.sendRedirect(url);
    }

    @GetMapping(value = "/shr/ssoLogin")
    public String shrSsoLogin(String ssoUsername) throws IOException {
        //s-HR地址
        System.out.println("begin");
        String shrLocal = "http://10.10.12.21:8080/shr/home.do";
        String redirectTo = URLEncoder.encode(shrLocal);
        System.out.println("begin1");


        System.out.println("ssoUsername: " + ssoUsername);
        if (StringUtil.isBlank(ssoUsername)) {
            return "";
        }
        //String ssoUsername = "administrator";
        //根据密钥生成的密码串
        String password = LtpaTokenManager.generate(ssoUsername, LtpaTokenManager.getDefaultLtpaConfig(), "OTP").toString();
        System.out.println("password: " + password);

        //生成SHR单点登录地址
        String url = "http://10.10.12.21:8080/shr/OTP2sso.jsp?username=" + ssoUsername + "&password=" + password + "&redirectTo=" + redirectTo + "&userAuthPattern=OTP&isNotCheckRelogin=true";
        //验证Token
        LtpaTokenManager.isValid(password);
        System.out.println(url);

        return url;
    }


}
