package weaver.interfaces.shuzhi.cronjob;

import com.alibaba.fastjson.JSONObject ;
import weaver.conn.RecordSet ;
import weaver.general.BaseBean ;
import weaver.general.MD5 ;
import org.apache.http.client.methods.HttpRequestBase ;
import org.apache.commons.collections.MapUtils ;
import java.io.IOException ;
import org.apache.http.client.methods.HttpPost ;
import org.apache.http.entity.StringEntity ;
import org.apache.http.Consts ;
import org.apache.http.impl.client.CloseableHttpClient ;
import org.apache.http.client.methods.CloseableHttpResponse ;
import org.apache.http.HttpEntity ;
import org.apache.http.util.EntityUtils ;
import org.apache.http.StatusLine ;
import javax.net.ssl.SSLContext ;
import org.apache.http.conn.socket.ConnectionSocketFactory ;
import org.apache.http.config.Registry ;
import org.apache.http.config.RegistryBuilder ;
import org.apache.http.conn.socket.PlainConnectionSocketFactory ;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory ;
import org.apache.http.conn.ssl.NoopHostnameVerifier ;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager ;
import org.apache.http.impl.client.HttpClients ;
import java.security.NoSuchAlgorithmException ;
import java.security.KeyManagementException ;
import javax.net.ssl.X509TrustManager ;
import java.security.cert.CertificateException ;
import javax.net.ssl.TrustManager ;
import org.apache.commons.lang3.StringUtils ;
import java.util.* ;
import com.alibaba.fastjson.JSON ;
import weaver.interfaces.schedule.BaseCronJob;

/**
 *
 *
 * @author:xuxy
 * @createTime: 2023/10/28
 * @version: 1.0
 */
public class SyndeliOrgJob extends BaseCronJob {

