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

import cn.estsh.i3plus.ext.mes.pcn.api.base.ISxWorkOrderExtService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.IPackageExtService;
import cn.estsh.i3plus.ext.mes.pcn.apiservice.dao.IProduceSnRepairDao;
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.MesWorkOrderExt;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.ProduceSnRepairModel;
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.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.MathOperation;
import cn.estsh.i3plus.pojo.base.enumutil.MesPcnEnumUtil;
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.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description : 工步业务-EP装托选择工单工步
 * @Reference :
 * @Author : wangjie
 * @CreateDate : 2019-07-11
 * @Modify:
 **/
@Slf4j
@Service("epPutPalletChooseWorkOrderStepService")
public class EpPutPalletChooseWorkOrderStepService extends BaseStepService {

    @Autowired
    private EpPutPalletModuleService putPalletModuleService;

    @Autowired
    private ISxWorkOrderExtService workOrderService;

    @Autowired
    private IPackageExtService packageExtService;

    @Autowired
    private IProduceSnRepairDao produceSnRepairDao;

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

        StationResultBean resultBean = new StationResultBean();
        String err;

        String curWorkOrderNo = (String) putPalletModuleService.doHandleCurWorkOrderNo(reqBean, 1, null);
        String curPartNo = (String) putPalletModuleService.doHandleCurPartNo(reqBean, 1, null);
        Integer curWorkOrderType = (Integer) putPalletModuleService.doHandleCurWorkOrderType(reqBean, 1, null);
        String selectWorkOrderNo = (String) putPalletModuleService.doHandleSelectWorkOrderNo(reqBean, 1, null);
        String changeProdType = (String) putPalletModuleService.doHandleChangeProdType(reqBean, 1, null);
        if (StringUtils.isEmpty(curWorkOrderNo) && StringUtils.isEmpty(selectWorkOrderNo)) {
            err = LocaleUtil.transferLanguage(reqBean.getUserInfo(), "请选择工单");
            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.GUIDE, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT);
            foundExThrowNoShowMsg();
        }

        if (StringUtils.isEmpty(selectWorkOrderNo) && !StringUtils.isEmpty(changeProdType)) {
            return StepResult.getSuccessComplete();
        }

        MesWorkOrderExt workOrderExt = null;
        if (!StringUtils.isEmpty(selectWorkOrderNo)) {
            putPalletModuleService.doHandleSelectWorkOrderNo(reqBean, 3, null);

            workOrderExt = workOrderService.getWorkOrderExtByOrderNo(reqBean.getOrganizeCode(), selectWorkOrderNo);
            if (null == workOrderExt) {
                err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "工单[%s]不存在,选择工单失败"), selectWorkOrderNo);
                this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                if (StringUtils.isEmpty(curWorkOrderNo)) {
                    foundExThrowNoShowMsg();
                }
            } else {
                if (!workOrderExt.getWorkCenterCode().equals(reqBean.getWorkCenterCode())) {
                    err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "工单[%s]关联的生产线[%s]与当前生产线[%s]不一致,选择工单失败"),
                            selectWorkOrderNo, workOrderExt.getWorkCenterCode(), reqBean.getWorkCenterCode());
                    this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                    if (StringUtils.isEmpty(curWorkOrderNo)) {
                        foundExThrowNoShowMsg();
                    }
                } else {
                    if (MesPcnExtEnumUtil.WORK_ORDER_TYPE.ATTEMPT_ORDER.getValue() == workOrderExt.getWorkOrderType()) {
                        err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "试制工单[%s]不能装托,选择工单失败"),
                                selectWorkOrderNo);
                        this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                        if (StringUtils.isEmpty(curWorkOrderNo)) {
                            foundExThrowNoShowMsg();
                        }
                    } else {
                        if (MesPcnExtEnumUtil.WORK_ORDER_STATUS.OPEN.getValue() != workOrderExt.getWorkOrderStatus() &&
                                MesPcnExtEnumUtil.WORK_ORDER_STATUS.CLOSE.getValue() != workOrderExt.getWorkOrderStatus()) {
                            err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "工单[%s]状态为[%s],选择工单失败"),
                                    selectWorkOrderNo, MesPcnExtEnumUtil.WORK_ORDER_STATUS.valueOfDescription(workOrderExt.getWorkOrderStatus()));
                            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                            if (StringUtils.isEmpty(curWorkOrderNo)) {
                                foundExThrowNoShowMsg();
                            }
                        } else {
                            if (StringUtils.isEmpty(curWorkOrderNo)) {
                                putPalletModuleService.doHandleCurWorkOrderNo(reqBean, 2, selectWorkOrderNo);
                                putPalletModuleService.doHandleCurPartNo(reqBean, 2, workOrderExt.getPartNo());
                                putPalletModuleService.doHandleCurWorkOrderType(reqBean, 2, workOrderExt.getWorkOrderType());
                                curWorkOrderNo = selectWorkOrderNo;
                            } else {
                                if (StringUtils.isEmpty(curPartNo) || StringUtils.isEmpty(curWorkOrderType)) {
                                    MesWorkOrderExt workOrderExtOld = workOrderService.getWorkOrderExtByOrderNo(reqBean.getOrganizeCode(), curWorkOrderNo);
                                    if (null == workOrderExtOld) {
                                        err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "缓存的当前工单[%s]无效,需要人工检查"), curWorkOrderNo);
                                        this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                                        foundExThrowNoShowMsg();
                                    }
                                    if (StringUtils.isEmpty(curPartNo)) {
                                        putPalletModuleService.doHandleCurPartNo(reqBean, 2, workOrderExtOld.getPartNo());
                                        curPartNo = workOrderExtOld.getPartNo();
                                    }
                                    if (StringUtils.isEmpty(curWorkOrderType)) {
                                        putPalletModuleService.doHandleCurWorkOrderType(reqBean, 2, workOrderExtOld.getWorkOrderType());
                                    }
                                }

                                if (curPartNo.equals(workOrderExt.getPartNo())) {
                                    putPalletModuleService.doHandleCurWorkOrderNo(reqBean, 2, selectWorkOrderNo);
                                    putPalletModuleService.doHandleCurWorkOrderType(reqBean, 2, workOrderExt.getWorkOrderType());
                                    curWorkOrderNo = selectWorkOrderNo;
                                } else {
                                    //判断是否需要重新获取标准容量
                                    EpPutPalletPlcDataModel curCtNoModel = (EpPutPalletPlcDataModel) putPalletModuleService.doHandleCurCtNo(reqBean, 1, null);
                                    if (null == curCtNoModel || !curCtNoModel.getBoo()) {
                                        putPalletModuleService.doHandleCurWorkOrderNo(reqBean, 2, selectWorkOrderNo);
                                        putPalletModuleService.doHandleCurPartNo(reqBean, 2, workOrderExt.getPartNo());
                                        putPalletModuleService.doHandleCurWorkOrderType(reqBean, 2, workOrderExt.getWorkOrderType());
                                        curWorkOrderNo = selectWorkOrderNo;
                                    } else {
                                        List<SxPutPalletModuleModel> putPalletModuleModelList = (List<SxPutPalletModuleModel>) putPalletModuleService.doHandlePackageDataByCtNo(reqBean, curCtNoModel.getCtNo(), 1, null);
                                        if (CollectionUtils.isEmpty(putPalletModuleModelList)) {
                                            EpPutPalletPlcDataModel curExecPackageNoModel = (EpPutPalletPlcDataModel) putPalletModuleService.doHandleCacheCurExecPackageNo(reqBean, 1, null);
                                            if (null == curExecPackageNoModel) {
                                                putPalletModuleService.doHandleCurWorkOrderNo(reqBean, 2, selectWorkOrderNo);
                                                putPalletModuleService.doHandleCurPartNo(reqBean, 2, workOrderExt.getPartNo());
                                                putPalletModuleService.doHandleCurWorkOrderType(reqBean, 2, workOrderExt.getWorkOrderType());
                                                curWorkOrderNo = selectWorkOrderNo;

                                                putPalletModuleService.doHandleCurCtQty(reqBean, 3, null);

                                            } else {
                                                err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "当前存在业务未执行结束的包装条码[%s],选择新工单[%s]失败,请稍后重试"),
                                                        curExecPackageNoModel.getPackageNo(), selectWorkOrderNo);
                                                this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                                            }
                                        } else {
                                            err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "选择的新工单[%s]关联的物料编码[%s]与当前装托中的物料编码[%s]不一致,选择工单失败"),
                                                    selectWorkOrderNo, workOrderExt.getPartNo(), curPartNo);
                                            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

        }

        if (null == workOrderExt || !workOrderExt.getOrderNo().equals(curWorkOrderNo)) {
            workOrderExt = workOrderService.getWorkOrderExtByOrderNo(reqBean.getOrganizeCode(), curWorkOrderNo);
            if (null == workOrderExt) {
                err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "缓存的工单[%s]无效"), curWorkOrderNo);
                this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                foundExThrowNoShowMsg();
            }
        }

        List<MesPackageExt> packageExtList = packageExtService.getPackageListByLastWorkOrderNo(reqBean.getOrganizeCode(), curWorkOrderNo);
        if (CollectionUtils.isEmpty(packageExtList)) {
            err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "工单[%s]未关联包装条码,选择工单失败"), curWorkOrderNo);
            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            foundExThrowNoShowMsg();
        }

        if (!StringUtils.isEmpty(selectWorkOrderNo)) {
            err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "工单[%s]选择成功"), selectWorkOrderNo);
            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT);
        }

        //判断是否存在未下线的包装条码,不存在时校验是否切换工单
        if (MathOperation.compareTo(workOrderExt.getQty(), new Double(packageExtList.size())) == 0) {

            //从PLC读取到包装条码,即有条码正在被执行中,此处不能判断暂无未装托的包装条码
            EpPutPalletPlcDataModel curPacakgeNoModel = (EpPutPalletPlcDataModel) putPalletModuleService.doHandleCacheCurExecPackageNo(reqBean, 1, null);

            List<String> putPalletingList = new ArrayList<>();
            EpPutPalletPlcDataModel curCtNoModel = (EpPutPalletPlcDataModel) putPalletModuleService.doHandleCurCtNo(reqBean, 1, null);
            if (null != curCtNoModel && curCtNoModel.getBoo()) {
                List<SxPutPalletModuleModel> putPalletModuleModelList = (List<SxPutPalletModuleModel>) putPalletModuleService.doHandlePackageDataByCtNo(reqBean, curCtNoModel.getCtNo(), 1, null);
                putPalletingList = CollectionUtils.isEmpty(putPalletModuleModelList) ? null :
                        putPalletModuleModelList.stream().filter(o -> null != o).map(SxPutPalletModuleModel::getPackageNo).collect(Collectors.toList());
            }

            List<String> finalPutPalletingList = putPalletingList;
            if (MesPcnExtEnumUtil.WORK_ORDER_TYPE.REWORK_ORDER.getValue() != workOrderExt.getWorkOrderType()) {
                packageExtList = CollectionUtils.isEmpty(packageExtList) ? null :
                        packageExtList.stream().filter(o -> (null != o && StringUtils.isEmpty(o.getCtNo()))).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(putPalletingList)) {
                    packageExtList = CollectionUtils.isEmpty(packageExtList) ? null :
                            packageExtList.stream().filter(o -> (null != o && !finalPutPalletingList.contains(o.getPackageNo()))).collect(Collectors.toList());
                }

                if (CollectionUtils.isEmpty(packageExtList)) {
                    if (null == curPacakgeNoModel) {
                        err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "工单[%s]下暂无未装托的包装条码,请检查或切换工单"), curWorkOrderNo);
                        this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT);
                        foundExThrowNoShowMsg();
                    }
                }
            } else {
                List<ProduceSnRepairModel> produceSnRepairModelList = produceSnRepairDao.queryRepairSnCtNoWithPackageNoListByWorkOrderNo(reqBean.getOrganizeCode(), workOrderExt.getOrderNo());
                produceSnRepairModelList = CollectionUtils.isEmpty(produceSnRepairModelList) ? null :
                        produceSnRepairModelList.stream().filter(o -> (null != o && StringUtils.isEmpty(o.getCtNo()))).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(putPalletingList)) {
                    produceSnRepairModelList = CollectionUtils.isEmpty(produceSnRepairModelList) ? null :
                            produceSnRepairModelList.stream().filter(o -> (null != o && !finalPutPalletingList.contains(o.getPackageNo()))).collect(Collectors.toList());
                }

                if (CollectionUtils.isEmpty(produceSnRepairModelList)) {
                    if (null == curPacakgeNoModel) {
                        err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "工单[%s]下暂无未装托的包装条码,请检查或切换工单"), curWorkOrderNo);
                        this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT);
                        foundExThrowNoShowMsg();
                    }
                }
            }
        }

        return StepResult.getSuccessComplete();
    }

}
