package com.ruoyi.business.util;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CompreFace {

    protected static final Logger logger = LoggerFactory.getLogger(CompreFace.class);

    private static final String FACE_VERIFY_URL = "http://50.146.63.165:8000/api/v1/verification/verify";




    public static JSONObject faceVerify(String source_image,String target_image){
        // 目标URL
        String url = FACE_VERIFY_URL + "?face_plugins=landmarks&face_plugins=gender&face_plugins=age&face_plugins=pose";

        StringBuilder jsonBuilder = new StringBuilder();
        jsonBuilder.append("{")
                .append("\"source_image\": \"")
                .append(source_image)
                .append("\",\"target_image\": \"")
                .append(target_image)
                .append("\"}");
        String json = jsonBuilder.toString();

//        logger.info("Sending request with JSON: {}", json);

        // 创建HttpClient实例
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 创建HttpPost实例
            HttpPost httpPost = new HttpPost(url);

            // 设置请求头
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setHeader("x-api-key", "77997347-5c11-4e41-b290-e00c7c441b23");

            // 创建StringEntity对象，将JSON字符串设置为请求体
            StringEntity entity = new StringEntity(json, "UTF-8");
            httpPost.setEntity(entity);

            // 发送请求并获取响应
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                // 读取响应内容
                String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
                logger.info("Response: {}", responseString);
                if (responseString != null){
                    JSONObject jsonObject = new JSONObject(responseString);
                    JSONArray result = jsonObject.getJSONArray("result");
                    if (result != null){
                        JSONObject resultJSONObject = result.getJSONObject(0);
                        if (resultJSONObject != null){
                            return resultJSONObject;
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("Error sending message", e);
        }
        return null;
    }
}
