<%@ 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/employee";
    String url = "http://v2-api.delicloud.com"+path;
    String userid = request.getParameter("userid");
    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");

            Map<String,String> userMap = getUserData(userid);
            String workcode = Util.null2String(userMap.get("workcode"));
            String lastname = Util.null2String(userMap.get("lastname"));
            String mobile = Util.null2String(userMap.get("mobile"));
            String deptcode = Util.null2String(userMap.get("departmentcode"));
            String deptname = Util.null2String(userMap.get("departmentname"));
            String deptid = Util.null2String(userMap.get("departmentid"));
            String subcompanyid1 = Util.null2String(userMap.get("subcompanyid1"));

            out.print("workcode:"+workcode+ "</br>");
            out.print("lastname:"+lastname+ "</br>");
            out.print("mobile:"+mobile+ "</br>");

            out.print("deptcode:"+deptcode+ "</br>");
            out.print("deptname:"+deptname+ "</br>");
            out.print("deptid:"+deptid+ "</br>");
            out.print("subcompanyid1:"+subcompanyid1+ "</br>");

            int errorcount = 0;
            int errorcount1 = updateSubcompanyData(subcompanyid1,key,secret);
            errorcount = errorcount + errorcount1 ;
            out.print("errorcount1:"+errorcount1+"</br>");

            int errorcount2 = updateDeptData(deptid,key,secret);
            errorcount = errorcount + errorcount2 ;
            out.print("errorcount2:"+errorcount2+"</br>");

            if(errorcount == 0){

                Map<String, Object> dataMap = new HashMap<String, Object>();
                dataMap.put("employee_ext_id", workcode);
                dataMap.put("name", lastname);
                dataMap.put("mobile", mobile);
                dataMap.put("employee_num", workcode);

                List<Map<String, Object>> department_infolist = new ArrayList<Map<String, Object>>();
                Map<String, Object> department_infos = new HashMap<String, Object>();
                department_infos.put("ext_id",deptcode);
                department_infos.put("title",deptname);
                department_infolist.add(department_infos);
                dataMap.put("department_infos", department_infolist);

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

                String back = doPostJsonRequest(url, heads, JSON.toJSONString(dataMap));
                bb.writeLog("response:" + back);
                out.print("employee-response:" + back + "</br>");
                JSONObject backObj = JSONObject.parseObject(back);
                String code = backObj.getString("code");
                String data = backObj.getString("data");
                out.print("employee-code:" + code + "</br>");
                if (!"0".equals(code)) {
                    errorcount++;
                }
            }
        }
    } catch (Exception e) {
        bb.writeLog("数据异常!");
        bb.writeLog(e.getMessage());
    }

%>

