package com.fizz.business.service.hanle;

import cn.hutool.json.JSONUtil;
import com.fizz.business.anno.OpcMessageHandlerType;
import com.fizz.business.constants.enums.L1OperateMatEnum;
import com.fizz.business.constants.enums.OpcMessageType;
import com.fizz.business.domain.msg.EntryMovementMessage;
import com.fizz.business.domain.msg.ExitCutMessage;
import com.fizz.business.dto.ExitCoilInfoDTO;
import com.fizz.business.dto.MatmapDTO;
import com.fizz.business.form.L1OperateMatForm;
import com.fizz.business.service.OpcMessageHandler;
import com.fizz.business.service.PdoExCoilService;
import com.fizz.business.service.TrackService;
import com.fizz.business.utils.MatmapUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import static com.fizz.business.constants.enums.DeviceEnum.TR;

@Component
@Slf4j
@RequiredArgsConstructor
@OpcMessageHandlerType(OpcMessageType.EXIT_CUT)
public class ExitCutHandler implements OpcMessageHandler<ExitCutMessage> {

    // 注入 PdoExCoilService
    private final PdoExCoilService pdoExCoilService;
    private final TrackService trackService;
    @Resource
    private OpcReceiverHandler opcReceiverHandler;
    @Override
    public void handle(ExitCutMessage message) {
        // 1. 获取卷取机 (TR) 上的物料信息
        MatmapDTO trMatmap = MatmapUtil.getMatmap(TR.getIdx());

        if (trMatmap == null) {
            log.error("卷取机不存在");
            return;
        }

        log.info("接受到出口剪切信号:{}", JSONUtil.toJsonStr(message));
        // 2. 根据剪切类型，生成产出卷信息
        ExitCoilInfoDTO exitCoilInfo = pdoExCoilService.genExitCoilInfo(trMatmap, message.getCutType());

        // 3. 补充 ExitCutMessage 中的长度和外径信息
        exitCoilInfo.setExitCutLength(message.getCutLength().doubleValue());
        exitCoilInfo.setOuterDiameter(message.getOuterDiameter().doubleValue());

        // 4. 调用服务进行产出卷的持久化
        pdoExCoilService.saveExCoil(exitCoilInfo);

        if (exitCoilInfo.isLastFlag()) {

            trackService.l1OperateMat(L1OperateMatForm.builder()
                    .trIdx(TR.getIdx())
                    .entryMatId(trMatmap.getMatId())
                    .planId(trMatmap.getPlanId())
                    .operation(L1OperateMatEnum.PRODUCT)
                    .build());

            // wangyu 配合二级发一个甩尾信号  01全甩一下
            EntryMovementMessage msg = new EntryMovementMessage();
            msg.setCounter(message.getCounter());
            msg.setMaterialPlaceSource(0);
            msg.setMaterialPlaceDestination(200);
            opcReceiverHandler.onMessageReceived(OpcMessageType.ENTRY_MOVEMENT,msg);
            msg.setMaterialPlaceSource(1);
            opcReceiverHandler.onMessageReceived(OpcMessageType.ENTRY_MOVEMENT,msg);
        }

        log.info("成功处理 EXIT_CUT 消息，已保存成品卷: " + exitCoilInfo.getExitMatId());
    }
}