    @Override
    public void execute() {
        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");
            bb.writeLog("key:"+key+"</br>");
            bb.writeLog("secret:"+secret+"</br>");

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

                bb.writeLog("sjc:"+sjc+"</br>");
                bb.writeLog("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>> topSubcompanyList = getTopSubcompanyList();
                for(int i=0;i<topSubcompanyList.size();i++){
                    Map<String,String> topSubcompanyMap = topSubcompanyList.get(i);
                    String subcompanycode = topSubcompanyMap.get("subcompanycode");
                    String subcompanyname = topSubcompanyMap.get("subcompanyname");

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

                    bb.writeLog("headers:"+JSONObject.toJSONString(heads)+"</br>");
                    bb.writeLog("top-subcompany-body:"+JSONObject.toJSONString(dataMap)+"</br>");

                    String back = doPostJsonRequest(url, heads, JSON.toJSONString(dataMap));
                    bb.writeLog("response:" + back);
                    bb.writeLog("response:"+back+"</br>");

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

                bb.writeLog("kao----------------------："+"</br>");
                for(int i=0;i<topSubcompanyList.size();i++) {
                    Map<String,String> topSubcompanyMap = topSubcompanyList.get(i);
                    String subcompany_id = topSubcompanyMap.get("subcompanyid");
                    bb.writeLog("subcompany_id："+subcompany_id+"</br>");
                    List<Map<String,String>> childSubcompanyList = getSubcompanyListByParentid(subcompany_id);
                    bb.writeLog("分部组织长度："+childSubcompanyList.size()+"</br>");
                    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);

                        bb.writeLog("headers:"+JSONObject.toJSONString(heads)+"</br>");
                        bb.writeLog("Subcompany-body:"+JSONObject.toJSONString(dataMap)+"</br>");

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

                List<Map<String,String>> topDepartmentList =  getTopDeptList();
                for(int i=0;i<topDepartmentList.size();i++){
                    Map<String,String> topDepartmentMap = topDepartmentList.get(i);
                    String departmentcode = topDepartmentMap.get("departmentcode");
                    String departmentname = topDepartmentMap.get("departmentname");
                    String subcompanycode = topDepartmentMap.get("subcompanycode");

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

                    bb.writeLog("headers:"+JSONObject.toJSONString(heads)+"</br>");
                    bb.writeLog("top-dept-body:"+JSONObject.toJSONString(dataMap)+"</br>");

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

                for(int i=0;i<topDepartmentList.size();i++) {
                    Map<String,String> topDeptMap = topDepartmentList.get(i);
                    String deptid = topDeptMap.get("deptid");

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

                        bb.writeLog("headers:"+JSONObject.toJSONString(heads)+"</br>");
                        bb.writeLog("dept-body:"+JSONObject.toJSONString(dataMap)+"</br>");

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

        BaseBean bb = new BaseBean();
        RecordSet rs = new RecordSet();
        String sql  = " select id,subcompanycode,subcompanyname,subcompanydesc \n" +
                      " from HrmSubCompany where supsubcomid = 0 and (canceled is null or canceled  = 0) " ;
        bb.writeLog("getSubcompanyListByParentid-sql:"+sql);
        rs.executeQuery(sql);
        while (rs.next()){
            String subcompanycode = rs.getString("subcompanycode");
            String subcompanyname = rs.getString("subcompanyname");
            String subcompany_id = rs.getString("id");

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


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

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

        bb.writeLog("getSubcompanyListByParentid-sql:"+sql);

        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);
        }
        return list;
    }



    public List<Map<String,String>> getTopDeptList(){
        List<Map<String,String>> list = new ArrayList<Map<String,String>>();
        Map<String,String> map = null;

        BaseBean bb = new BaseBean();
        RecordSet rs = new RecordSet();
        String sql  =   " select t.id,t.departmentcode,t.departmentname,t.subcompanyid1,h.subcompanycode\n" +
                        " from HrmDepartment t\n" +
                        " left join HrmSubCompany h on h.id = t.subcompanyid1\n" +
                        " where t.supdepid = 0 and (t.canceled is null or t.canceled  = 0) ";

        bb.writeLog("getTopDeptList-sql:"+sql);
        rs.executeQuery(sql);
        while (rs.next()){
            String departmentcode = rs.getString("departmentcode");
            String departmentname = rs.getString("departmentname");
            String deptid = rs.getString("id");
            String subcompanycode = rs.getString("subcompanycode");

            map = new HashMap<String,String>();
            map.put("departmentcode",departmentcode);
            map.put("departmentname",departmentname);
            map.put("deptid",deptid);
            map.put("subcompanycode",subcompanycode);
            list.add(map);
        }
        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();
        BaseBean bb = new BaseBean();

        String sql =" with tem_table(id,departmentname,supdepid,departmentcode,curlevel,canceled) as(\n" +
                    "   select id,departmentname,supdepid,departmentcode,1 as level,canceled \n" +
                    "        from HrmDepartment where id = "  + supsubcomid +
                    "   union all\n" +
                    "   select a.id,a.departmentname,a.supdepid,a.departmentcode,b.curlevel+1,a.canceled                          \n" +
                    "        from HrmDepartment  a \n" +
                    "   inner join tem_table b on (a.supdepid = b.id) \n" +
                    " )\n" +
                    " select p.*,k.departmentcode as supdeptcode from tem_table p\n" +
                    " left join HrmDepartment k on p.supdepid = k.id  " +
                    " where p.id <> "+supsubcomid +"" +
                    " and (p.canceled is null or p.canceled  = 0)";

        bb.writeLog("getDeptListByParentid-sql:"+sql);
        rs.executeQuery(sql);
        while (rs.next()){
            String departmentcode = rs.getString("departmentcode");
            String departmentname = rs.getString("departmentname");
            String sup_depid = rs.getString("supdepid");
            String supdeptcode = rs.getString("supdeptcode");

            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);
        }
        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 {
        BaseBean bb = new BaseBean();
        bb.writeLog("doPostJsonRequest-url:"+url);
        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);
        bb.writeLog("doPostJsonRequest2");
        return sendRequest(httpost);
    }


    private static String sendRequest(HttpRequestBase httpRequest) throws IOException {
        BaseBean bb = new BaseBean();
        bb.writeLog("sendRequest");
        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请求
        BaseBean bb = new BaseBean();
        bb.writeLog("CloseableHttpClient");
        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;
    }
}
