package com.mmc.iuav.user.util;

import com.alibaba.fastjson2.JSONException;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mmc.iuav.http.HttpHelper;
import com.mmc.iuav.http.HttpsRequestUtil;
import com.mmc.iuav.user.constant.UserSystemConstant;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.client.methods.HttpHead;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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


/**
 * @author: zj
 * @Date: 2023/5/17 13:37
 */
@Component
public class QccEntAuthUtil {

    @Autowired
    private UserSystemConstant userSystemConstant;

    public String fuzzySearch(String searchKey) {
        String reqInterNme = "http://api.qichacha.com/FuzzySearch/GetList";
        //pageSize=6,显示6条
        //String paramStr = "searchKey="+searchKey;
        String status = "";
        try {
            HttpHead reqHeader = new HttpHead();
            String[] autherHeader = RandomAuthentHeader();
            reqHeader.setHeader("Token", autherHeader[0]);
            reqHeader.setHeader("Timespan", autherHeader[1]);
            reqHeader.setHeader("Content-Type", "application/json; charset=UTF-8");
            reqHeader.setHeader("Accept", "application/json; charset=UTF-8");
            reqHeader.setHeader("Accept-language", "zh-CN,zh;q=0.9");
            reqHeader.setHeader("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            final String reqUri = reqInterNme.concat("?key=").concat(userSystemConstant.getQccAppKey()).concat("&searchKey=").concat(searchKey).concat("&pageSize=6");
            String tokenJson = HttpHelper.httpGet(reqUri, reqHeader.getAllHeaders());
            return tokenJson;
        } catch (Exception e1) {
            e1.printStackTrace();
            return null;
        }
    }

    public String check2(String companyName, String creditCode){
        String reqInterNme = "https://api.qichacha.com/ECITwoElVerify/GetInfo";
        String status = "";
        try {
            HttpHead reqHeader = new HttpHead();
            String[] autherHeader = RandomAuthentHeader();
            reqHeader.setHeader("Token", autherHeader[0]);
            reqHeader.setHeader("Timespan", autherHeader[1]);
            String verifyType = "1";
            final String reqUri = reqInterNme.concat("?key=").concat(userSystemConstant.getQccAppKey()).concat("&verifyName=").concat(companyName).concat("&creditCode=").concat(creditCode).concat("&verifyType=").concat(verifyType);
            String tokenJson = HttpHelper.httpGet(reqUri, reqHeader.getAllHeaders());
            status = FormartJson(tokenJson, "Status");
            if (!HttpCodeRegex.isAbnornalRequest(status)) {
                PrettyPrintJson(tokenJson);
            }
            return tokenJson;
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return null;
    }

//    public static String check3(String companyName, String creditCode, String operName){
//        String reqInterNme = "https://api.qichacha.com/ECIThreeElVerify/GetInfo";
//        String status = "";
//        try {
//            HttpHead reqHeader = new HttpHead();
//            String[] autherHeader = RandomAuthentHeader();
//            reqHeader.setHeader("Token", autherHeader[0]);
//            reqHeader.setHeader("Timespan", autherHeader[1]);
//            final String reqUri = reqInterNme.concat("?key=").concat(APP_KEY).concat("&companyName=").concat(companyName).concat("&creditCode=").concat(creditCode).concat("&operName=").concat(operName);
//            String tokenJson = HttpHelper.httpGet(reqUri, reqHeader.getAllHeaders());
//            status = FormartJson(tokenJson, "Status");
//            if (!HttpCodeRegex.isAbnornalRequest(status)) {
//                PrettyPrintJson(tokenJson);
//            }
//            return tokenJson;
//        } catch (Exception e1) {
//            e1.printStackTrace();
//        }
//        return null;
//    }

    public String businessLicenseCheck(String businessLicenseUrl){
        String url = "https://bizlicense.market.alicloudapi.com/rest/160601/ocr/ocr_business_license.json";
        String method = "POST";
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Authorization", "APPCODE " + userSystemConstant.getAliAppCode());
        headers.put("Content-Type", "application/json; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        String bodys = "{\"image\":\""+businessLicenseUrl+"\"}";
        try {
            String response = HttpsRequestUtil.httpsRequest(url, method, headers, bodys);
            //获取response的body
            if(response.equals("Invalid Result - invalid business license")){
                return null;
            }
            return response;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取返回码 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
     * @return
     */
    protected String[] RandomAuthentHeader() {
        String timeSpan = String.valueOf(System.currentTimeMillis() / 1000);
        String[] authentHeaders = new String[] { DigestUtils.md5Hex(userSystemConstant.getQccAppKey().concat(timeSpan).concat(userSystemConstant.getQccSecretKey())).toUpperCase(), timeSpan };
        return authentHeaders;
    }

    /**
     * 解析JSON
     * @param jsonString
     * @param key
     * @return
     * @throws JSONException
     */
    public String FormartJson(String jsonString, String key) throws JSONException {
        //JSONObject jObject = new JSONObject(jsonString);
        JSONObject jsonObject = JSONObject.parseObject(jsonString);
        return (String) jsonObject.get(key);
    }

    /**
     * 解析JSON
     * @param jsonString
     * @return
     * @throws JSONException
     */
    public Integer resultFormatJson(String jsonString) throws JSONException {
        //JSONObject jObject = new JSONObject(jsonString);
        JSONObject jsonObject = JSONObject.parseObject(jsonString);
        Object object = jsonObject.get("Result");
        JSONObject result = JSONObject.parseObject(object.toString());
        return (Integer) result.get("VerifyResult");
    }

    /**
     * pretty print 返回值
     * @param jsonString
     * @throws JSONException
     */
    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();
        }
    }
}
