package com.chinaitop.depot.intelligent.utils;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.unissoft.model.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.Iterator;
import java.util.Map;

/**
 * @author qingsong.han
 * @description: http远程工具类
 * @create 2023-07-10 17:22
 */
@Component
public class RemoteControlUtil {

    /**
     * rest接口注入
     */
    @Resource
    private RestTemplate restTemplate;

    /**
     * POST 方法重载
     * @param url http
     * @param requestEntity 参数对象
     * @return ResponseEntity
     */
    public JSONObject remoteScan(@Valid @NotNull String url, JSONObject requestEntity) {
        return restTemplate.postForObject(url, requestEntity, JSONObject.class);
    }

    /**
     * GET 方法重载
     * @param url http
     * @param requestMap 参数对象
     * @return ResponseEntity
     */
    public ResponseEntity remoteScan(@Valid @NotNull String url, Map requestMap) {
        return restTemplate.getForObject(getForObject(url, requestMap), ResponseEntity.class);
    }

    /**
     * 封装的get请求，暂时只支持map传参，并且value只支持基本类型和String
     *
     * @param url    库端配置url
     * @param object 接收数据(只支持map类型)
     * @return string类型带参数get请求url
     */
    private static String getForObject(String url, Object object) {
        StringBuilder stringBuilder = new StringBuilder(url);
        if (object instanceof Map) {
            Iterator iterator = ((Map) object).entrySet().iterator();
            if (iterator.hasNext()) {
                stringBuilder.append("?");
                Object element;
                while (iterator.hasNext()) {
                    element = iterator.next();
                    Map.Entry entry = (Map.Entry) element;
                    //过滤value为null，value为null时进行拼接字符串会变成 "null"字符串
                    if (entry.getValue() != null) {
                        stringBuilder.append(element).append("&");
                    }
                    url = stringBuilder.substring(0, stringBuilder.length() - 1);
                }
            }
        } else {
            throw new RuntimeException("url请求:" + url + "请求参数有误不是map类型");
        }
        return url;
    }

}
