package com.fs.aicall.utils;


import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fs.aicall.config.AiCallConfig;
import lombok.extern.slf4j.Slf4j;

import java.time.Instant;
import java.util.function.Function;

@Slf4j
public class AiCallUtils {

    private final AiCallConfig config;
    private final static ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    public AiCallUtils(AiCallConfig config) {
        this.config = config;
    }

    public String getDialogUrl(){
        return config.getDialogUrl();
    }

    public String encrypt(String customer, long timestamp, int seq, String password) {

        // 获取输入字符串的字节数组
        byte[] messageDigest = Md5Utils.md5(customer + "@" + timestamp + "@" + seq + "@" + password);
        // 将字节数组转为十六进制字符串
        StringBuilder hexString = new StringBuilder();
        for (byte b : messageDigest) {
            // 将每个字节转换为两位的十六进制表示
            String hex = Integer.toHexString(0xFF & b);
            if (hex.length() == 1) {
                hexString.append("0");
            }
            hexString.append(hex);
        }
        // 返回 MD5 加密后的字符串
        return hexString.toString();
    }

    public String getParams(ObjectNode params){
        try {
            long timestamp = Instant.now().getEpochSecond();
            int seq = RandomUtil.randomInt(1000, 1000000);
            ObjectNode rootNode = OBJECT_MAPPER.createObjectNode();
            rootNode.putObject("authentication")
                    .put("customer", config.getCustomer())
                    .put("timestamp", timestamp)
                    .put("seq", seq)
                    .put("digest", encrypt(config.getCustomer(), timestamp, seq, config.getPassword()));
            if(params == null){
                rootNode.putObject("request").put("seq", seq);
            }else{
                rootNode.set("request", params);
            }
            return OBJECT_MAPPER.writeValueAsString(rootNode);
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    public <T> T send(String addr, Function<JSONObject, T> dataFun){
        return send(addr, null, dataFun);
    }
    public <T> T send(String addr, ObjectNode params, Function<JSONObject, T> dataFun){
        String url = config.getUrl() + addr;
        String body = getParams(params);
        HttpRequest request = HttpUtil.createPost(url).body(body);
        request.header("Accept", "application/json");
        request.header("Content-Type", "application/json");
        HttpResponse execute = request.execute();
        JSONObject json = JSON.parseObject(execute.body());
        JSONObject result = json.getJSONObject("result");
        if(!"0".equals(result.getString("error"))){
            log.error("AI外呼接口异常数据:{}", json);
            throw new RuntimeException(result.getString("msg"));
        }
        return dataFun.apply(json.getJSONObject("data").getJSONObject("response"));
    }




}
