package com.fjhx.controller;

import com.alibaba.fastjson.JSONObject;
import org.springblade.core.tool.api.R;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.lang.NonNull;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.ResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;

@RestController
public class forward {

    private static final String prefix = "http://192.168.1.73:10010";


    private static final RestTemplate restTemplate;

    static {
        ResponseErrorHandler responseErrorHandler = new ResponseErrorHandler() {
            @Override
            public boolean hasError(@NonNull ClientHttpResponse response) {
                return false;
            }

            @Override
            public void handleError(@NonNull ClientHttpResponse response) {
            }
        };

        restTemplate = new RestTemplateBuilder().errorHandler(responseErrorHandler).build();
    }


    @PostMapping("/py/**")
    public R post(@RequestBody Object obj, HttpServletRequest request) {
        String path = prefix + request.getRequestURI().substring(3);

        //headers
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.add("User-Id", "23124124231342");

        //HttpEntity
        HttpEntity<Object> requestEntity = new HttpEntity<>(obj, requestHeaders);

        // ResponseEntity封装了返回的数据，包括了request、body、header等
        ResponseEntity<String> response = restTemplate.postForEntity(path, requestEntity, String.class);

        if (response.getStatusCode().is5xxServerError()) {
            return R.fail("服务器异常");
        }

        return R.data(response.getStatusCode().value(), JSONObject.parseObject(response.getBody()), "");
    }

//    @GetMapping("/py/**")
//    public R get() {
//
//        String requestURI = request.getRequestURI();
//        System.out.println(requestURI.substring(8));
//
//
//        String result = restTemplate.getForObject(path + requestURI.substring(3), String.class);
//        System.out.println(result);
//
//        return R.success(JSONObject.parseObject(result));
//    }

}
