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

import cn.com.poc.common.utils.StringUtils;
import cn.com.poc.thirdparty.resource.baidu.entity.response.BaiduTextDiffResponse;
import cn.com.poc.thirdparty.resource.baidu.entity.response.text_diff.BaiduTextDiffQueryResult;
import cn.com.poc.thirdparty.resource.baidu.entity.result.BaiduTextDiffResult;
import cn.com.yict.framemax.core.exception.BusinessException;
import com.google.gson.Gson;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.io.IOException;
import java.nio.file.Files;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 百度文档对比API
 *
 * @author alex.yao
 * @desc 接口描述
 * 文档比对支持精准比对文档的增删改差异，快速定位并高亮显示差异原文，支持导出完整的比对报告，大幅提升比对准确性和效率。
 * 如希望快速可视化体验效果，可登录智能文档分析平台，一键上传文档，在线测试；在线工具和API服务的额度共享互通。
 * 文档比对API服务为异步接口，需要先调用提交请求接口获取 taskID，
 * 然后调用获取结果接口进行结果轮询，建议提交请求后5～10秒开始轮询。提交请求接口QPS为2，获取结果接口QPS为10。
 * @url https://cloud.baidu.com/doc/OCR/s/Glqd7jgmf
 * @date 2025/6/25
 */
@Component
public class BaiduTextDiffApi implements BaiduBaseApi {

    private final Logger logger = LoggerFactory.getLogger(BaiduTextDiffApi.class);

    public final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().readTimeout(300, TimeUnit.SECONDS).build();

    /**
     * 提交请求接口
     * <p>
     * https://aip.baidubce.com/file/2.0/brain/online/v1/textdiff/create_task
     */
    public BaiduTextDiffResult textDiff(BaiduTextDiffResponse response, String token) {
        Assert.notNull(response);
        Assert.notNull(token);
        String url = BASE_API + "file/2.0/brain/online/v1/textdiff/create_task?access_token=" + token;
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);

        try {
            if (StringUtils.isNotBlank(response.getBaseFileURL())) {
                builder = builder
                        .addFormDataPart("baseFileURL", response.getBaseFileURL())
                        .addFormDataPart("compareFileURL", response.getCompareFileURL());
            } else {
                RequestBody baseFile = RequestBody.create(MediaType.parse(Objects.requireNonNull(Files.probeContentType(response.getBaseFile().toPath()))), response.getBaseFile());
                RequestBody compareFile = RequestBody.create(MediaType.parse(Objects.requireNonNull(Files.probeContentType(response.getBaseFile().toPath()))), response.getCompareFile());
                builder = builder.addFormDataPart("baseFile", response.getBaseFile().getName(), baseFile)
                        .addFormDataPart("compareFile", response.getCompareFile().getName(), compareFile);
            }
            MultipartBody body = builder.build();
            Request request = new Request.Builder()
                    .url(url)
                    .method("POST", body)
                    .addHeader("Content-Type", "multipart/form-data")
                    .build();
            String result = Objects.requireNonNull(HTTP_CLIENT.newCall(request).execute().body()).string();
            Gson gson = new Gson();
            return gson.fromJson(result, BaiduTextDiffResult.class);
        } catch (IOException e) {
            logger.error("百度文本对比接口调用失败", e);
            throw new BusinessException("百度文本对比接口调用失败");
        }
    }

    /**
     * 获取结果接口
     * https://aip.baidubce.com/file/2.0/brain/online/v1/textdiff/query_task
     */
    public BaiduTextDiffQueryResult queryTask(String taskId, String token) {
        Assert.notNull(taskId);
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        builder.addFormDataPart("taskId", taskId);
        MultipartBody body = builder.build();
        Request request = new Request.Builder()
                .url(BASE_API + "file/2.0/brain/online/v1/textdiff/query_task?access_token=" + token)
                .method("POST", body)
                .addHeader("Content-Type", "multipart/form-data")
                .build();
        try {
            String result = Objects.requireNonNull(HTTP_CLIENT.newCall(request).execute().body()).string();
            Gson gson = new Gson();
            return gson.fromJson(result, BaiduTextDiffQueryResult.class);
        } catch (IOException e) {
            logger.error("查询文本对比任务失败", e);
            throw new BusinessException("查询文本对比任务失败");
        }
    }


}

