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

import com.beanit.iec61850bean.*;
import com.yfd.platform.modules.auxcontrol.mapper.DeviceSignalMapper;
import com.yfd.platform.modules.auxcontrol.service.IDeviceWorkDataService;
import com.yfd.platform.modules.patroltask.service.IAlarmLogService;
import com.yfd.platform.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

@Component
@RequiredArgsConstructor
public class IEC61850ClientListener extends Thread implements ClientEventListener {

    private static final Logger log = LoggerFactory.getLogger(StringUtils.class);

    private final DeviceSignalMapper deviceSignalMapper;
    private final IAlarmLogService alarmLogService;
    private final IDeviceWorkDataService deviceWorkDataService;

    @Override
    public void newReport(Report report) {
        //遥测 测量值（浮点数）
        for (FcModelNode value : report.getValues()) {
            if ("MX".equals(value.getFc().name())) {
                String node_name = value.getChild("mag").getChild("f").toString().split(":")[0].replace(".mag.f", "");
                BdaFloat32 f = (BdaFloat32) value.getChild("mag").getChild("f");
                String node_value = f.getValueString();
                BdaTimestamp t = (BdaTimestamp) value.getChild("t");
                String datestr = changeUTCtoLocalTime(t.getValueString());
                log.info(node_name + ":" + node_value + ":" + datestr);
                //更新信号数据值
                deviceSignalMapper.updateDeviceSignalValue_yc(node_name, node_value, datestr);
                //插入历史数据
                deviceWorkDataService.insertData("IEC61850", null, node_name, node_value, datestr);
                //执行报警处理
                alarmLogService.doAlaramRecord("IEC61850", "yc", null, node_name, node_value);

            } else if ("ST".equals(value.getFc().name())) {
                //遥信 状态值
                String node_name = value.getChild("stVal").toString().split(":")[0].replace(".stVal", "");
                BdaBoolean state = (BdaBoolean) value.getChild("stVal");
                String node_value = state.getValue() ? "1" : "0";
                BdaTimestamp t = (BdaTimestamp) value.getChild("t");
                String datestr = changeUTCtoLocalTime(t.getValueString());
                log.info(node_name + ":" + node_value + ":" + datestr);
                //更新信号状态
                deviceSignalMapper.updateDeviceSignalValue_yx(node_name, node_value, datestr);
                //执行报警处理：生成设备自身报警记录（status=1）
                alarmLogService.doAlaramRecord("IEC61850", "yx", null, node_name, node_value);
            }
        }
    }

    private String changeUTCtoLocalTime(String utctime) {
        // 解析UTC时间字符串为ZonedDateTime对象
        ZonedDateTime utcDateTime = ZonedDateTime.parse(utctime);
        // 将UTC时间转换为本地时间（假设本地时区为Asia/Shanghai）
        ZonedDateTime localDateTime = utcDateTime.withZoneSameInstant(ZoneId.of("Asia/Shanghai"));
        DateTimeFormatter LocalFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
        return localDateTime.format(LocalFormatter);

    }

    @Override
    public void associationClosed(IOException e) {
        log.info("客户端已连接到服务器！");
    }

}
