package com.crm.ucard.util;

import com.alibaba.fastjson.JSON;
import com.crm.rely.backend.util.HttpUtil;
import com.crm.rely.backend.util.MapUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Connection.Response;

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

/**
 * @Author houn
 * @Date 2025/3/31 18:55
 * @PackageName:com.crm.ucard.utils
 * @ClassName: CommonUtil
 * @Description: TODO
 */
@Slf4j
public class UcardCommonUtil {

    /**
     * post json
     *
     * @param url
     * @param paramStr
     * @return
     */
    public static String postJson(String url, String paramStr) {
        long startTime = System.currentTimeMillis();
        Response response = null;
        try {
            log.info("sendRequestJson--url:{}, ret: {}", url, paramStr);
            response = HttpUtil.post(url, paramStr);
            log.info("sendPostJson--url:{}, ret: {}, cost: {}", url, response.body(),
                    System.currentTimeMillis() - startTime);
        } catch (Exception e) {
            log.error("sendPostForm exception", e);
        }
        return response != null ? response.body() : null;
    }

    /**
     * post json
     *
     * @param url
     * @param file
     * @param paramMap
     * @return
     */
    public static String postFormData(String url, File file, Map<String, Object> paramMap) {
        long startTime = System.currentTimeMillis();
        Response response = null;
        try {
            Map<String, String> stringParamMap = MapUtil.convertToStringMap(paramMap);
            Map<String, File> fileMap = MapUtil.singletonMap("file", file);

            response = HttpUtil.post(url, stringParamMap, fileMap);
            log.info("sendPostJson url {}, param {}. result: code {}, ret: {}, cost: {}", url,
                    getExeFileString(JSON.toJSONString(paramMap)), response.statusCode(), response.body(),
                    System.currentTimeMillis() - startTime);
        } catch (Exception e) {
            log.error("exception", e);
        }
        return response != null ? response.body() : null;
    }

    private static String getExeFileString(String param) {
        if (StringUtils.isNotBlank(param)) {
            return param.replaceAll("(\"[a-zA-Z]*template\":)(\"[^\"]+\")", "#");
        }
        return param;
    }

    /**
     * post json
     * @param url
     * @param paramStr
     * @return
     */
    public static String postJsons(String url, String paramStr) {
        long startTime = System.currentTimeMillis();
        Response response = null;
        try {
            response = HttpUtil.post(url, paramStr);
            log.info("sendRequestJson--url:{}, ret: {}", url, paramStr);
            //log.info("sendPostJson--url:{}, cost: {}", url,System.currentTimeMillis() - startTime);
        } catch (Exception e) {
            log.error("sendPostForm exception", e);
        }
        return response != null ? response.body() : null;
    }


}