package net.northking.cctp.executePlan.api.third.util;

import com.alibaba.cloud.commons.lang.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

/**
 * 飞狼调用工具类
 *
 * @author yujinfa
 * @date 2023/09/18
 */
public class FLHttpClientUtils {

    private final static Logger log = LoggerFactory.getLogger(FLHttpClientUtils.class);

    public static String doPostFormData(String url, String fileParamName, MultipartFile multipartFile, Map<String, String> paramMap,String ak) {
        log.info("sendurl:" + url+"data:" + paramMap);
        // 创建Http实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建HttpPost实例
        HttpPost httpPost = new HttpPost(url);
        // 请求参数配置
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000)
                .setConnectionRequestTimeout(60000).build();
        httpPost.setConfig(requestConfig);
        if (StringUtils.isNotBlank(ak)){
            httpPost.setHeader("ak",ak);
        }
        try {
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setCharset(java.nio.charset.Charset.forName("UTF-8"));
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            if (multipartFile !=null) {
                String fileName = multipartFile.getOriginalFilename();
                // 文件流
                builder.addBinaryBody(fileParamName, multipartFile.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);
            }
                //表单中其他参数
            for(Map.Entry<String, String> entry: paramMap.entrySet()) {
                builder.addPart(entry.getKey(),new StringBody(entry.getValue(), ContentType.create("text/plain", Consts.UTF_8)));
            }
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);// 执行提交
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 返回
                String res = EntityUtils.toString(response.getEntity(), java.nio.charset.Charset.forName("UTF-8"));
                log.info("返回结果："+res);
                return res;
            }else{
                log.error("[{}]请求返回http code 为 [{}]",url,response.getStatusLine().getStatusCode());
            }
        } catch (Exception e) {
            log.error("",e);
            log.error("调用HttpPost失败！" + e.toString());
        } finally {
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    log.error("关闭HttpPost连接失败！");
                }
            }
        }
        return null;
    }
}
