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

import cn.estsh.i3plus.ext.mes.pcn.api.busi.IWorkCenterContainerLocationService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.ep.ISxWorkCenterMovtrnCfgService;
import cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.busi.station.ep.EpPutPalletModuleService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.*;
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.repository.MesPackageExtRepository;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.MesProduceSnRepairRepository;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.SxProductOffLineExtRepository;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.SxProductOffLineMovtrnRepository;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.ConvertBeanExt;
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.convert.ConvertBean;
import cn.estsh.i3plus.pojo.base.enumutil.MesPcnEnumUtil;
import cn.estsh.i3plus.pojo.mes.bean.MesContainer;
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 cn.estsh.i3plus.pojo.mes.repository.MesContainerRepository;
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 : 工步业务-EP装托完成工步
 * @Reference :
 * @Author : wangjie
 * @CreateDate : 2019-07-11
 * @Modify:
 **/
@Slf4j
@Service("epPutPalletCompleteStepService")
public class EpPutPalletCompleteStepService extends BaseStepService {

    @Autowired
    private EpPutPalletModuleService putPalletModuleService;

    @Autowired
    private MesPackageExtRepository packageExtRepository;

    @Autowired
    private MesProduceSnRepairRepository produceSnRepairRepository;

    @Autowired
    private SxProductOffLineExtRepository productOffLineExtRepository;

    @Autowired
    private IWorkCenterContainerLocationService workCenterContainerLocationService;

    @Autowired
    private ISxWorkCenterMovtrnCfgService workCenterMovtrnCfgService;

    @Autowired
    private MesContainerRepository containerRepository;

    @Autowired
    private SxProductOffLineMovtrnRepository productOffLineMovtrnRepository;

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

        StationResultBean resultBean = new StationResultBean();
        String err;

        MesWorkCenterContainerLocation curLocation = (MesWorkCenterContainerLocation) putPalletModuleService.doHandleCurLocation(reqBean, 1, null);
        if (null == curLocation) {
            err = LocaleUtil.transferLanguage(reqBean.getUserInfo(), "当前未锁定位置编号");
            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            return StepResult.getSuccessComplete();
        }

        EpPutPalletPlcDataModel ctNoModel = (EpPutPalletPlcDataModel) putPalletModuleService.doHandleCurCtNo(reqBean, 1, null);
        if (null == ctNoModel || !ctNoModel.getBoo()) {
            err = LocaleUtil.transferLanguage(reqBean.getUserInfo(), "当前未固定容器代码");
            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            return StepResult.getSuccessComplete();
        }

