package com.mortals.xhx.busiz.web;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
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 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<>();
        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());
        }
        req.remove("method");
        req.remove("path");
        String targetUrl = "http://127.0.0.1:11078" + 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());
                }

                if ("/base/matter/channel/interlist".equals(path)) {
                    JSONObject rspJson = JSON.parseObject(response.body().string());
                    JSONObject data = rspJson.getJSONObject("data");
                    JSONArray dataJSONArray = data.getJSONArray("data");

                    for (int i = 0; i < dataJSONArray.size(); i++) {
                        JSONObject jsonObject = dataJSONArray.getJSONObject(i);
                        String icon = jsonObject.getString("icon");
                        if (!ObjectUtils.isEmpty(icon) && icon.startsWith("/file")) {
                            String filePath = uploadService.getFilePath(icon);
                            boolean empty = FileUtil.isEmpty(new File(filePath));
                            if (!empty) {
                                String base64Str = Base64.encode(new File(filePath));
                                //log.info("base64Str:{}", base64Str);
                                jsonObject.put("icon", base64Str);
                            }
                        }
                        String qrCode = jsonObject.getString("qrCode");
                        if (!ObjectUtils.isEmpty(qrCode) && qrCode.startsWith("/file")) {
                            String filePath = uploadService.getFilePath(qrCode);
                            String base64Str = Base64.encode(new File(filePath));
                            //log.info("base64Str:{}", base64Str);
                            boolean empty = FileUtil.isEmpty(new File(filePath));
                            if (!empty) {
                                jsonObject.put("qrCode", base64Str);
                            }
                        }
                    }
                    return Rest.ok("透传请求成功！", rspJson.toJSONString());
                }
                return Rest.ok("透传请求成功！", response.body().string());
            } catch (IOException e) {
                rsp.setCode(ApiRespCodeEnum.FAILED.getValue());
                rsp.setMsg("Proxy error: " + e.getMessage());
                return Rest.fail(rsp.getMsg());
            }
        } else if ("get".equalsIgnoreCase(method)) {
            Map<String, Object> map = req.toJavaObject(Map.class);
            try {
                String resp = HttpUtil.get(url.toString(), map, 30 * 1000);
                if ("/base/matter/interinfo".equals(path)) {
                    JSONObject rspJson = JSON.parseObject(resp);
                    JSONObject data = rspJson.getJSONObject("data");
                    String tid = data.getString("tid");
                    if (!ObjectUtils.isEmpty(tid) && tid.startsWith("/file")) {
                        String filePath = uploadService.getFilePath(tid);
                        boolean empty = FileUtil.isEmpty(new File(filePath));
                        if (!empty) {
                            String base64Str = Base64.encode(new File(filePath));
                            //log.info("base64Str:{}", base64Str);
                            data.put("tid", base64Str);
                        }
                    }
                    return Rest.ok("透传请求成功！", rspJson.toJSONString());
                }
                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());
        }

    }

    public static void main(String[] args) {

    }

}
