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

import com.alibaba.fastjson.JSON;
import com.fhs.common.spring.SpringContextUtil;
import com.zt.plat.module.qms.iot.tcpserver.IotPacket;
import com.zt.plat.module.qms.iot.tcpserver.consoleclient.bean.Register;
import com.zt.plat.module.qms.iot.tcpserver.core.ClientType;
import com.zt.plat.module.qms.iot.tcpserver.core.Command;
import com.zt.plat.module.qms.iot.tcpserver.core.ReplyResult;
import com.zt.plat.module.qms.iot.tcpserver.device.RedisSessionComponent;
import com.zt.plat.module.qms.iot.tcpserver.handler.IotDataHander;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import tech.zzjc.tio.core.ChannelContext;
import tech.zzjc.tio.core.Tio;
import tech.zzjc.tio.utils.SystemTimer;

import java.nio.charset.Charset;
import java.util.Date;

import static com.zt.plat.module.qms.iot.tcpserver.core.GroupConstant.CAA_ALL_CLIENT;

/**
 * <b>IotCaaClientRegisterHander</b>
 * <p>更新历史：</p>
 * <pre> 版本         更新时间            更新者        更新内容
 * V1.0      2021-10-20          王兴荣         Add</pre>
 * <b>Copyright (C)  云南志者竟成科技有限公司</b> 
 * @author 王兴荣 &lt;xingrong_wang@will-way.cn&gt;
 * @version V1.0 
 * @since 2021-10-20
 */
@Slf4j
@Component
public class IotCaaClientRegisterHander implements IotDataHander {

    @Override
    public Object hander(String msgId, String data, ChannelContext channelContext) throws Exception {
        Register register = JSON.parseObject(data, Register.class);

        Tio.bindUser(channelContext, register.getUserId());
        Tio.bindToken(channelContext, register.getUserId());
        channelContext.set("regTime", new Date());
        channelContext.set("user-real-name", register.getUserRealName());
        IotPacket resppacket = new IotPacket();
        resppacket.setBody((ReplyResult.success(msgId, ClientType.CAA_CLIENT.getName(), Command.REPLY_REGISTER.getName()) + "\r\n").getBytes(Charset.forName(IotPacket.CHARSET)));
        //回复注册成功
        Tio.send(channelContext, resppacket);
        //绑定群组
        Tio.bindGroup(channelContext, CAA_ALL_CLIENT);

        //在redis记录客户端信息
//        RedisSessionComponent redisSessionComponent = (RedisSessionComponent) SpringContextUtil.getBean("redisSessionComponent");
//        redisSessionComponent.regClient(channelContext);


        //


        return null;
    }

}
