<%@ page import="com.alibaba.fastjson.JSONObject" %>
<%@ page import="weaver.conn.RecordSet" %>
<%@ page import="weaver.general.Util" %>
<%@ page import="weaver.general.BaseBean" %>
<%@ page import="weaver.general.MD5" %>
<%@ page import="org.apache.http.client.methods.HttpRequestBase" %>
<%@ page import="org.apache.commons.collections.MapUtils" %>
<%@ page import="java.io.IOException" %>
<%@ page import="org.apache.http.client.methods.HttpPost" %>
<%@ page import="org.apache.http.entity.StringEntity" %>
<%@ page import="org.apache.http.Consts" %>
<%@ page import="org.apache.http.impl.client.CloseableHttpClient" %>
<%@ page import="org.apache.http.client.methods.CloseableHttpResponse" %>
<%@ page import="org.apache.http.HttpEntity" %>
<%@ page import="org.apache.http.util.EntityUtils" %>
<%@ page import="org.apache.http.StatusLine" %>
<%@ page import="javax.net.ssl.SSLContext" %>
<%@ page import="org.apache.http.conn.socket.ConnectionSocketFactory" %>
<%@ page import="org.apache.http.config.Registry" %>
<%@ page import="org.apache.http.config.RegistryBuilder" %>
<%@ page import="org.apache.http.conn.socket.PlainConnectionSocketFactory" %>
<%@ page import="org.apache.http.conn.ssl.SSLConnectionSocketFactory" %>
<%@ page import="org.apache.http.conn.ssl.NoopHostnameVerifier" %>
<%@ page import="org.apache.http.impl.conn.PoolingHttpClientConnectionManager" %>
<%@ page import="org.apache.http.impl.client.HttpClients" %>
<%@ page import="java.security.NoSuchAlgorithmException" %>
<%@ page import="java.security.KeyManagementException" %>
<%@ page import="javax.net.ssl.X509TrustManager" %>
<%@ page import="java.security.cert.CertificateException" %>
<%@ page import="javax.net.ssl.TrustManager" %>
<%@ page import="org.apache.commons.lang3.StringUtils" %>
<%@ page import="java.util.*" %>
<%@ page import="com.alibaba.fastjson.JSON" %>
<%@ page contentType="text/html;charset=UTF-8" %>
<%
    BaseBean bb = new BaseBean();

    String path = "/v2.0/department";
    String url = "http://v2-api.delicloud.com"+path;

    try {

        String key = bb.getPropValue("deliCloud","key");
        String secret = bb.getPropValue("deliCloud","secret");
        out.print("key:"+key+"</br>");
        out.print("secret:"+secret+"</br>");

        if(StringUtils.isNotBlank(key) && StringUtils.isNotBlank(secret)){
            String sjc = String.valueOf(Calendar.getInstance().getTimeInMillis());
            String appSig = getAppSigData(path,key,secret,sjc);

            out.print("sjc:"+sjc+"</br>");
            out.print("appSig:"+appSig+"</br>");

            Map<String, String> heads = new HashMap<String, String>();
            heads.put("App-Key", key);
            heads.put("App-Timestamp", sjc);
            heads.put("App-Sig", appSig);
            heads.put("Api-Module", "CHECKIN");
            heads.put("Api-Cmd", "checkin_query");

            List<Map<String,String>> list = getTopSubcompanyList();
            for(int i=0;i<list.size();i++){
                Map<String,String> map = list.get(i);
                String subcompanyid = map.get("subcompanyid");
                String subcompanyname = map.get("subcompanyname");

                Map<String, Object> dataMap = new HashMap<String, Object>();
                dataMap.put("department_ext_id", subcompanyid);
                dataMap.put("name", subcompanyname);
                dataMap.put("p_ext_id", "");

                out.print("headers:"+JSONObject.toJSONString(heads)+"</br>");
                out.print("body:"+JSONObject.toJSONString(dataMap)+"</br>");

                bb.writeLog("headers:" + JSONObject.toJSONString(heads));
                bb.writeLog("body:" + JSONObject.toJSONString(dataMap));

//                String back = doPostJsonRequest(url, heads, JSON.toJSONString(dataMap));
//                bb.writeLog("response:" + back);
//                out.print("response:"+back+"</br>");
//                JSONObject backObj = JSONObject.parseObject(back);
//                String code = backObj.getString("code");
//                String data = backObj.getString("data");
//                out.print("code:"+code+"</br>");
//                if ("0".equals(code)) {
//                    bb.writeLog("新接口调用成功");
//                    JSONObject dataObj = JSONObject.parseObject(data);
//                    out.print("dataObj:"+dataObj.toJSONString()+"</br>");
//                } else {
//                    bb.writeLog("接口调用失败");
//                    out.print("接口调用失败");
//                }
            }

        }
    } catch (Exception e) {
        bb.writeLog("数据异常!");
        bb.writeLog(e.getMessage());
    }

