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

import cn.estsh.i3plus.ext.mes.pcn.api.busi.IPackageExtService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.IProduceSnExtService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.IProduceSnRepairService;
import cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.busi.station.ep.EpPutPalletModuleService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesPackageExt;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesProduceSnExt;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesProduceSnRepair;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.SxPutPalletModuleModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.ep.EpPutPalletPlcDataModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtEnumUtil;
import cn.estsh.i3plus.mes.pcn.serviceimpl.base.BaseStepService;
import cn.estsh.i3plus.mes.pcn.util.LocaleUtil;
import cn.estsh.i3plus.platform.common.tool.TimeTool;
import cn.estsh.i3plus.pojo.base.enumutil.MesPcnEnumUtil;
import cn.estsh.i3plus.pojo.mes.bean.MesPackageDetail;
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.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description : 工步业务-EP装托人工模式扫描包装条码工步
 * @Reference :
 * @Author : wangjie
 * @CreateDate : 2019-07-11
 * @Modify:
 **/
@Slf4j
@Service("epPutPalletHandWorkScanPackageNoStepService")
public class EpPutPalletHandWorkScanPackageNoStepService extends BaseStepService {

    @Autowired
    private EpPutPalletModuleService putPalletModuleService;

    @Autowired
    private IPackageExtService packageExtService;

    @Autowired
    private IProduceSnExtService produceSnExtService;

    @Autowired
    private IProduceSnRepairService produceSnRepairService;

    //失败回到自己
    @Override
    public StepResult execute(StationRequestBean reqBean) {
        log.info("EpPutPalletHandWorkScanPackageNoStepService[execute] 参数：{}", reqBean);

        try {
            StationResultBean resultBean = new StationResultBean();
            String err;

            //从PLC读取到包装条码并校验成功,直接跳转满托校验
            EpPutPalletPlcDataModel curExecPackageNoModel = (EpPutPalletPlcDataModel) putPalletModuleService.doHandleCacheCurExecPackageNo(reqBean, 1, null);
            String cmdPlcPutPallet = (String) putPalletModuleService.doHandleCmdPlcPutPallet(reqBean, 1, null);
            if (null != curExecPackageNoModel && curExecPackageNoModel.getBoo()) {
                err = LocaleUtil.transferLanguage(reqBean.getUserInfo(), "当前缓存中存在一个产品已经装托,但之后未进行满托验证,此时即将进入满托验证...");
                this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT);
                return StepResult.getSuccessComplete();
            }
            if (!StringUtils.isEmpty(cmdPlcPutPallet)) {
                err = LocaleUtil.transferLanguage(reqBean.getUserInfo(), "当前缓存中存在必要装托指令,此时即将进入满托验证...");
                this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT);
                return StepResult.getSuccessComplete();
            }

