package io.renren.application.common.util;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Data
@Slf4j
public class BaiduUtils {
    private static final String API_KEY="BaOevEgABbOPTfJo686CJvRL";
    private static final String API_SECRET="PrFtaiHcU2KkGS5apqIhRlP1K7sgCzHw";
    private static final CacheToken cacheToken = new CacheToken();


    private static String getCacheToken(){
        if (cacheToken.getToken()!=null&&cacheToken.getExpireTime().isAfter(LocalDateTime.now())){
            return cacheToken.getToken();
        }
        return getBaiduToken();
    }

    private static String getBaiduToken(){
        Map param = new HashMap();
        param.put("grant_type","client_credentials");
        param.put("client_id",API_KEY);
        param.put("client_secret",API_SECRET);
        String result = HttpUtil.get("https://aip.baidubce.com/oauth/2.0/token",param);
        log.info("获取百度token结果：{}",result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        cacheToken.setToken(jsonObject.getString("access_token"));
        cacheToken.setExpireTime(LocalDateTime.now().plusSeconds(jsonObject.getInteger("expires_in")-10));
        return jsonObject.getString("access_token");
    }

    public static String getImageText(String image){
        HttpRequest request = HttpRequest.post("https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token="+
                getCacheToken());
        request.header("Content-Type","application/x-www-form-urlencoded");
        Map<String,String> param = new HashMap<>();
        param.put("url",image);
        request.body(JSONObject.toJSONString(param));
        request.form("url",image);
        String result = request.execute().body();
        log.info("图像识别请求结果:{}",result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String words = jsonObject.getJSONArray("words_result").getJSONObject(0).getString("words").trim().replace(" ","");
        return words;
    }
    public static String getImageTextBase64(String image) throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        // image 可以通过 getFileContentAsBase64("C:\fakepath\code.jfif") 方法获取,如果Content-Type是application/x-www-form-urlencoded时,第二个参数传true
        RequestBody body = RequestBody.create(mediaType, "image="+image+"&detect_direction=false&detect_language=false&paragraph=false&probability=false");
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=" + getCacheToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();
        OkHttpClient client = new OkHttpClient();
        Response response = client.newCall(request).execute();
        String result = response.body().string();
        log.info("图像识别请求结果:{}",result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String words = jsonObject.getJSONArray("words_result").getJSONObject(0).getString("words").trim().replace(" ","");
        return words;
    }
    @Data
    public static class CacheToken{
        String token;
        LocalDateTime expireTime;
    }
}
