
package com.bcxin.identify.util.huawei;

import com.alibaba.fastjson.JSON;
import com.bcxin.identify.util.codes.HuaweiMeetConst;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Map;

@Slf4j
public class HttpBuildUtil {

    private static String url = HuaweiMeetConst.GATEWAY_URL;


    private static String schema = CheckPathUtil.getSchemeFromHttpAddress(url);

    private static String ip = CheckPathUtil.getIpFromHttpAddress(url);

    private static int port = CheckPathUtil.getPortFromHttpAddress(url);

    public static HttpHost getHttpHost(){
        HttpHost httpHost = new HttpHost(ip,port,schema);
        return httpHost;
    }

    public static RestRequest buildRestRequest(String method, Map<String,String> headers, String entity,Map<String,String> params){
        RestRequest restRequest = new RestRequest();
        headers.put("Content-Type","application/json");
        restRequest.setHttpHeaders(headers);
        restRequest.setHttpMethod(method);

        if(entity != null){
            restRequest.setEntity(entity);
        }

        if(params != null){
            restRequest.setParameters(params);
        }

        log.info("restRequest is: " + restRequest.toString());
        return restRequest;
    }

    public static RestResponse sendMsg(String resourceUri, RestRequest restRequest) {
        log.info("enter sendMsg");
        HttpHost host = getHttpHost();
        RestResponse response = null;
        try {
            response = HttpUtil.getInstance().sendMessage(host, resourceUri, restRequest);
            log.info("response is: "+ response.toString());
        } catch (URISyntaxException e) {
            log.error("send msg uri syntax error:" + e.getMessage());
        } catch (IOException e) {
            log.error("send msg io error:" + e.getMessage());
        }
        log.info("out sendMsg");
        return response;
    }

    /**
     * <b> 返回结果处理 </b>
     * @author ZXF
     * @create 2020/04/15 0015 14:22
     * @version
     * @注意事项 </b>
     */
    public static String failMsg(RestResponse response) {
        String msg = "";
        int httpCode = response.getHttpCode();
        if(httpCode != 200){
            Map<String, Object> resultMap = getMapData(response);
            if(resultMap != null && resultMap.get("error_code")!=null){
                String error_code = String.valueOf(resultMap.get("error_code"));
                msg = ErrorEnum.errorMsg(error_code);
            }else{
                msg = "服务端异常！";
            }
        }
        return msg;
    }

    public static Map<String, Object> getMapData(RestResponse response) {
        if(response.getEntity() == null){
            return null;
        }
        return JSON.parseObject(response.getEntity(), Map.class);
    }

}
