package com.zehong.system.modbus.business;

import com.serotonin.modbus4j.ModbusFactory;
import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.exception.ModbusInitException;
import com.serotonin.modbus4j.exception.ModbusTransportException;
import com.serotonin.modbus4j.ip.IpParameters;
import com.serotonin.modbus4j.ip.tcp.TcpMaster;
import com.serotonin.modbus4j.msg.ModbusResponse;
import com.serotonin.modbus4j.msg.ReadHoldingRegistersRequest;
import com.serotonin.modbus4j.msg.ReadHoldingRegistersResponse;
import com.zehong.system.domain.TEquipmentAlarmData;
import com.zehong.system.modbus.handler.dto.DeviceStatusReaderDto;
import com.zehong.system.modbus.util.Modbus4jUtils;
import com.zehong.system.service.ITEquipmentAlarmDataService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.net.Socket;
import java.util.List;
import java.util.concurrent.*;
import java.util.function.Consumer;
import java.util.function.Predicate;

/**
 * @author lenovo
 * @date 2025/6/27
 * @description modbus4j 单独提取出来的 读设备状态并设置时间
 */
@Component
public class DeviceStatusReaderAndTimeSetter {

    // 常量改为public以便外部访问
    public static final int START_ADDRESS = 0;
    public static final int REGISTER_COUNT = 10;
    public static final int TARGET_VALUE = 1;
    public static final int MAX_RETRIES = 3;
    public static final int RETRY_DELAY = 500;
    public static final int TIMEOUT_MINUTES = 5;
    public static final int TIMEOUT_SECONDS = 30; // 总超时30秒
    // 工厂
    private static final ModbusFactory modbusFactory = new ModbusFactory();

    // 1. 关键优化：固定线程池大小（不随设备数变化，根据CPU核数设置，如10）

    // 线程池优化：添加线程工厂，便于问题追踪
    private static final ExecutorService FIXED_THREAD_POOL = new ThreadPoolExecutor(
            5,
            10,
            60,
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(100),
            new ThreadFactory() {
                private int count = 0;
                @Override
                public Thread newThread(Runnable r) {
                    Thread thread = new Thread(r, "modbus-pool-" + (count++));
                    thread.setDaemon(true); // 设为守护线程，避免阻塞JVM退出
                    return thread;
                }
            },
            new ThreadPoolExecutor.CallerRunsPolicy()
    );

    @Resource
    private ITEquipmentAlarmDataService alarmDataService;

    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(DeviceStatusReaderAndTimeSetter.class);
    /**
     * 读取设备寄存器（线程安全版）
     */
    private int[] readDeviceRegisters(ModbusMaster master, int deviceId )
            throws ModbusTransportException {

        // 创建读取请求
        ReadHoldingRegistersRequest request = Modbus4jUtils.getReadHoldingRegistersRequest(deviceId,START_ADDRESS, REGISTER_COUNT);

        // 发送请求并获取响应
        ModbusResponse response = master.send(request);

        // 检查响应类型
        if (!(response instanceof ReadHoldingRegistersResponse)) {
            throw new IllegalArgumentException("Invalid response type: " + response.getClass().getName());
        }

        ReadHoldingRegistersResponse regResponse = (ReadHoldingRegistersResponse) response;
        short[] signedValues = regResponse.getShortData();

        // 转换为无符号整数
        int[] unsignedValues = new int[signedValues.length];
        for (int i = 0; i < signedValues.length; i++) {
            unsignedValues[i] = signedValues[i] & 0xFFFF;
        }

        return unsignedValues;
    }
    /**
     * 带自定义条件的重试读取（线程安全版）
     */
    private int[] readWithConditionalRetry(ModbusMaster threadMaster,String ip, int port, int deviceId,
                                                  Predicate<int[]> conditionChecker)
            throws InterruptedException {

        TEquipmentAlarmData alarmData;

        int[] result = null;
        int attempt = 0;
        boolean conditionMet = false;

        if(threadMaster != null) {

            while (attempt <= MAX_RETRIES && !conditionMet) {
                attempt++;
                try {
                    log.info("当前 - 尝试第:{}次 读取设备ip:{} port:{} device:{}的数据", attempt, ip,port,deviceId);

                    // 读取数据
                    result = readDeviceRegisters(threadMaster, deviceId);

                    // 使用自定义条件检查
                    if (conditionChecker.test(result)) {
                        log.info("当前  设备ip:{} port:{} device:{}的数据条件满足", ip,port,deviceId);
                        conditionMet = true;
                    } else if (attempt <= MAX_RETRIES) {
                        log.info("当前  设备ip:{} port:{} device:{}的数据条件未满足，等待重试...", ip,port,deviceId);
                        Thread.sleep(RETRY_DELAY);
                    }
                } catch (Throwable e) {
                    log.error("设备{}: 第{}次读取异常", deviceId, attempt, e);
                    recordAlarm("04", "ip:" + ip + ",port:" + port + ",deviceId:" + deviceId, "第" + attempt + "次读取失败");
                    if (attempt <= MAX_RETRIES) {
                        Thread.sleep(RETRY_DELAY);
                    }
                }
            }

            // 如果达到最大重试次数仍未满足条件
            if (!conditionMet) {
                log.info("当前  设备ip:{} port:{} device:{}的尝试次数达到最大:{}", ip,port,deviceId,MAX_RETRIES);
            }
        }
        return result != null ? result : new int[REGISTER_COUNT];
    }