<%!

    public List<Map<String,String>> getSubcompanyListByParentid(String supsubcomid){
        List<Map<String,String>> list = new ArrayList<Map<String,String>>();
        Map<String,String> map = null;
        RecordSet rs = new RecordSet();

        String sql =" with tem_table(id,subcompanyname,supsubcomid,subcompanycode,curlevel) as (\n" +
                "   select id,subcompanyname,supsubcomid,1 as level \n" +
                "          from HrmSubCompany where id = " + supsubcomid +
                "   union all\n" +
                "   select a.id,a.subcompanyname,a.supsubcomid,subcompanycode,b.curlevel+1\n" +
                "   from HrmSubCompany a \n" +
                "   inner join tem_table  b on (a.id = b.supsubcomid)\n" +
                " )\n" +
                " select l.*,k.subcompanycode as supsubcompanycode from tem_table l " +
                " left join HrmSubCompany k on l.supsubcomid = k.id " ;

        rs.executeQuery(sql);
        while (rs.next()){
            String subcompanycode = rs.getString("subcompanycode");
            String subcompanyname = rs.getString("subcompanyname");
            String sup_subcomid = rs.getString("supsubcomid");
            String supsubcompanycode = rs.getString("supsubcompanycode");

            map = new HashMap<String,String>();
            map.put("subcompanycode",subcompanycode);
            map.put("subcompanyname",subcompanyname);
            map.put("supsubcomid",sup_subcomid);
            map.put("supsubcompanycode",supsubcompanycode);
            list.add(map);
        }

        if(list !=null && list.size() > 0){
            Collections.reverse(list);
        }

        return list;
    }


    public List<Map<String,String>> getDeptListByParentid(String supsubcomid){
        List<Map<String,String>> list = new ArrayList<Map<String,String>>();
        Map<String,String> map = null;
        RecordSet rs = new RecordSet();

        String sql =" with tem_table(id,departmentname,supdepid,departmentcode,subcompanyid1,curlevel) as(\n" +
                    "   select id,departmentname,supdepid,departmentcode,subcompanyid1,1 as level \n" +
                    "        from HrmDepartment where id =" + supsubcomid +
                    "   union all\n" +
                    "   select a.id,a.departmentname,a.supdepid,a.departmentcode,a.subcompanyid1,b.curlevel+1                          \n" +
                    "        from HrmDepartment  a \n" +
                    "   inner join tem_table b on (a.id = b.supdepid) \n" +
                    " )\n" +
                    " select p.*,k.departmentcode as supdeptcode,h.subcompanycode from tem_table p\n" +
                    " left join HrmDepartment k on p.supdepid = k.id " +
                    " left join hrmsubcompany h on h.id = p.subcompanyid1 " ;

        rs.executeQuery(sql);
        while (rs.next()){
            String departmentcode = rs.getString("departmentcode");
            String subcompanycode = rs.getString("subcompanycode");
            String departmentname = rs.getString("departmentname");
            String sup_depid = rs.getString("supdepid");
            String supdeptcode = rs.getString("supdeptcode");
            if(StringUtils.isBlank(supdeptcode)){
                supdeptcode = subcompanycode;
            }
            map = new HashMap<String,String>();
            map.put("departmentcode",departmentcode);
            map.put("departmentname",departmentname);
            map.put("supdepid",sup_depid);
            map.put("supdeptcode",supdeptcode);
            list.add(map);
        }

        if(list !=null && list.size() > 0){
            Collections.reverse(list);
        }

        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;
    }


    public Map<String,String> getUserData(String userid){

        Map<String,String> userMap = new HashMap<String,String>();
        String workcode = "";
        String departmentid = "";
        String subcompanyid1 = "";
        String departmentcode = "";
        String lastname = "";
        String mobile = "";
        String departmentname = "";

        RecordSet rs = new RecordSet();


        try{
            if(StringUtils.isNotBlank(userid)){
                String sql =" select t.workcode,t.departmentid,t.subcompanyid1,t.lastname,t.mobile,k.departmentcode,k.departmentname " +
                            " from hrmresource t inner join hrmdepartment k on k.id = t.departmentid" +
                            " where t.id = ? and t.status in (0,1,2,3) ";

                rs.executeQuery(sql,new Object[]{userid});
                if(rs.next()){
                    workcode = Util.null2String(rs.getString("workcode"));
                    departmentid = Util.null2String(rs.getString("departmentid"));
                    subcompanyid1 = Util.null2String(rs.getString("subcompanyid1"));
                    departmentcode = Util.null2String(rs.getString("departmentcode"));
                    lastname = Util.null2String(rs.getString("lastname"));
                    mobile = Util.null2String(rs.getString("mobile"));

                    departmentname = Util.null2String(rs.getString("departmentname"));
                }
            }
        }catch (Exception e){

        }

        userMap.put("workcode",workcode);
        userMap.put("lastname",lastname);
        userMap.put("mobile",mobile);
        userMap.put("departmentcode",departmentcode);
        userMap.put("departmentname",departmentname);
        userMap.put("departmentid",departmentid);
        userMap.put("subcompanyid1",subcompanyid1);

        return userMap;
    }


    public int updateSubcompanyData(String subcompanyid1,String key,String secret){

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

        String sjc = String.valueOf(Calendar.getInstance().getTimeInMillis());
        String appSig = getAppSigData(path,key,secret,sjc);


        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");

        int errorcount = 0;
        List<Map<String,String>> childSubcompanyList = getSubcompanyListByParentid(subcompanyid1);
        for(int k=0;k<childSubcompanyList.size();k++) {
            Map<String, String> childSubcompanyMap = childSubcompanyList.get(k);
            String subcompanycode = childSubcompanyMap.get("subcompanycode");
            String subcompanyname = childSubcompanyMap.get("subcompanyname");
            String supsubcompanycode = childSubcompanyMap.get("supsubcompanycode");

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

            String back = null;
            try {
                back = doPostJsonRequest(url, heads, JSON.toJSONString(dataMap));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            JSONObject backObj = JSONObject.parseObject(back);
            String code = backObj.getString("code");
            String data = backObj.getString("data");
            if (!"0".equals(code)) {
                errorcount++;
            }
        }
        return errorcount;
    }


    public int updateDeptData(String deptid,String key,String secret){

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

        String sjc = String.valueOf(Calendar.getInstance().getTimeInMillis());
        String appSig = getAppSigData(path,key,secret,sjc);


        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");

        int errorcount = 0;
        List<Map<String,String>> childDepartmentList = getDeptListByParentid(deptid);
        for(int k=0;k<childDepartmentList.size();k++){
            Map<String,String> childDepartmentMap = childDepartmentList.get(k);
            String departmentcode = childDepartmentMap.get("departmentcode");
            String departmentname = childDepartmentMap.get("departmentname");
            String supdeptcode = childDepartmentMap.get("supdeptcode");


            Map<String, Object> dataMap = new HashMap<String, Object>();
            dataMap.put("department_ext_id", departmentcode);
            dataMap.put("name", departmentname);
            dataMap.put("p_ext_id", supdeptcode);


            String back = null;
            try {
                back = doPostJsonRequest(url, heads, JSON.toJSONString(dataMap));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            JSONObject backObj = JSONObject.parseObject(back);
            String code = backObj.getString("code");
            String data = backObj.getString("data");
            if (!"0".equals(code)) {
                errorcount++;
            }
        }
        return errorcount;
    }

%>

