package com.fizz.business.service.hanle;

import com.fizz.business.anno.OpcMessageHandlerType;
import com.fizz.business.constants.enums.DeviceEnum;
import com.fizz.business.constants.enums.OpcMessageType;
import com.fizz.business.domain.msg.*;
import com.fizz.business.service.OpcMessageHandler;
import com.fizz.business.service.strip.SegmentTrackerService;
import com.fizz.business.service.strip.StripPositionService;
import com.fizz.business.utils.WebSocketUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

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

    private final SegmentTrackerService tracker;

    @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);

        // 2) extract key fields
        String coilId = entry == null ? "UNKNOWN" : entry.getEntryCoilId();
        BigDecimal lengthAtWelder = entry == null || entry.getStripLocation() == null ? BigDecimal.ZERO : entry.getStripLocation();

        // 3) delegate core processing to tracker
        tracker.handleMeasure(coilId, lengthAtWelder, entry, furnace, coat, exit);

        // 调用新的方法来跟踪钢卷头部位置，并处理快照和 matmap 更新
        // 使用焊机长度作为最接近的钢卷头部位置
        tracker.trackCoilHeadPosition(coilId, lengthAtWelder, entry, exit);
    }
}