package cn.com.poc.thirdparty.resource.baidu.api;

import cn.com.poc.thirdparty.resource.baidu.entity.response.TextReviewSubmitResponse;
import cn.com.poc.thirdparty.resource.baidu.entity.response.TextReviewResultQueryResponse;
import cn.com.poc.thirdparty.resource.baidu.entity.result.TextReviewRequest;
import com.google.gson.Gson;
import okhttp3.*;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;


/**
 * @author alex.yao
 * @date 2025/5/21
 */

@Component
public class TextReviewApi {

    // https://aip.baidubce.com/file/2.0/brain/online/v1/textreview/task
    public static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().readTimeout(300, TimeUnit.SECONDS).build();

    public TextReviewSubmitResponse textReview(TextReviewRequest textReviewRequest, String token) throws IOException {

        File file = textReviewRequest.getFile();

        RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("file", file.getName(), RequestBody.create(null, file))
                .addFormDataPart("templateName", textReviewRequest.getTemplateName())
                .addFormDataPart("commentRiskLevel", textReviewRequest.getCommentRiskLevel())
                .build();
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/file/2.0/brain/online/v1/textreview/task?access_token=" + token)
                .method("POST", body)
                .addHeader("Content-Type", "multipart/form-data")
                .build();
        String response = HTTP_CLIENT.newCall(request).execute().body().string();
        Gson gson = new Gson();
        return gson.fromJson(response, TextReviewSubmitResponse.class);
    }


    public TextReviewResultQueryResponse textReviewTaskQuery(String taskId, String token) throws IOException {
        MediaType mediaType = MediaType.parse("multipart/form-data");
        RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("taskId", taskId)
                .build();
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/file/2.0/brain/online/v1/textreview/task/query?access_token=" + token)
                .method("POST", body)
                .addHeader("Content-Type", "multipart/form-data")
                .build();
        String response = HTTP_CLIENT.newCall(request).execute().body().string();
        Gson gson = new Gson();
        return gson.fromJson(response, TextReviewResultQueryResponse.class);
    }


}
