package cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.step;

import cn.estsh.i3plus.ext.mes.pcn.api.busi.IMesProductionDispatchContextStepService;
import cn.estsh.i3plus.ext.mes.pcn.apiservice.util.BarCodeUtils;
import cn.estsh.i3plus.ext.mes.pcn.pojo.context.MesEquipVariableCollectContext;
import cn.estsh.i3plus.mes.pcn.serviceimpl.fsm.BaseStepService;
import cn.estsh.i3plus.pojo.base.enumutil.MesPcnEnumUtil;
import cn.estsh.i3plus.pojo.mes.bean.shipping.MesShippingQueue;
import cn.estsh.i3plus.pojo.mes.model.StationRequestBean;
import cn.estsh.i3plus.pojo.mes.model.StationResultBean;
import cn.estsh.i3plus.pojo.mes.model.StepResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @Description : 发运队列RFID匹配工步
 * @Author : wangjie
 **/
@Slf4j
@Service("mesShippingRfidMatchStepService")
public class MesShippingRfidMatchStepService extends BaseStepService {

    @Autowired
    private IMesProductionDispatchContextStepService productionDispatchContextStepService;

    @Override
    public StepResult execute(StationRequestBean reqBean) {

        StationResultBean resultBean = new StationResultBean();

        StepResult stepResult = StepResult.getSuccessComplete();

        //获取上下文发运队列信息
        MesShippingQueue shippingQueue = productionDispatchContextStepService.getShippingQueueContext(reqBean);
        if ((null == shippingQueue || StringUtils.isEmpty(shippingQueue.getRfidSn())))
            return stepNonCompleteAndSendMsgReturn(reqBean, resultBean.writeDbLog(), stepResult, "当前未获取到缓存中有效的发运队列!");

        //获取上下文扫/读信息:主条码
        List<MesEquipVariableCollectContext> equipVariableCollectContextList = productionDispatchContextStepService.getScanProductSnContext(reqBean);
        //设备写的条码, rfid条码存在特殊字符, 所以要先取 realEquipVariableValue , 没有再取 equipVariableValue
        String productSn = CollectionUtils.isEmpty(equipVariableCollectContextList) ? null :
                (!StringUtils.isEmpty(equipVariableCollectContextList.get(0).getRealEquipVariableValue())
                        ? equipVariableCollectContextList.get(0).getRealEquipVariableValue() : equipVariableCollectContextList.get(0).getEquipVariableValue());
        if (StringUtils.isEmpty(productSn)) return stepNonCompleteAndSendMsgReturn(reqBean, resultBean.writeDbLog(), stepResult, "当前未获取到设备写入的主条码信息!");

        if (!shippingQueue.getRfidSn().equals(productSn))
            return stepNonCompleteAndSendMsgReturn(reqBean, resultBean.writeDbLog(), stepResult, String.format("RFID匹配失败!读条码[%s]与RFID条码[%s]不一致!", productSn, shippingQueue.getRfidSn()));

        return stepSuccessCompleteAndSendMsgReturn(reqBean, resultBean.writeDbLog(), stepResult, "RFID匹配成功!", MesPcnEnumUtil.PROMPT_SOUND.SUCCESS.getValue());

    }

}
