<%@ page language="java" contentType="text/html; charset=UTF-8" %>

<%@ page import="weaver.general.Util,weaver.conn.RecordSet" %>
<%@ page import="weaver.integration.logging.Logger"%>
<%@ page import="weaver.integration.logging.LoggerFactory"%>
<%@ page import="java.io.IOException" %>
<%@ page import="java.io.BufferedReader" %>
<%@ page import="java.io.OutputStreamWriter" %>
<%@ page import="java.net.URL" %>
<%@ page import="java.io.InputStreamReader" %>
<%@ page import="java.net.URLConnection" %>
<%@ page import="org.apache.commons.lang3.StringUtils" %>
<%@ page import="weaver.interfaces.HrmTransferDao" %>
<%@ include file="/systeminfo/init_wev8.jsp" %>

<%
    Logger log = LoggerFactory.getLogger();

    RecordSet rs = new RecordSet();

    String workflowId = request.getParameter("workflowid");
    String sysId = request.getParameter("sysid");
	String isMsg = Util.null2String(request.getParameter("_weaverofsmsg"));

    int userId = user.getUID() ;
    String appURL ;
    if(StringUtils.isNotBlank(workflowId)){
        //新建异构系统
        log.error("workflowid="+workflowId);
        rs.executeQuery("select * from ofs_workflow where workflowid = ?",workflowId);
        rs.next();
        appURL = rs.getString("APPCWURL");
        if ("".equals(Util.null2String(sysId))){
            sysId = rs.getString("SYSID");
        }
    }else{
        //访问异构系统流程
        String todoDataId = request.getParameter("tododataid");
        log.error("todoDataId="+todoDataId);
        String isRemark = request.getParameter("isremark");
        log.error("isRemark="+isRemark);

        if( "0".equals(isRemark) || "8".equals(isRemark)){
            rs.executeQuery("select * from ofs_todo_data where id = ?",todoDataId);
            rs.next();
            appURL =  Util.null2String(rs.getString("appurlsrc"));
            if ("".equals(Util.null2String(sysId))){
                sysId = rs.getString("SYSID");
            }
        }else{
            rs.executeQuery("select * from ofs_done_data where id = ?",todoDataId);
            rs.next();
            appURL =  Util.null2String(rs.getString("appurlsrc"));
            if ("".equals(Util.null2String(sysId))){
                sysId = rs.getString("SYSID");
            }
        }
    }

    rs.executeQuery("select * from ofs_sysinfo where sysid = ?" , sysId);
    if(rs.next()){
        String prefixURL = Util.null2String(rs.getString("Appprefixurl"));
        String hrmTransRule = Util.null2String(rs.getString("HRMTRANSRULE"));//人员转换关系

        HrmTransferDao hrmTransferDao = new HrmTransferDao();
        String loginId = hrmTransferDao.getHrmResourceIdByHrmTransRule(hrmTransRule, Util.null2String(userId));

        String token = this.getToken(prefixURL , loginId) ;
		if ("".equals(token)){
			out.println("get Token is null ");
			return ;
		}
		if (token.contains(":")){
			out.println("get Token is err : " + token);
			return ;
		}
        String toURL = this.getURL(prefixURL , appURL , token , isMsg) +"&ofsComeFrom=e9";
        log.error("APP端访问异构系统地址："+toURL);
%>
<script type="text/javascript">

    location.replace('<%=toURL%>');

</script>
<%

    }else{
        log.error("根据标识："+sysId+"未查询到数据");
        return;
    }


%>



<%!
    Logger log = LoggerFactory.getLogger();

    private String getURL(String prefixURL , String toURL , String token, String isMsg){
        StringBuilder url = new StringBuilder() ;
        if(toURL.startsWith("http://") || toURL.startsWith("https://")){
            url.append(toURL);
        }else{
            url.append(prefixURL).append(toURL);
        }
        if(url.toString().contains("#")){
            StringBuilder ssoToken = new StringBuilder("&ssoToken=");
            ssoToken.append(token) ;
			if(!"".equals(isMsg)){
				ssoToken.append("&_weaverofsmsg=1") ;
			}
            int i = url.toString().indexOf("#") ;
            url.insert(i, ssoToken) ;
        }else{
            if(toURL.contains("?")){
                url.append("&");
            }else{
                url.append("?");
            }
            url.append("ssoToken=").append(token) ;
			if(!"".equals(isMsg)){
				url.append("&_weaverofsmsg=1") ;
			}
        }
        return url.toString() ;
    }


    private String getToken(String prefixURL ,String loginId){

        //TODO 1 调用e9接口获取token
        OutputStreamWriter oout = null;
        BufferedReader iin = null;
        String result = "";
        try {
            // 发送请求参数
            URL realUrl = new URL(prefixURL + "/ssologin/getToken?appid=fore9&loginid=" + java.net.URLEncoder.encode(loginId, "UTF-8"));
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "application/json");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            oout = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");

            oout.write("");
            // flush输出流的缓冲
            oout.flush();
            // 定义BufferedReader输入流来读取URL的响应
            iin = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = iin.readLine()) != null) {
                result += line;
            }
            log.error("result：" + result);
        } catch (Exception e) {
            log.error("发送 POST 请求出现异常！", e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (oout != null) {
                    oout.close();
                }
                if (iin != null) {
                    iin.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result ;
    }

%>