package com.fizz.business.service.strip;

import com.fizz.business.constants.enums.DeviceEnum;
import com.fizz.business.service.LogDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * 位置计算服务 —— 根据 entry.stripLocation（焊机参考）和活套长度动态判断设备的比较位置
 */
@Service
@Slf4j
public class StripPositionService {

    @Resource
    LogDataService logDataService;

    public double calculate(DeviceEnum device, BigDecimal celLength, BigDecimal cxlLength) {
        double base = device.getBasePosition();
        double cel = celLength == null ? 0.0 : celLength.doubleValue();
        double cxl = cxlLength == null ? 0.0 : cxlLength.doubleValue();

        double result;

        switch (device.getSectionType()) {
            case ENTRY:
                // 入口段：不开活套
                result = base;
                break;

            case PROCESS:
                // 工艺段：加入口活套偏移
                result = base + cel;
                break;

            case EXIT:
                // 出口段：加入口 + 出口活套偏移
                result = base + cel + cxl;
                break;

            default:
                result = base;
        }

        // === 日志输出（控制频率，防止刷屏）===
        if (log.isDebugEnabled()) {
            log.debug("【POSITION-CALC】设备: {}, 区域: {}, Base: {}, Cel: {}, Cxl: {}, 结果: {}",
                    device.getDesc(),
                    device.getSectionType(),
                    String.format("%.3f", base),
                    String.format("%.3f", cel),
                    String.format("%.3f", cxl),
                    String.format("%.3f", result)
            );
        }

        // 可选：持久化关键信息（只针对关键设备或每隔一段时间）
        if (device == DeviceEnum.WELDER || device == DeviceEnum.COAT || device == DeviceEnum.TR) {
            logDataService.logInfo("POSITION",
                    String.format("设备:%s | 区域:%s | Base:%.3f | Cel:%.3f | Cxl:%.3f | Result:%.3f",
                            device.getDesc(), device.getSectionType(), base, cel, cxl, result));
        }

        return result;
    }

}