package com.jkcredit.invoice.util;

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.*;
import java.util.Iterator;

/**
 * @author mashengyi
 */
public class QueryDemoTest {

    /**
     * 测试地址
     */
    private static final String URL = "http://127.0.0.1:18081/gateway?api=credit.sec.data";

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

    /**
     * 分配的appSecret
     */
    private static final String APP_SECRET = "7697CE9BB9D5A856CFDDE738320AD34EA53E483C";

    /**
     * 企业编号
     */
    private static final String COMPANY_NUM = "10004616";

    /**
     * 方法入口
     *
     * @param args
     */
    public static void main(String[] args) throws Exception {
        QueryDemoTest demo = new QueryDemoTest();
        demo.runMainService();
    }

    /**
     * 流转字符串
     *
     * @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 void runMainService() {
        try {
            /**
             * 实名demo
             */
            JSONObject paramJsonObj = initParamJsonObjRealname();
            String ret = postClient(URL, paramJsonObj);
            System.out.println(ret);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 整合参数
     *
     * @return
     */
    public JSONObject initParamJsonObjRealname() {
        /**
         * 基本参数
         */
        JSONObject paramJsonObj = new JSONObject();
        //CMCC_MOBILE_CHECK_V8//CMCC_3RD_V2//CMCC_3RD_DETAIL_V1//
        paramJsonObj.put("api", "PROTOCOL_ADD_V1");
        paramJsonObj.put("appKey", APP_KEY);
        paramJsonObj.put("appSecret", APP_SECRET);


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

    public JSONObject initMainServiceParamJsonObjRealname() {
        /**
         * 具体业务参数放在data中
         */
        JSONObject dataJson = new JSONObject();
        dataJson.put("companyNum", COMPANY_NUM);
        dataJson.put("serviceStartTime", "2022-05-11T17:30:37");
        dataJson.put("serviceEndTime", "2023-05-11T21:30:37");
        dataJson.put("contractFileName", "etc高速开票抵扣(1).pdf");
        dataJson.put("serviceType", "3");
        dataJson.put("base64Str", Base64Utils.fileToBase64Str(new File("/Users/mashengyi/Desktop/etc高速开票抵扣(1).pdf")));
        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/json;charset=utf-8");
            NameValuePair[] param = new NameValuePair[paramObj.size()];
            @SuppressWarnings("unchecked")
            Iterator<String> keys = paramObj.keys();
            int i = 0;
            while (keys.hasNext()) {
                String key = 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;
    }

}
