<%@ 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="org.apache.commons.lang3.StringUtils" %>
<%@ page import="weaver.interfaces.outter.CheckIpNetWorkForUpcoming" %>
<%@ page import="weaver.file.Prop" %>
<%@ page import="com.alibaba.fastjson.JSONObject" %>
<%@ page import="java.io.*" %>
<%@ page import="com.engine.common.biz.EncryptConfigBiz" %>
<%@ include file="/systeminfo/init_wev8.jsp" %>

<%
    Logger log = LoggerFactory.getLogger();

    RecordSet rs = new RecordSet();

    String type = Util.null2String(request.getParameter("type")) ;

    String workflowId = request.getParameter("workflowid");
    String sysId = request.getParameter("sysid");

    String forURL ;
    if(StringUtils.isNotBlank(workflowId)){
        //新建异构系统
        log.error("workflowid="+workflowId);
        rs.executeQuery("select * from ofs_workflow where workflowid = ?",workflowId);
        rs.next();
        if ("pc".equalsIgnoreCase(type)){
            forURL = rs.getString("pccwurl");
        }else{
            forURL = 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();
            if ("pc".equalsIgnoreCase(type)){
                forURL =  Util.null2String(rs.getString("pcurlsrc"));
            }else{
                forURL =  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();
            if ("pc".equalsIgnoreCase(type)){
                forURL =  Util.null2String(rs.getString("pcurlsrc"));
            }else{
                forURL =  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 ;
        String sysCode = rs.getString("syscode") ;

        if ("pc".equalsIgnoreCase(type)){
            //自动内外网登录
            String clientIp = Util.getIpAddr(request);
            boolean notInOuter = this.notInOuter(sysCode , clientIp);

            if (notInOuter){
                prefixURL = Util.null2String(rs.getString("pcouterfixurl"));
            }else{
                prefixURL = Util.null2String(rs.getString("pcprefixurl"));
            }
        }else{
            prefixURL = Util.null2String(rs.getString("Appprefixurl"));
        }

        String mobile = user.getMobile();
        //将加密数据进行解密
        mobile = EncryptConfigBiz.getDecryptData(mobile);
        log.error("获取到的用户手机号码为：  "+mobile);
        String result = this.getToken(mobile , sysCode) ;
        if ("".equals(Util.null2String(result))){
            out.println("返回token为 null 无法跳转");
            return;
        }
        JSONObject json = JSONObject.parseObject(result) ;
        if (!"0".equals(Util.null2String(json.getString("errcode")))){
            out.println("返回 报文异常:"+result);
            log.error("返回 报文异常:"+result);
            return;
        }
        String token = Util.null2String(json.getString("etLoginToken")) ;
        if ("".equals(token)){
            out.println("获取token为空 ："+result);
            log.error("获取token为空 ："+result);
            return;
        }
        String toURL = this.getURL(prefixURL , forURL , token) ;
        String typeName ;
        if ("pc".equalsIgnoreCase(type)){
            typeName = "PC端" ;
        }else{
            typeName = "APP端" ;
        }
        log.error(typeName +"访问异构系统地址："+toURL);
%>
<script type="text/javascript">
    window.location.replace('<%=toURL%>');

</script>
<%

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


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

    //外网地址返回 true ,内网 false
    private boolean notInOuter(String sysCode , String clientIp){

        //0代表不开启，则所有通过内网访问
        //1代表开启，并且有设置网段
        //2代表开启，但是没有设置网段
        RecordSet rs = new RecordSet();
        rs.executeQuery("SELECT * FROM autologin_status WHERE syscode= ? " , sysCode) ;
        if (rs.next()){
            String status = Util.null2String(rs.getString("status"),"0");
            if ("0".equals(status)){
                return false ;
            }else if ("2".equals(status)){
                return true ;
            }
        }
        //检测IP
        CheckIpNetWorkForUpcoming checkIpNetWorkForUpcoming = new CheckIpNetWorkForUpcoming();
        return checkIpNetWorkForUpcoming.checkIpSeg(clientIp);//不在网段策略中 返回true
    }

    private String getURL(String prefixURL , String toURL , String token) {
        StringBuilder url = new StringBuilder(prefixURL) ;
        url.append("/papi/open/singleSignon?singleToken=")
                .append(token).append("&oauthType=singlesign&redirect_uri=") ;
        try{
            url.append(java.net.URLEncoder.encode(toURL, "UTF-8")) ;
        }catch (Exception e){
            e.printStackTrace();
        }
        return url.toString() ;
    }


    private String getToken(String account , String sysCode){

        //TODO 1 调用e9接口获取token
        OutputStreamWriter oout = null;
        BufferedReader iin = null;
        String result = "";
        try {
            String prefixURL = Prop.getPropValue("ofsForEteams" , "url") ;
            String appKey = Prop.getPropValue("ofsForEteams" , sysCode+"_appKey") ;
            String security = Prop.getPropValue("ofsForEteams" , sysCode+"_security") ;
            // 发送请求参数
            URL realUrl = new URL(prefixURL + "?app_key="+appKey+"&app_security="+security+"&account="+account);
            // 打开和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 ;
    }
%>