package com.zg.project.wisdom.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zg.project.wisdom.config.QwenOcrRemoteProperties;
import okhttp3.*;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Base64;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class QwenOcrRemoteService {

    private final QwenOcrRemoteProperties properties;
    private final ObjectMapper objectMapper = new ObjectMapper();

    private final OkHttpClient httpClient = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(25, TimeUnit.SECONDS)
            .writeTimeout(25, TimeUnit.SECONDS)
            .build();

    public QwenOcrRemoteService(QwenOcrRemoteProperties properties) {
        this.properties = properties;
    }

    /**
     * 从上传的图片文件中提取ERP订单号
     * 调用 250 上的 /ocr/extractErpByBase64 接口，返回采购订单号(ERP)
     *
     * @param file 上传的图片文件，支持JPEG和PNG格式
     * @return 提取到的ERP订单号，如果未找到则返回空字符串
     * @throws RuntimeException 当调用OCR服务失败或发生IO异常时抛出
     */
    public String extractErpOrderNo(MultipartFile file) {
        try {
            // 读取文件字节内容
            byte[] bytes = file.getBytes();

            // 推断文件的content type，如果无法获取则根据文件扩展名判断
            String contentType = file.getContentType();
            if (contentType == null || contentType.isEmpty()) {
                String name = file.getOriginalFilename();
                if (name != null && name.toLowerCase().endsWith(".png")) {
                    contentType = "image/png";
                } else {
                    contentType = "image/jpeg";
                }
            }

            // 将图片字节转换为Base64编码并添加data URI前缀
            String base64 = Base64.getEncoder().encodeToString(bytes);
            String imageBase64 = "data:" + contentType + ";base64," + base64;

            // 构建包含Base64图片数据的JSON请求体
            String json = objectMapper.createObjectNode()
                    .put("imageBase64", imageBase64)
                    .toString();

            RequestBody body = RequestBody.create(
                    MediaType.parse("application/json"),
                    json
            );

            String url = properties.getBaseUrl(); // yml 里配置的 /ocr/extractErpByBase64

            Request request = new Request.Builder()
                    .url(url)
                    .post(body)
                    .build();

            // 发送HTTP POST请求到OCR服务
            Response response = httpClient.newCall(request).execute();
            try {
                if (!response.isSuccessful()) {
                    String errorBody = response.body() != null ? response.body().string() : "no error body";
                    throw new RuntimeException("调用远程 OCR 服务失败，HTTP 状态码：" +
                            response.code() + "，错误信息：" + errorBody);
                }

                String resp = Objects.requireNonNull(response.body()).string();
                JsonNode rootNode = objectMapper.readTree(resp);

                // 远程服务返回：{ success: true, found: true/false, erpOrderNo: "0101398982" }
                JsonNode erpNode = rootNode.get("erpOrderNo");

                if (erpNode == null || erpNode.isNull()) {
                    return "";
                }
                return erpNode.asText("");
            } finally {
                response.close();
            }

        } catch (IOException e) {
            throw new RuntimeException("调用远程 OCR 服务异常：" + e.getMessage(), e);
        }
    }

}