    /**
     * 创建新的Modbus连接
     */
    private static ModbusMaster createModbusMaster(String ip, int port) throws ModbusInitException {
        IpParameters params = new IpParameters();
        params.setHost(ip);
        params.setPort(port);

        // 显式声明为TcpMaster，避免后续反射类型转换问题
        TcpMaster master = (TcpMaster) modbusFactory.createTcpMaster(params, true);
        master.setTimeout(3000); // 3秒连接超时
        master.setRetries(1);    // 1次重试
        master.init();
        log.debug("Modbus连接创建成功：IP={}, 端口={}, Master={}", ip, port, master);
        return master;
    }

    /**
     * 核心修复：反射获取TcpMaster底层Socket（处理私有字段权限）
     */
    private static Socket getUnderlyingSocket(ModbusMaster master) {
        if (!(master instanceof TcpMaster)) {
            log.error("ModbusMaster不是TcpMaster类型，无法获取Socket");
            return null;
        }

        TcpMaster tcpMaster = (TcpMaster) master;
        try {
            // 1. 关键：内部类路径用 "$" 连接外部类（必须与你的Modbus4j版本匹配）
            String transportClassName = "sun.rmi.transport.tcp.TcpTransport";
            Class<?> transportClass = Class.forName(transportClassName);
            log.debug("成功加载TcpMaster内部类：{}", transportClassName);

            // 2. 获取TcpMaster的private字段 "transport"（存储内部类实例）
            Field transportField = TcpMaster.class.getDeclaredField("transport");
            transportField.setAccessible(true); // 取消私有字段访问限制
            Object transport = transportField.get(tcpMaster);
            if (transport == null) {
                log.error("TcpMaster的transport字段为null（连接未初始化？）");
                return null;
            }

            // 3. 获取内部类TcpTransport的private字段 "socket"（底层Socket）
            // 注意：若报错"NoSuchFieldException"，需打开Modbus4j源码确认字段名（如"clientSocket"）
            Field socketField = transportClass.getDeclaredField("socket");
            socketField.setAccessible(true); // 取消私有字段访问限制
            Socket socket = (Socket) socketField.get(transport);

            log.debug("成功获取Socket：IP={}, 本地端口={}", socket.getInetAddress(), socket.getLocalPort());
            return socket;
        } catch (ClassNotFoundException e) {
            log.error("=== 致命错误：TcpTransport类未找到！===\n" +
                    "原因：1. Modbus4j版本不兼容；2. 内部类路径错误（需确认是否为 TcpMaster$TcpTransport）\n" +
                    "解决方案：1. 打开Modbus4j源码，找到TcpMaster的内部类TcpTransport，复制完整类名；\n" +
                    "         2. 将 transportClassName 改为实际路径（如 com.xxx.TcpMaster$TcpTransport）", e);
        } catch (NoSuchFieldException e) {
            log.error("=== 致命错误：字段未找到！===\n" +
                    "原因：1. TcpMaster的transport字段名错误；2. TcpTransport的socket字段名错误\n" +
                    "解决方案：1. 打开TcpMaster源码，确认传输字段名（如'tcpTransport'）；\n" +
                    "         2. 打开TcpTransport源码，确认Socket字段名（如'clientSocket'）", e);
        } catch (IllegalAccessException e) {
            log.error("反射访问字段权限失败（可能被安全管理器拦截）", e);
        } catch (Exception e) {
            log.error("获取底层Socket异常", e);
        }
        return null;
    }
    /**
     * 销毁ModbusMaster并关闭底层Socket（确保资源彻底释放）
     */
    private static void destroyModbusMaster(ModbusMaster master, int deviceId) {
        if (master == null) return;

        try {
            // 1. 先关闭底层Socket（反射获取）
            Socket socket = getUnderlyingSocket(master);
            if (socket != null && !socket.isClosed()) {
                socket.close();
                log.debug("设备{}: 底层Socket已强制关闭", deviceId);
            }
        } catch (Exception e) {
            log.error("设备{}: 关闭底层Socket异常", deviceId, e);
        } finally {
            // 2. 再销毁ModbusMaster
            try {
                master.destroy();
                log.debug("设备{}: ModbusMaster已销毁", deviceId);
            } catch (Exception e) {
                log.error("设备{}: 销毁ModbusMaster异常", deviceId, e);
            }
        }
    }

