package com.yfd.platform.component.iec104.client;

import cn.hutool.core.util.ObjUtil;
import com.ydl.iec.util.ByteUtil;
import com.yfd.platform.component.iec104.message.MessageDetail;
import com.yfd.platform.component.iec104.message.MessageInfo;
import com.yfd.platform.component.iec104.server.handler.ChannelHandler;
import com.yfd.platform.component.iec104.server.handler.DataHandler;
import com.yfd.platform.component.iec104.server.master.BootNettyClientChannel;
import com.yfd.platform.component.iec104.server.master.BootNettyClientChannelCache;
import com.yfd.platform.modules.auxcontrol.service.IDeviceSignalService;
import com.yfd.platform.modules.auxcontrol.service.IDeviceWorkDataService;
import com.yfd.platform.modules.auxcontrol.service.IGatewayDeviceService;
import com.yfd.platform.modules.patroltask.service.IAlarmLogService;
import com.yfd.platform.utils.SpringContextHolder;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * @author Admin
 */
@io.netty.channel.ChannelHandler.Sharable
public class MasterSysDataHandler implements DataHandler {

    private static final Logger log = LoggerFactory.getLogger(MasterSysDataHandler.class);
    IDeviceSignalService signalService = SpringContextHolder.getBean(IDeviceSignalService.class);
    IDeviceWorkDataService workDataService = SpringContextHolder.getBean(IDeviceWorkDataService.class);
    IGatewayDeviceService gatewayDeviceService = SpringContextHolder.getBean(IGatewayDeviceService.class);
    IAlarmLogService alarmLogService = SpringContextHolder.getBean(IAlarmLogService.class);

    @Override
    public void handlerAdded(ChannelHandler ctx) throws Exception {
        ChannelHandlerContext currentctx = ctx.getCtx();
        BootNettyClientChannel channel = BootNettyClientChannelCache.get(currentctx.channel().id().asShortText());
        String slaveIp = channel.getCode();
        log.info(String.format("%s-对应的终端连接成功！", slaveIp));
    }

    @Override
    public void channelRead(ChannelHandler ctx, MessageDetail ruleDetail104) throws Exception {
        ChannelHandlerContext currentctx = ctx.getCtx();
        //------------从通道中获取当前连接的IP-----------------//
        BootNettyClientChannel channel = BootNettyClientChannelCache.get(currentctx.channel().id().asShortText());
        if (ObjUtil.isNotEmpty(channel)) {
            //通道已关闭
            String slaveIp = channel.getCode();
            String hexString = ByteUtil.byteArrayToHexString(ruleDetail104.getControl());
            if ("83000000".equals(hexString)) {
                //测试确认，更新心跳时间
                gatewayDeviceService.updateKeepLiveTime(slaveIp);
                return;
            }
            int type = ruleDetail104.getTypeIdentifier().getValue();
            if (type == 1 || type == 3 || type == 30 || type == 31) {
                //遥信值
                List<MessageInfo> list = ruleDetail104.getMessages();
                for (MessageInfo messageInfo : list) {
                    String address = String.valueOf(messageInfo.getMessageAddress());
                    String status = String.valueOf(messageInfo.getStatus());
                    String dateTime = messageInfo.getTimeScale();
                    signalService.updateDeviceSignalValue(slaveIp, address, "yx", status, dateTime);
                    //生成设备自身报警记录（status=1）
                    alarmLogService.doAlaramRecord("IEC104", "yx", slaveIp, address, status);
                }
            }
            if (type == 9 || type == 11 || type == 13 || type == 34 || type == 35 || type == 36) {
                //遥测值
                List<MessageInfo> list = ruleDetail104.getMessages();
                for (MessageInfo messageInfo : list) {
                    String address = String.valueOf(messageInfo.getMessageAddress() - 16384);
                    //从设备上去的地址减去
                    // 4000H对应的偏差值16384
                    String value = String.valueOf(messageInfo.getValue());
                    String dateTime = messageInfo.getTimeScale();
                    workDataService.insertData("IEC104", slaveIp, address, value, dateTime);
                    signalService.updateDeviceSignalValue(slaveIp, address, "yc", value, dateTime);
                    //生成阈值越限报警记录
                    alarmLogService.doAlaramRecord("IEC104", "yc", slaveIp, address, value);
                }
            }

        }

    }

}
