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

import com.zt.plat.module.qms.iot.tcpserver.IotDeviceType;
import com.zt.plat.module.qms.iot.tcpserver.IotPacket;
import com.zt.plat.module.qms.iot.tcpserver.IotUtils;
import com.zt.plat.module.qms.iot.tcpserver.core.ChannelContextConstant;
import com.zt.plat.module.qms.iot.tcpserver.core.IotDeviceSessionContext;
import com.zt.plat.module.qms.iot.tcpserver.core.IotDeviceSessionForRedisContext;
import com.zt.plat.module.qms.iot.tcpserver.device.RedisSessionComponent;
import com.zt.plat.module.qms.iot.tcpserver.device.handler.IotDeviceBalanceHandler;
import com.zt.plat.module.qms.iot.tcpserver.device.handler.IotDeviceThermometerHandler;
import com.zt.plat.module.qms.iot.tcpserver.device.handler.IotDeviceWeighbridgeHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import tech.zzjc.tio.core.ChannelContext;
import tech.zzjc.tio.core.Tio;

import java.util.HashMap;
import java.util.Map;

/**
 * <b>IotDeviceHandler</b>
 * <p>更新历史：</p>
 * <pre> 版本         更新时间            更新者        更新内容
 * V1.0      2021-6-28          王兴荣         Add</pre>
 * <b>Copyright (C)  云南志者竟成科技有限公司</b> 
 * @author 王兴荣 &lt;xingrong_wang@will-way.cn&gt;
 * @version V1.0 
 * @since 2021-6-28
 */
@Slf4j
@Component
public class IotDeviceHandler implements IotHander {
    
    private static Map<String, IotDataHander> handlerMap = new HashMap<>();

    @Autowired public RedisSessionComponent redisSessionComponent;


    static {
        handlerMap.put(IotDeviceType.WEIGHBRIDGE.getType(), new IotDeviceWeighbridgeHandler());
        handlerMap.put(IotDeviceType.BALANCE.getType(), new IotDeviceBalanceHandler());
        handlerMap.put(IotDeviceType.THERMOMETER.getType(), new IotDeviceThermometerHandler());
    }
    
    @Override
    public Object hander(IotPacket iotPacket, ChannelContext channelContext) throws Exception {
        channelContext.set(ChannelContextConstant.CONNECT_TYPE, ChannelContextConstant.CONNECT_DEVICE);
        //获取客户端连接信息
        String realClientIp = channelContext.get("realClientIp") == null ? channelContext.getClientNode().getIp() : channelContext.get("realClientIp").toString();
        String realClientPort = channelContext.get("realClientPort") == null ? channelContext.getClientNode().getPort() + "" : channelContext.get("realClientPort").toString();
        String realClient = realClientIp + ":" + realClientPort + ", bsId=" + channelContext.getBsId();
        String text = new String(iotPacket.getBody(), IotPacket.CHARSET);
//        if(!text.contains("0.00"))
//            log.info("{}, 接收到数据：{}", realClient, text);
        String[] infos = text.split("\\$");
        String reginfo = infos[0];
        String[] regs = reginfo.split("-");
        String deviceType = null;   //设备类型
        String deviceCode = null;   //设备编码
        String deviceData = null;   //设备数据
        boolean regFlag = false;
        String errMsg = "{}, 传入参数错误，无注册信息，断开连接！传入参数：{}";
        IotDeviceSessionContext sessionContext = (IotDeviceSessionContext) channelContext.get(IotDeviceSessionContext.DEFAULT_DEVICE_SESSION_CONTEXT_KEY);
        deviceCode = sessionContext.getDeviceCode();
        IotDeviceSessionForRedisContext deviceContext = null;
        if(!ObjectUtils.isEmpty(deviceCode)){
            deviceContext = redisSessionComponent.getByDeviceCode(deviceCode);
        }
        if(deviceContext == null
                && !reginfo.startsWith("reg-iot-")
                && !reginfo.startsWith("r-i-")
                && !reginfo.startsWith("iot-")){
            //无注册信息，断开连接
            log.error(errMsg, realClient, text);
            Tio.close(channelContext, "无注册信息，断开连接！");
            return null;
        }
        //设备注册信息
        if ((reginfo.startsWith("reg-iot-") || reginfo.startsWith("r-i-") ) && regs.length == 4) {
            deviceType = regs[2];
            deviceCode = regs[3];
            regFlag = true;
        }else if(reginfo.startsWith("iot-") && regs.length == 3){
            deviceType = regs[1];
            deviceCode = regs[2];
            deviceData = infos[1];
        }else{
            deviceData = text;
            deviceType = deviceContext.getDeviceType();
        }
        if(ObjectUtils.isEmpty(deviceCode)){
            log.error(errMsg, realClient, text);
            Tio.close(channelContext, "无注册信息，断开连接！");
            return null;
        }
        if(regFlag){
            redisSessionComponent.regDevice(channelContext, deviceCode, deviceType);
            //在sessionContext记录设备id
            sessionContext.setDeviceCode(deviceCode);
            sessionContext.setDeviceId(IotUtils.transDeviceCodeToId(deviceCode));
            return null;
        }
        if(deviceContext == null || Tio.getByBsId(channelContext.getTioConfig(), deviceCode) == null){
            redisSessionComponent.regDevice(channelContext, deviceCode, deviceType);
        }else{
            //更新过期时间
            redisSessionComponent.update(deviceContext);
        }
        IotDataHander iotDataHander = handlerMap.get(deviceType);
        if (iotDataHander == null) {
            log.error("{}, 找不到处理类，设备类型：{}", realClient, deviceType);
            return null;
        }
        iotDataHander.hander(null, deviceData.trim(), channelContext);
        return null;
    }
}