    /**
     * 启动多设备监控（反射方案，确保资源释放）
     */
    public void startMultiDeviceMonitoring(
            String ip, int port, List<Integer> deviceIds,
            Consumer<DeviceStatusReaderDto> resultHandler,
            Predicate<int[]> stopCondition) {
        if (deviceIds == null || deviceIds.isEmpty()) {
            log.warn("⚠️ 设备ID列表为空，不执行监控");
            return;
        }

        final CountDownLatch latch = new CountDownLatch(deviceIds.size());
        log.info("开始监控设备：IP={}, 端口={}, 设备数={}（线程池活跃线程：{}）",
                ip, port, deviceIds.size(), ((ThreadPoolExecutor) FIXED_THREAD_POOL).getActiveCount());

        for (int deviceId : deviceIds) {
            final int devId = deviceId;
            FIXED_THREAD_POOL.submit(() -> {
                ModbusMaster threadMaster = null;
                try {
                    // 1. 创建独立连接（每个设备任务一个连接，避免复用泄漏）
                    threadMaster = createModbusMaster(ip, port);
                    if (threadMaster == null) {
                        log.error("设备{}: Modbus连接创建失败，终止任务", devId);
                        recordAlarm("03", "ip:" + ip + ",port:" + port + ",deviceId:" + devId, "连接创建失败");
                        return;
                    }

                    // 2. 读取数据（带重试和异常处理）
                    int[] result = readWithConditionalRetry(threadMaster, ip, port, devId, stopCondition);

                    // 3. 回调处理结果（判空避免NPE）
                    if (resultHandler != null) {
                        resultHandler.accept(new DeviceStatusReaderDto(ip, port, devId, result));
                    }

                } catch (ModbusInitException e) {
                    log.error("设备{}: Modbus连接初始化失败", devId, e);
                    recordAlarm("03", "ip:" + ip + ",port:" + port + ",deviceId:" + devId,
                            "连接初始化失败：" + e.getMessage());
                } catch (Throwable e) {
                    log.error("设备{}: 监控任务致命异常", devId, e);
                    String alarmMsg = e instanceof OutOfMemoryError ? "内存溢出：" + e.getMessage() : "监控任务异常：" + e.getMessage();
                    recordAlarm("03", "ip:" + ip + ",port:" + port + ",deviceId:" + devId, alarmMsg);

                } finally {
                    // 关键：无论成功/失败，都强制销毁连接（避免资源泄漏）
                    destroyModbusMaster(threadMaster, devId);
                    latch.countDown();
                    log.info("设备{}: 监控任务完成（剩余任务：{}）", devId, latch.getCount());
                }
            });
        }

        // 等待所有任务完成，超时后强制中断（避免长期阻塞）
        try {
            if (!latch.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)) {
                log.warn("IP{}: 部分设备监控超时（未完成任务数：{}），强制中断", ip, latch.getCount());
                recordAlarm("03", "ip:" + ip + ",port:" + port,
                        "部分设备监控超时（未完成：" + latch.getCount() + "）");
                // 超时后关闭线程池（避免任务堆积）
                FIXED_THREAD_POOL.shutdownNow();
            }
        } catch (InterruptedException e) {
            log.error("IP{}: 监控任务被中断", ip, e);
            Thread.currentThread().interrupt(); // 恢复中断状态
        }
    }


    /**
     * 统一告警记录（抽离避免重复代码）
     */
    private void recordAlarm(String alarmType, String equipmentCode, String alarmData) {
        try {
            TEquipmentAlarmData alarm = new TEquipmentAlarmData();
            alarm.setfAlarmType(alarmType);
            alarm.setfEquipmentCode(equipmentCode);
            alarm.setfAlarmData(alarmData);
            alarm.setfCreateTime(new java.util.Date());
            alarmDataService.insertTEquipmentAlarmData(alarm);
        } catch (Exception e) {
            log.error("告警记录失败：{}", alarmData, e);
        }
    }
}
