package com.gic.haoban.manage.api.util;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigService;
import com.gic.haoban.manage.api.constants.StatisticsApolloKeyConstant;
import com.gic.haoban.manage.api.dto.statistics.StatisticsDTO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 描述: DataHttpUtil
 *
 * @author yujie
 * @date 2021/12/29 17:57
 */
public class DataHttpUtil {

    private final static Logger logger = LoggerFactory.getLogger(DataHttpUtil.class);


    public static StatisticsDTO post(String apolloKey, Object body) {
        Config config = ConfigService.getConfig("COMMON.data-api-config");
        String value = config.getProperty(apolloKey, "");
        if (StringUtils.isBlank(value)) {
            throw new RuntimeException("配置有误！");
        }
        String[] split = value.split(StatisticsApolloKeyConstant.INTERVAL);
        String url = split[0];
        String token = split[1];
        HttpRequest request = HttpUtil.createPost(url);
        request.body(JSON.toJSONString(body));
        // milliseconds – 超时毫秒数
        request.timeout(10000);
        request.header("API-TOKEN", token);
        logger.info("当前请求: {}", JSON.toJSONString(request, true));
        logger.info("当前请求参数: {}", JSON.toJSONString(body, true));
        HttpResponse execute = request.execute();
        String responseBody = execute.body();
        logger.info("当前请求结果 : {}", JSONUtil.formatJsonStr(responseBody));
        StatisticsDTO responseBodyDTO = JSON.parseObject(responseBody, StatisticsDTO.class);
        if (!execute.isOk() || !responseBodyDTO.getSuccess()) {
            logger.error("请求数据组失败：{}", responseBody);
        }
        return responseBodyDTO;
    }
}