package com.seer.teach.netty.im.handler.im.business;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.seer.teach.iot.api.DeviceInfoServiceApi;
import com.seer.teach.iot.api.resp.DeviceRespDTO;
import com.seer.teach.netty.common.annotation.ImMessageType;
import com.seer.teach.netty.common.proto.MessageProtobuf;
import com.seer.teach.netty.im.handler.im.ImMsgHandler;
import com.seer.teach.netty.im.manager.ImChannelManager;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 处理设备鉴权握手逻辑（消息类型1001）
 *
 * @author Captain
 * @date 2025-05-20
 */
@Service
@Slf4j
@RequiredArgsConstructor
@ImMessageType(1001)
public class ImAuthHandshakeHandler implements ImMsgHandler {

    private static final int READ_IDLE_SECONDS = 20;

    private final DeviceInfoServiceApi deviceInfoServiceApi;

    @Override
    public void handle(ChannelHandlerContext ctx, MessageProtobuf.Msg msg) {
        log.info("设备{}尝试 握手", msg.getHead().getDevice());
        String device = msg.getHead().getDevice();
        try {
            JSONObject jsonObj = JSON.parseObject(msg.getHead().getExtend());
            String authorize = jsonObj.getString("authorize");
            if (authorize != null) {
                authorize = authorize.replace("authorize_", "");
            }

            JSONObject resp = new JSONObject();
            DeviceRespDTO deviceInfo = deviceInfoServiceApi.getDevice(device);

            if (Objects.equals(device, authorize) && deviceInfo != null) {
                // 鉴权成功
                resp.put("status", 1);
                ImChannelManager.add(device, ctx.channel());
                ChannelPipeline p = ctx.pipeline();
                if (p.get("idle") == null) {
                    p.addAfter("pbDecoder", "idle", new IdleStateHandler(READ_IDLE_SECONDS, 0, 0, TimeUnit.SECONDS));
                    log.info("IdleStateHandler 已动态添加。ch={}, device={}", ctx.channel().id(), device);
                }
                log.info("TV端设备 [{}] 认证成功！", device);
            } else {
                // 鉴权失败
                resp.put("status", -1);
                log.warn("TV端设备 [{}] 认证失败！", device);
            }

            // 构造响应消息并发送
            MessageProtobuf.Msg responseMsg = msg.toBuilder()
                    .setHead(msg.getHead().toBuilder()
                            .setExtend(resp.toJSONString())
                            .build())
                    .build();
            ctx.writeAndFlush(responseMsg);

        } catch (Exception e) {
            e.printStackTrace();
            log.error("设备鉴权异常，device={}，错误={}", device, e.getMessage(), e);
        }
    }

}
