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

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

import cn.com.poc.common.utils.DocumentLoad;
import cn.com.poc.common.utils.http.LocalHttpClient;
import cn.com.poc.thirdparty.resource.demand.ai.function.extraction.entity.Config;
import cn.com.poc.thirdparty.resource.demand.ai.function.extraction.entity.KeyInfo;
import cn.com.poc.thirdparty.resource.demand.ai.function.extraction.entity.RequestData;
import cn.com.yict.framemax.core.exception.BusinessException;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TextInClient {

    final private Logger logger = LoggerFactory.getLogger(TextInClient.class);
    private String appId = "dafd04a574230c00ccba61132160de0c";
    private String secretCode = "3bc03c7e6f9402963e6e71d16d786a9c";

    public TextInClient() {
    }

    public TextInClient(String appId, String secretCode) {
        this.appId = appId;
        this.secretCode = secretCode;
    }

    /**
     * ocr
     *
     * @param fileContent
     * @param options
     * @return
     * @throws IOException
     */
    public String OCR(byte[] fileContent, HashMap<String, Object> options) throws IOException {
        StringBuilder queryParams = new StringBuilder();
        for (Map.Entry<String, Object> entry : options.entrySet()) {
            if (queryParams.length() > 0) {
                queryParams.append("&");
            }
            queryParams.append(URLEncoder.encode(entry.getKey(), "UTF-8"))
                    .append("=")
                    .append(URLEncoder.encode(entry.getValue().toString(), "UTF-8"));
        }
        HttpURLConnection connection = getOCRHttpURLConnection(queryParams);
        try (OutputStream os = connection.getOutputStream()) {
            os.write(fileContent);
            os.flush();
        }

        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            try (BufferedReader in = new BufferedReader(
                    new InputStreamReader(connection.getInputStream()))) {
                StringBuilder response = new StringBuilder();
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                return response.toString();
            }
        } else {
            logger.error("HTTP request failed with code: {}, Error message view :{}", responseCode, "https://www.textin.com/document/pdf_to_markdown");
            throw new IOException("HTTP request failed with code: " + responseCode);
        }
    }


    private HttpURLConnection getOCRHttpURLConnection(StringBuilder queryParams) throws IOException {
        String baseUrl = "https://api.textin.com/ai/service/v1/pdf_to_markdown";
        String fullUrl = baseUrl + (queryParams.length() > 0 ? "?" + queryParams : "");
        URL url = new URL(fullUrl);

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("x-ti-app-id", appId);
        connection.setRequestProperty("x-ti-secret-code", secretCode);
        connection.setRequestProperty("Content-Type", "text/plain;charset=utf-8");
        connection.setDoOutput(true);
        return connection;
    }

    /**
     * 【合同抽取】-创建抽取
     * https://www.textin.com/document/doc_extraction_create
     *
     * @param fileUrl
     * @param keyInfoList
     * @return
     */

    public String extraction(String fileUrl, List<KeyInfo> keyInfoList) {
        try {
            // 读取文件并将其转换为Base64编码
            File file = DocumentLoad.downloadURLDocument(fileUrl);
            byte[] fileData = Files.readAllBytes(file.toPath());
            String base64FileData = Base64.getEncoder().encodeToString(fileData);

            // 获取文件名
            String fileName = file.getName();

            // 构建请求数据
            Config config = new Config("table", "true", "true", "false");
            RequestData requestData = new RequestData("", config, base64FileData, fileName, keyInfoList.toArray(new KeyInfo[0]));

            // 创建ObjectMapper对象，序列化Java对象为JSON
            ObjectMapper objectMapper = new ObjectMapper();
            String requestDataJson = objectMapper.writeValueAsString(requestData);

            // 创建URL对象
            URL url = new URL("https://doc-compare.intsig.com/api/contracts/v3/extraction/external/create");

            // 打开HTTP连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("x-ti-app-id", appId);
            connection.setRequestProperty("x-ti-secret-code", secretCode);
            connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            connection.setDoOutput(true); // 开启输出流

            // 发送请求数据
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = requestDataJson.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 获取响应代码
            int status = connection.getResponseCode();
            logger.info("Response Code: {}", status);

            // 读取响应内容
            try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                String inputLine;
                StringBuilder response = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                // 输出响应内容
                logger.info("Response: {}", response);
                JSONObject jsonResponse = JSONObject.parseObject(response.toString());
                String taskId = jsonResponse.getJSONObject("result").getString("task_id");
                return extractedResults(taskId);
            }
        } catch (IOException e) {
            throw new BusinessException(e);
        }
    }

    /**
     * 【合同抽取】 -获取抽取结果
     * https://www.textin.com/document/doc_extraction_result
     *
     * @param taskId
     * @return
     */
    private String extractedResults(String taskId) {
        String baseUrl = "https://doc-compare.intsig.com/doc_extraction/keyinfo/extracted_results?format=json&task_id=" + taskId;
        HttpUriRequest httpUriRequest = RequestBuilder.post()
                .setUri(baseUrl)
                .addHeader("x-ti-app-id", appId)
                .addHeader("x-ti-secret-code", secretCode)
                .addHeader("Content-Type", "application/json;charset=utf-8")
                .build();
        String result = LocalHttpClient.executeJsonResult(httpUriRequest, String.class);
        JSONObject resultJson = JSONObject.parseObject(result);
        Integer code = resultJson.getInteger("code");
        if (code.equals(200)) {
            return resultJson.getJSONObject("result").toJSONString();
        } else {
            logger.error("获取token失败，错误码：{}", code);
            return StringUtils.EMPTY;
        }
    }

}