package com.fizz.business.service.hanle;

import com.fizz.business.anno.OpcMessageHandlerType;
import com.fizz.business.constants.enums.OpcMessageType;
import com.fizz.business.domain.msg.*;
import com.fizz.business.dto.MatmapDTO;
import com.fizz.business.service.LogDataService;
import com.fizz.business.service.OpcMessageHandler;
import com.fizz.business.service.strip.SegmentTrackerService;
import com.fizz.business.utils.MatmapUtil;
import com.fizz.business.utils.WebSocketUtil;
import com.ruoyi.common.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicInteger;

@OpcMessageHandlerType(OpcMessageType.APP_MEASURE)
@Component
@RequiredArgsConstructor
@Slf4j
public class AppMeasureHandler implements OpcMessageHandler<AppMeasureMessage> {

    private final SegmentTrackerService tracker;
    private final LogDataService logDataService;
    private final Executor coilTrackExecutor; // 注入线程池接口

    private static final AtomicInteger LOG_COUNTER = new AtomicInteger(0);

    @Override
    public void handle(AppMeasureMessage message) {
        if (message == null) return;

        AppMeasureEntryMessage entry = message.getAppMeasureEntryMessage();
        AppMeasureFurnaceMessage furnace = message.getAppMeasureFurnaceMessage();
        AppMeasureCoatMessage coat = message.getAppMeasureCoatMessage();
        AppMeasureExitMessage exit = message.getAppMeasureExitMessage();

        WebSocketUtil.sendMeasureMsg(message);


        BigDecimal lengthAtWelder = entry == null || entry.getStripLocation() == null ? BigDecimal.ZERO : entry.getStripLocation();
        // 处理钢卷ID为空的情况
        String coilId ="";
//        if (entry != null && entry.getEntryCoilId() != null){
//            coilId = entry.getEntryCoilId();
//
//        }else {
        if (entry != null) {
            log.error("entry{}",entry.getPayOffReelNumber());
        }
        MatmapDTO matmapDTO =getCurrentRunningCoilId(entry);
            coilId = matmapDTO.getMatId();
//        }

        if (StringUtils.isEmpty(coilId) || "".equals(coilId)){
            log.error("钢卷号为空，无法执行焊缝跟踪！！！！！！");
            return;
        }



        // 每10次请求输出一次日志
        int count = LOG_COUNTER.incrementAndGet();
        if (count % 10 == 0) {
            logDataService.logInfo("WELDER",
                    "接收到钢卷焊缝跟踪信号：当前焊缝长度 lengthAtWelder：{} 当前钢卷信息 coilId：{}",
                    lengthAtWelder, coilId);

        }

        // 核心逻辑处理
        tracker.handleMeasure(coilId, lengthAtWelder, entry, furnace, coat, exit);

        // 异步执行 trackCoilHeadPosition
//        coilTrackExecutor.execute(() -> {
//            try {
//                log.warn(">>> trackCoilHeadPosition start, thread: {}, coilId: {}",
//                        Thread.currentThread().getName(), coilId);
//
//                tracker.trackCoilHeadPosition(coilId, lengthAtWelder, entry, exit);
//
//            } catch (Exception e) {
//                log.error("trackCoilHeadPosition 执行异常，coilId=" + coilId, e);
//            }
//        });
    }

    private MatmapDTO getCurrentRunningCoilId(AppMeasureEntryMessage entry) {

       return   MatmapUtil.getMatmap(entry.getPayOffReelNumber()-1);

    }
}
