package com.mortals.xhx.busiz.web;

import com.alibaba.fastjson.JSON;
import com.mortals.framework.annotation.UnAuth;
import com.mortals.xhx.busiz.rsp.ApiResp;
import com.mortals.xhx.common.code.ApiRespCodeEnum;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

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

@RestController
@RequestMapping("/proxy")
@Slf4j
public class ProxyController {

    private final WebClient webClient;

    private final OkHttpClient client = new OkHttpClient();

    public ProxyController(WebClient.Builder webClientBuilder) {
        this.webClient = webClientBuilder.build();
    }

   /* @PostMapping("/post")
    @UnAuth
    public Mono<ResponseEntity<String>> proxyPost(
            @RequestParam Map<String, String> params,  // 透传 URL 参数
            @RequestBody(required = false) String body, // 透传 Body
            @RequestHeader Map<String, String> headers // 透传 Headers
    ) {

        log.info("proxyPost params: {}, body: {}, headers: {}", params, body, headers);

        ApiResp<String> rsp = new ApiResp<>();
        String path = params.getOrDefault("path", "");
        if (ObjectUtils.isEmpty(path)) {

            rsp.setCode(ApiRespCodeEnum.FAILED.getValue());
            rsp.setMsg("path is empty！");
            return Mono.just(ResponseEntity.ok().body(JSON.toJSONString(rsp)));
        }

        String method = params.getOrDefault("method", "post");
        params.remove("method");
        params.remove("path");


        String targetUrl = "http://127.0.0.1:11078/basics_api/" + path;
        String targetPath = "/basics_api" + path;
        log.info("proxyPost targetUrl: {}", targetUrl);
        if ("post".equalsIgnoreCase(method)) {
            return webClient.post()
                    .uri(uriBuilder -> {
                        uriBuilder
                                .scheme("http")
                                .host("127.0.0.1")
                                .port(11078)
                                .path(targetPath);
                        params.forEach((key, value) ->
                                uriBuilder.queryParam(key, UriUtils.encode(value, StandardCharsets.UTF_8))
                        );
                        return uriBuilder.build();

                    })
           *//*         .uri(uriBuilder -> {
                        uriBuilder.scheme("http");
                        uriBuilder.path(targetUrl);

                        params.forEach((key, value) ->
                                uriBuilder.queryParam(key, UriUtils.encode(value, StandardCharsets.UTF_8))
                        );
                        log.info("proxyPost uriBuilder: {}", uriBuilder.build());
                        return uriBuilder.build();
                    })*//*
                    .headers(httpHeaders -> headers.forEach(httpHeaders::set))
                    .bodyValue(body != null ? body : "")  // 透传 Body
                    .retrieve()
                    .toEntity(String.class);
        } else if ("get".equalsIgnoreCase(method)) {

        } else {
            //不支持
        }
        return Mono.just(ResponseEntity.ok().body(JSON.toJSONString(rsp)));
    }*/


    @PostMapping("/post")
    @UnAuth
    @CrossOrigin
    public ResponseEntity<String> proxyPost(
            @RequestParam Map<String, String> params,   // 透传 Query Params
            @RequestBody(required = false) String body, // 透传 Body
            @RequestHeader Map<String, String> headers // 透传 Headers
    ) {

        log.info("proxyPost params: {}, body: {}, headers: {}", params, body, headers);
        ApiResp<String> rsp = new ApiResp<>();
        String path = params.getOrDefault("path", "");
        if (ObjectUtils.isEmpty(path)) {
            rsp.setCode(ApiRespCodeEnum.FAILED.getValue());
            rsp.setMsg("path is empty！");
            return ResponseEntity.ok().body(JSON.toJSONString(rsp));
        }

        String method = params.getOrDefault("method", "post");
        params.remove("method");
        params.remove("path");
        String targetUrl = "http://127.0.0.1:11078/basics_api" + path; // 目标 URL

        // 拼接 Query 参数
        HttpUrl.Builder urlBuilder = HttpUrl.parse(targetUrl).newBuilder();
        params.forEach(urlBuilder::addQueryParameter);
        HttpUrl url = urlBuilder.build();

        // 构造请求体
        okhttp3.RequestBody requestBody = body != null ?
                okhttp3.RequestBody.create(MediaType.parse("application/json"), body) :
                okhttp3.RequestBody.create(null, new byte[0]);

        if ("post".equalsIgnoreCase(method)) {
            // 构造请求
            Request.Builder requestBuilder = new Request.Builder()
                    .url(url)
                    .post(requestBody);

            // 透传 Headers（过滤掉 Host 避免冲突）
            headers.forEach((key, value) -> {
                if (!key.equalsIgnoreCase("host")) {
                    requestBuilder.addHeader(key, value);
                }
            });

            // 发送请求
            try (Response response = client.newCall(requestBuilder.build()).execute()) {
                if (!response.isSuccessful()) {
                    return ResponseEntity.status(response.code()).body(response.message());
                }
                return ResponseEntity.status(response.code()).body(response.body().string());
            } catch (IOException e) {
                rsp.setCode(ApiRespCodeEnum.FAILED.getValue());
                rsp.setMsg("Proxy error: " + e.getMessage());
                return ResponseEntity.ok().body(JSON.toJSONString(rsp));
            }
        } else if ("get".equalsIgnoreCase(method)) {
            Request.Builder requestBuilder = new Request.Builder()
                    .url(url)
                    .get();
            // 透传 Headers（过滤掉 Host 避免冲突）
            headers.forEach((key, value) -> {
                if (!key.equalsIgnoreCase("host")) {
                    requestBuilder.addHeader(key, value);
                }
            });

            // 发送请求
            try (Response response = client.newCall(requestBuilder.build()).execute()) {
                if (!response.isSuccessful()) {
                    return ResponseEntity.status(response.code()).body(response.message());
                }
                return ResponseEntity.status(response.code()).body(response.body().string());
            } catch (IOException e) {
                rsp.setCode(ApiRespCodeEnum.FAILED.getValue());
                rsp.setMsg("Proxy error: " + e.getMessage());
                return ResponseEntity.ok().body(JSON.toJSONString(rsp));

            }
        } else {
            rsp.setCode(ApiRespCodeEnum.FAILED.getValue());
            rsp.setMsg("method is not support！");
            return ResponseEntity.ok().body(JSON.toJSONString(rsp));
        }

    }


    public static void main(String[] args) {

    }

}
