package com.jkcredit.invoice.util;

import com.alibaba.fastjson.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class QueryDemo_3rd2 {

    /**
     * 测试地址
     */
    private static final String URL = "http://etc.jkcredit.com:9999/api/rest";
    //  private static final String URL = "http://127.0.0.1:18081/api/rest";

    /**
     * 分配的appKey
     */
    //  private static final String appKey = "yqxd";

    static String filename = "/Users/mashengyi/Downloads/";
    static String writename = "/Users/mashengyi/Downloads/msy.txt";
    static String logname = "hccc.txt";

    /**
     * 方法入口
     *
     * @param args
     */

    public static void main(String args[]) throws Exception {

        QueryDemo_3rd2 demo = new QueryDemo_3rd2();



        int count = 0;
        int total = 0;

        HashMap hashMap = new HashMap();

        try {
            File file = new File(filename + logname);
            FileInputStream fis = new FileInputStream(file);
            InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
            LineNumberReader lr = new LineNumberReader(isr, 512);
            String laststr = "";
            int count_d = 0;
            int total_d = 0;
            while (true) {

                String str = lr.readLine();

                try {
                    if (str == null)
                        break;


                    com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(str);
                    JSONArray jsonArray = jsonObject.getJSONArray("result");

                    try (BufferedWriter writer = new BufferedWriter(new FileWriter("/Users/mashengyi/Downloads/msy.txt"))) {
                        // 遍历数组并写入每行数据到txt文件

                        for (int i = 0; i < jsonArray.size(); i++) {
                            com.alibaba.fastjson.JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                            String sellerName = jsonObject1.getString("invoiceCode");
                            writer.write(sellerName);
                            writer.newLine();
                        }

                        System.out.println("数据已成功写入txt文件！");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }


                    //  demo.runMainService(appKey,appSecret,num);


                } catch (Exception e) {

                    //   System.out.println("无法解析：" + str);
                }
            }
            lr.close();

        } catch (FileNotFoundException e) {
            System.out.println("FILENAME:" + filename);
            System.out.println("File not found");
        } catch (IOException e) {
            System.out.println("IO error");
        }

        Iterator it = hashMap.keySet().iterator();

        while (it.hasNext()) {

            String key = (String) it.next();
            Integer ttttttt = (Integer) hashMap.get(key);

            System.out.println(key + "====" + ttttttt);
        }

    }

    public static String getsrt(String startkeystr, String endstr, String str) {
        int customerindex = str.indexOf(startkeystr);
        String temp = str.substring(customerindex + startkeystr.length());
        int endindex = temp.indexOf(endstr);
        String sss = temp.substring(0, endindex);
        return sss;
    }

    public static String getsrt1(String startkeystr, String str) {
        int customerindex = str.indexOf(startkeystr);
        String temp = str.substring(customerindex + startkeystr.length());
        return temp;
    }

    /**
     * 利用正则表达式判断字符串是否是数字
     *
     * @param str
     * @return
     */
    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    /**
     * 调用主接口
     */
    public void runMainService(String appKey,String appSecret,String num) {
        try {
            /**
             * 实名demo
             */

                JSONObject paramJsonObj = initParamJsonObj_Realname(appKey,appSecret,num);
                 String ret = postClient(URL, paramJsonObj);
                System.out.println(ret);


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 整合参数(实名认证)
     *
     * @return
     */
    public JSONObject initParamJsonObj_Realname(String appKey,String appSecret,String num) {
        /**
         * 基本参数
         */
        JSONObject paramJsonObj = new JSONObject();
        paramJsonObj.put("api", "WAY_BILL_NUM_FIND_OWNER_INVOICE");
        paramJsonObj.put("appKey", appKey);
        paramJsonObj.put("appSecret",
                appSecret);


        /**
         * 业务参数
         */
        JSONObject dataJson = initMainServiceParamJsonObj_Realname(num);
        paramJsonObj.put("data", dataJson);
        return paramJsonObj;
    }

    /*
     * 初始化业务参数(实名认证)
     *
     * 姓名,身份证,手机号
     *
     * @return
     */
    public JSONObject initMainServiceParamJsonObj_Realname(String num) {
        /**
         * 具体业务参数放在data中
         */
        JSONObject dataJson = new JSONObject();
        dataJson.put("num", num);
        return dataJson;
    }

    /**
     * 实现http post请求 注意编码 UTF-8
     *
     * @param url
     * @param paramObj
     * @return
     */
    public String postClient(String url, JSONObject paramObj) {
        String str = "";
        HttpClient client = null;
        PostMethod method = null;
        try {
            client = new HttpClient();
            method = new PostMethod(url);
            method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            NameValuePair[] param = new NameValuePair[paramObj.size()];
            Iterator<String> keys = paramObj.keys();
            int i = 0;
            while (keys.hasNext()) {
                String key = (String) keys.next();
                String value = paramObj.getString(key);
                param[i] = new NameValuePair(key, value);
                i++;
            }
            method.setRequestBody(param);
            client.executeMethod(method);
            str = convertStreamToString(method.getResponseBodyAsStream());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (method != null) {
                method.releaseConnection();
            }
        }
        return str;
    }

    /**
     * 流转字符串
     *
     * @param is
     * @return
     */
    public static String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder builder = new StringBuilder();
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                builder.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return builder.toString();
    }


    public static void writeToFile(String filePath, String content) throws IOException {
        FileWriter writer = new FileWriter(filePath);

        try (BufferedWriter bufferedWriter = new BufferedWriter(writer)) {
            bufferedWriter.write(content);
        } catch (IOException e) {
            throw e; // 可根据需要进行处理或重新抛出异常
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }
}
