package com.bocloud.ims.service.installation;

import com.alibaba.fastjson.JSONObject;
import com.bocloud.cmp.entity.enums.installation.EndPoints;
import com.bocloud.common.enums.BoCloudMethod;
import com.bocloud.common.enums.PostDataFormat;
import com.bocloud.common.http.HttpClient;
import com.bocloud.common.model.Result;
import com.bocloud.common.utils.MapTools;
import com.bocloud.ims.common.config.installation.RackHdConfig;
import com.bocloud.ims.common.utils.constant.Constant;
import com.bocloud.ims.interfaces.installation.RackHdService;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntityEnclosingRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

/**
 * 请求Rackhd方法的实现
 *
 * @author 007
 */
@Component("rackHdServiceImpl")
public class RackHdServiceImpl implements RackHdService {

    private static Logger logger = LoggerFactory.getLogger(RackHdServiceImpl.class);

    private static Map<String, Object> headers = MapTools.simpleMap("Content-Type", "application/json");

    @Autowired
    private RackHdConfig rackHdConfig;

    @Override
    public String buildUrl(String ref) {
        StringBuilder builder = new StringBuilder();
        builder.append(Constant.HTTP_PREFIX).append(rackHdConfig.getIp()).append(":").append(rackHdConfig.getPort())
                .append(ref);
        return builder.toString();
    }

    @Override
    public String buildUrl(final EndPoints endPoints, String param) {
        StringBuilder builder = new StringBuilder();
        builder.append(Constant.HTTP_PREFIX).append(rackHdConfig.getIp()).append(":").append(rackHdConfig.getPort())
                .append(String.format(endPoints.getValue(), param));
        return builder.toString();
    }

    @Override
    public String buildUrl(final EndPoints endPoints, String param, Map<String, String> paramMap) {
        StringBuilder builder = new StringBuilder();
        builder.append(Constant.HTTP_PREFIX).append(rackHdConfig.getIp()).append(":").append(rackHdConfig.getPort())
                .append(String.format(endPoints.getValue(), param));
        if (paramMap != null) {
            Set<Map.Entry<String, String>> entrySet = paramMap.entrySet();
            int index = 0;
            for (Map.Entry<String, String> e : entrySet) {
                index++;
                if (index == 1) {
                    builder.append("?");
                } else {
                    builder.append("&");
                }
                builder.append(e.getKey()).append("=").append(e.getValue());
            }
        }
        return builder.toString();
    }

    @SuppressWarnings("unchecked")
    @Override
    public Result request(String jsonData, String url, BoCloudMethod method) {
        Result result;
        try {
            HttpClient client = new HttpClient(1000 * 10, PostDataFormat.RAW) {
                @Override
                public void buildEntity(HttpEntityEnclosingRequest request, Object params) {
                    if (params == null) {
                        return;
                    }
                    super.buildEntity(request, params);
                }
            };
            Map<String, Object> params = null;
            if (StringUtils.isNotEmpty(jsonData)) {
                params = JSONObject.parseObject(jsonData, HashMap.class);
            }
            switch (method) {
                case GET:
                    result = client.get(headers, params, url);
                    break;
                case POST:
                    result = client.post(headers, params, url);
                    break;
                case PATCH:
                    result = client.patch(headers, params, url);
                    break;
                case PUT:
                    result = client.put(headers, params, url);
                    break;
                case DELETE:
                    result = client.delete(headers, params, url);
                    break;
                default:
                    result = new Result(false, "请求方法不支持");
                    break;
            }
        } catch (Exception e) {
            logger.error("远程服务调用失败:", e);
            return new Result(false, "远程服务调用失败");
        }
        return result;
    }

}
