package com.wms_main.repository.http.entity;

import com.wms_main.repository.http.enums.HttpMethodEnum;
import com.wms_main.repository.utils.StringUtils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.HashMap;
import java.util.Map;

/**
 * HTTP 请求类
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class HttpRequest {
    /**
     * url
     */
    private String url;
    /**
     * 超时时长
     */
    private Integer timeout = 5000;
    /**
     * 请求方式
     */
    private HttpMethodEnum method;
    /**
     * 内容格式
     */
    private String contentType = "application/json";
    /**
     * 数据
     */
    private String data;
    /**
     * token
     */
    private String token;
    /**
     * header
     */
    private Map<String, String> header;

    /**
     * 构建一个POST请求
     * @param url 接口地址
     * @param data 数据
     * @param timeout 超时时长
     * @param contentType 请求头
     * @param token token
     * @return post请求体
     * @param <T> 数据类型
     */
    public static <T> HttpRequest postInstanceOf(String url, T data, Integer timeout, String contentType, String token) {
        if (timeout == null || timeout <= 1000) {
            timeout = 5000;
        }
        if (StringUtils.isEmpty(contentType)) {
            contentType = "application/json";
        }
        return new HttpRequest(url.trim(), timeout, HttpMethodEnum.POST, contentType, StringUtils.objectToString(data), token, new HashMap<>());
    }

    /**
     * 构建一个POST请求
     * @param url 接口地址
     * @param data 数据
     * @return post请求体
     * @param <T> 数据类型
     */
    public static <T> HttpRequest postInstanceOf(String url, T data) {
        return postInstanceOf(url.trim(), data, 5000, "application/json",  "");
    }

    /**
     * 构建get请求
     * @param url url
     * @param timeout 超时
     * @param header 请求头
     * @return 结果
     */
    public static HttpRequest getInstanceOf(String url, Integer timeout, Map<String, String> header) {
        if (timeout == null || timeout <= 1000) {
            timeout = 5000;
        }
        return new HttpRequest(url.trim(), timeout, HttpMethodEnum.GET, "", "", "", header);
    }
}
