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

import cn.com.poc.common.service.RedisService;
import cn.com.poc.common.utils.JsonUtils;
import cn.com.poc.common.utils.StringUtils;
import cn.com.poc.thirdparty.resource.baidu.api.BaiduTextDiffApi;
import cn.com.poc.thirdparty.resource.baidu.entity.result.BaiduTextDiffResult;
import cn.com.poc.thirdparty.resource.minerU.MinerUResponse;
import cn.com.poc.thirdparty.resource.minerU.MinerUResult;
import cn.com.yict.framemax.core.exception.BusinessException;
import cn.com.yict.framemax.frame.service.FmxParamConfigService;
import com.google.gson.Gson;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author alex.yao
 * @date 2025/10/29
 */
@Component
public class MinerUAPI {

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

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

    private String BASE_URL_PARAM_CODE = "mineru_base_url";

    private String BASE_URL_CACHE_KEY = "MINERU_BASE_URL";

    @Resource
    private RedisService redisService;

    @Resource
    private FmxParamConfigService fmxParamConfigService;


    private String getMinerU_URL() {
        if (redisService.hasKey(BASE_URL_CACHE_KEY)) {
            return redisService.get(BASE_URL_CACHE_KEY).toString();
        }

        String baseURL = fmxParamConfigService.getParam(BASE_URL_PARAM_CODE);
        redisService.set(BASE_URL_CACHE_KEY, baseURL, 600);
        return baseURL;
    }

    public MinerUResult parsePDF(MinerUResponse minerUResponse) {
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        File file = minerUResponse.getFiles();
        try {
            RequestBody files = RequestBody.create(MediaType.parse(Objects.requireNonNull(Files.probeContentType(file.toPath()))), file);
            builder = builder.addFormDataPart("files", file.getName(), files);
            builder.addFormDataPart("output_dir", minerUResponse.getOutput_dir());
            builder.addFormDataPart("lang_list", minerUResponse.getLang_list());
            builder.addFormDataPart("backend", minerUResponse.getBackend());
            builder.addFormDataPart("parse_method", minerUResponse.getParse_method());
            builder.addFormDataPart("formula_enable", String.valueOf(minerUResponse.getFormula_enable()));
            builder.addFormDataPart("table_enable", String.valueOf(minerUResponse.getTable_enable()));
            builder.addFormDataPart("server_url", "");
            builder.addFormDataPart("return_md", String.valueOf(minerUResponse.getReturn_md()));
            builder.addFormDataPart("return_middle_json", String.valueOf(minerUResponse.getReturn_middle_json()));
            builder.addFormDataPart("return_model_output", String.valueOf(minerUResponse.getReturn_model_output()));
            builder.addFormDataPart("return_content_list", String.valueOf(minerUResponse.getReturn_content_list()));
            builder.addFormDataPart("return_images", String.valueOf(minerUResponse.getReturn_images()));
            builder.addFormDataPart("response_format_zip", String.valueOf(minerUResponse.getResponse_format_zip()));
            builder.addFormDataPart("start_page_id", minerUResponse.getStart_page_id().toString());
            builder.addFormDataPart("end_page_id", minerUResponse.getEnd_page_id().toString());


            MultipartBody body = builder.build();
            Request request = new Request.Builder()
                    .url(getMinerU_URL() + "file_parse")
                    .method("POST", body)
                    .addHeader("Content-Type", "multipart/form-data")
                    .build();
            String result = Objects.requireNonNull(HTTP_CLIENT.newCall(request).execute().body()).string();
            if (StringUtils.isNotBlank(result)) {
                return JsonUtils.deSerialize(result, MinerUResult.class);
            }
            return null;
        } catch (IOException e) {
            logger.error("MinerU 调用失败", e);
            throw new BusinessException("MinerU 调用失败");
        }
    }


}
