package com.tashow.cloud.app.mq.message;

import cn.hutool.core.util.IdUtil;
import com.tashow.cloud.common.util.json.JsonUtils;
import com.tashow.cloud.common.util.servlet.ServletUtils;
import com.tashow.cloud.common.util.spring.SpringUtils;
import com.tashow.cloud.mq.core.BaseMqMessage;
import jakarta.servlet.http.HttpServletRequest;
import lombok.Data;
import org.springframework.web.method.HandlerMethod;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;

import static com.tashow.cloud.web.apilog.core.interceptor.ApiAccessLogInterceptor.ATTRIBUTE_HANDLER_METHOD;

/**
 * 埋点消息
 */
@Data
public class BuriedMessages extends BaseMqMessage {
    private static final String ATTRIBUTE_REQUEST_ID = "BuriedPoint.RequestId";


    /**
     * 交换机名称
     */
    public static final String EXCHANGE = "tashow.buried.point.exchange";
    
    /**
     * 队列名称
     */
    public static final String QUEUE = "tashow.buried.point.queue";
    
    /**
     * 路由键
     */
    public static final String ROUTING_KEY = "tashow.buried.point.routing.key";

    /**
     * 消息状态：处理中
     */
    public static final int STATUS_PROCESSING = 10;
    
    /**
     * 消息状态：成功
     */
    public static final int STATUS_SUCCESS = 20;
    
    /**
     * 消息状态：失败
     */
    public static final int STATUS_ERROR = 30;

    /**
     * 事件时间
     */
    private Date eventTime;
    
    /**
     * 用户ID
     */
    private String userId;
    
    /**
     * 事件类型
     */
    private String eventType;
    
    /**
     * 方法名称
     */
    private String method;
    
    /**
     * 会话ID
     */
    private String sessionId;
    
    /**
     * 客户端IP
     */
    private String clientIp;
    
    /**
     * 服务端IP
     */
    private String serverIp;
    
    /**
     * 页面路径
     */
    private String pagePath;
    
    /**
     * 元素ID
     */
    private String elementId;

    /**
     * 服务名称
     */
    private String service;

    public BuriedMessages() {
    }

    /**
     * 从请求创建埋点消息
     * 
     * @param request HTTP请求
     * @param handlerMethod 处理方法
     */
    public BuriedMessages(HttpServletRequest request, HandlerMethod handlerMethod) {
        try {
            int requestId = (int)(Math.abs(IdUtil.getSnowflakeNextId()) % Integer.MAX_VALUE);
            this.setId(requestId);
            this.eventTime = new Date();
            this.service = SpringUtils.getApplicationName();
            this.method = request.getMethod() + " " + request.getRequestURI() + 
                          JsonUtils.toJsonString(request.getParameterMap());
            Object userId = request.getSession().getAttribute("USER_ID");
            this.userId = userId != null ? userId.toString() : "anonymous";
            this.sessionId = request.getSession().getId();
            this.clientIp = ServletUtils.getClientIP(request);
            try {
                this.serverIp = InetAddress.getLocalHost().getHostAddress();
            } catch (UnknownHostException e) {
                this.serverIp = "unknown";
            }
            String controllerName = handlerMethod.getBeanType().getSimpleName();
            String actionName = handlerMethod.getMethod().getName();
            this.pagePath = controllerName + "#" + actionName;
            this.eventType = "API_REQUEST_START";
            this.setStatusCode(STATUS_PROCESSING);
            request.setAttribute(ATTRIBUTE_REQUEST_ID, this.getId());
        } catch (Exception e) {
            throw new RuntimeException("创建埋点消息失败", e);
        }
    }
}
