package cn.ezhizao.common.utils.qichacha;


import cn.hutool.json.JSONException;
import cn.hutool.json.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.IOException;
import java.util.regex.Pattern;

public class QichachaRequest {

    private static final String appkey = "appkey";
    private static final String secretKey = "secretKey";

//    public static String getBusinessInfo(String searchKey) {
//        String reqInterNme = "https://api.qichacha.com/ECIInfoVer";
//        String status = "";
//        String key = "";
//        try {
//            HttpHead reqHeader = new HttpHead();
//            String[] autherHeader = RandomAuthentHeader();
//            reqHeader.setHeader("Token", autherHeader[0]);
//            reqHeader.setHeader("Timespan", autherHeader[1]);
//            RestTemplate restTemplate = new RestTemplate();
//
//            String responseBody = response.getBody();
//
//            final String reqUri = reqInterNme.concat("?key=").concat(appkey).concat("&").concat(paramStr);
//            String tokenJson = HttpHelper.httpGet(reqUri, reqHeader.getAllHeaders());
//
//            status = FormartJson(tokenJson, "Status");
//            if (!HttpCodeRegex.isAbnornalRequest(status)) {
//                PrettyPrintJson(tokenJson);
//            }
//        } catch (Exception e1) {
//            e1.printStackTrace();
//        }
//    }

    // 获取返回码 Res Code
    static class HttpCodeRegex {
        private static final String ABNORMAL_REGIX = "(101)|(102)";
        private static final Pattern pattern = Pattern.compile(ABNORMAL_REGIX);
        protected static boolean isAbnornalRequest(final String status) {
            return pattern.matcher(status).matches();
        }
    }

    // 获取Auth Code
    protected static final String[] RandomAuthentHeader() {
        String timeSpan = String.valueOf(System.currentTimeMillis() / 1000);
        String[] authentHeaders = new String[] { DigestUtils.md5Hex(appkey.concat(timeSpan).concat(secretKey)).toUpperCase(), timeSpan };
        return authentHeaders;
    }

    // 解析JSON
    protected static String FormartJson(String jsonString, String key) throws JSONException {
        JSONObject jObject = new JSONObject(jsonString);
        return (String) jObject.get(key);
    }

    // pretty print 返回值
    protected static void PrettyPrintJson(String jsonString) throws JSONException {
        try {
            ObjectMapper mapper = new ObjectMapper();
            Object obj = mapper.readValue(jsonString, Object.class);
            String indented = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
