package cn.ezhizao.project.business.company.util;

import cn.ezhizao.common.constant.Constants;
import cn.ezhizao.common.utils.http.HttpUtils;
import cn.hutool.json.JSONException;
import cn.hutool.json.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;

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

import static java.lang.System.out;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;


public class QiChaChaRequest {
    private static final String appkey = "appkey";
    private static final String secretKey = "secretKey";

    public static String getCompanyInfo(String param) {
        String path = "https://api.qichacha.com/ECIV4/GetBasicDetailsByName";
        String paramStr = "keyword="+param+"&key="+appkey;

        String status = "";
        Map<String, String> headers = new HashMap<String, String>();
        String[] autherHeader = RandomAuthentHeader();
//        reqHeader.setHeader("Token", autherHeader[0]);
//        reqHeader.setHeader("Timespan", autherHeader[1]);
        headers.put("Token", autherHeader[0]);
        headers.put("Timespan", autherHeader[1]);
        return HttpUtils.sendGet(path, paramStr, Constants.UTF8, headers);
    }

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

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

    // 解析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);
            out.println(indented);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
