package com.pj.api.jh.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.pj.project4sp.global.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@Slf4j
public class JhHttpUtils {

    @Retryable(maxAttempts = 10, backoff = @Backoff(delay = 3000, maxDelay = 6200))
    public String postJson(String url, String body) {
        log.info("开始请求接口:{},{}", url, body);
        String resp = HttpUtil.createPost(url)
                .header("Content-Type", "application/json")
                .setConnectionTimeout(3000).setReadTimeout(2000)
                .body(body)
                .execute().body();
        log.info("接口返回:{},{}", url, resp);
        return resp;
    }

    @Retryable(maxAttempts = 10, backoff = @Backoff(delay = 3000, maxDelay = 4000))
    public String postForm(String url, Map<String, Object> params) {
        log.info("开始请求接口:{},{}", url, JSONUtil.toJsonStr(params));
        String resp = HttpUtil.createPost(url)
                .setConnectionTimeout(3000).setReadTimeout(2000)
                .form(params)
                .execute().body();
        log.info("接口返回:{},{}", url, resp);
        return resp;
    }

    @Retryable(maxAttempts = 15, backoff = @Backoff(delay = 3000, maxDelay = 10000))
    public JSONObject checkStatus(String url, Map<String, Object> params) {
        log.info("检查支付状态:{},{}", url, JSONUtil.toJsonStr(params));
        String resp = HttpUtil.createPost(url)
                .setConnectionTimeout(3000)
                .setReadTimeout(2000)
                .form(params)
                .execute().body();
        log.info("检查支付状态返回:{},{}", url, resp);
        JSONObject result = JSONUtil.parseObj(resp);
        if (!StrUtil.equals(result.getStr("resultCode"), "0000")) {
            throw new BusinessException(result.getStr("errMsg"));
        }
        return result;
    }
}