%>

<%!

    /***
     *
     * @return
     */
    public List<Map<String,String>> getTopSubcompanyList(){
        List<Map<String,String>> list = new ArrayList<Map<String,String>>();
        Map<String,String> map = null;
        RecordSet rs = new RecordSet();
        String sql =" select id,subcompanyname,subcompanydesc \n" +
                    " from HrmSubCompany where supsubcomid = 0 \n" +
                    " and (canceled is null or canceled  = 0)" ;
        rs.executeQuery(sql);
        while (rs.next()){
            String id = rs.getString("id");
            String subcompanyname = rs.getString("subcompanyname");

            map = new HashMap<String,String>();
            map.put("subcompanyid",id);
            map.put("subcompanyname",subcompanyname);
            list.add(map);
        }
        return list;
    }

    /***
     *
     * @param path
     * @param key
     * @param sercet
     * @param sjc
     * @return
     */
    public String getAppSigData(String path,String key,String sercet,String sjc){

        String appSig = "";
        BaseBean bb = new BaseBean();
        try{
            MD5 md5 = new MD5();
            String all = path + sjc + key + sercet;
            String sig = md5.getMD5ofStr(all);
            bb.writeLog("sig:" + sig);
            Scanner sc = new Scanner(md5.getMD5ofStr(all));
            String str = sc.next();
            char[] arrays = str.toCharArray();

            for (int i = 0; i < arrays.length; i++) {
                char c1 = arrays[i];
                if (c1 >= 65 && c1 <= 90) {
                    char c2 = toLowerCase(c1);//如果输入是大写  ,则调用toLowerCase方法
                    appSig = appSig + c2;
                } else {
                    appSig = appSig + c1;
                }
            }
            bb.writeLog("appSig:" + appSig);
        }catch (Exception e){

        }
        return appSig;
    }


    /***
     *
     * @param c1
     * @return
     */
    public static char toLowerCase(char c1){
        int a = (int) c1;//将接收到的小写字符c1转换成int类型的数据给a
        int b =a+32;     //a+32得出大写写对应小写的ascll数值
        char bb = (char)b;//最后将b转换成char类型字符给bb
        return bb;        //返回bb；就是返回字母小写的字符

    }


    private static void prepareHeaders(HttpRequestBase httpRequest, Map<String, String> headers) {
        if (!MapUtils.isEmpty(headers)) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpRequest.addHeader(entry.getKey(), entry.getValue());
            }
        }
    }


    public static String doPostJsonRequest(String url, Map<String, String> headers, String jsonStr) throws IOException {
        HttpPost httpost = new HttpPost(url);
        prepareHeaders(httpost, headers);
        StringEntity entity = new StringEntity(jsonStr, Consts.UTF_8);
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httpost.setEntity(entity);
        return sendRequest(httpost);
    }


    private static String sendRequest(HttpRequestBase httpRequest) throws IOException {
        String result = null;
        CloseableHttpClient httpclient = creteClient();
        try (CloseableHttpResponse resp = httpclient.execute(httpRequest)) {
            HttpEntity entity = resp.getEntity();
            result = (entity == null ? null : EntityUtils.toString(entity, Consts.UTF_8));
            StatusLine statusLine = resp.getStatusLine();
            if (statusLine.getStatusCode() >= 300) {
                EntityUtils.consume(entity);
//                String errorMsg = Strings.lenientFormat("Http status abnormal-status code is %s, response is %s", resp.getStatusLine().getStatusCode(), result);
            }
        }
        return result;
    }


    public static CloseableHttpClient creteClient() {
        //采用绕过验证的方式处理https请求
        try {
            SSLContext sslcontext = createIgnoreVerifySSL();
            // 设置协议http和https对应的处理socket链接工厂的对象
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.INSTANCE)
                    .register("https", new SSLConnectionSocketFactory(sslcontext, NoopHostnameVerifier.INSTANCE))
                    .build();
            PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            HttpClients.custom().setConnectionManager(connManager);

            //创建自定义的httpclient对象
            CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
            return client;
        } catch (Exception e) {
            return null;
        }

    }


    /**
     * 绕过验证
     *
     * @return
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     */
    public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
        SSLContext sc = SSLContext.getInstance("SSLv3");

        // 实现一个X509TrustManager接口，用于绕过验证，不用修改里面的方法
        X509TrustManager trustManager = new X509TrustManager() {
            @Override
            public void checkClientTrusted(
                    java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                    String paramString) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(
                    java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                    String paramString) throws CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        sc.init(null, new TrustManager[]{trustManager}, null);
        return sc;
    }
%>

