package com.huigou.topsun.sap.common;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.huigou.cache.SystemCache;
import com.huigou.topsun.sap.common.serializer.MessageSerializer;
import com.huigou.uasp.bmp.common.application.BaseApplication;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Base64;
import java.util.Map;
import java.util.stream.Collectors;

/**
 */
@Component
public class DefaultHttpClient extends BaseApplication implements HttpClient {

    private final static Logger LOG = LoggerFactory.getLogger(DefaultHttpClient.class);
    private final MessageSerializer messageSerializer;
    private final org.apache.http.client.HttpClient http = HttpClientBuilder.create().build();

    @Autowired
    public DefaultHttpClient(MessageSerializer messageSerializer) {
        this.messageSerializer = messageSerializer;
    }

    @Override
    public String execute(Object param,String url) throws IOException {
        //系统接口地址
        //  ip地址
        String ip = SystemCache.getParameter("sap.service.ip", String.class);
        //  上下文
        String applicationContext = SystemCache.getParameter("sap.service.application.context", String.class);
        //  用户名
        String password = SystemCache.getParameter("ap.service.password", String.class);
        //  密码
        String username = SystemCache.getParameter("sap.service.username", String.class);
        //  客户端
        String client = SystemCache.getParameter("sap.service.client", String.class);
        //String serverUrl = "http://192.168.3.109:8000/sap/bc/erp_ep/bd_mastdata/material?sap-client=200";
        StringBuffer serverUrl = new StringBuffer();
        serverUrl
                .append(ip)
                .append(applicationContext)
                .append(url)
                .append("?")
                .append(client);
        HttpPost post = new HttpPost(serverUrl.toString());
        String usernameAndPassword = username + ":" + password;
        post.addHeader("Authorization", "Basic " + Base64.getEncoder().encodeToString(usernameAndPassword.getBytes()));
        //post.addHeader("token",SystemCache.getParameter("material.token",String.class));
//        String requestText = messageSerializer.serialize(param);


        String requestText = new ObjectMapper().writeValueAsString(param);
        LOG.info("requestText={}", requestText);
        post.setEntity(new StringEntity(requestText, ContentType.APPLICATION_JSON));
        LOG.info("post={}", post);
        HttpResponse response;
        String responseText = "";
        try {
            response = http.execute(post);
            LOG.info("response={}", response);
            StatusLine statusLine = response.getStatusLine();
            LOG.info("statusLine={}", statusLine);
            int statusCode = statusLine.getStatusCode();
            if (statusLine.getStatusCode() < HttpStatus.SC_OK || statusLine.getStatusCode() >= HttpStatus.SC_MULTIPLE_CHOICES) {
                throw new IOException(String.format("调用SAP系统出错，statusCode=%s, %s", statusCode, statusLine.getReasonPhrase()));
            }
            responseText = IOUtils.readLines(response.getEntity().getContent())
                    .stream()
                    .collect(Collectors.joining("\n"));
            LOG.info("responseText={}", responseText);
            LOG.info("----------->> 调用SAP接口 {} 成功 <<-----------", serverUrl);
        }finally {
            post.releaseConnection();
        }
    return responseText;
    }

}
