package shop.alien.util.common.netease;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.http.Consts;
import org.apache.http.client.HttpClient;
import shop.alien.util.common.netease.util.HttpClient4Utils;
import shop.alien.util.common.netease.util.SignatureUtils;
import shop.alien.util.common.netease.util.Utils;
import shop.alien.util.common.netease.util.HttpClient4Utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

/**
 * @author ssk
 * @version 1.0
 * @date 2025/4/15 16:02
 */
public class ImageCheckUtil {

    /**
     * 产品密钥ID，产品标识
     */
    private final static String SECRETID = "3d5df66745bfcce3677b3750120b53c6";
    /**
     * 产品私有密钥，服务端生成签名信息使用，请严格保管，避免泄露
     */
    private final static String SECRETKEY = "4e8b4c4bbc063e4d9224b0ada5da40ab";
    /**
     * 业务ID，易盾根据产品业务特点分配
     */
    private final static String BUSINESSID = "4662902327fca4bf62efe73ea3fcfb12";
    /**
     * 易盾反垃圾云服务图片在线检测接口地址
     */
    private static String API_URL;
    /**
     * 实例化HttpClient，发送http请求使用，可根据需要自行调参
     */
    private static HttpClient httpClient = HttpClient4Utils.createHttpClient(100, 20, 10000, 2000, 2000);

    /**
     * 检测图片内容
     *
     * @param content   图片
     * @param imageType 1:链接, 2:base64
     * @return map
     */
    public static Map<String, String> check(String content, Integer imageType) {
        Map<String, String> resultMap = new HashMap<>();
        Map<String, String> params = new HashMap<>();
        // 1.设置公共参数
        params.put("secretId", SECRETID);
        params.put("businessId", BUSINESSID);
        params.put("version", "v5.1");
        params.put("timestamp", String.valueOf(System.currentTimeMillis()));
        params.put("nonce", String.valueOf(new Random().nextInt()));
        // MD5, SM3, SHA1, SHA256
        params.put("signatureMethod", "MD5");
        // 2.设置私有参数
        JsonArray jsonArray = new JsonArray();

        if (imageType == 1) {
            //链接
            API_URL = "https://as.dun.163.com/v5/image/check";
            JsonObject image1 = new JsonObject();
            image1.addProperty("name", content);
            image1.addProperty("type", 1);
            image1.addProperty("data", content);
            jsonArray.add(image1);
        } else {
            //base64
            API_URL = "https://as.dun.163.com/v5/image/base64Check";
            JsonObject image2 = new JsonObject();
            String uuid = UUID.randomUUID().toString();
            image2.addProperty("name", "{\"imageId\": " + uuid + ", \"contentId\": " + uuid + "}");
            image2.addProperty("type", 2);
            image2.addProperty("data", content);
            jsonArray.add(image2);
        }

        params.put("images", jsonArray.toString());

        // 预处理参数
        params = Utils.pretreatmentParams(params);
        // 3.生成签名信息
        String signature = SignatureUtils.genSignature(SECRETKEY, params);
        params.put("signature", signature);

        // 4.发送HTTP请求，这里使用的是HttpClient工具包，产品可自行选择自己熟悉的工具包发送请求
        String response = HttpClient4Utils.sendPost(httpClient, API_URL, params, Consts.UTF_8);

        // 5.解析接口返回值
        JsonObject resultObject = new JsonParser().parse(response).getAsJsonObject();
        int code = resultObject.get("code").getAsInt();
        String msg = resultObject.get("msg").getAsString();
        if (code == 200) {
            // 图片反垃圾结果
            JsonArray resultArray = resultObject.getAsJsonArray("result");
            for (JsonElement jsonElement : resultArray) {
                JsonObject jObject = jsonElement.getAsJsonObject();
                JsonObject antispam = jObject.get("antispam").getAsJsonObject();
                int status = antispam.get("status").getAsInt();
                // 检测状态 0 未开始、1检测中、2检测成功、3检测失败
                if (2 == status) {
                    // 图片维度结果
                    //建议动作，0：通过，1：嫌疑，2：不通过
                    int suggestion = antispam.get("suggestion").getAsInt();
                    switch (suggestion) {
                        case 0:
                            resultMap.put("suggestion", "通过");
                            resultMap.put("result", "0");
                            break;
                        case 1:
                            resultMap.put("suggestion", "嫌疑");
                            resultMap.put("result", "1");
                            break;
                        case 2:
                            resultMap.put("suggestion", "不通过");
                            resultMap.put("result", "1");
                            break;
                        default:
                            break;
                    }
                } else {
                    resultMap = null;
                }
            }
        } else {
            resultMap = null;
        }
        return resultMap;
    }

    /**
     * file转换为base64
     * 注意：这里转换为base64后，是不包含文件head头的
     */
    public static String fileToBase64(File file) {
        Base64.Encoder base64 = Base64.getEncoder();
        String base64Str = null;
        try (FileInputStream fis = new FileInputStream(file);
             ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            base64Str = base64.encodeToString(bos.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return base64Str;
    }

}
