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

import cn.estsh.i3plus.ext.mes.pcn.api.busi.IProduceSnExtService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesProduceSnExt;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesProduceSnTravelExt;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.MesProduceSnTravelExtRepository;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.mes.pcn.actor.shipping.dispatch.IFsmCommonService;
import cn.estsh.i3plus.mes.pcn.serviceimpl.base.BaseStepService;
import cn.estsh.i3plus.mes.pcn.util.LocaleUtil;
import cn.estsh.i3plus.pojo.base.bean.DdlPackBean;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.enumutil.MesPcnEnumUtil;
import cn.estsh.i3plus.pojo.base.tool.DdlPreparedPack;
import cn.estsh.i3plus.pojo.mes.bean.MesProduceSn;
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;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description : 工步业务-本体包装前置校验条码生产顺序工步
 * @Reference :
 * @Author : wangjie
 * @CreateDate : 2019-07-11
 * @Modify:
 **/
@Slf4j
@Service("sxNoumenonPackagePreCheckProdSeqStepService")
public class SxNoumenonPackagePreCheckProdSeqStepService extends BaseStepService {

    @Autowired
    private IProduceSnExtService produceSnExtService;

    @Autowired
    private MesProduceSnTravelExtRepository produceSnTravelExtRepository;

    @Autowired
    private IFsmCommonService fsmCommonService;

    @Override
    public StepResult init(StationRequestBean reqBean) {
        return super.init(reqBean);
    }

    @Override
    public StepResult execute(StationRequestBean reqBean) {
        log.info("SxNoumenonPackagePreCheckProdSeqStepService[execute] 参数：{}", reqBean);

        StationResultBean resultBean = new StationResultBean();
        String err;

        if (StringUtils.isEmpty(reqBean.getOrganizeCode())) {
            err = LocaleUtil.transferLanguage(reqBean.getUserInfo(), "入参缺少工厂代码");
            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            return StepResult.getNonComplete(err);
        }

        if (StringUtils.isEmpty(reqBean.getWorkOrderNo())) {
            err = LocaleUtil.transferLanguage(reqBean.getUserInfo(), "入参缺少工单号");
            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            return StepResult.getNonComplete(err);
        }

        if (StringUtils.isEmpty(reqBean.getSerialNumber())) {
            err = LocaleUtil.transferLanguage(reqBean.getUserInfo(), "入参缺少产品条码");
            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            return StepResult.getNonComplete(err);
        }

        List<MesProduceSnExt> produceSnExtList = produceSnExtService.getProduceSnExtListByOrderNo(reqBean.getOrganizeCode(), reqBean.getWorkOrderNo());
        List<String> serialNumberList = CollectionUtils.isEmpty(produceSnExtList) ? null :
                produceSnExtList.stream().filter(o -> null != o).map(MesProduceSn::getSerialNumber).collect(Collectors.toList());
        serialNumberList = CollectionUtils.isEmpty(serialNumberList) ? null :
                serialNumberList.stream().filter(o -> !StringUtils.isEmpty(o)).sorted(String::compareTo).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(serialNumberList)) {
            err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "生产工单[%s]未关联条码"), reqBean.getWorkOrderNo());
            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            return StepResult.getNonComplete(err);
        }

        DdlPackBean packBean = DdlPackBean.getDdlPackBean(reqBean.getOrganizeCode());
        DdlPreparedPack.getStringEqualPack(reqBean.getProcessCode(), MesPcnExtConstWords.PROCESS_CODE, packBean);
        DdlPreparedPack.getStringEqualPack(reqBean.getWorkCellCode(), MesPcnExtConstWords.WORK_CELL_CODE, packBean);
        DdlPreparedPack.getStringEqualPack(reqBean.getWorkOrderNo(), MesPcnExtConstWords.WORK_ORDER_NO, packBean);
        DdlPreparedPack.getOrderByPack(new Object[]{CommonEnumUtil.ASC_OR_DESC.DESC.getValue()}, new String[]{MesPcnExtConstWords.CREATE_DATE_TIME}, packBean);
        MesProduceSnTravelExt produceSnTravelExt = produceSnTravelExtRepository.getByProperty(packBean);
        if (null != produceSnTravelExt) {
            Integer indexOld = serialNumberList.indexOf(produceSnTravelExt.getSerialNumber());
            if (indexOld.compareTo(-1) == 0) {
                err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "上次扫描的产品条码[%s]未关联工单[%s]"), produceSnTravelExt.getSerialNumber(), reqBean.getWorkOrderNo());
                this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                return StepResult.getNonComplete(err);
            }
            Integer indexNew = serialNumberList.indexOf(reqBean.getSerialNumber());
            if (indexNew.compareTo(-1) == 0) {
                err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "本次扫描的产品条码[%s]未关联工单[%s]"), reqBean.getSerialNumber(), reqBean.getWorkOrderNo());
                this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                return StepResult.getNonComplete(err);
            }

            int checkSnSeqMaxNum = 90;
            Map<String, String> wcpcMap  = fsmCommonService.getCachedWorkCellParam(reqBean);
            if (!CollectionUtils.isEmpty(wcpcMap) && wcpcMap.containsKey("CHECK_SN_SEQ_MAX_NUM") && !StringUtils.isEmpty(wcpcMap.get("CHECK_SN_SEQ_MAX_NUM"))) {
                checkSnSeqMaxNum = Integer.parseInt(wcpcMap.get("CHECK_SN_SEQ_MAX_NUM"));
            }

            if (Math.abs(indexNew - indexOld) >= checkSnSeqMaxNum) {
                err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "本次扫描的产品条码[%s]与上次扫描的产品条码[%s]间隔区间超过[%s],需验证跳号码"),
                        reqBean.getSerialNumber(), produceSnTravelExt.getSerialNumber(), checkSnSeqMaxNum);
                this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);

                reqBean.getDataMap().put("LAST_SN", produceSnTravelExt.getSerialNumber());
                reqBean.getDataMap().put(MesPcnExtConstWords.WORK_ORDER_NO, reqBean.getWorkOrderNo());
                StepResult stepResult = StepResult.getSuccessComplete();
                stepResult.setNextTriggerEvent("CHECK_SN_SEQ");
                return stepResult;
            }
        }
        return StepResult.getSuccessComplete();
    }

}