            if (StringUtils.isEmpty(reqBean.getScanInfo())) {
                err = LocaleUtil.transferLanguage(reqBean.getUserInfo(), "请扫描包装条码");
                this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.GUIDE, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT);
                foundExThrowNoShowMsg();
            }

            err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "包装条码[%s]扫描成功"), reqBean.getScanInfo());
            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.RUNNING_INFO, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT);

            //此时如果是刚切换的模式,可能存在PLC的产品组或完托组数据,直接删除
            putPalletModuleService.doHandleCurPlcData(reqBean,3,null);

            EpPutPalletPlcDataModel curCtNoModel = (EpPutPalletPlcDataModel) putPalletModuleService.doHandleCurCtNo(reqBean, 1, null);
            if (null == curCtNoModel || !curCtNoModel.getBoo()) {
                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);
            }

            MesPackageExt pack = packageExtService.getPackageByPackNo(reqBean.getOrganizeCode(), reqBean.getScanInfo());
            if (null == pack) {
                err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "包装条码[%s]不存在"), reqBean.getScanInfo());
                this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                return StepResult.getNonComplete(err);
            }

            if (StringUtils.isEmpty(pack.getLotNo())) {
                err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "包装条码[%s]没有批次号,不能装托"), pack.getPackageNo());
                this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                return StepResult.getNonComplete(err);
            }

            List<SxPutPalletModuleModel> putPalletModuleModelList = (List<SxPutPalletModuleModel>) putPalletModuleService.doHandlePackageDataByCtNo(reqBean, curCtNoModel.getCtNo(), 1, null);
            if (!CollectionUtils.isEmpty(putPalletModuleModelList) && !putPalletModuleModelList.get(0).getPartNo().equals(pack.getPartNo())) {
                err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "包装条码[%s]关联的物料编码[%s]与当前已装托的物料编码[%s]不一致,不能装托"),
                        pack.getPackageNo(), pack.getPartNo(), putPalletModuleModelList.get(0).getPartNo());
                this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                return StepResult.getNonComplete(err);
            }

            String curPartNo = (String) putPalletModuleService.doHandleCurPartNo(reqBean, 1, null);
            String curWorkOrderNo = (String) putPalletModuleService.doHandleCurWorkOrderNo(reqBean, 1, null);
            Integer curWorkOrderType = (Integer) putPalletModuleService.doHandleCurWorkOrderType(reqBean, 1, null);
            if (MesPcnExtEnumUtil.WORK_ORDER_TYPE.REWORK_ORDER.getValue() != curWorkOrderType) {
                if (!pack.getWorkOrderNo().equals(curWorkOrderNo)) {
                    err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "包装条码[%s]不属于当前选择的工单[%s],不能装托"),
                            pack.getPackageNo(), curWorkOrderNo);
                    this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                    return StepResult.getNonComplete(err);
                }
            }

            if (!pack.getPartNo().equals(curPartNo)) {
                err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "包装条码[%s]关联的物料号[%s]与当前选择的工单[%s]关联的物料号[%s]不一致,不能装托"),
                        pack.getPackageNo(), pack.getPartNo(), curWorkOrderNo, curPartNo);
                this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                return StepResult.getNonComplete(err);
            }

            MesPackageDetail packageDetail = packageExtService.getPackageDetailByPackNo(reqBean.getOrganizeCode(), pack.getPackageNo());
            if (null == packageDetail) {
                err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "包装条码[%s]对应的明细信息不存在,不能装托"), pack.getPackageNo());
                this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                return StepResult.getNonComplete(err);
            }

            MesProduceSnExt produceSnExt = produceSnExtService.getProduceSnExtBySn(reqBean.getOrganizeCode(), packageDetail.getSerialNumber());
            if (null == produceSnExt) {
                err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "包装条码[%s]关联的产品条码[%s]对应的产品条码信息不存在,不能装托"),
                        pack.getPackageNo(), packageDetail.getSerialNumber());
                this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                return StepResult.getNonComplete(err);
            }

            if (MesPcnExtEnumUtil.PRODUCE_SN_QC_STATUS.QUALIFIED.getValue() != produceSnExt.getQcStatus()) {
                err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "包装条码[%s]关联的产品条码[%s]质量状态为[%s],不能装托"),
                        pack.getPackageNo(), produceSnExt.getSerialNumber(), MesPcnExtEnumUtil.PRODUCE_SN_QC_STATUS.valueOfDescription(produceSnExt.getQcStatus()));
                this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                return StepResult.getNonComplete(err);
            }

            if (MesPcnExtEnumUtil.PRODUCE_SN_STATUS.OFFLINE.getValue() != produceSnExt.getSnStatus()) {
                err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "包装条码[%s]关联的产品条码[%s]状态为[%s],不能装托"),
                        pack.getPackageNo(), produceSnExt.getSerialNumber(), MesPcnExtEnumUtil.PRODUCE_SN_STATUS.valueOfDescription(produceSnExt.getSnStatus()));
                this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                return StepResult.getNonComplete(err);
            }

            String idStr = pack.getId().toString();
            String lotNo = pack.getLotNo();
            if (MesPcnExtEnumUtil.WORK_ORDER_TYPE.REWORK_ORDER.getValue() == curWorkOrderType) {
                MesProduceSnRepair produceSnRepair = produceSnRepairService.getProduceSnRepairBySn(reqBean.getOrganizeCode(), packageDetail.getSerialNumber());
                if (null == produceSnRepair) {
                    err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "包装条码[%s]对应的产品条码[%s]未关联返工工单[%s],不能装托"),
                            pack.getPackageNo(), packageDetail.getSerialNumber(), curWorkOrderNo);
                    this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                    return StepResult.getNonComplete(err);
                }
                if (!produceSnRepair.getWorkOrderNo().equals(curWorkOrderNo)) {
                    err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "包装条码[%s]对应的产品条码关联的最新返工工单为[%s],不属于当前选择的返工工单[%s],不能装托"),
                            pack.getPackageNo(), produceSnRepair.getWorkOrderNo(), curWorkOrderNo);
                    this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                    return StepResult.getNonComplete(err);
                }
                if (!reqBean.getWorkCenterCode().equals(produceSnRepair.getWorkCenterCode())) {
                    err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "包装条码[%s]关联的返工工单类型的产品条码[%s]关联的生产线[%s]与当前生产线[%s]不一致,不能装托"),
                            pack.getPackageNo(), produceSnRepair.getSerialNumber(), produceSnRepair.getWorkCenterCode(), reqBean.getWorkCenterCode());
                    this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                    return StepResult.getNonComplete(err);
                }
                if (StringUtils.isEmpty(produceSnRepair.getLotNo())) {
                    err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "包装条码[%s]关联的返工工单类型的产品条码[%s]未下线,不能装托"),
                            pack.getPackageNo(), produceSnRepair.getSerialNumber());
                    this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                    return StepResult.getNonComplete(err);
                }
                if (!StringUtils.isEmpty(produceSnRepair.getCtNo())) {
                    err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "包装条码[%s]已经装托在容器编码[%s]中,操作失败"), pack.getPackageNo(), produceSnRepair.getCtNo());
                    this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                    return StepResult.getNonComplete(err);
                }
                idStr = produceSnRepair.getId().toString();
                lotNo = produceSnRepair.getLotNo();
            } else {
                if (!reqBean.getWorkCenterCode().equals(pack.getWorkCenterCode())) {
                    err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "包装条码[%s]关联的生产线[%s]与当前生产线[%s]不一致,不能装托"),
                            pack.getPackageNo(), pack.getWorkCenterCode(), reqBean.getWorkCenterCode());
                    this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                    return StepResult.getNonComplete(err);
                }
                if (!StringUtils.isEmpty(pack.getCtNo())) {
                    err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "包装条码[%s]已经装托在容器编码[%s]中,操作失败"), pack.getPackageNo(), pack.getCtNo());
                    this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                    return StepResult.getNonComplete(err);
                }
            }

            if (!CollectionUtils.isEmpty(putPalletModuleModelList)) {
                putPalletModuleModelList = putPalletModuleModelList.stream().sorted(Comparator.comparing(SxPutPalletModuleModel::getLotNo).reversed()).collect(Collectors.toList());
                if (TimeTool.stringParseToDate(lotNo, MesPcnExtConstWords.DATE_FORMAT).compareTo(TimeTool.stringParseToDate(putPalletModuleModelList.get(0).getLotNo(), MesPcnExtConstWords.DATE_FORMAT)) < 0) {
                    err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "包装条码[%s]的批次号[%s]早于上一个已装托包装条码的批次号[%s],不能装托"),
                            pack.getPackageNo(), lotNo, putPalletModuleModelList.get(0).getLotNo());
                    this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                    return StepResult.getNonComplete(err);
                }
            }

            SxPutPalletModuleModel model = new SxPutPalletModuleModel();
            model.setIdStr(idStr);
            model.setWorkOrderType(curWorkOrderType);
            model.setWorkOrderNo(curWorkOrderNo);
            model.setPartNo(pack.getPartNo());
            model.setLotNo(lotNo);
            model.setPackageNo(pack.getPackageNo());
            model.setCtNo(curCtNoModel.getCtNo());
            model.setScanDatetime(TimeTool.getNowTime(true));
            if (!(Boolean) putPalletModuleService.doHandlePackageDataByCtNo(reqBean, curCtNoModel.getCtNo(), 2, model)) {
                err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "包装条码[%s]已装托在容器代码[%s]中,请勿重复扫描"), pack.getPackageNo(), curCtNoModel.getCtNo());
                this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                return StepResult.getNonComplete(err);
            }

            EpPutPalletPlcDataModel  packageNoModel = new EpPutPalletPlcDataModel();
            packageNoModel.setPackageNo(pack.getPackageNo());
            packageNoModel.setBoo(true);
            packageNoModel.setReadDatetime(model.getScanDatetime());
            putPalletModuleService.doHandleCacheCurExecPackageNo(reqBean, 2, packageNoModel);

            err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "包装条码[%s]装托成功"), pack.getPackageNo());
            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT);

            return StepResult.getSuccessComplete();
        } finally {
            reqBean.setScanInfo(null);
        }
    }

}
