package com.zm.order.tool.server.controller;

import com.alibaba.fastjson.JSON;
import com.zm.order.tool.server.request.ForwardRequest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

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

/**
 * @Description 商品中心运维工具转发
 * @Author: ph
 * @Date: 2020/12/3 15:47
 */
@RestController
@RequestMapping(value = "qapi/goods-center-tool/")
@Api(value = "商品中心运维工具", tags = "商品中心运维工具")
public class GoodsCenterToolController {

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

    @Value("${goods.center.tool.url}")
    private String goodsCenterToolUrl;

    @RequestMapping(value = "/forward", method = RequestMethod.POST)
    @ApiOperation("重定向")
    public void forward(@RequestBody ForwardRequest request) throws URISyntaxException, IOException {
        logger.info("forward request:{}", request.toString());
        HttpClientBuilder httpClientBuilder = HttpClients.custom();
        CloseableHttpClient httpClient = httpClientBuilder.build();
        String uri = goodsCenterToolUrl + request.getPath();
        HttpPost httpPost = new HttpPost();
        httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
        httpPost.setHeader("X-APP-ID", "");
        httpPost.setHeader("X-APP-KEY", "");
        httpPost.setHeader("X-Transaction-ID", UUID.randomUUID().toString());
        httpPost.setURI(new URI(uri));
        HttpEntity requestEntity = new StringEntity(JSON.toJSONString(request.getParam()));
        httpPost.setEntity(requestEntity);
        CloseableHttpResponse response = httpClient.execute(httpPost);
        HttpEntity responseEntity = response.getEntity();
        String response1 = EntityUtils.toString(responseEntity);
        logger.info("forward url:{}, response:{}", uri, response1);

    }
}
