package com.zt.plat.module.qms.iot.tcpserver.cluster;

import com.alibaba.fastjson.JSONObject;
import com.zt.plat.module.qms.iot.service.IotConnectManagerStatsService;
import com.zt.plat.module.qms.iot.tcpserver.IotPacket;
import com.zt.plat.module.qms.iot.tcpserver.handler.IotDataHander;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tech.zzjc.tio.core.ChannelContext;
import tech.zzjc.tio.core.Tio;
import tech.zzjc.tio.core.TioConfig;
import tech.zzjc.tio.server.ServerTioConfig;
import tech.zzjc.tio.server.TioServer;
import tech.zzjc.tio.starter.TioServerBootstrap;
import tech.zzjc.tio.utils.lock.SetWithLock;

import static com.zt.plat.module.qms.iot.tcpserver.cluster.TioServerMessageConfig.SERVER_CLUSTER_TOPIC_CHANNEL;

@Component
@Slf4j
public class TioServerMessageSubscriber {

    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private InstanceIdProvider instanceIdProvider;

    @Autowired
    private IotDataHander iotCaaClientControlDeviceHander;

    @Autowired private TioServerBootstrap tioServerBootstrap;
    @Autowired private IotConnectManagerStatsService iotConnectManagerStatsService;

    @PostConstruct
    public void subscribe() {
        RTopic topic = redissonClient.getTopic(SERVER_CLUSTER_TOPIC_CHANNEL);
        topic.addListener(TioServerMessageVo.class, (channel, msg) -> {
            String senderId = msg.getSenderInstanceId();
            String channelId = msg.getChannelId();
            String msgType = msg.getServerClusterMsgType();
            String currentId = instanceIdProvider.getInstanceId();
            if (currentId.equals(senderId)) {
                log.debug("[Subscriber] 跳过自己发送的消息");
                return;
            }
            log.debug("[Subscriber] 收到消息频道 '" + channel + "' 的内容: " + msg);

            if(TioServerMessageConfig.MESSAGE_TYPE_CLEAR_MANUAL.equals(msgType)){
                try {
                    iotConnectManagerStatsService.clearDeviceControl(channelId,"1");
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                return;
            }
            if(TioServerMessageConfig.MESSAGE_TYPE_CLOSE_MANUAL.equals(msgType)){
                try {
                    iotConnectManagerStatsService.close(channelId,"1");
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                return;
            }

            ServerTioConfig serverTioConfig = tioServerBootstrap.getServerTioConfig();
            SetWithLock<ChannelContext> all = Tio.getAll(serverTioConfig);
            ChannelContext targetContext = null;
            for(ChannelContext context : all.getObj()){
                targetContext = context;
                String id = context.getId();
                if(id.equals(channelId)){
                    break;
                }
            }
            IotPacket packet = (IotPacket) msg.getPacket();
            byte[] body = packet.getBody();
            String bodyStr = new String(body);
            JSONObject json = JSONObject.parseObject(bodyStr);
            try {
                iotCaaClientControlDeviceHander.hander(json.getString("msgId"), bodyStr, targetContext);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
    }

}