        List<SxPutPalletModuleModel> putPalletModuleModelList = (List<SxPutPalletModuleModel>) putPalletModuleService.doHandlePackageDataByCtNo(reqBean, ctNoModel.getCtNo(), 1, null);
        if (CollectionUtils.isEmpty(putPalletModuleModelList)) {
            err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "容器代码[%s]未绑定包装条码"), ctNoModel.getCtNo());
            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            return StepResult.getSuccessComplete();
        }

        try {
            MesContainer container = workCenterContainerLocationService.getContainerByCtNo(reqBean.getOrganizeCode(), ctNoModel.getCtNo());
            if (null == container) {
                err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "容器代码[%s]无效"), ctNoModel.getCtNo());
                this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                foundExThrowNoShowMsg();
            }
            container.setUseStatus(String.valueOf(MesPcnEnumUtil.MES_CONTAINER_STATUS.OCCUPY.getValue()));
            ConvertBean.serviceModelUpdate(container, reqBean.getUserInfo());
            containerRepository.save(container);

            MesWorkCenterMovtrnCfg movtrnCfg = workCenterMovtrnCfgService.getWorkCenterMovtrnCfgByCenter(reqBean.getOrganizeCode(), reqBean.getWorkCenterCode());

            for (SxPutPalletModuleModel model : putPalletModuleModelList) {
                if (null == model) {
                    continue;
                }

                SxProductOffLineMovtrn movtrn = new SxProductOffLineMovtrn();

                if (MesPcnExtEnumUtil.WORK_ORDER_TYPE.REWORK_ORDER.getValue() != model.getWorkOrderType()) {
                    MesPackageExt pack = packageExtRepository.getById(Long.parseLong(model.getIdStr()));
                    if (null == pack) {
                        err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "包装条码ID[%s]数据不存在"), model.getIdStr());
                        this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                        foundExThrowNoShowMsg();
                    }
                    pack.setCtNo(ctNoModel.getCtNo());
                    ConvertBean.serviceModelUpdate(pack, reqBean.getUserInfo());
                    pack.setSystemSyncStatus(MesPcnExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
                    new ConvertBeanExt(pack).convertBean(pack);
                    packageExtRepository.save(pack);

                    movtrn.setPartNo(pack.getPartNo());
                    movtrn.setPartNameRdd(pack.getPartNameRdd());
                    movtrn.setLotNo(pack.getLotNo());
                } else {
                    MesProduceSnRepair produceSnRepair = produceSnRepairRepository.getById(Long.parseLong(model.getIdStr()));
                    if (null == produceSnRepair) {
                        err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "返工条码ID[%s]数据不存在"), model.getIdStr());
                        this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                        foundExThrowNoShowMsg();
                    }
                    produceSnRepair.setCtNo(ctNoModel.getCtNo());
                    ConvertBean.serviceModelUpdate(produceSnRepair, reqBean.getUserInfo());
                    produceSnRepairRepository.save(produceSnRepair);

                    movtrn.setPartNo(produceSnRepair.getPartNo());
                    movtrn.setPartNameRdd(produceSnRepair.getPartNameRdd());
                    movtrn.setLotNo(produceSnRepair.getLotNo());
                }

                SxProductOffLineExt productOffLineExt = new SxProductOffLineExt();
                productOffLineExt.setWorkOrderNo(model.getWorkOrderNo());
                productOffLineExt.setPackageNo(model.getPackageNo());
                productOffLineExt.setCtNo(ctNoModel.getCtNo());
                productOffLineExt.setStrarPoint(curLocation.getCtLocationNo());
                productOffLineExt.setIsAGVCarry(MesPcnExtEnumUtil.IS_AGV_CARRY.YES.getValue());
                productOffLineExt.setSyncStatus(MesPcnExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
                productOffLineExt.setOrganizeCode(reqBean.getOrganizeCode());
                ConvertBean.serviceModelInitialize(productOffLineExt, reqBean.getUserInfo());
                productOffLineExtRepository.insert(productOffLineExt);

                movtrn.setWorkCenterCode(reqBean.getWorkCenterCode());
                movtrn.setPackageNo(ctNoModel.getCtNo());
                movtrn.setSerialNumber(model.getPackageNo());
                movtrn.setSerialNumberQty(putPalletModuleModelList.size());
                movtrn.setStatus((null != movtrnCfg && !StringUtils.isEmpty(movtrnCfg.getStatus()) ? Integer.valueOf(movtrnCfg.getStatus()) : MesPcnExtEnumUtil.WORK_CENTER_MOVTRN_STATUS.UN_MOVTRN.getValueInt()));
                movtrn.setFlag(0);
                movtrn.setOrganizeCode(reqBean.getOrganizeCode());
                ConvertBean.serviceModelInitialize(movtrn, reqBean.getUserInfo());
                productOffLineMovtrnRepository.insert(movtrn);
            }


        } catch (Exception e) {
            err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "容器代码[%s]执行满托发生异常,请执行强制完成!异常原因[%s]"),
                    ctNoModel.getCtNo(), e.getMessage());
            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            foundExThrowNoShowMsg();
        }

        putPalletModuleService.doHandleCurCtNo(reqBean, 3, null);
        putPalletModuleService.doHandleCurCtQty(reqBean, 3, null);
        putPalletModuleService.doHandlePackageDataByCtNo(reqBean, ctNoModel.getCtNo(), 3, null);

        err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "容器代码[%s]已完成装托"), ctNoModel.getCtNo());
        this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT);
        return StepResult.getSuccessComplete();
    }

}
