package com.zehong.web.task;


import com.serotonin.modbus4j.ModbusMaster;
import com.zehong.framework.modbus4j.Modbus4jUtils;
import com.zehong.system.domain.TEquipmentAlarmData;
import com.zehong.system.domain.TStoreyInfo;
import com.zehong.system.mapper.TStoreyInfoMapper;
import com.zehong.system.service.ITEquipmentAlarmDataService;
import com.zehong.system.service.ITStoreyInfoService;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.Instant;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author lenovo
 * @date 2025/6/25
 * @description TODO
 */
@Component
public class DeviceCommunicationJob implements Job {
    private static final Logger log = LoggerFactory.getLogger(DeviceCommunicationJob.class);

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

    @Override
    public void execute(JobExecutionContext context) {
        JobDataMap data = context.getJobDetail().getJobDataMap();
        String fStoreyId = data.getString("fStoreyId");
        log.info("DeviceCommunicationJob.execute 的 fStoreyId:{}", fStoreyId);
        long l = Long.parseLong(fStoreyId);
        TStoreyInfo tStoreyInfo = tStoreyInfoMapper.selectTStoreyInfoById(l);
        try {
            // 1. 执行Modbus通信
            String s = tStoreyInfo.getfPort();
            String ip = tStoreyInfo.getfIp();
            // 三个端口号，对应三组Modbus通信
            String[] split = s.split(",");

            List<Integer> registerOffsetsOne = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26);

            log.info("registerOffsetsOne.ip:{}, port{}", ip, Integer.parseInt(split[0]));
            Map<Integer, Object> integerObjectMapOne = Modbus4jUtils.batchReadAgingCabinetStatus(Modbus4jUtils.getMaster(ip, Integer.parseInt(split[0])), registerOffsetsOne);
            for (Map.Entry<Integer, Object> integerObjectEntry : integerObjectMapOne.entrySet()) {
                log.info("integerObjectMapOne 的 key是:{}  value: {}", integerObjectEntry.getKey(), integerObjectEntry.getValue());
            }

            List<Integer> registerOffsetsTwo = Arrays.asList(27,28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53);

            log.info("integerObjectMapTwo.ip:{}, port{}", ip, Integer.parseInt(split[1]));
            Map<Integer, Object> integerObjectMapTwo = Modbus4jUtils.batchReadAgingCabinetStatus(Modbus4jUtils.getMaster(ip, Integer.parseInt(split[1])), registerOffsetsTwo);
            for (Map.Entry<Integer, Object> integerObjectEntry : integerObjectMapTwo.entrySet()) {
                log.info("integerObjectMapTwo 的 key是:{}  value: {}", integerObjectEntry.getKey(), integerObjectEntry.getValue());
            }

            List<Integer> registerOffsetsThree = Arrays.asList(54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71);
            Map<Integer, Object> integerObjectMapThree = Modbus4jUtils.batchReadAgingCabinetStatus(Modbus4jUtils.getMaster(ip, Integer.parseInt(split[2])), registerOffsetsThree);

            log.info("integerObjectMapThree.ip:{}, port{}", ip, Integer.parseInt(split[2]));
            for (Map.Entry<Integer, Object> integerObjectEntry : integerObjectMapThree.entrySet()) {
                log.info("integerObjectMapThree 的 key是:{}  value: {}", integerObjectEntry.getKey(), integerObjectEntry.getValue());
            }

            // 2. 检查是否到达特殊时间点
            //checkSpecialTimePoints(tStoreyInfo);
        } catch (Exception e) {
            // 记录异常
            TEquipmentAlarmData alarmData = new TEquipmentAlarmData();
            alarmData.setfAlarmType("03"); // 老化层
            alarmData.setfEquipmentCode(tStoreyInfo.getfStoreyCode());
            alarmData.setfAlarmData("通信失败: " + e.getMessage());
            alarmDataService.insertTEquipmentAlarmData(alarmData);
        }
    }

    private void checkSpecialTimePoints(TStoreyInfo tStoreyInfo) {
        if (tStoreyInfo == null || "COMPLETED".equals(tStoreyInfo.getfStatus())) return;

        // 计算已运行小时数
        long hours = Duration.between(
                tStoreyInfo.getfAgingStartTime().toInstant(), Instant.now()).toHours();

        // 特殊时间点处理 (24小时和48小时)
        if (hours == 24 || hours == 48) {
            log.info("设备[{}]到达特殊时间点: {}小时", tStoreyInfo.getfStoreyCode(), hours);
            // 执行特殊操作
            performSpecialOperation(tStoreyInfo);
        }
    }

    // ... 其他辅助方法
    private void performSpecialOperation(TStoreyInfo tStoreyInfo) {

    }
}
