package org.springblade.api.utils;

import com.squareup.okhttp.*;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springblade.core.log.exception.ServiceException;

import java.io.IOException;

public class BaidubceUtils {
	public static final String API_KEY = "dvoNNcARO5fix6atBByzfD57";
	public static final String SECRET_KEY = "H3nunwNO2CosQdeZ4rw5QGax7Wv19sWK";

	static final OkHttpClient HTTP_CLIENT = new OkHttpClient();

	public static void main(String []args) throws IOException{
		JSONArray jsonArray= imageOcr("https://ai.my-123.cn/pic/product-line/upload/20240205/4c99db572805d6c7a00c45c1820ac414.jpg");
		System.out.println(jsonArray);

	}

	public static JSONArray imageOcr(String url){
		try{
			MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
			RequestBody body = RequestBody.create(mediaType, "url="+url+"&language_type=ENG&detect_direction=true&paragraph=false&probability=false");
			Request request = new Request.Builder()
				.url("https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?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();
			if(response.code()==200){
				return new JSONObject(response.body().string()).getJSONArray("words_result");
			}else{
				throw new ServiceException("调用百度ocr异常"+response.message());
			}
		}catch (Exception e){
			e.printStackTrace();
			throw new ServiceException("系统异常"+e.getMessage());
		}
	}

	/**
	 * 从用户的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 new JSONObject(response.body().string()).getString("access_token");
	}
}
