/*
 * 文 件 名:  IdleStateEventHandler
 * 版    权:  华设设计集团股份有限公司
 * 描    述:  空闲状态事件处理器
 * 修 改 人:  lvwenbin
 * 修改时间:  2025/12/22
 */
package com.ruoyi.ems.charging.core;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 空闲状态事件处理器
 * 用于检测心跳超时，关闭无响应的连接
 *
 * @author lvwenbin
 * @version [版本号, 2025/12/22]
 */
@Component
@ChannelHandler.Sharable
public class IdleStateEventHandler extends ChannelInboundHandlerAdapter {
    
    private static final Logger log = LoggerFactory.getLogger(IdleStateEventHandler.class);
    
    @Autowired
    private ChargingPileSessionManager sessionManager;
    
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            
            if (event.state() == IdleState.READER_IDLE) {
                // 读空闲，说明长时间没有收到数据
                String pileCode = sessionManager.getPileCodeByChannel(ctx.channel());
                log.warn("充电桩[{}]心跳超时，关闭连接: {}", 
                    pileCode != null ? pileCode : "未知",
                    ctx.channel().remoteAddress());
                
                ctx.close();
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        String pileCode = sessionManager.getPileCodeByChannel(ctx.channel());
        log.error("充电桩[{}]连接异常: {} - {}", 
            pileCode != null ? pileCode : "未知",
            ctx.channel().remoteAddress(),
            cause.getMessage());
        ctx.close();
    }
}
