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 org.springframework.http.ResponseEntity;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.util.UriUtils;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.Map;

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

    private final WebClient webClient;

    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/basic_api/" + path;
        log.info("proxyPost targetUrl: {}", targetUrl);
        if ("post".equalsIgnoreCase(method)) {
            return webClient.post()
                    .uri(uriBuilder -> {
                        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)));
    }
}
