package com.ho.business.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

public class BaiduImageIdentifyUtil {
    public static final String API_KEY = "kNL8gHHrHVCGWPjVfl7eR3lZ";
    public static final String SECRET_KEY = "hM5xxxs6sfWioMaPmMkS3tuCs0fO3rG0";

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    public static JSONObject getImageObject(byte[] b) throws IOException{
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");

        // image 可以通过 getFileContentAsBase64("C:\fakepath\1703491531637.jpg") 方法获取,如果Content-Type是application/x-www-form-urlencoded时,第二个参数传true
        //RequestBody body = RequestBody.create(mediaType, "image=iVBORw0KGgoAAAANSUhEUgAABTUAAAEyCAYAAAArwzQ%2BAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADs...&cell_contents=false&return_excel=false");
        String image = getFileContentAsBase64(b,true);
        RequestBody body = RequestBody.create(mediaType, "image="+image+"&cell_contents=false&return_excel=false");
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/ocr/v1/table?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        JSONObject jsonObject = JSON.parseObject(response.body().string());
        return  jsonObject;
    }
    /**
     * 获取文件base64编码
     *
     * @param urlEncode 如果Content-Type是application/x-www-form-urlencoded时,传true
     * @return base64编码信息，不带文件头
     * @throws IOException IO异常
     */
    static String getFileContentAsBase64(byte[] b, boolean urlEncode) throws IOException {
        String base64 = Base64.getEncoder().encodeToString(b);
        if (urlEncode) {
            base64 = URLEncoder.encode(base64, "utf-8");
        }
        return base64;
    }

    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return JSON.parseObject(response.body().string()).getString("access_token");
    }
}