package weaver.interfaces.mfkj.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.kq.util.KQDurationCalculatorUtil;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.*;

/**
 * @Title  http 封装类
 * @Author wangchaofa
 * @CreateDate 2023/8/7
 * @Version 1.0
 * @Description
 */
public class HttpUtils extends BaseBean {

    public static void main(String[] args) throws IOException{
        String corpCode = "";
        String userName = "";
        String password = "";

        Map<String,String> headers = new HashMap<>();

        String url = "http://api.wintalent.cn/wt/api/2.0/getToken";
        String url2 = "http://api.wintalent.cn/wt/api/2.0/auth/resume/getUnEnterDuty";
        String url3 = "http://api.wintalent.cn/wt/api/2.0/auth/login/interview";

        String data1 = "{\"corpCode\":\"MATFRON\",\"userName\":\"MATFRON\",\"password\":\"5FC46CE8934E3BDAB6C1ADC45695F66D\"}";

        System.out.println(data1);

        Map<String,Object> map = getTokenInfo(url,headers,data1,null);

        System.out.println(map);

        String token = (String) map.get("token");

        String expire = (String) map.get("expire");

        System.out.println(token);
        System.out.println(expire);

        headers.put("Authorization", "Bearer "+token);

        JSONObject json1 = new JSONObject();
        json1.put("email","jeff.zhang@matfron.com");
        String urll = getLoginUrl(url3,headers,json1.toString(),"UTF-8");
        System.out.println(urll);

        JSONObject json = new JSONObject();

        json.put("rowSize","10");
        json.put("cType","2,4,400");
        json.put("vType","1");

        String data = getResumeInfo(url2,headers,json.toString(),"UTF-8");
        System.out.println(data);
        JSONObject json_data = JSONObject.parseObject(data);
        String resume = json_data.getString("resume");
        JSONArray jsonArray = JSONArray.parseArray(resume);
        System.out.println(jsonArray);

        for(int i=0;i<jsonArray.size();i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            System.out.println(jsonObject);
            String resumeContent = jsonObject.getString("resumeContent");
            System.out.println(resumeContent);
            JSONObject json_resumeContent = JSONObject.parseObject(resumeContent);

            String applyId = jsonObject.getString("applyId");
            System.out.println(applyId);

            // 个人基本信息
            String personalInformation = json_resumeContent.getString("personalInformation");
            System.out.println(personalInformation);
            JSONObject json_personalInformation = JSONObject.parseObject(personalInformation);

            //  求职意向
            String careerObjective = json_resumeContent.getString("careerObjective");
            System.out.println(careerObjective);
            JSONObject json_careerObjective = JSONObject.parseObject(careerObjective);

            // 家庭关系
            String familyRelationship = json_resumeContent.getString("familyRelationship");
            System.out.println(familyRelationship);
            JSONArray array_familyRelationship = JSONArray.parseArray(familyRelationship);

            // 明细1
            for(int j=0;j<array_familyRelationship.size();j++) {
                JSONObject jsonObject_family = array_familyRelationship.getJSONObject(j);
                System.out.println(jsonObject_family);

                // 姓名
                String name = Util.null2String(jsonObject_family.getString("name"));
                // 关系
                String relationship = Util.null2String(jsonObject_family.getString("relationship"));
                // 联系方式
                String contactNumber = Util.null2String(jsonObject_family.getString("contactNumber"));
                // 职业
                String jobTitle = Util.null2String(jsonObject_family.getString("jobTitle"));
                // 地址
                String address = Util.null2String(jsonObject_family.getString("address"));
                // 是否紧急联系人  0 是 1 否
                String emergencyContact = Util.null2String(jsonObject_family.getString("emergencyContact"));
            }

            // 教育经历
            String educationBackground = json_resumeContent.getString("educationBackground");
            System.out.println(educationBackground);
            JSONArray array_educationBackground = JSONArray.parseArray(educationBackground);

            // 明细2
            for(int j=0;j<array_educationBackground.size();j++) {
                JSONObject jsonObject_education = array_educationBackground.getJSONObject(j);
                System.out.println(jsonObject_education);

                //学校
                String schoolName = Util.null2String(jsonObject_education.getString("schoolName"));
                //专业
                String major = Util.null2String(jsonObject_education.getString("major"));
                //入学时间
                String startDate = Util.null2String(jsonObject_education.getString("startDate"));
                //毕业时间
                String endDate = Util.null2String(jsonObject_education.getString("endDate"));
                //学历 0 初中及以下 1 中专 2 高中 3 大专 4 本科 5 硕士及以上
                String diploma = Util.null2String(jsonObject_education.getString("diploma"));
                //学历类型  0 统招 1 自考 2 函授
                String educationType = Util.null2String(jsonObject_education.getString("educationType"));

            }

            // 工作经历
            String workingExperience = json_resumeContent.getString("workingExperience");
            System.out.println(workingExperience);
            JSONArray array_workingExperience = JSONArray.parseArray(workingExperience);

            // 明细3
            for(int j=0;j<array_workingExperience.size();j++) {
                JSONObject jsonObject_working = array_workingExperience.getJSONObject(j);
                System.out.println(jsonObject_working);

                //工作单位
                String companyName = Util.null2String(jsonObject_working.getString("companyName"));
                //工作开始日期
                String startDate = Util.null2String(jsonObject_working.getString("startDate"));
                //工作结束日期
                String endDate = Util.null2String(jsonObject_working.getString("endDate"));
                //职位
                String jobTitle = Util.null2String(jsonObject_working.getString("jobTitle"));
                //最后月度薪资
                String salaryMonthly = Util.null2String(jsonObject_working.getString("salaryMonthly"));
                //离职原因
                String reasonForQuit = Util.null2String(jsonObject_working.getString("reasonForQuit"));
            }

            // 姓名
            String name = Util.null2String(json_personalInformation.getString("name"));
            // 英文名
            String englishName = Util.null2String(json_personalInformation.getString("englishName"));
            // 国籍
            String nation = Util.null2String(json_personalInformation.getString("nation"));
            // 国籍编码
            String nationCode = Util.null2String(json_personalInformation.getString("nationCode"));
            // 性别
            String gender = Util.null2String(json_personalInformation.getString("gender"));
            // 邮箱地址
            String email = Util.null2String(json_personalInformation.getString("email"));
            // 手机号码
            String mobilePhone = Util.null2String(json_personalInformation.getString("mobilePhone"));
            // 现住址
            String currentCity = Util.null2String(json_personalInformation.getString("currentCity"));
            // 身份证地址
            String hukou = Util.null2String(json_personalInformation.getString("hukou"));
            // 婚姻情况
            String maritalStatus = Util.null2String(json_personalInformation.getString("maritalStatus"));
            // 出生日期
            String dateOfBirth = Util.null2String(json_personalInformation.getString("dateOfBirth"));
            // 应聘职位
            String desiredPosition = Util.null2String(json_careerObjective.getString("desiredPosition"));
            // 最快到岗时间
            String onBoardTime = Util.null2String(json_careerObjective.getString("onBoardTime"));
        }

//        Calendar cal1 = Calendar.getInstance();
//
//        long now_time = cal1.getTimeInMillis();
//        System.out.println(now_time);
//
//        long timestamp = Long.parseLong(expire)*1000;
//
//        if(now_time > timestamp){
//            System.out.println("========= 过期了哦 ====================");
//        }else{
//            System.out.println("========= 哈哈，还没呢 ====================");
//        }
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        Date date = new Date(timestamp);
//        String strDate = sdf.format(date);
//        System.out.println(strDate);

//        net.sf.json.JSONObject json = new net.sf.json.JSONObject();
//        json.put("key","8ua9ws89wls8w7s8nlws");
//        json.put("secret","okmlksjudiausdywe7plikjsqz");
//        json.put("name","青发集团数智化项目年度开发建设计划表-段红梅-2023-08-04");
//        json.put("introduction","您有一条OA流程待办消息（青发集团数智化项目年度开发建设计划表-段红梅-2023-08-04）请及时办理！");
//        json.put("source","fanweidblctx");
//        json.put("reType",2);
//        json.put("accType","6");
//        json.put("linkeds","[15712766101]");
//        json.put("jumpUrl","http://27.223.8.42:7555/interface/qfkg/CustomMessage.jsp?type=1&requestid=102085");
//        json.put("appJumpUrl","http://27.223.8.42:7555/interface/qfkg/CustomMessage.jsp?type=2&requestid=102085");
//        json.put("wxJumpUrl","");
//        json.put("isHandler",1);
//        json.put("businessId","102085");
//
//        System.out.println(json.toString());
//
//        JSONArray jsonArray = new JSONArray();
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("externalOrgKey","1001");
//        jsonObject.put("orgName","上海铭沣科技股份有限公司");
//        jsonObject.put("order","1");
//
//        jsonArray.add(jsonObject);
//
//        JSONObject jsonObject1 = new JSONObject();
//        jsonObject1.put("externalOrgKey","IT");
//        jsonObject1.put("orgName","IT部");
//        jsonObject1.put("externalParentOrgKey","1001");
//        jsonObject1.put("order","2");
//
//        jsonArray.add(jsonObject1);
//
//        JSONObject jsonObject2 = new JSONObject();
//        jsonObject2.put("externalOrgKey","SC(Semi)");
//        jsonObject2.put("orgName","半导体销售中心");
//        jsonObject2.put("externalParentOrgKey","1001");
//        jsonObject2.put("order","3");
//
//        jsonArray.add(jsonObject2);
//
//        System.out.println(jsonArray.toString());
//
//        String currentdate = TimeUtil.getCurrentDateString();
//        String currenttime = TimeUtil.getOnlyCurrentTimeString();
//        String currentdatetime = currentdate+" "+currenttime;
//        int formmodeid = 72;
//        String uuid = UUID.randomUUID().toString();
//
//        System.out.println(currentdate);
//        System.out.println(currenttime);
//        System.out.println(uuid);
//
//
//        String aa = "23.244";
//        System.out.println(KQDurationCalculatorUtil.getDurationRound(aa));
    }



