package com.yunyan.business.utils.baiduNlp;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.yunyan.business.utils.baiduNlp.pojo.*;
import com.yunyan.common.utils.StringUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.List;

/**
 * 百度 文本纠错
 */
@Slf4j
public class BaiduEcnetUtils {

    private final static String TOKEN_URL = "https://aip.baidubce.com/oauth/2.0/token";

    private final static String ECNET_URL = "https://aip.baidubce.com/rpc/2.0/nlp/v1/ecnet";

    @SneakyThrows
    public static void main(String[] args) {
        getAccessToken("w44MD4OgLfHzTFMVutsvuvOL", "oWgMplNUeUnTWA8iBS8h7jzaiEwqMS3y");
        //ecnet("百度是一家人工只能公司,百度是一家人工智障公司", "24.36b706428116f6280b60a3d5f797415c.2592000.1696492880.282335-38824649");
        ecnet("百度是一家人工只能公司,百度是一家人慌指能公司", "24.cb8048a203e185c513d1e1141218939b.2592000.1700893836.282335-38824649");
    }

    public static BaiduEcnetVo ecnet(String text, String token) {
        String url = ECNET_URL + "?charset=UTF-8&access_token=" + token ;

        BaiduEcnetDto dto = new BaiduEcnetDto();
        dto.setText(text);
        String bodyJson = JSONUtil.toJsonStr(dto);

        String result = HttpRequest.post(url)
                .body(bodyJson)
                .timeout(20000)
                .execute().body();

        log.debug("百度纠错的 返回 " + result);

        BaiduEcnetVo resultVo = JSONObject.parseObject(result, new TypeReference<BaiduEcnetVo>(){});

        return resultVo;
    }

    /**
     * 获取 百度的nlp 的 token
     * @param
     * @return
     * @throws IOException
     */
    public static String getAccessToken(String client_id, String client_secret) throws IOException {

        BaiduTokenDto dto = new BaiduTokenDto();
        dto.setClient_id(client_id);
        dto.setClient_secret(client_secret);
        String bodyJson = JSONUtil.toJsonStr(dto);

        String url = TOKEN_URL + String.format("?charset=UTF-8&grant_type=client_credentials&client_id=%s&client_secret=%s&", client_id, client_secret) ;

        String result = HttpRequest.post(url)
                .body(bodyJson)
                .timeout(20000)
                .execute().body();
        if(StringUtils.isBlank(result)) {
            return "";
        }

        log.debug("token result [{}]", result);

        String accessToken = String.valueOf(JSONUtil.parseObj(result).get("access_token"));

        return accessToken;
    }


}
