package com.fastbee.controller.ruleEngine;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.fastbee.common.core.domain.AjaxResult;
import com.fastbee.iot.model.ScriptCondition;
import com.fastbee.ruleEngine.context.MsgContext;
import com.fastbee.iot.service.IScriptService;
import com.fastbee.ruleEngine.core.FlowLogExecutor;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@RestController
@RequestMapping("/bridge")
public class HttpBridgeController {

    @Resource
    private IScriptService scriptService;

    @Autowired
    private FlowLogExecutor flowExecutor;

    /**
     * 数据桥接入口（支持GET/POST/PUT）
     */
    @ApiOperation("数据桥接入口")
    @PermitAll
    @RequestMapping(value = "/get", method = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT})
    public ResponseEntity<Object> bridgeGetOrPostOrPut(HttpServletRequest request,
                                                       @RequestBody(required = false) String rawBody) {
        String method = request.getMethod();

        // 记录请求详细信息到日志
        logRequestDetails(request, rawBody);

        if ("GET".equalsIgnoreCase(method)) {
            return ResponseEntity.ok(handleGetRequest(request));
        } else if ("POST".equalsIgnoreCase(method)) {
            return ResponseEntity.ok(handlePostRequest(request,  rawBody));
        } else if ("PUT".equalsIgnoreCase(method)) {
            return ResponseEntity.ok(handlePutRequest(request,  rawBody));
        } else {
            return ResponseEntity.status(405).body("Unsupported  method");
        }
    }

    /**
     * 记录请求详细信息
     */
    private void logRequestDetails(HttpServletRequest request, String body) {
        StringBuilder logBuilder = new StringBuilder("\n========== 请求详细信息 ==========\n");

        // 基本信息
        logBuilder.append(" 请求方法: ").append(request.getMethod()).append("\n");
        logBuilder.append(" 请求URL: ").append(request.getRequestURL()).append("\n");
        logBuilder.append("Content-Type:  ").append(request.getContentType()).append("\n");

        // 请求头
        logBuilder.append("=====  请求头 =====\n");
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements())  {
            String headerName = headerNames.nextElement();
            logBuilder.append(headerName).append(":  ").append(request.getHeader(headerName)).append("\n");
        }

        // 请求参数
        logBuilder.append("=====  请求参数 =====\n");
        Map<String, String[]> params = request.getParameterMap();
        if (params != null && !params.isEmpty())  {
            params.forEach((key,  values) ->
                    logBuilder.append(key).append(":  ").append(Arrays.toString(values)).append("\n"));
        } else {
            logBuilder.append(" 无请求参数\n");
        }

        // 请求体
        logBuilder.append("=====  原始请求体 =====\n");
        logBuilder.append(body  != null ? body : "无请求体").append("\n");

        logBuilder.append("===============================\n");
        log.info(logBuilder.toString());
    }

    /**
     * 处理GET请求
     */
    private String handleGetRequest(HttpServletRequest request) {
        String msg = request.getParameter("msg");
        return msg != null && !msg.isEmpty()  ? msg : "Invalid request";
    }

    /**
     * 处理POST请求
     */
    private AjaxResult handlePostRequest(HttpServletRequest request, String rawBody) {
        // 构建包含完整请求信息的Map
        Map<String, Object> requestInfo = buildCompleteRequestInfo(request, rawBody);

        // 创建脚本执行上下文
        ScriptCondition scriptCondition = ScriptCondition.builder()
                .scriptPurpose(1)
                .scriptEvent(5)
                .route("/bridge/post")
                .build();

        MsgContext context = MsgContext.builder()
                .dataMap(new ConcurrentHashMap<>(requestInfo))
                .payload(rawBody != null ? rawBody : "")
                .build();

        // 执行规则脚本并返回结果
        Object result = scriptService.execRuleScript(scriptCondition,  context);
        return AjaxResult.success(result);
    }

    /**
     * 处理PUT请求
     */
    private AjaxResult handlePutRequest(HttpServletRequest request, String rawBody) {
        // 构建包含完整请求信息的Map
        Map<String, Object> requestInfo = buildCompleteRequestInfo(request, rawBody);

        ScriptCondition scriptCondition = ScriptCondition.builder()
                .scriptPurpose(1)
                .scriptEvent(5)
                .route("/bridge/put")
                .build();

        MsgContext context = MsgContext.builder()
                .dataMap(new ConcurrentHashMap<>(requestInfo))
                .payload(rawBody != null ? rawBody : "")
                .build();

        return AjaxResult.success(scriptService.execRuleScript(scriptCondition,  context));
    }

    /**
     * 构建完整的请求信息Map
     */
    private Map<String, Object> buildCompleteRequestInfo(HttpServletRequest request, String rawBody) {
        Map<String, Object> requestInfo = new LinkedHashMap<>();

        // 1. 基本信息
        requestInfo.put("method",  request.getMethod());
        requestInfo.put("requestURL",  request.getRequestURL().toString());
        requestInfo.put("contentType",  request.getContentType());
        requestInfo.put("characterEncoding",  request.getCharacterEncoding());

        // 2. 请求头
        Map<String, String> headers = new LinkedHashMap<>();
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements())  {
            String headerName = headerNames.nextElement();
            headers.put(headerName,  request.getHeader(headerName));
        }
        requestInfo.put("headers",  headers);

        // 3. 请求参数
        Map<String, String[]> params = request.getParameterMap();
        if (params != null && !params.isEmpty())  {
            Map<String, Object> parameters = new LinkedHashMap<>();
            params.forEach((key,  values) ->
                    parameters.put(key,  values.length  == 1 ? values[0] : values));
            requestInfo.put("parameters",  parameters);
        }

        // 4. 原始请求体
        if (rawBody != null && !rawBody.isEmpty())  {
            try {
                // 尝试解析JSON，如果失败则保持原始字符串
                requestInfo.put("rawBody",  JSON.parse(rawBody));
            } catch (Exception e) {
                requestInfo.put("rawBody",  rawBody);
            }
        }

        // 5. 其他信息
        requestInfo.put("remoteAddr",  request.getRemoteAddr());
        requestInfo.put("serverName",  request.getServerName());
        requestInfo.put("serverPort",  request.getServerPort());

        return requestInfo;
    }
}