package com.mortals.xhx.busiz.web;

import cn.hutool.core.codec.Base64;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.annotation.UnAuth;
import com.mortals.framework.common.Rest;
import com.mortals.xhx.base.system.upload.service.UploadService;
import com.mortals.xhx.busiz.rsp.ApiResp;
import com.mortals.xhx.common.code.ApiRespCodeEnum;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.http.util.TextUtils;
import org.springframework.beans.factory.annotation.Autowired;
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.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Map;

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

    private final WebClient webClient;
    @Autowired
    private UploadService uploadService;

    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
    public Rest<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", "");


        JSONObject req = JSON.parseObject(body);

        String method = req.getString("method");
        String path = req.getString("path");

        if (ObjectUtils.isEmpty(path)) {
            rsp.setCode(ApiRespCodeEnum.FAILED.getValue());
            rsp.setMsg("path is empty！");

            return Rest.fail(rsp.getMsg());

            // return ResponseEntity.ok().body(JSON.toJSONString(rsp));
        }


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

        req.remove("method");

        req.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 = req.toJSONString() != null ?
                okhttp3.RequestBody.create(MediaType.parse("application/json"), req.toJSONString()) :
                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 Rest.fail(response.code(), response.message());
                    // return ResponseEntity.status(response.code()).body(response.message());
                }
                return Rest.ok("透传请求成功！", response.body().string());

                // return ResponseEntity.status(response.code()).body(response.body().string());
            } catch (IOException e) {
                rsp.setCode(ApiRespCodeEnum.FAILED.getValue());
                rsp.setMsg("Proxy error: " + e.getMessage());
                return Rest.fail(rsp.getMsg());
                // return ResponseEntity.ok().body(JSON.toJSONString(rsp));
            }
        } else if ("get".equalsIgnoreCase(method)) {

            Map<String, Object> map = req.toJavaObject(Map.class);
/*            String bodyParams = getBodyParams(map);
            log.info(bodyParams);*/
            // String urlGet = HttpUtil.urlWithForm(url.toString(), map, Charset.forName("utf-8"), false);
            try {
                String resp = HttpUtil.get(url.toString(), map, 30 * 1000);
                //todo 将文件转换成base64

                if ("/base/matter/interinfo".equals(path)) {
                    JSONObject rspJson = JSON.parseObject(resp);

                    JSONObject data = rspJson.getJSONObject("data");

                    JSONObject interdata = data.getJSONObject("data");

                    String tid = interdata.getString("tid");

                    if (!ObjectUtils.isEmpty(tid) && "/file".startsWith(tid)) {

                        String filePath = uploadService.getFilePath(tid);

                        String base64Str = Base64.encode(new File(filePath));
                        log.info("base64Str:{}", base64Str);

                        interdata.put("tid", base64Str);
                        return Rest.ok("透传请求成功！", rspJson.toJSONString());
                    }


                }

                // rspJson.get


                //String resp = HttpUtil.get(urlGet);
                return Rest.ok("透传请求成功！", resp);
            } catch (Exception e) {
                rsp.setCode(ApiRespCodeEnum.FAILED.getValue());
                rsp.setMsg("Proxy error: " + e.getMessage());
                return Rest.fail(rsp.getMsg());
            }

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

    }

    /**
     * 添加参数
     *
     * @param bodyParams
     * @return
     */
    private String getBodyParams(Map<String, String> bodyParams) {
        //1.添加请求参数
        //遍历map中所有参数到builder
        if (bodyParams != null && bodyParams.size() > 0) {
            StringBuffer stringBuffer = new StringBuffer("?");
            for (String key : bodyParams.keySet()) {
                if (!TextUtils.isEmpty(key) && !TextUtils.isEmpty(bodyParams.get(key))) {
                    //如果参数不是null并且不是""，就拼接起来
                    stringBuffer.append(key);
                    stringBuffer.append("=");
                    stringBuffer.append(bodyParams.get(key));
                }
            }

            return stringBuffer.toString();
        } else {
            return "";
        }
    }


    public static void main(String[] args) {

    }

}
