package com.zehong.web.task;

import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.exception.ModbusInitException;
import com.serotonin.modbus4j.exception.ModbusTransportException;
import com.zehong.framework.modbus4j.Modbus4jUtils;
import com.zehong.system.domain.TEquipmentAlarmData;
import com.zehong.system.domain.TStoreyInfo;
import com.zehong.system.service.ITEquipmentAlarmDataService;
import com.zehong.system.service.ITStoreyInfoService;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author lenovo
 * @date 2025/6/17
 * @description TODO
 */
@Component
public class AllCommandHandler {
    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(AllCommandHandler.class);

    @Resource
    private ITEquipmentAlarmDataService alarmDataService;
    @Resource
    private ITStoreyInfoService tStoreyInfoService;

    @Async  // 异步执行
    @EventListener(PowerOffCommandEvent.class)
    public void handlePowerOffCommand(PowerOffCommandEvent event) {
        try {
            String storeyCode = event.getDeviceCode() + "-" + event.getLayer();
            log.info("需要发送断电指令 - 设备:{} 层:{}", event.getDeviceCode(), event.getLayer());
            TStoreyInfo tStoreyInfo = tStoreyInfoService.selectTStoreyInfoByCode(storeyCode);
            if (tStoreyInfo == null) {
                TEquipmentAlarmData alarmData = new TEquipmentAlarmData();
                // 记录异常数据
                alarmData.setfAlarmType("01"); //01.老化柜 02.机械臂 03.老化层 04.点位
                alarmData.setfEquipmentCode(event.getDeviceCode());
                alarmData.setfAlarmData("下属" + storeyCode + "号老化层不存在");
                alarmDataService.insertTEquipmentAlarmData(alarmData);
            } else {
                ModbusMaster master = Modbus4jUtils.getMaster(tStoreyInfo.getfIp(), tStoreyInfo.getfPort());
                Modbus4jUtils.writeCoil(master, 1, event.getLayer(), false);
                log.info("已发送断电指令 - 设备:{} 层:{}", event.getDeviceCode(), event.getLayer());
                master.destroy();
            }
        } catch (ModbusInitException | ModbusTransportException e) {
            log.error("断电指令执行失败 - 设备:{} 层:{}", event.getDeviceCode(), event.getLayer(), e);

            // 记录异常
            TEquipmentAlarmData alarmData = new TEquipmentAlarmData();
            alarmData.setfAlarmType("03"); // 老化层
            alarmData.setfEquipmentCode(event.getDeviceCode());
            alarmData.setfAlarmData("断电指令执行失败: " + e.getMessage());
            alarmDataService.insertTEquipmentAlarmData(alarmData);
        }
    }
}
