package com.fizz.business.service.hanle;

import cn.hutool.core.util.ObjectUtil;
import com.fizz.business.anno.OpcMessageHandlerType;
import com.fizz.business.constants.enums.OpcMessageType;
import com.fizz.business.domain.msg.ExitMovementMessage;
import com.fizz.business.dto.MatmapDTO;
import com.fizz.business.service.OpcMessageHandler;
import com.fizz.business.service.ProMatmapService;
import com.fizz.business.utils.MatmapUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
@OpcMessageHandlerType(OpcMessageType.EXIT_MOVEMENT)
@RequiredArgsConstructor
public class ExitMovementHandler implements OpcMessageHandler<ExitMovementMessage> {

    @Resource
    ProMatmapService proMatmapService;

    @Override
    public void handle(ExitMovementMessage message) {

        // 1. 获取源位置的物料信息
        int srcIndex = message.getExSrc() ;
        MatmapDTO srcMatmap = MatmapUtil.getMatmap(srcIndex);

        if (ObjectUtil.isNull(srcMatmap) || ObjectUtil.isNull(srcMatmap.getMatId())) {
            log.error("源位置 {} 没有物料信息，跳过移动处理。", srcIndex);
            // 如果源位置没有物料，则可能是一次无效的移动，直接返回
            return;
        }

        // 2. 清空源位置的物料信息
        MatmapUtil.clearMatmap(srcIndex);
        log.info("成功清空源位置 {} 的物料信息。{}", srcIndex,srcMatmap.getMatId());

        // 3. 将物料信息设置到目标位置
        int destIndex = message.getExDesc();
        MatmapUtil.setMatmap(destIndex, srcMatmap.getMatId(), srcMatmap.getPlanId(), srcMatmap.getPlanNo());
        log.info("成功设置目标位置 {} 的物料信息为钢卷 {}", destIndex, srcMatmap.getMatId());

        proMatmapService.flushMatmap();
    }



}