    /**
     *
     * @param url
     * @param headers
     * @param stringJson
     * @param encode
     * @return
     */
    public static Map<String,Object> getTokenInfo(String url, Map<String,String> headers, String stringJson, String encode){
        Map<String,Object> result = new HashMap<>();
        if(encode == null){
            encode = "utf-8";
        }
        String content = null;
        CloseableHttpResponse httpResponse = null;
        CloseableHttpClient closeableHttpClient = null;
        try {
            closeableHttpClient = HttpClients.createDefault();
            HttpPost httpost = new HttpPost(url);
            //设置header
            httpost.setHeader("Content-type", "application/json");
            if (headers != null && headers.size() > 0) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    httpost.setHeader(entry.getKey(),entry.getValue());
                }
            }
            //组织请求参数
            StringEntity stringEntity = new StringEntity(stringJson, encode);
            httpost.setEntity(stringEntity);
            //响应信息
            httpResponse = closeableHttpClient.execute(httpost);
            HttpEntity entity = httpResponse.getEntity();
            content = EntityUtils.toString(entity, encode);
            if(content != null && !"".equals(content)){
                JSONObject json = JSONObject.parseObject(content);
                String code = json.getString("state");
                if("0".equals(code)){
                    JSONObject json1 = JSONObject.parseObject(json.toJSONString());
                    JSONObject json2 = JSONObject.parseObject(json1.getString("data"));
                    String token = json2.getString("token");
                    String expire = json2.getString("expire");

                    result.put("token",token);
                    result.put("expire",expire);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                httpResponse.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {  //关闭连接、释放资源
            closeableHttpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 全量推送组织结构数据
     * @param url
     * @param headers
     * @param stringJson
     * @param encode
     * @return
     */
    public static boolean pushPostJsoninfo(String url, Map<String,String> headers, String stringJson, String encode){
        boolean result = false;
        if(encode == null){
            encode = "utf-8";
        }
        String content = null;
        CloseableHttpResponse  httpResponse = null;
        CloseableHttpClient closeableHttpClient = null;
        try {
            closeableHttpClient = HttpClients.createDefault();
            HttpPost httpost = new HttpPost(url);
            //设置header
            httpost.setHeader("Content-type", "application/json");
            if (headers != null && headers.size() > 0) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    httpost.setHeader(entry.getKey(),entry.getValue());
                }
            }
            //组织请求参数
            StringEntity stringEntity = new StringEntity(stringJson, encode);
            httpost.setEntity(stringEntity);
            //响应信息
            httpResponse = closeableHttpClient.execute(httpost);
            HttpEntity entity = httpResponse.getEntity();
            content = EntityUtils.toString(entity, encode);
            if(content != null && !"".equals(content)){
                JSONObject json = JSONObject.parseObject(content);
                String code = json.getString("state");
                if("0".equals(code)){
                    result = true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                httpResponse.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {  //关闭连接、释放资源
            closeableHttpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 全量推送组织结构数据
     * @param url
     * @param headers
     * @param stringJson
     * @param encode
     * @return
     */
    public static String getResumeInfo(String url, Map<String,String> headers, String stringJson, String encode){
        String result = "";
        if(encode == null){
            encode = "utf-8";
        }
        String content = null;
        CloseableHttpResponse  httpResponse = null;
        CloseableHttpClient closeableHttpClient = null;
        try {
            closeableHttpClient = HttpClients.createDefault();
            HttpPost httpost = new HttpPost(url);
            //设置header
            httpost.setHeader("Content-type", "application/json");
            if (headers != null && headers.size() > 0) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    httpost.setHeader(entry.getKey(),entry.getValue());
                }
            }
            //组织请求参数
            StringEntity stringEntity = new StringEntity(stringJson, encode);
            httpost.setEntity(stringEntity);
            //响应信息
            httpResponse = closeableHttpClient.execute(httpost);
            HttpEntity entity = httpResponse.getEntity();
            content = EntityUtils.toString(entity, encode);
            if(content != null && !"".equals(content)){
                JSONObject json = JSONObject.parseObject(content);
                String code = json.getString("state");
                if("0".equals(code)){
                    result = json.getString("data");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                httpResponse.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {  //关闭连接、释放资源
            closeableHttpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 单点的 url
     * @param url
     * @param headers
     * @param stringJson
     * @param encode
     * @return
     */
    public static String getLoginUrl(String url, Map<String,String> headers, String stringJson, String encode){
        String result = "";
        if(encode == null){
            encode = "utf-8";
        }
        String content = null;
        CloseableHttpResponse  httpResponse = null;
        CloseableHttpClient closeableHttpClient = null;
        try {
            closeableHttpClient = HttpClients.createDefault();
            HttpPost httpost = new HttpPost(url);
            //设置header
            httpost.setHeader("Content-type", "application/json");
            if (headers != null && headers.size() > 0) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    httpost.setHeader(entry.getKey(),entry.getValue());
                }
            }
            //组织请求参数
            StringEntity stringEntity = new StringEntity(stringJson, encode);
            httpost.setEntity(stringEntity);
            //响应信息
            httpResponse = closeableHttpClient.execute(httpost);
            HttpEntity entity = httpResponse.getEntity();
            content = EntityUtils.toString(entity, encode);
            if(content != null && !"".equals(content)){
                JSONObject json = JSONObject.parseObject(content);
                String code = json.getString("state");
                if("0".equals(code)){
                    String data = json.getString("data");
                    JSONObject json_data = JSONObject.parseObject(data);
                    result = json_data.getString("url");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                httpResponse.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {  //关闭连接、释放资源
            closeableHttpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

}
