package com.css.txw.common.net;

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Map;

@Slf4j
@Service
public class HttpHutoolImpl implements IHttpService {

    public final static String CONTENT_TYPE_JSON = "application/json";
    public final static String CONTENT_TYPE_FORM = "multipart/form-data;";
    public final static String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36";
    public final static String ACCEPT = "application/json, text/plain, */*";

    public HttpResponse get(String url) {
        HttpRequest request = HttpUtil.createGet(url);
        return this.executeReq(request);
    }

    @Override
    public HttpResponse get(String url, Map<String, Object> params) {
        HttpRequest request = HttpUtil.createGet(url);
        request.form(params);
        return this.executeReq(request);
    }

    @Override
    public HttpResponse postForm(String url, Map<String, Object> form) {
        HttpRequest request = HttpUtil.createPost(url);
        request.form(form);
        return this.executeReq(request, CONTENT_TYPE_FORM);
    }

    @Override
    public HttpResponse postForm(String url, Map<String, Object> form, Map<String, File> files) {
        HttpRequest request = HttpUtil.createPost(url);
        request.form(form);
        if (null != files) {
            for (String key : files.keySet()) {
                request.form(key, files.get(key), files.get(key).getName());
            }
            request.timeout(1000 * 60);
        }
        return this.executeReq(request, CONTENT_TYPE_FORM);
    }

    @Override
    public <T> T postJson(String url, String body, Class<T> resType) {
        HttpRequest request = HttpUtil.createPost(url);
        if (StringUtils.isNotBlank(body)) {
            request.body(body);
        }
        try {
            HttpResponse response = this.executeReq(request);
            if (response.isOk()) {
                String resBody = response.body();
                log.info("Hutool http response body: {}", resBody);
                return new Gson().fromJson(resBody, resType);
            } else {
                log.info("请求失败，状态码：{}", response.getStatus());
            }
        } catch (Exception e) {
            log.error("error:", e);
        }
        return null;
    }

    private HttpResponse executeReq(HttpRequest request) {
        return this.executeReq(request, CONTENT_TYPE_JSON);
    }

    private HttpResponse executeReq(HttpRequest request,String contentType) {
        request.contentType(contentType).header(Header.USER_AGENT, USER_AGENT).header(Header.ACCEPT, ACCEPT);
        return request.execute();
    }


}
