package cn.estsh.i3plus.ext.mes.apiservice.serviceimpl.base;

import cn.estsh.i3plus.ext.mes.api.base.IWorkOrderExtService;
import cn.estsh.i3plus.ext.mes.api.busi.IWorkOrderLogExtService;
import cn.estsh.i3plus.ext.mes.api.busi.IWorkOrderStartService;
import cn.estsh.i3plus.ext.mes.icloud.sdk.IWmsErpHouseCheckCloud;
import cn.estsh.i3plus.ext.mes.pojo.bean.*;
import cn.estsh.i3plus.ext.mes.pojo.model.*;
import cn.estsh.i3plus.ext.mes.pojo.repository.*;
import cn.estsh.i3plus.ext.mes.pojo.util.ConvertBeanExt;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtConstWords;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtEnumUtil;
import cn.estsh.i3plus.mes.api.iservice.base.IConfigService;
import cn.estsh.i3plus.mes.api.iservice.busi.IDataAuthService;
import cn.estsh.i3plus.mes.api.iservice.busi.ISyncFuncService;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.exception.BaseImppException;
import cn.estsh.i3plus.platform.common.exception.ImppExceptionEnum;
import cn.estsh.i3plus.platform.common.tool.ConvertUtil;
import cn.estsh.i3plus.platform.common.tool.MathOperation;
import cn.estsh.i3plus.platform.common.tool.TimeTool;
import cn.estsh.i3plus.platform.common.util.MesConstWords;
import cn.estsh.i3plus.pojo.base.bean.BaseResultBean;
import cn.estsh.i3plus.pojo.base.bean.DdlPackBean;
import cn.estsh.i3plus.pojo.base.bean.ListPager;
import cn.estsh.i3plus.pojo.base.common.Pager;
import cn.estsh.i3plus.pojo.base.common.PagerHelper;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.enumutil.MesEnumUtil;
import cn.estsh.i3plus.pojo.base.tool.DdlPreparedPack;
import cn.estsh.i3plus.pojo.mes.bean.*;
import cn.estsh.i3plus.pojo.mes.model.GenSerialNoModel;
import cn.estsh.i3plus.pojo.mes.model.MesButtonFlagModel;
import cn.estsh.i3plus.pojo.mes.repository.MesProdBindRecordRepository;
import cn.estsh.i3plus.pojo.mes.repository.MesWorkCenterRepository;
import cn.estsh.i3plus.pojo.mes.sqlpack.MesHqlPack;
import cn.estsh.i3plus.pojo.platform.bean.SysRole;
import cn.estsh.impp.framework.boot.auth.AuthUtil;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import cn.estsh.impp.framework.boot.util.ImppRedis;
import cn.estsh.impp.framework.boot.util.SpringContextsUtil;
import cn.estsh.impp.framework.boot.util.ValidatorBean;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author yumingxing
 * @version 1.0
 * @date 2021/1/13 9:28
 **/
@Service
@Slf4j
public class WorkOrderExtService implements IWorkOrderExtService {

    @Autowired
    private MesWorkOrderExtRepository workOrderExtRepository;

    @Autowired
    private MesWorkOrderLogExtRepository workOrderLogRepository;

    @Autowired
    private MesPartExtRepository partExtRepository;

    @Autowired
    private MesWorkCenterExtRepository workCenterRepository;

    @Autowired
    private ISyncFuncService syncFuncService;

    @Autowired
    private IDataAuthService dataAuthService;

    @Autowired
    private MesWorkCenterRepository mesWorkCenterRDao;

    @Autowired
    private MesAffiliatedStartConfigRepository affiliatedStartConfigRepository;

    @Autowired
    private IWorkOrderLogExtService workOrderLogExtService;

    @Autowired
    private IWmsErpHouseCheckCloud wmsErpHouseCheckCloud;

    @Autowired
    private IConfigService configService;

    @Resource(name = MesExtConstWords.REDIS_MES)
    private ImppRedis redisMes;
    @Autowired
    private MesProdBindRecordRepository prodBindRecordRepository;

    /**
     * 生成生产工单
     *
     * @param workOrderDto 生产工单
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertManualGenerate(GenerateWorkOrderDto workOrderDto) {
        MesWorkOrderExt mesWorkOrderExt = new MesWorkOrderExt();
        Double qty = workOrderDto.getQty();
        Double planQty = workOrderDto.getPlanQty();
        if(planQty > qty){
            throw new BaseImppException("计划返工数量不能大于计划生产数量");
        }
        BeanUtils.copyProperties(workOrderDto,mesWorkOrderExt);
        String userName = AuthUtil.getSessionUser().getUserName();
        String organizeCode = AuthUtil.getOrganize().getOrganizeCode();
        mesWorkOrderExt.setOrderNo(getOrderNo(userName,organizeCode));
        mesWorkOrderExt.setWorkOrderSource(MesExtEnumUtil.WORK_ORDER_SOURCE.MANUALLY_GENERATE.getValue());
        insertNewWorkOrder(mesWorkOrderExt);
    }

    private void insertNewWorkOrder(MesWorkOrderExt mesWorkOrderExt) {
        String organizeCode = AuthUtil.getOrganize().getOrganizeCode();
        Integer workOrderType = mesWorkOrderExt.getWorkOrderType();
        //如果是返工工单 设置是否生成条码为不生成
        if (MesExtEnumUtil.WORK_ORDER_TYPE.REWORK_ORDER.getValue() == workOrderType) {
            mesWorkOrderExt.setSnCreateStatus(MesExtEnumUtil.WORK_ORDER_SN_CREATE_STATUS.NO_CREATE.getValue());
        } else {
            //不是返工工单
            MesPartExt mesPart = partExtRepository.getByProperty(
                    new String[]{"partNo", "organizeCode", "isValid", "isDeleted"},
                    new Object[]{mesWorkOrderExt.getPartNo(), organizeCode,
                            CommonEnumUtil.IS_VAILD.VAILD.getValue(),
                            CommonEnumUtil.IS_DEAL.NO.getValue()});
            //判断物料是否需要生成条码
            if (!ObjectUtils.isEmpty(mesPart)) {
                Integer isCreateSn = mesPart.getIsCreateSn();
                if (isCreateSn != null && CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue() == isCreateSn) {
                    mesWorkOrderExt.setSnCreateStatus(MesExtEnumUtil.WORK_ORDER_SN_CREATE_STATUS.UN_CREATE.getValue());
                } else {
                    mesWorkOrderExt.setSnCreateStatus(MesExtEnumUtil.WORK_ORDER_SN_CREATE_STATUS.NO_CREATE.getValue());
                }
            }
        }
        boolean havePart = isHavePart(mesWorkOrderExt.getPartNo(), organizeCode);
        if (!havePart) {
            throw new BaseImppException("物料号不存在");
        }
        mesWorkOrderExt.setWorkOrderStatus(MesExtEnumUtil.WORK_ORDER_STATUS.CREATE.getValue());

        mesWorkOrderExt.setOrganizeCode(organizeCode);

        mesWorkOrderExt.setSeq(MathOperation.add(getWorkOrderExtMaxSeq(organizeCode, 1), new Double(1)));

        ConvertBean.modelInitialize(mesWorkOrderExt, AuthUtil.getSessionUser());
        mesWorkOrderExt.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
        new ConvertBeanExt(mesWorkOrderExt).convertBean(mesWorkOrderExt);
        MesWorkOrderExt workOrderExt = workOrderExtRepository.insert(mesWorkOrderExt);
        insertMesWorkOrderLog(workOrderExt);
    }


    /**
     * 生产工单日志入库
     *
     * @param workOrderExt
     */
    public void insertMesWorkOrderLog(MesWorkOrderExt workOrderExt) {
        workOrderLogExtService.insertMesWorkOrderLogExt(workOrderExt);
    }



    private void updateWorkOrder(MesWorkOrderExt mesWorkOrderExt, boolean flag) {
        //在更新时导入的工单如果状态不是创建或暂停的工单，进行异常提醒。
        Integer workOrderStatus = mesWorkOrderExt.getWorkOrderStatus();
        boolean isCreate = MesExtEnumUtil.WORK_ORDER_STATUS.CREATE.getValue() == workOrderStatus;
        boolean isPause = MesExtEnumUtil.WORK_ORDER_STATUS.PAUSE.getValue() == workOrderStatus;
        //从SAP获取的订单如果状态不是创建或者暂停的工单，忽略更新。
        if (isCreate || isPause) {
            mesWorkOrderExt.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
            if(mesWorkOrderExt.getWorkOrderType() != MesExtEnumUtil.WORK_ORDER_TYPE.REWORK_ORDER.getValue()){
                MesPartExt mesPart = partExtRepository.getByProperty(
                        new String[]{MesExtConstWords.PART_NO, MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_VALID, MesExtConstWords.IS_DELETED},
                        new Object[]{mesWorkOrderExt.getPartNo(), mesWorkOrderExt.getOrganizeCode(),
                                CommonEnumUtil.IS_VAILD.VAILD.getValue(),
                                CommonEnumUtil.IS_DEAL.NO.getValue()});
                if(mesPart.getIsCreateSn() == CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue()){
                    mesWorkOrderExt.setSnCreateStatus(MesExtEnumUtil.WORK_ORDER_SN_CREATE_STATUS.UN_CREATE.getValue());
                }else{
                    mesWorkOrderExt.setSnCreateStatus(MesExtEnumUtil.WORK_ORDER_SN_CREATE_STATUS.NO_CREATE.getValue());
                }
            }
            new ConvertBeanExt(mesWorkOrderExt).convertBean(mesWorkOrderExt);
            MesWorkOrderExt workOrderExt = workOrderExtRepository.save(mesWorkOrderExt);
            insertMesWorkOrderLog(workOrderExt);
        } else {
            if (flag) {
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("工单【%s】不是创建或暂停的工单,不能被更新",
                                mesWorkOrderExt.getOrderNo())
                        .build();
            }

        }

    }

    private MesWorkOrderExt isHaveWorkOrder(String orderNo, String organizeCode) {
        MesWorkOrderExt mesWorkOrderExt = workOrderExtRepository.getByProperty(
                new String[]{MesConstWords.ORGANIZE_CODE, MesConstWords.IS_DELETED, MesConstWords.IS_VALID, "orderNo"},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue(), orderNo});
        if (null == mesWorkOrderExt) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("工单【%s】无效", orderNo)
                    .build();
        }
        return  mesWorkOrderExt;
    }

    /**
     * excel导入生成生产工单
     *
     * @param mesWorkOrderExtList mes工作单et列表
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importGenerate(List<ExcelWorkOrderDto> mesWorkOrderExtList) {


        MesWorkCenter mesWorkCenter = null;

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sf = new SimpleDateFormat("yyyy/MM/dd");
        SimpleDateFormat sf1 = new SimpleDateFormat("yyyy-MM-dd");
        MesPart mesPart;

        Integer i = 2;

        String organizeCode = AuthUtil.getOrganizeCode();
        if (CollectionUtils.isEmpty(mesWorkOrderExtList)) {
            return;
        }
        for (ExcelWorkOrderDto excelWorkOrderDto : mesWorkOrderExtList) {

            //判断数量是否为0
            if (excelWorkOrderDto.getQty() == null || excelWorkOrderDto.getQty() <= 0) {
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("第【%s】行的数量【%s】必须大于0", i,
                                excelWorkOrderDto.getQty())
                        .build();
            }

            //判断日期格式是否正确,正确则转换格式
            try {
                String startTime = excelWorkOrderDto.getStartTime();
                String endTime = excelWorkOrderDto.getEndTime();
                if (startTime.contains("/")) {
                    excelWorkOrderDto.setStartTime(sdf.format(sf.parse(startTime)));
                } else {
                    if (startTime.contains(",")) {
                        startTime = startTime.replace(",", "");
                    }
                    excelWorkOrderDto.setStartTime(sdf.format(org.apache.poi.ss.usermodel.DateUtil.getJavaDate(Double.parseDouble(startTime))));
                }

                if (endTime.contains("/")) {
                    excelWorkOrderDto.setEndTime(sdf.format(sf.parse(endTime)));
                } else {
                    if (endTime.contains(",")) {
                        endTime = endTime.replace(",", "");
                    }
                    excelWorkOrderDto.setEndTime(sdf.format(org.apache.poi.ss.usermodel.DateUtil.getJavaDate(Double.parseDouble(endTime))));
                }


            } catch (ParseException e) {
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("第【%s】行的时间格式不正确，应该为yyyy/MM/dd格式", i)
                        .build();
            }

            //根据零件号查询零件信息
            mesPart = partExtRepository.getByProperty(
                    new String[]{"partNo", "organizeCode", "isValid", "isDeleted"},
                    new Object[]{excelWorkOrderDto.getPartNo(), organizeCode,
                            CommonEnumUtil.IS_VAILD.VAILD.getValue(),
                            CommonEnumUtil.IS_DEAL.NO.getValue()});

            if (mesPart == null) {
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("第【%s】行的零件号【%s】在零件信息中不存在数据", i, excelWorkOrderDto.getPartNo())
                        .build();
            }

            //根据产线获取产线信息
            mesWorkCenter = workCenterRepository.getByProperty(
                    new String[]{"workVer", "organizeCode", "isValid", "isDeleted"},
                    new Object[]{excelWorkOrderDto.getWorkVer(), organizeCode,
                            CommonEnumUtil.IS_VAILD.VAILD.getValue(),
                            CommonEnumUtil.IS_DEAL.NO.getValue()});

            if (mesWorkCenter == null) {
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("第【%s】行的产线代码【%s】在产线信息中不存在数据", i, excelWorkOrderDto.getWorkVer())
                        .build();
            }

            MesWorkOrderExt mesWorkOrderExt = new MesWorkOrderExt();

            String orderNo = excelWorkOrderDto.getOrderNo();
            MesWorkOrderExt haveWorkOrder = isHaveWorkOrder(orderNo, organizeCode);



            if(haveWorkOrder !=null){
                BeanUtils.copyProperties(excelWorkOrderDto, haveWorkOrder);
                ConvertBean.modelInitialize(haveWorkOrder, AuthUtil.getSessionUser());
                updateWorkOrder(haveWorkOrder, false);
            } else {
                BeanUtils.copyProperties(excelWorkOrderDto, mesWorkOrderExt);
                mesWorkOrderExt.setWorkCenterCode(mesWorkCenter.getWorkCenterCode());
                mesWorkOrderExt.setAreaCode(mesWorkCenter.getAreaCode());
                mesWorkOrderExt.setWorkOrderSource(MesExtEnumUtil.WORK_ORDER_SOURCE.IMPORT_GENERATE.getValue());
                mesWorkOrderExt.setWorkOrderType(MesExtEnumUtil.WORK_ORDER_TYPE.STANDARD_ORDER.getValue());
                insertNewWorkOrder(mesWorkOrderExt);
            }

            i++;

        }
    }

    /**
     * sop同步接口生成生产工单 todo(同步接口还未开发)
     *
     * @param mesWorkOrderExtList mes工作单ext列表
     */
    @Override
    public void sopGenerate(List<MesWorkOrderExt> mesWorkOrderExtList) {

    }

    /**
     * 调整工作顺序
     *
     * @param generateWorkOrderDto 生成工作单dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void adjustWorkOrder(GenerateWorkOrderDto generateWorkOrderDto) {
        String orderNo = generateWorkOrderDto.getOrderNo();
        String organizeCode = AuthUtil.getOrganize().getOrganizeCode();
        MesWorkOrderExt mesWorkOrderExt = isHaveWorkOrder(orderNo, organizeCode);
        if(mesWorkOrderExt == null){
            throw new BaseImppException("工单不存在");
        }
        //计划返工数量不能大于计划生产数量
        Double qty = generateWorkOrderDto.getQty();
        Double planQty = generateWorkOrderDto.getPlanQty();
        if (planQty > qty) {
            throw new BaseImppException("计划返工数量不能大于计划生产数量");
        }


        //调整后的计划数量不能低于当前生产的数量
        Double completeQty = mesWorkOrderExt.getCompleteQty();
        if (qty < completeQty) {
            throw new BaseImppException("调整后的计划数量不能低于当前生产的数量");
        }
        mesWorkOrderExt.setAreaCode(generateWorkOrderDto.getAreaCode());
        mesWorkOrderExt.setWorkCenterCode(generateWorkOrderDto.getWorkCenterCode());
        mesWorkOrderExt.setWorkCenterName(generateWorkOrderDto.getWorkCenterName());
        mesWorkOrderExt.setQty(generateWorkOrderDto.getQty());
        mesWorkOrderExt.setPlanQty(generateWorkOrderDto.getPlanQty());
        mesWorkOrderExt.setWorkOrderType(generateWorkOrderDto.getWorkOrderType());
        mesWorkOrderExt.setMemo(generateWorkOrderDto.getMemo());
        mesWorkOrderExt.setStartTime(generateWorkOrderDto.getStartTime());
        mesWorkOrderExt.setEndTime(generateWorkOrderDto.getEndTime());
        mesWorkOrderExt.setErpWarehouse(generateWorkOrderDto.getErpWarehouse());

        ConvertBean.modelUpdate(mesWorkOrderExt, AuthUtil.getSessionUser());
        updateWorkOrder(mesWorkOrderExt, true);
    }

    /**
     * 工单新增/编辑-校验
     *
     * @param organizeCode 组织代码
     */
    private boolean isHavePart(String partNo, String organizeCode) {
        MesPart mesPart = partExtRepository.getByProperty(
                new String[]{MesConstWords.ORGANIZE_CODE, MesConstWords.IS_DELETED, MesConstWords.IS_VALID, "partNo"},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(),CommonEnumUtil.IS_VAILD.VAILD.getValue(), partNo});
        return null != mesPart;
    }


    private String getOrderNo(String userName, String organizeCode) {
        String orderNo = "";
        BaseResultBean oneCodeResult = syncFuncService.syncSerialNo(new GenSerialNoModel(MesExtEnumUtil.COMMON_SN.WC_NO.getCode()), userName, organizeCode, 1);
        if (oneCodeResult != null && oneCodeResult.isSuccess()) {
            orderNo = oneCodeResult.getResultList().get(0).toString();
        } else {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.CLOUD_CALL_EXCEPTION.getCode())
                    .setErrorDetail("生成唯一工单号失败")
                    .build();
        }
        return orderNo;
    }


    /**
     * 生产工单分页查询
     *
     * @param workOrderQueryDto 查询参数
     * @param pager             分页参数
     * @return {@link ListPager<MesWorkOrderExt>}
     */
    @Override
    public ListPager<WorkOrderPageVo> getListPageByCondition(WorkOrderQueryDto workOrderQueryDto, Pager pager) {
        String organizeCode = AuthUtil.getOrganize().getOrganizeCode();
        DdlPackBean ddlPackBean = DdlPackBean.getDdlPackBean(organizeCode);
        if (!ObjectUtils.isEmpty(workOrderQueryDto)) {
            DdlPreparedPack.getStringEqualPack(workOrderQueryDto.getWorkCenterCode(), MesExtConstWords.WORK_CENTER_CODE, ddlPackBean);
            DdlPreparedPack.getStringLikerPack(workOrderQueryDto.getOrderNo(), MesExtConstWords.ORDER_NO, ddlPackBean);
            DdlPreparedPack.getStringLikerPack(workOrderQueryDto.getPartNo(), MesExtConstWords.PART_NO, ddlPackBean);
            DdlPreparedPack.getStringLikerPack(workOrderQueryDto.getCreateUser(), "createUser", ddlPackBean);
            DdlPreparedPack.getStringLikerPack(workOrderQueryDto.getErpWarehouse(), MesExtConstWords.ERP_WARE_HOUSE, ddlPackBean);
            DdlPreparedPack.getNumEqualPack(workOrderQueryDto.getWorkOrderStatus(), MesExtConstWords.WORK_ORDER_STATUS, ddlPackBean);
            DdlPreparedPack.getNumEqualPack(workOrderQueryDto.getWorkOrderType(), "workOrderType", ddlPackBean);
            DdlPreparedPack.getIsNotNull(MesExtConstWords.WORK_CENTER_CODE, ddlPackBean);
            if (!StringUtils.isEmpty(workOrderQueryDto.getStartTimeStart()) || !StringUtils.isEmpty(workOrderQueryDto.getStartTimeEnd())) {
                DdlPreparedPack.timeBuilder(workOrderQueryDto.getStartTimeStart(), workOrderQueryDto.getStartTimeEnd(), MesExtConstWords.START_TIME, ddlPackBean, true);
            }
            if (!StringUtils.isEmpty(workOrderQueryDto.getEndTimeStart()) || !StringUtils.isEmpty(workOrderQueryDto.getEndTimeEnd())) {
                DdlPreparedPack.timeBuilder(workOrderQueryDto.getEndTimeStart(), workOrderQueryDto.getEndTimeEnd(), MesExtConstWords.END_TIME, ddlPackBean, true);
            }
            if (StringUtils.isEmpty(workOrderQueryDto.getOrderByParam())) {
                DdlPreparedPack.getOrderByPack(new Object[]{MesEnumUtil.ASC_OR_DESC.DESC.getValue()}, new String[]{MesExtConstWords.MODIFY_DATE_TIME}, ddlPackBean);
            } else {
                if (workOrderQueryDto.getOrderByParam().equals(MesExtConstWords.SEQ) ||
                        workOrderQueryDto.getOrderByParam().equals(MesExtConstWords.ORDER_NO) ) {
                    DdlPreparedPack.getOrderByPack(new Object[]{workOrderQueryDto.getAscOrDesc()}, new String[]{workOrderQueryDto.getOrderByParam()}, ddlPackBean);
                } else {
                    DdlPreparedPack.getOrderByPack(
                            new Object[]{workOrderQueryDto.getAscOrDesc(), MesEnumUtil.ASC_OR_DESC.ASC.getValue()},
                            new String[]{workOrderQueryDto.getOrderByParam(), MesExtConstWords.SEQ}, ddlPackBean);
                }
            }
        }

        pager = PagerHelper.getPager(pager, workOrderExtRepository.findByHqlWhereCount(ddlPackBean));

        List<MesWorkOrderExt> mesWorkOrderExtList = workOrderExtRepository.findByHqlWherePage(ddlPackBean, pager);
        List<WorkOrderPageVo> workOrderPageVos = JSON.parseObject(JSON.toJSONString(mesWorkOrderExtList), new TypeReference<List<WorkOrderPageVo>>() {
        });

        if (!CollectionUtils.isEmpty(workOrderPageVos)) {
            List<String> workCenterCodeList = workOrderPageVos.stream()
                    .filter(o -> (null != o && !StringUtils.isEmpty(o.getWorkCenterCode()))).map(WorkOrderPageVo::getWorkCenterCode).collect(Collectors.toList());
            Map<String, MesWorkCenterExt> workCenterCodeMap = null;
            if (!CollectionUtils.isEmpty(workCenterCodeList)) {
                DdlPackBean ddl = DdlPackBean.getDdlPackBean(organizeCode);
                DdlPreparedPack.getInPackList(workCenterCodeList, MesExtConstWords.WORK_CENTER_CODE, ddl);
                List<MesWorkCenterExt> workCenterList = workCenterRepository.findByHqlWhere(ddl);
                workCenterCodeMap = workCenterList.stream().filter(o -> null != o).collect(Collectors.toMap(MesWorkCenter::getWorkCenterCode, Function.identity(), (x,y) -> y));
            }

            for (WorkOrderPageVo workOrderPageVo : workOrderPageVos) {
                Integer workOrderStatus = workOrderPageVo.getWorkOrderStatus();
                String workOrderStatusName = MesExtEnumUtil.WORK_ORDER_STATUS.valueOfDescription(workOrderStatus);
                workOrderPageVo.setWorkOrderStatusName(workOrderStatusName);

                Integer workOrderType = workOrderPageVo.getWorkOrderType();
                String workOrderTypeName = MesExtEnumUtil.WORK_ORDER_TYPE.valueOfDescription(workOrderType);
                workOrderPageVo.setWorkOrderTypeName(workOrderTypeName);

                workOrderPageVo.setWorkOrderSourceName(MesExtEnumUtil.WORK_ORDER_SOURCE.valueOfDescription(workOrderPageVo.getWorkOrderSource()));

                if(!StringUtils.isEmpty(workOrderPageVo.getWorkCenterCode()) && !CollectionUtils.isEmpty(workCenterCodeMap)){

                    MesWorkCenterExt workCenterExt = workCenterCodeMap.get(workOrderPageVo.getWorkCenterCode());

                    workOrderPageVo.setWorkCenterName(workCenterExt.getWorkCenterName());

                    workOrderPageVo.setIsNoumenon(workCenterExt.getLineType().equals(String.valueOf(MesExtEnumUtil.LINE_TYPE.ONTOLOGY_LINE.getValue())) ? MesExtEnumUtil.YES_OR_NO.YES.getValue() : MesExtEnumUtil.YES_OR_NO.NO.getValue());

                }

                //mes生产工单页面按钮控制
                workOrderPageVo.setMesButtonFlagModel(this.getMesButtonFlagModel(workOrderPageVo));
            }

        }
        return  new ListPager(workOrderPageVos, pager);
    }


    /**
     * mes生产工单页面按钮控制
     *
     * @param workOrderPageVo
     * @return
     */
    private MesButtonFlagModel getMesButtonFlagModel(WorkOrderPageVo workOrderPageVo) {
        if (workOrderPageVo == null) {
            return null;
        }
        Double completeQty = StringUtils.isEmpty(workOrderPageVo.getCompleteQty()) ? 0 : workOrderPageVo.getCompleteQty();

        MesButtonFlagModel mesButtonFlagModel = new MesButtonFlagModel();
        Integer workOrderStatus = workOrderPageVo.getWorkOrderStatus();

        //编辑：创建状态
        if (MesExtEnumUtil.WORK_ORDER_STATUS.CREATE.getValue() == workOrderStatus) {
            mesButtonFlagModel.setUpdateButton(true);
            mesButtonFlagModel.setTransmitButton(true);
        }

        if (MesExtEnumUtil.WORK_ORDER_STATUS.LANDED.getValue() == workOrderStatus) {
            mesButtonFlagModel.setStartUpButton(true);
            mesButtonFlagModel.setSuspendButton(true);
        }
        if (MesExtEnumUtil.WORK_ORDER_STATUS.PAUSE.getValue() == workOrderStatus) {
            mesButtonFlagModel.setStartUpButton(true);
            mesButtonFlagModel.setCloseButton(true);
        }
        if (MesExtEnumUtil.WORK_ORDER_STATUS.OPEN.getValue() == workOrderStatus) {
            mesButtonFlagModel.setSuspendButton(true);
        }
        return mesButtonFlagModel;
    }

    /**
     * 停止工作订单
     *
     * @param orderNo 订单编号
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void stopWorkOrder(String orderNo) {
        String organizeCode = AuthUtil.getOrganize().getOrganizeCode();
        MesWorkOrderExt haveWorkOrder = isHaveWorkOrder(orderNo, organizeCode);
        if (ObjectUtils.isEmpty(haveWorkOrder)) {
            throw new BaseImppException("工单不存在");
        }
        Integer workOrderStatus = haveWorkOrder.getWorkOrderStatus();
        boolean isCreate = MesExtEnumUtil.WORK_ORDER_STATUS.CREATE.getValue() == workOrderStatus;
        boolean isLanded = MesExtEnumUtil.WORK_ORDER_STATUS.LANDED.getValue() == workOrderStatus;
        boolean isOpen = MesExtEnumUtil.WORK_ORDER_STATUS.OPEN.getValue() == workOrderStatus;
        if (isCreate || isLanded || isOpen) {
            ConvertBean.serviceModelUpdate(haveWorkOrder, AuthUtil.getSessionUser().getUserName());
            haveWorkOrder.setWorkOrderStatus(MesExtEnumUtil.WORK_ORDER_STATUS.PAUSE.getValue());
            haveWorkOrder.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
            new ConvertBeanExt(haveWorkOrder).convertBean(haveWorkOrder);
            MesWorkOrderExt mesWorkOrderExt = workOrderExtRepository.save(haveWorkOrder);
            insertMesWorkOrderLog(mesWorkOrderExt);
        } else {
            throw new BaseImppException("只有创建,下达,启动才可以暂停");
        }
    }

    /**
     * 启动工单
     *
     * @param orderNo 订单编号
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void startWorkOrder(String orderNo) {
        String organizeCode = AuthUtil.getOrganize().getOrganizeCode();
        MesWorkOrderExt haveWorkOrder = isHaveWorkOrder(orderNo, organizeCode);
        if (ObjectUtils.isEmpty(haveWorkOrder)) {
            throw new BaseImppException("工单不存在");
        }
        Integer workOrderStatus = haveWorkOrder.getWorkOrderStatus();
        boolean isLanded = MesExtEnumUtil.WORK_ORDER_STATUS.LANDED.getValue() == workOrderStatus;
        boolean isPause = MesExtEnumUtil.WORK_ORDER_STATUS.PAUSE.getValue() == workOrderStatus;

        if (isLanded) {
            haveWorkOrder.setWorkOrderStatus(MesExtEnumUtil.WORK_ORDER_STATUS.OPEN.getValue());
            ConvertBean.serviceModelUpdate(haveWorkOrder, AuthUtil.getSessionUser().getUserName());
            haveWorkOrder.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
            new ConvertBeanExt(haveWorkOrder).convertBean(haveWorkOrder);
            MesWorkOrderExt mesWorkOrderExt = workOrderExtRepository.save(haveWorkOrder);
            //生成点检单
            insertMesWorkOrderLog(mesWorkOrderExt);
        } else {
            if (isPause) {
                //更改未暂停前状态
                //获取暂停前的状态
                DdlPackBean ddlPackBean = new DdlPackBean();
                DdlPreparedPack.getStringEqualPack(orderNo,"orderNo",ddlPackBean);
                List<MesWorkOrderLogExt> mesWorkOrderLogs = workOrderLogRepository.findByHqlWhere(ddlPackBean);
                if (!CollectionUtils.isEmpty(mesWorkOrderLogs)) {
                    int size = mesWorkOrderLogs.size();
                    if(size>1){
                        MesWorkOrderLog mesWorkOrderLog = mesWorkOrderLogs.get(size - 1);
                        Integer workOrderStatus1 = mesWorkOrderLog.getWorkOrderStatus();
                        boolean isPause1 = MesExtEnumUtil.WORK_ORDER_STATUS.PAUSE.getValue() == workOrderStatus1;
                        if(isPause1){
                            MesWorkOrderLog mesWorkOrderLog2 = mesWorkOrderLogs.get(size - 2);
                            Integer workOrderStatus2 = mesWorkOrderLog2.getWorkOrderStatus();
                            haveWorkOrder.setWorkOrderStatus(workOrderStatus2);
                            ConvertBean.serviceModelUpdate(haveWorkOrder, AuthUtil.getSessionUser().getUserName());
                            haveWorkOrder.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
                            new ConvertBeanExt(haveWorkOrder).convertBean(haveWorkOrder);
                            workOrderExtRepository.save(haveWorkOrder);
                        }
                    }
                }

            }else{
                throw new BaseImppException("工单不满足启动条件,不能被启动");
            }
        }
    }

    /**
     * 关闭工单
     *
     * @param orderNo 订单编号
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void closeWorkOrder(String orderNo) {
        String organizeCode = AuthUtil.getOrganize().getOrganizeCode();
        MesWorkOrderExt haveWorkOrder = isHaveWorkOrder(orderNo, organizeCode);
        if(ObjectUtils.isEmpty(haveWorkOrder)){
            throw new BaseImppException("工单不存在");
        }
        Double qty = haveWorkOrder.getQty();
        Double completeQty = haveWorkOrder.getCompleteQty();
        if (qty.equals(completeQty)) {
            //更改为关闭状态
            haveWorkOrder.setWorkOrderStatus(MesExtEnumUtil.WORK_ORDER_STATUS.CLOSE.getValue());
            ConvertBean.serviceModelUpdate(haveWorkOrder, AuthUtil.getSessionUser().getUserName());
            haveWorkOrder.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
            new ConvertBeanExt(haveWorkOrder).convertBean(haveWorkOrder);
            MesWorkOrderExt mesWorkOrderExt = workOrderExtRepository.save(haveWorkOrder);
            insertMesWorkOrderLog(mesWorkOrderExt);
        }

        Integer workOrderStatus = haveWorkOrder.getWorkOrderStatus();
        boolean isPause = MesExtEnumUtil.WORK_ORDER_STATUS.PAUSE.getValue() == workOrderStatus;
        if(isPause) {
            //更改为关闭状态
            haveWorkOrder.setWorkOrderStatus(MesExtEnumUtil.WORK_ORDER_STATUS.CLOSE.getValue());
            ConvertBean.serviceModelUpdate(haveWorkOrder, AuthUtil.getSessionUser().getUserName());
            haveWorkOrder.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
            new ConvertBeanExt(haveWorkOrder).convertBean(haveWorkOrder);
            MesWorkOrderExt mesWorkOrderExt = workOrderExtRepository.save(haveWorkOrder);
            insertMesWorkOrderLog(mesWorkOrderExt);
        }else{
            throw new BaseImppException("不是暂停状态的不能手动关闭");
        }
    }

    /**
     * 发布工作指令
     *
     * @param orderNo 订单编号
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void releaseWorkOrder(String orderNo) {
        String organizeCode = AuthUtil.getOrganize().getOrganizeCode();
        MesWorkOrderExt haveWorkOrder = isHaveWorkOrder(orderNo, organizeCode);
        if(ObjectUtils.isEmpty(haveWorkOrder)){
            throw new BaseImppException("工单不存在");
        }
        Integer workOrderStatus = haveWorkOrder.getWorkOrderStatus();
        boolean isCreate = MesExtEnumUtil.WORK_ORDER_STATUS.CREATE.getValue() == workOrderStatus;

        if(isCreate) {
            haveWorkOrder.setWorkOrderStatus(MesExtEnumUtil.WORK_ORDER_STATUS.LANDED.getValue());
            ConvertBean.serviceModelUpdate(haveWorkOrder, AuthUtil.getSessionUser().getUserName());
            haveWorkOrder.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
            new ConvertBeanExt(haveWorkOrder).convertBean(haveWorkOrder);
            MesWorkOrderExt mesWorkOrderExt = workOrderExtRepository.save(haveWorkOrder);
            insertMesWorkOrderLog(mesWorkOrderExt);
        }else{
                throw new BaseImppException("工单不满足启动条件,不能被启动");
        }
    }

    @Override
    public void updateSeq(WorkOrderSeq workOrderSeq) {

        String organizeCode = AuthUtil.getOrganize().getOrganizeCode();

        String needUpdateOrderNo = workOrderSeq.getNeedUpdateOrderNo();
        MesWorkOrderExt workOrder3 = isHaveWorkOrder(needUpdateOrderNo, organizeCode);
        if (MesExtEnumUtil.WORK_ORDER_SN_CREATE_STATUS.UN_CREATE.getValue() == workOrder3.getSnCreateStatus()) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("工单[%s]未生成条码不允许调序", needUpdateOrderNo)
                    .build();
        }

        String insertBeforeOrderNo = workOrderSeq.getInsertBeforeOrderNo();
        MesWorkOrderExt workOrder1 = isHaveWorkOrder(insertBeforeOrderNo, organizeCode);

        String insertAfterOrderNo = workOrderSeq.getInsertAfterOrderNo();
        MesWorkOrderExt workOrder2 = isHaveWorkOrder(insertAfterOrderNo, organizeCode);


        Double workOrder1Seq = workOrder1.getSeq();
        Double workOrder2Seq = workOrder2.getSeq();

        BigDecimal newSeq = BigDecimal.valueOf(workOrder1Seq).add(BigDecimal.valueOf(workOrder2Seq)).divide(BigDecimal.valueOf(2));
        workOrder3.setSeq(newSeq.doubleValue());
        ConvertBean.serviceModelUpdate(workOrder3, AuthUtil.getSessionUser().getUserName());
        workOrder3.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
        new ConvertBeanExt(workOrder3).convertBean(workOrder3);
        workOrderExtRepository.save(workOrder3);
    }


    public Double getSeqMax(){
        List<MesWorkOrderExt> mesWorkOrderExtList = workOrderExtRepository.findAll();
        if (!CollectionUtils.isEmpty(mesWorkOrderExtList)) {
            Optional<MesWorkOrderExt> mesWorkOrderExt = mesWorkOrderExtList.stream().max(Comparator.comparing(MesWorkOrderExt::getSeq));
            if (mesWorkOrderExt.isPresent()) {
                Double seq = mesWorkOrderExt.get().getSeq();
                if(seq == null){
                    return 0.0d;
                }
                return mesWorkOrderExt.get().getSeq();
            }else{
                return 0.0d;
            }

        }
        return 0.0d;
    }


    /**
     * 生产工单状态批量调整
     *
     * @param workOrderStatus 状态
     * @param orderNoList     工单号
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public void updateWorkOrderStatus(Integer workOrderStatus, List<String> orderNoList) {
        String organizeCode = AuthUtil.getOrganize().getOrganizeCode();

        List<MesWorkOrderExt> mesWorkOrderList = new ArrayList<>();
        for (String orderNo : orderNoList) {
            //获取所有数据
            DdlPackBean packBean = MesHqlPack.getAllBaseData(organizeCode);
            DdlPreparedPack.getStringEqualPack(orderNo, "orderNo", packBean);
            MesWorkOrderExt workOrderExt = workOrderExtRepository.getByProperty(packBean);
            if(workOrderExt != null){
                mesWorkOrderList.add(workOrderExt);
            }
        }

        if (CollectionUtils.isEmpty(mesWorkOrderList)) {
            throw ImppExceptionBuilder.newInstance().setErrorCode(ImppExceptionEnum.BUSINESS_EXCEPTION_DATA_ERROR.getCode())
                    .setErrorDetail("数据不存在")
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorSolution("校验生产工单表数据")
                    .build();
        }

        Optional<MesWorkOrderExt> optional = mesWorkOrderList.stream().filter(o -> (null != o && StringUtils.isEmpty(o.getWorkCenterCode()))).findFirst();
        if (null != optional && optional.isPresent()) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("工单[%s]未关联生产线", optional.get().getOrderNo())
                    .build();
        }

        Map<Integer, List<MesWorkOrderExt>> listMap = mesWorkOrderList.stream().filter(Objects::nonNull)
                .collect(Collectors.groupingBy(MesWorkOrderExt::getWorkOrderStatus));
        if (CollectionUtils.isEmpty(listMap)) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                    .setErrorDetail("记录不存在")
                    .build();
        } else {
            if (listMap.size() > 1) {
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("只能批量%s状态一样的生产工单", MesExtEnumUtil.WORK_ORDER_STATUS.valueOfDescription(workOrderStatus))
                        .build();
            } else if (listMap.size() == 1 && MesExtEnumUtil.WORK_ORDER_STATUS.OPEN.getValue() == workOrderStatus) {
                Map<String, List<MesWorkOrderExt>> listMapWorkCenterCode = mesWorkOrderList.stream().filter(Objects::nonNull)
                        .collect(Collectors.groupingBy(MesWorkOrderExt::getWorkCenterCode));
                for (List<MesWorkOrderExt> list : listMapWorkCenterCode.values()) {
                    //相同产线下是否存在多个工单
                    Map<String, List<MesWorkOrder>> orderNoMap = list.stream().filter(Objects::nonNull)
                            .collect(Collectors.groupingBy(MesWorkOrder::getOrderNo));
                    if (!CollectionUtils.isEmpty(orderNoMap) && orderNoMap.size() > 1) {
                        throw ImppExceptionBuilder.newInstance().setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                                .setErrorDetail("同生产线下只能启动一条工单")
                                .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                                .build();
                    }
                }
            }
        }

        // 一个工单号下的多个工单
        for (MesWorkOrderExt mesWorkOrder : mesWorkOrderList) {
//            Double completeQty = StringUtils.isEmpty(mesWorkOrder.getCompleteQty()) ? 0 : mesWorkOrder.getCompleteQty();
            //启动
            if (MesExtEnumUtil.WORK_ORDER_STATUS.OPEN.getValue() == workOrderStatus) {
                boolean isLanded = MesExtEnumUtil.WORK_ORDER_STATUS.LANDED.getValue() == mesWorkOrder.getWorkOrderStatus();
                boolean isPause = MesExtEnumUtil.WORK_ORDER_STATUS.PAUSE.getValue() == mesWorkOrder.getWorkOrderStatus();
                if (isLanded) {
                    //调用启动工单附属启动的方法
                    //校验是否存在已经启动的工单
                    DdlPackBean pb1 = MesHqlPack.getMesAllData(organizeCode);
                    DdlPreparedPack.getStringEqualPack(mesWorkOrder.getWorkCenterCode(), "workCenterCode", pb1);
                    DdlPreparedPack.getNumEqualPack(MesExtEnumUtil.WORK_ORDER_STATUS.LANDED.getValue(), "workOrderStatus", pb1);
                    List<MesWorkOrderExt> mesWorkOrderList1 = workOrderExtRepository.findByHqlWhere(pb1);
                    if (!CollectionUtils.isEmpty(mesWorkOrderList1)) {
                        mesWorkOrderList1.sort(Comparator.comparing(MesWorkOrderExt::getSeq));
                        MesWorkOrderExt mesWorkOrderExt = mesWorkOrderList1.get(0);
                        if (!mesWorkOrder.getOrderNo().equals(mesWorkOrderExt.getOrderNo())) {
                            throw ImppExceptionBuilder.newInstance().setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                                    .setErrorDetail("工单号【%s】的工单不是产线下当前排序最前的，不能启动", mesWorkOrder.getOrderNo())
                                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                                    .setErrorSolution("校验生产工单表数据")
                                    .build();
                        }


                    }
                    DdlPackBean ddlPackBean = DdlPackBean.getDdlPackBean(organizeCode);
                    List<MesAffiliatedStartConfig> mesAffiliatedStartConfigs = affiliatedStartConfigRepository.findByHqlWhere(ddlPackBean);
                    for (MesAffiliatedStartConfig mesAffiliatedStartConfig : mesAffiliatedStartConfigs) {
                        try {
                            IWorkOrderStartService workOrderStartService = (IWorkOrderStartService) SpringContextsUtil.getBean(mesAffiliatedStartConfig.getAffiliatedStartClass());
                            workOrderStartService.execute(mesWorkOrder);
                        } catch (Exception e) {
                            log.error(e.getMessage());
                            StackTraceElement[] stackTrace = e.getStackTrace();
                            log.error(Arrays.toString(stackTrace));
                        }
                    }
                }else{
                    if(isPause){
                        //更改未暂停前状态
                        //获取暂停前的状态
                        DdlPackBean ddlPackBean = new DdlPackBean();
                        DdlPreparedPack.getStringEqualPack(mesWorkOrder.getOrderNo(),"orderNo",ddlPackBean);
                        DdlPreparedPack.getNumNOEqualPack(mesWorkOrder.getWorkOrderStatus(),"workOrderStatus",ddlPackBean);
                        List<MesWorkOrderLogExt> mesWorkOrderLogs = workOrderLogRepository.findByHqlWhere(ddlPackBean);
                        if (!CollectionUtils.isEmpty(mesWorkOrderLogs)) {
                            mesWorkOrderLogs.sort(Comparator.comparing(MesWorkOrderLog::getModifyDatetime).reversed());
                            MesWorkOrderLog mesWorkOrderLog2 = mesWorkOrderLogs.get(0);
                            Integer workOrderStatus2 = mesWorkOrderLog2.getWorkOrderStatus();
                            mesWorkOrder.setWorkOrderStatus(workOrderStatus2);

                            ConvertBean.serviceModelUpdate(mesWorkOrder, AuthUtil.getSessionUser().getUserName());
                            mesWorkOrder.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
                            new ConvertBeanExt(mesWorkOrder).convertBean(mesWorkOrder);
                            workOrderExtRepository.save(mesWorkOrder);
                            DdlPackBean ddlPackBean2 = DdlPackBean.getDdlPackBean(organizeCode);
                            List<MesAffiliatedStartConfig> mesAffiliatedStartConfigs = affiliatedStartConfigRepository.findByHqlWhere(ddlPackBean2);
                            if (workOrderStatus2 == MesExtEnumUtil.WORK_ORDER_STATUS.OPEN.getValue()) {
                                for (MesAffiliatedStartConfig mesAffiliatedStartConfig : mesAffiliatedStartConfigs) {
                                    try {
                                        IWorkOrderStartService workOrderStartService = (IWorkOrderStartService) SpringContextsUtil.getBean(mesAffiliatedStartConfig.getAffiliatedStartClass());
                                        workOrderStartService.execute(mesWorkOrder);
                                    } catch (Exception e) {
                                        log.error(e.getMessage());
                                    }
                                }
                            }
                            insertMesWorkOrderLog(mesWorkOrder);
                            continue;
                        }

                    }else{
                        throw ImppExceptionBuilder.newInstance().setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                                .setErrorDetail("工单号【%s】的工单状态不是下达或暂停状态，不能启动", mesWorkOrder.getOrderNo())
                                .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                                .setErrorSolution("校验生产工单表数据")
                                .build();
                    }
                }

//            } else if (MesExtEnumUtil.WORK_ORDER_STATUS.CANCEL.getValue() == workOrderStatus) {
//                //取消
//                //校验工单是否是创建/下达/启动（还未开始生产，即完成数=0的）状态
//                if (MesExtEnumUtil.WORK_ORDER_STATUS.CREATE.getValue() != mesWorkOrder.getWorkOrderStatus() &&
//                        MesExtEnumUtil.WORK_ORDER_STATUS.LANDED.getValue() != mesWorkOrder.getWorkOrderStatus() &&
//                        (MesExtEnumUtil.WORK_ORDER_STATUS.OPEN.getValue() != mesWorkOrder.getWorkOrderStatus() ||
//                                completeQty.compareTo((double) 0) > 0)) {
//                    throw ImppExceptionBuilder.newInstance().setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
//                            .setErrorDetail("工单号【%s】的工单状态不是创建或下达或启动且完成数为0的状态，不能取消", mesWorkOrder.getOrderNo())
//                            .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
//                            .setErrorSolution("校验生产工单表数据")
//                            .build();
//                }

                try {
                    if( TimeTool.getSecoundsBetweenTime(4, mesWorkOrder.getStartTime(), TimeTool.getNowTime(true)) == 1 &&
                            StringUtils.isEmpty(mesWorkOrder.getReusePlanDatetime())){
                        mesWorkOrder.setReusePlanDatetime(TimeTool.getNowTime(true));
                        mesWorkOrder.setReusePlanCompleteQty(BigDecimal.valueOf(mesWorkOrder.getQty()).subtract(BigDecimal.valueOf(mesWorkOrder.getCompleteQty())).doubleValue());
                    }
                } catch (ParseException e) {
                    log.info("启动工单时计算计划时间与工单启动时间失败");
                }


            } else if (MesExtEnumUtil.WORK_ORDER_STATUS.PAUSE.getValue() == workOrderStatus) {
                //暂停
                //校验工单是否是启动状态
                boolean isCreate = MesExtEnumUtil.WORK_ORDER_STATUS.CREATE.getValue() == mesWorkOrder.getWorkOrderStatus();
                boolean isLanded = MesExtEnumUtil.WORK_ORDER_STATUS.LANDED.getValue() == mesWorkOrder.getWorkOrderStatus();
                boolean isOpen = MesExtEnumUtil.WORK_ORDER_STATUS.OPEN.getValue() == mesWorkOrder.getWorkOrderStatus();
                if (!isCreate && !isLanded && !isOpen) {
                    throw ImppExceptionBuilder.newInstance().setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                            .setErrorDetail("工单号【%s】的工单状态不是启动,下达,创建状态，不能暂停", mesWorkOrder.getOrderNo())
                            .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                            .setErrorSolution("校验生产工单表数据")
                            .build();
                }
            } else if (MesExtEnumUtil.WORK_ORDER_STATUS.CLOSE.getValue() == workOrderStatus) {
                //关闭
                //校验工单是否是暂停状态
                /*if (MesExtEnumUtil.WORK_ORDER_STATUS.PAUSE.getValue() != mesWorkOrder.getWorkOrderStatus()) {
                    throw ImppExceptionBuilder.newInstance().setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                            .setErrorDetail("工单号【%s】的工单状态不是暂停状态，不能完成", mesWorkOrder.getOrderNo())
                            .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                            .setErrorSolution("校验生产工单表数据")
                            .build();
                }*/
            } else if (MesExtEnumUtil.WORK_ORDER_STATUS.LANDED.getValue() == workOrderStatus) {
                //下达 ： 校验WMS的存储区是否存在
                BaseResultBean baseResultBean =  wmsErpHouseCheckCloud.getWmsZone(mesWorkOrder.getErpWarehouse(), organizeCode);
                if (null == baseResultBean) {
                    throw ImppExceptionBuilder.newInstance()
                            .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                            .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                            .setErrorDetail("调用校验WMS存储区微服接口失败,BaseResultBean对象为NULL")
                            .build();
                }
                if (!baseResultBean.success) {
                    throw ImppExceptionBuilder.newInstance()
                            .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                            .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                            .setErrorDetail(baseResultBean.errorMsg)
                            .build();
                }
            }

            mesWorkOrder.setWorkOrderStatus(workOrderStatus);
            ConvertBean.serviceModelUpdate(mesWorkOrder, AuthUtil.getSessionUser().getUserName());

            mesWorkOrder.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
            new ConvertBeanExt(mesWorkOrder).convertBean(mesWorkOrder);
            MesWorkOrderExt mesWorkOrderDb = workOrderExtRepository.save(mesWorkOrder);

            //生产工单日志
            this.insertMesWorkOrderLog(mesWorkOrderDb);
        }

    }

    /**
     * 生产工单状态批量调整
     *
     * @param workOrderStatus 状态
     * @param orderNoList     工单号
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public void updateEpWorkOrderStatus(Integer workOrderStatus, List<String> orderNoList) {
        String organizeCode = AuthUtil.getOrganize().getOrganizeCode();

        //获取所有数据
        DdlPackBean packBean = MesHqlPack.getAllBaseData(organizeCode);
        DdlPreparedPack.getInPackList(orderNoList, MesExtConstWords.ORDER_NO, packBean);
        List<MesWorkOrderExt> mesWorkOrderList = workOrderExtRepository.findByHqlWhere(packBean);
        if (CollectionUtils.isEmpty(mesWorkOrderList)) {
            throw ImppExceptionBuilder.newInstance().setErrorCode(ImppExceptionEnum.BUSINESS_EXCEPTION_DATA_ERROR.getCode())
                    .setErrorDetail("数据不存在")
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorSolution("校验生产工单表数据")
                    .build();
        }

        Optional<MesWorkOrderExt> optional = mesWorkOrderList.stream().filter(o -> (null != o && StringUtils.isEmpty(o.getWorkCenterCode()))).findFirst();
        if (null != optional && optional.isPresent()) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("工单[%s]未关联生产线", optional.get().getOrderNo())
                    .build();
        }

        Map<Integer, List<MesWorkOrderExt>> listMap = mesWorkOrderList.stream().filter(Objects::nonNull)
                .collect(Collectors.groupingBy(MesWorkOrderExt::getWorkOrderStatus));
        if (CollectionUtils.isEmpty(listMap)) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                    .setErrorDetail("记录不存在")
                    .build();
        } else {
            if (listMap.size() > 1) {
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("只能批量%s状态一样的生产工单", MesExtEnumUtil.WORK_ORDER_STATUS.valueOfDescription(workOrderStatus))
                        .build();
            } else if (listMap.size() == 1 && MesExtEnumUtil.WORK_ORDER_STATUS.OPEN.getValue() == workOrderStatus) {
                Map<String, List<MesWorkOrderExt>> listMapWorkCenterCode = mesWorkOrderList.stream().filter(Objects::nonNull)
                        .collect(Collectors.groupingBy(MesWorkOrderExt::getWorkCenterCode));
                for (List<MesWorkOrderExt> list : listMapWorkCenterCode.values()) {
                    //相同产线下是否存在多个工单
                    Map<String, List<MesWorkOrder>> orderNoMap = list.stream().filter(Objects::nonNull)
                            .collect(Collectors.groupingBy(MesWorkOrder::getOrderNo));
                    if (!CollectionUtils.isEmpty(orderNoMap) && orderNoMap.size() > 1) {
                        throw ImppExceptionBuilder.newInstance().setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                                .setErrorDetail("同生产线下只能启动一条工单")
                                .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                                .build();
                    }
                }
            }
        }

        // 一个工单号下的多个工单
        for (MesWorkOrderExt mesWorkOrder : mesWorkOrderList) {

            updateEpWorkOrderCreateSn(mesWorkOrder);
//            Double completeQty = StringUtils.isEmpty(mesWorkOrder.getCompleteQty()) ? 0 : mesWorkOrder.getCompleteQty();
            //启动
            if (MesExtEnumUtil.WORK_ORDER_STATUS.OPEN.getValue() == workOrderStatus) {


                boolean isLanded = MesExtEnumUtil.WORK_ORDER_STATUS.LANDED.getValue() == mesWorkOrder.getWorkOrderStatus();
                boolean isPause = MesExtEnumUtil.WORK_ORDER_STATUS.PAUSE.getValue() == mesWorkOrder.getWorkOrderStatus();

                if (isLanded) {
                    //调用启动工单附属启动的方法
                    //校验是否存在已经启动的工单
                    DdlPackBean pb1 = MesHqlPack.getMesAllData(organizeCode);
                    DdlPreparedPack.getStringEqualPack(mesWorkOrder.getWorkCenterCode(), "workCenterCode", pb1);
                    DdlPreparedPack.getNumEqualPack(MesExtEnumUtil.WORK_ORDER_STATUS.LANDED.getValue(), "workOrderStatus", pb1);
                    List<MesWorkOrderExt> mesWorkOrderList1 = workOrderExtRepository.findByHqlWhere(pb1);
                    if (!CollectionUtils.isEmpty(mesWorkOrderList1)) {
                        mesWorkOrderList1.sort(Comparator.comparing(MesWorkOrderExt::getSeq));
                        MesWorkOrderExt mesWorkOrderExt = mesWorkOrderList1.get(0);
                        if (!mesWorkOrder.getOrderNo().equals(mesWorkOrderExt.getOrderNo())) {
                            throw ImppExceptionBuilder.newInstance().setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                                    .setErrorDetail("工单号【%s】的工单不是产线下当前排序最前的，不能启动", mesWorkOrder.getOrderNo())
                                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                                    .setErrorSolution("校验生产工单表数据")
                                    .build();
                        }


                    }
                    DdlPackBean ddlPackBean = DdlPackBean.getDdlPackBean(organizeCode);
                    List<MesAffiliatedStartConfig> mesAffiliatedStartConfigs = affiliatedStartConfigRepository.findByHqlWhere(ddlPackBean);
                    for (MesAffiliatedStartConfig mesAffiliatedStartConfig : mesAffiliatedStartConfigs) {
                        try {
                            IWorkOrderStartService workOrderStartService = (IWorkOrderStartService) SpringContextsUtil.getBean(mesAffiliatedStartConfig.getAffiliatedStartClass());
                            workOrderStartService.execute(mesWorkOrder);
                        } catch (Exception e) {
                            log.error(e.getMessage());
                            StackTraceElement[] stackTrace = e.getStackTrace();
                            log.error(Arrays.toString(stackTrace));
                        }
                    }
                }else{
                    if(isPause){
                        //更改未暂停前状态
                        //获取暂停前的状态
                        DdlPackBean ddlPackBean = new DdlPackBean();
                        DdlPreparedPack.getStringEqualPack(mesWorkOrder.getOrderNo(),MesExtConstWords.ORDER_NO,ddlPackBean);
                        DdlPreparedPack.getNumNOEqualPack(mesWorkOrder.getWorkOrderStatus(),MesExtConstWords.WORK_ORDER_STATUS,ddlPackBean);
                        List<MesWorkOrderLogExt> mesWorkOrderLogs = workOrderLogRepository.findByHqlWhere(ddlPackBean);
                        if (!CollectionUtils.isEmpty(mesWorkOrderLogs)) {
                            mesWorkOrderLogs.sort(Comparator.comparing(MesWorkOrderLog::getModifyDatetime).reversed());
                            MesWorkOrderLog mesWorkOrderLog2 = mesWorkOrderLogs.get(0);
                            Integer workOrderStatus2 = mesWorkOrderLog2.getWorkOrderStatus();
                            mesWorkOrder.setWorkOrderStatus(workOrderStatus2);

                            ConvertBean.serviceModelUpdate(mesWorkOrder, AuthUtil.getSessionUser().getUserName());
                            mesWorkOrder.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
                            new ConvertBeanExt(mesWorkOrder).convertBean(mesWorkOrder);
                            workOrderExtRepository.save(mesWorkOrder);
                            DdlPackBean ddlPackBean2 = DdlPackBean.getDdlPackBean(organizeCode);
                            List<MesAffiliatedStartConfig> mesAffiliatedStartConfigs = affiliatedStartConfigRepository.findByHqlWhere(ddlPackBean2);
                            if (workOrderStatus2 == MesExtEnumUtil.WORK_ORDER_STATUS.OPEN.getValue()) {
                                for (MesAffiliatedStartConfig mesAffiliatedStartConfig : mesAffiliatedStartConfigs) {
                                    try {
                                        IWorkOrderStartService workOrderStartService = (IWorkOrderStartService) SpringContextsUtil.getBean(mesAffiliatedStartConfig.getAffiliatedStartClass());
                                        workOrderStartService.execute(mesWorkOrder);
                                    } catch (Exception e) {
                                        log.error(e.getMessage());
                                    }
                                }
                            }
                            insertMesWorkOrderLog(mesWorkOrder);
                            continue;
                        }

                    }else{
                        throw ImppExceptionBuilder.newInstance().setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                                .setErrorDetail("工单号【%s】的工单状态不是下达或暂停状态，不能启动", mesWorkOrder.getOrderNo())
                                .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                                .setErrorSolution("校验生产工单表数据")
                                .build();
                    }
                }

//            } else if (MesExtEnumUtil.WORK_ORDER_STATUS.CANCEL.getValue() == workOrderStatus) {
//                //取消
//                //校验工单是否是创建/下达/启动（还未开始生产，即完成数=0的）状态
//                if (MesExtEnumUtil.WORK_ORDER_STATUS.CREATE.getValue() != mesWorkOrder.getWorkOrderStatus() &&
//                        MesExtEnumUtil.WORK_ORDER_STATUS.LANDED.getValue() != mesWorkOrder.getWorkOrderStatus() &&
//                        (MesExtEnumUtil.WORK_ORDER_STATUS.OPEN.getValue() != mesWorkOrder.getWorkOrderStatus() ||
//                                completeQty.compareTo((double) 0) > 0)) {
//                    throw ImppExceptionBuilder.newInstance().setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
//                            .setErrorDetail("工单号【%s】的工单状态不是创建或下达或启动且完成数为0的状态，不能取消", mesWorkOrder.getOrderNo())
//                            .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
//                            .setErrorSolution("校验生产工单表数据")
//                            .build();
//                }

                try {
                    if( TimeTool.getSecoundsBetweenTime(4, mesWorkOrder.getStartTime(), TimeTool.getNowTime(true)) == 1 &&
                            StringUtils.isEmpty(mesWorkOrder.getReusePlanDatetime())){
                        mesWorkOrder.setReusePlanDatetime(TimeTool.getNowTime(true));
                        mesWorkOrder.setReusePlanCompleteQty(BigDecimal.valueOf(mesWorkOrder.getQty()).subtract(BigDecimal.valueOf(mesWorkOrder.getCompleteQty())).doubleValue());
                    }
                } catch (ParseException e) {
                    log.info("启动工单时计算计划时间与工单启动时间失败");
                }


            } else if (MesExtEnumUtil.WORK_ORDER_STATUS.PAUSE.getValue() == workOrderStatus) {
                //暂停
                //校验工单是否是启动状态
                boolean isCreate = MesExtEnumUtil.WORK_ORDER_STATUS.CREATE.getValue() == mesWorkOrder.getWorkOrderStatus();
                boolean isLanded = MesExtEnumUtil.WORK_ORDER_STATUS.LANDED.getValue() == mesWorkOrder.getWorkOrderStatus();
                boolean isOpen = MesExtEnumUtil.WORK_ORDER_STATUS.OPEN.getValue() == mesWorkOrder.getWorkOrderStatus();
                if (!isCreate && !isLanded && !isOpen) {
                    throw ImppExceptionBuilder.newInstance().setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                            .setErrorDetail("工单号【%s】的工单状态不是启动,下达,创建状态，不能暂停", mesWorkOrder.getOrderNo())
                            .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                            .setErrorSolution("校验生产工单表数据")
                            .build();
                }
            } else if (MesExtEnumUtil.WORK_ORDER_STATUS.CLOSE.getValue() == workOrderStatus) {
                //关闭
                //校验工单是否是暂停状态
                /*if (MesExtEnumUtil.WORK_ORDER_STATUS.PAUSE.getValue() != mesWorkOrder.getWorkOrderStatus()) {
                    throw ImppExceptionBuilder.newInstance().setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                            .setErrorDetail("工单号【%s】的工单状态不是暂停状态，不能完成", mesWorkOrder.getOrderNo())
                            .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                            .setErrorSolution("校验生产工单表数据")
                            .build();
                }*/
            } else if (MesExtEnumUtil.WORK_ORDER_STATUS.CLOSE.getValue() == workOrderStatus) {
                //完成
                //校验工单是否是暂停状态
                /*if (MesExtEnumUtil.WORK_ORDER_STATUS.PAUSE.getValue() != mesWorkOrder.getWorkOrderStatus()) {
                    throw ImppExceptionBuilder.newInstance().setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                            .setErrorDetail("工单号【%s】的工单状态不是暂停状态，不能完成", mesWorkOrder.getOrderNo())
                            .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                            .setErrorSolution("校验生产工单表数据")
                            .build();
                }*/
            } else if (MesExtEnumUtil.WORK_ORDER_STATUS.REMOVE.getValue() == workOrderStatus) {
                //删除
                //校验工单是否是暂停状态
                /*if (MesExtEnumUtil.WORK_ORDER_STATUS.PAUSE.getValue() != mesWorkOrder.getWorkOrderStatus()) {
                 *//*if (MesExtEnumUtil.WORK_ORDER_STATUS.CREATE.getValue() != mesWorkOrder.getWorkOrderStatus()){
                        throw ImppExceptionBuilder.newInstance().setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                                .setErrorDetail("工单号【%s】的工单状态不是暂停或启动状态，不能删除", mesWorkOrder.getOrderNo())
                                .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                                .setErrorSolution("校验生产工单表数据")
                                .build();
                    }*//*
                }*/
                if (mesWorkOrder.getCompleteQty() > 0){
                    throw ImppExceptionBuilder.newInstance().setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                            .setErrorDetail("工单号【%s】的完成数量大于0，不能删除", mesWorkOrder.getOrderNo())
                            .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                            .setErrorSolution("校验生产工单表数据")
                            .build();
                }else if(mesWorkOrder.getCompleteQty() == 0){
                    // 要自动解绑已绑定的关键件 看一下是什么
                    DdlPackBean packBeanBind = DdlPackBean.getDdlPackBean(organizeCode);
                    DdlPreparedPack.getStringEqualPack(mesWorkOrder.getOrderNo(),MesExtConstWords.WORK_ORDER_NO,packBeanBind);
                    List<MesProdBindRecord> prodBindRecordList = prodBindRecordRepository.findByHqlWhere(packBeanBind);
                    prodBindRecordList.forEach(p -> {
                        p.setActionType(MesEnumUtil.MES_ACTION_TYPE.UNTYING.getValue());
                        prodBindRecordRepository.update(p);
                    });
                }
            } else if (MesExtEnumUtil.WORK_ORDER_STATUS.LANDED.getValue() == workOrderStatus) {
                //下达 ： 校验WMS的存储区是否存在
                BaseResultBean baseResultBean =  wmsErpHouseCheckCloud.getWmsZone(mesWorkOrder.getErpWarehouse(), organizeCode);
                if (null == baseResultBean) {
                    throw ImppExceptionBuilder.newInstance()
                            .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                            .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                            .setErrorDetail("调用校验WMS存储区微服接口失败,BaseResultBean对象为NULL")
                            .build();
                }
                if (!baseResultBean.success) {
                    throw ImppExceptionBuilder.newInstance()
                            .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                            .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                            .setErrorDetail(baseResultBean.errorMsg)
                            .build();
                }
            }
            mesWorkOrder.setWorkOrderStatus(workOrderStatus);
            ConvertBean.serviceModelUpdate(mesWorkOrder, AuthUtil.getSessionUser().getUserName());

            mesWorkOrder.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
            new ConvertBeanExt(mesWorkOrder).convertBean(mesWorkOrder);
            MesWorkOrderExt mesWorkOrderDb = workOrderExtRepository.save(mesWorkOrder);

            //生产工单日志
            this.insertMesWorkOrderLog(mesWorkOrderDb);
        }

    }

    //根据物料信息 更新ep工单状态为不创建条码
    private void updateEpWorkOrderCreateSn(MesWorkOrderExt mesWorkOrderExt){

        if(mesWorkOrderExt.getSnCreateStatus() != MesExtEnumUtil.WORK_ORDER_SN_CREATE_STATUS.CREATED.getValue() ) {
            MesPartExt mesPart = partExtRepository.getByProperty(
                    new String[]{MesExtConstWords.PART_NO, MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_VALID, MesExtConstWords.IS_DELETED},
                    new Object[]{mesWorkOrderExt.getPartNo(), mesWorkOrderExt.getOrganizeCode(),
                            CommonEnumUtil.IS_VAILD.VAILD.getValue(),
                            CommonEnumUtil.IS_DEAL.NO.getValue()});
            if (null!= mesPart.getIsCreateSn() && CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue() == mesPart.getIsCreateSn()) {
                mesWorkOrderExt.setSnCreateStatus(MesExtEnumUtil.WORK_ORDER_SN_CREATE_STATUS.UN_CREATE.getValue());
            } else {
                mesWorkOrderExt.setSnCreateStatus(MesExtEnumUtil.WORK_ORDER_SN_CREATE_STATUS.NO_CREATE.getValue());
            }
        }
    }
    @Override
    public GenerateWorkOrderDto getMesWorkOrderDetail(String orderNo) {
        String organizeCode = AuthUtil.getOrganize().getOrganizeCode();
        MesWorkOrderExt haveWorkOrder = isHaveWorkOrder(orderNo, organizeCode);
        if(haveWorkOrder != null){
            GenerateWorkOrderDto generateWorkOrderDto = new GenerateWorkOrderDto();
            BeanUtils.copyProperties(haveWorkOrder,generateWorkOrderDto);
            MesWorkCenter mesWorkCenter = workCenterRepository.getByProperty(
                    new String[]{"workCenterCode", "organizeCode", "isValid", "isDeleted"},
                    new Object[]{haveWorkOrder.getWorkCenterCode(), organizeCode,
                            CommonEnumUtil.IS_VAILD.VAILD.getValue(),
                            CommonEnumUtil.IS_DEAL.NO.getValue()});
            if(!ObjectUtils.isEmpty(mesWorkCenter)){
                generateWorkOrderDto.setWorkCenterName(mesWorkCenter.getWorkCenterName());
            }
            return generateWorkOrderDto;
        }
        return null;
    }

    @Override
    public List<MesWorkOrderExt> findMesWorkOrderBySeqAsc(MesWorkOrder mesWorkOrder) {
        List<MesWorkOrderExt> workOrderList = null;
        DdlPackBean packBean = new DdlPackBean();
        String partNoList = null;
        String partNameList = null;
        DdlPreparedPack.getStringEqualPack(mesWorkOrder.getWorkCenterCode(), "workCenterCode", packBean);
        DdlPreparedPack.getStringEqualPack(mesWorkOrder.getOrganizeCode(), "organizeCode", packBean);
        DdlPreparedPack.getNumEqualPack(MesExtEnumUtil.WORK_ORDER_STATUS.LANDED.getValue(), "workOrderStatus", packBean);
        DdlPreparedPack.getNumEqualPack(CommonEnumUtil.VALID, "isValid", packBean);
        DdlPreparedPack.getNumEqualPack(CommonEnumUtil.FALSE, "isDeleted", packBean);
        List<SysRole> roles = AuthUtil.getSessionUser().getUser().getRoleList();
        for (SysRole role : roles) {
            dataAuthService.getDataAuth(role.getId(), MesWorkOrder.class.getSimpleName(), AuthUtil.getOrganize().getOrganizeCode(), packBean);
        }
        packBean.setWhereAppend(packBean.getWhereAppend() + " group by orderNo order by model.seq asc");
        List<MesWorkOrderExt> mesWorkOrderList = workOrderExtRepository.findByHqlWhere(packBean);

        if (!CollectionUtils.isEmpty(mesWorkOrderList)) {
            for (MesWorkOrderExt workOrder : mesWorkOrderList) {
                partNoList = "";
                partNameList = "";
                //根据工单号查询工单信息集合
                workOrderList = workOrderExtRepository.findByProperty(
                        new String[]{"orderNo", "organizeCode", "isValid", "isDeleted"},
                        new Object[]{workOrder.getOrderNo(), workOrder.getOrganizeCode(),
                                CommonEnumUtil.IS_VAILD.VAILD.getValue(),
                                CommonEnumUtil.IS_DEAL.NO.getValue()});

                int i = 1;
                for (MesWorkOrder workOrder1 : workOrderList) {
                    if (workOrderList.size() == i) {
                        partNoList = partNoList + workOrder1.getPartNo();
                        partNameList = partNameList + workOrder1.getPartNameRdd();
                    } else {
                        partNoList = partNoList + workOrder1.getPartNo() + ",";
                        partNameList = partNameList + workOrder1.getPartNameRdd() + ",";
                    }
                    i++;
                }
                workOrder.setPartNoList(partNoList);
                workOrder.setPartNameList(partNameList);
            }
        }

        return mesWorkOrderList;
    }


    @Override
    public void updateSortByMesWorkOrder(List<MesWorkOrderExt> mesWorkOrderList) {
        List<MesWorkOrderExt> workOrderList = null;
        List<Integer> srcSeqList = new ArrayList<>();
        MesWorkCenter mesWorkCenter = null;
        MesWorkOrder mesWorkOrder = null;
        MesPartTakt mesPartTakt = null;
        MesWorkOrderExt workOrder1 = null;

        MesConfig config = configService.getConfigByCfgCode(MesExtConstWords.CHANGE_ORDER_SEQ_UN_CHECK_SN_CREATE_STATUS, mesWorkOrderList.get(0).getOrganizeCode());

        //根据产线分组数据
        Map<String, List<MesWorkOrderExt>> mesWorkOrderListMap = ConvertUtil.transListToMapGroupByCol(
                new String[]{"workCenterCode"}, mesWorkOrderList, false, null);
        for (Map.Entry<String, List<MesWorkOrderExt>> mesWorkOrderGroupList : mesWorkOrderListMap.entrySet()) {
            //各个产线的工单集合信息
            workOrderList = mesWorkOrderGroupList.getValue();
            //根据产线查询产线信息
            mesWorkCenter = mesWorkCenterRDao.getByProperty(
                    new String[]{"workCenterCode", "organizeCode", "isValid", "isDeleted"},
                    new Object[]{workOrderList.get(0).getWorkCenterCode(), workOrderList.get(0).getOrganizeCode(),
                            CommonEnumUtil.IS_VAILD.VAILD.getValue(),
                            CommonEnumUtil.IS_DEAL.NO.getValue()});

            if (mesWorkCenter == null) {
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("产线代码【%s】在产线信息中不存在数据", workOrderList.get(0).getWorkCenterCode())
                        .build();
            }

            //循环获取各个产线原序号的最小序号
            for (MesWorkOrder workOrder : workOrderList) {
                srcSeqList.add(workOrder.getSrcSeq().intValue());
            }

            Integer srcSeq = Collections.min(srcSeqList);

            mesWorkOrder = workOrderExtRepository.getByProperty(
                    new String[]{"areaCode", "workCenterCode", "seq", "organizeCode", "isValid", "isDeleted"},
                    new Object[]{mesWorkCenter.getAreaCode(), mesWorkCenter.getWorkCenterCode(), Double.valueOf(String.valueOf(srcSeq)),
                            workOrderList.get(0).getOrganizeCode(),
                            CommonEnumUtil.IS_VAILD.VAILD.getValue(),
                            CommonEnumUtil.IS_DEAL.NO.getValue()});

            if (mesWorkOrder == null) {
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("根据序号为【%s】、产线代码【%s】和区域代码【%s】找不到对应的生产工单信息",
                                srcSeq, mesWorkCenter.getWorkCenterCode(), mesWorkCenter.getAreaCode())
                        .build();
            }

            String planStartTime = mesWorkOrder.getStartTime();
            String planEndTime = null;
            //循环计算时间
            for (MesWorkOrderExt workOrder : workOrderList) {
                if (null == config) {
                    if (MesExtEnumUtil.WORK_ORDER_SN_CREATE_STATUS.UN_CREATE.getValue() == workOrder.getSnCreateStatus()) {
                        throw ImppExceptionBuilder.newInstance()
                                .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                                .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                                .setErrorDetail("工单[%s]未生成条码不允许调序", workOrder.getOrderNo())
                                .build();
                    }
                }

                ConvertBean.serviceModelUpdate(workOrder, AuthUtil.getSessionUser().getUserName());

                workOrder.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
                new ConvertBeanExt(workOrder).convertBean(workOrder);
                workOrderExtRepository.save(workOrder);

                DdlPackBean packBean = new DdlPackBean();

                DdlPreparedPack.getStringNoEqualPack(workOrder.getPartNo(), "partNo", packBean);
                DdlPreparedPack.getStringEqualPack(workOrder.getOrderNo(), "orderNo", packBean);
                DdlPreparedPack.getStringEqualPack(workOrder.getOrganizeCode(), "organizeCode", packBean);
                DdlPreparedPack.getNumEqualPack(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue(), "isValid", packBean);
                DdlPreparedPack.getNumEqualPack(CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), "isDeleted", packBean);

                workOrder1 = workOrderExtRepository.getByProperty(packBean);
                if (workOrder1 != null) {
                    workOrder1.setStartTime(planStartTime);
                    workOrder1.setEndTime(planEndTime);
                    workOrder1.setSeq(workOrder.getSeq());

                    ConvertBean.serviceModelUpdate(workOrder1, AuthUtil.getSessionUser().getUserName());
                    workOrder1.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
                    new ConvertBeanExt(workOrder1).convertBean(workOrder1);
                    workOrderExtRepository.save(workOrder1);
                }

                planStartTime = planEndTime;
            }
        }
    }


    private String getPlanEndTime(String planStartTime, Integer seconds, Integer qty, Integer i) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        seconds = seconds * qty;
        Date afterDate = null;
        try {
            afterDate = new Date(sdf.parse(planStartTime).getTime() + seconds * 1000);
        } catch (ParseException e) {
            if (i == 0) {
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("日期解析失败，请检查参数")
                        .build();
            } else {
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("第【%s】行的日期解析失败，请检查参数", i)
                        .build();
            }

        }
        return sdf.format(afterDate);
    }

    @Override
    public synchronized Double getWorkOrderExtMaxSeq(String organizeCode, Integer count) {
        String key = new StringJoiner(MesExtConstWords.COLON).add(organizeCode).add(MesExtConstWords.WORK_ORDER_MAX_SEQ).toString();
        count = StringUtils.isEmpty(count) ? 1 : count;

        Double maxSeq = (Double) redisMes.getObject(key);
        maxSeq = StringUtils.isEmpty(maxSeq) ? new Double(0) : maxSeq;

        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getOrderByPack(new Object[]{CommonEnumUtil.ASC_OR_DESC.DESC.getValue()}, new String[]{MesExtConstWords.SEQ}, packBean);
        MesWorkOrderExt workOrderExt = workOrderExtRepository.getByProperty(packBean);
        if (null != workOrderExt) {
            if (MathOperation.compareTo(maxSeq, workOrderExt.getSeq()) < 0) {
                maxSeq = workOrderExt.getSeq();
            }
        }

        redisMes.putObject(key, MathOperation.add(maxSeq, new Double(count)), MesEnumUtil.EXPIRE_TIME.NEVER.getValue());
        return maxSeq;
    }

    @Override
    public SxWmsToMesWorkOrderModel doHandleWmsWorkOrder(SxWmsToMesWorkOrderModel model) throws Exception {

        String s = JSONObject.toJSONString(model);

        log.info("调试的日志: "+s);

        List<SxWmsToMesWorkOrderModel> workOrderList = model.getWorkOrderList();

        for (SxWmsToMesWorkOrderModel sxWmsToMesWorkOrderModel : workOrderList) {
            log.info("SAP下发单号：{}-SAP下发物料号：{}-SAP下发物料名称：{}-SAP_SEQ：{}",
                    sxWmsToMesWorkOrderModel.getOrderNo(),sxWmsToMesWorkOrderModel.getPartNo(),sxWmsToMesWorkOrderModel.getPartNameRdd(), sxWmsToMesWorkOrderModel.getSapSeq());
        }

        //与wms约定，物料名为空的数据无效
        workOrderList = CollectionUtils.isEmpty(workOrderList) ? null : workOrderList.stream().filter(w -> !StringUtils.isEmpty(w.getPartNameRdd())).collect(Collectors.toList());

        workOrderList = CollectionUtils.isEmpty(workOrderList) ? null :
                workOrderList.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getOrderNo()))).collect(
                        Collectors.collectingAndThen(
                                Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(SxWmsToMesWorkOrderModel::getOrderNo))), ArrayList::new)
                );
        if (CollectionUtils.isEmpty(workOrderList)) {
            model.setResult(false);
            return model;
        }

        workOrderList = workOrderList.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getSapSeq())))
                .sorted(Comparator.comparing(SxWmsToMesWorkOrderModel::getSapSeq)).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(workOrderList)) {
            ValidatorBean.beginValid(workOrderList.get(0))
                    .notNull(MesExtConstWords.SAP_SEQ, workOrderList.get(0).getSapSeq());
            model.setResult(false);
            return model;
        }

        List<MesWorkCenter> workCenterList = mesWorkCenterRDao.findByProperty(
                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED, MesExtConstWords.IS_VALID},
                new Object[]{model.getOrganizeCode(), CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue()});
        Map<String, List<MesWorkCenter>> workVerMap = CollectionUtils.isEmpty(workCenterList) ? null :
                workCenterList.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getWorkVer()))).collect(Collectors.groupingBy(MesWorkCenter::getWorkVer));

        List<String> partNoList = (workOrderList.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getPartNo())))
                .map(SxWmsToMesWorkOrderModel::getPartNo).collect(Collectors.toList()))
                .stream().distinct().collect(Collectors.toList());
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(model.getOrganizeCode());
        DdlPreparedPack.getInPackList(partNoList, MesExtConstWords.PART_NO, packBean);
        List<MesPartExt> partExtList = partExtRepository.findByHqlWhere(packBean);
        Map<String, List<MesPartExt>> partNoMap = CollectionUtils.isEmpty(partExtList) ? null :
                partExtList.stream().filter(o -> null != o).collect(Collectors.groupingBy(MesPartExt::getPartNo));

        List<MesWorkOrderExt> newWorkOrderList = new ArrayList<>();
        List<SxWmsToMesWorkOrderModel> newWmsWorkOrderList = new ArrayList<>();
        for (SxWmsToMesWorkOrderModel workOrderModel : workOrderList) {
            log.info("工单信息：{} --- orderNo:{} --- erpWarehouse:{}", workOrderModel, workOrderModel.getOrderNo(), workOrderModel.getErpWarehouse());
            if (null == workOrderModel) {
                continue;
            }
            ValidatorBean.beginValid(workOrderModel)
                    .notNull(MesExtConstWords.PART_NO, workOrderModel.getPartNo())
                    //.notNull(MesExtConstWords.PART_NAME_RDD, workOrderModel.getPartNameRdd())
                    .notNull(MesExtConstWords.QTY, workOrderModel.getQty())
                    .notNull(MesExtConstWords.START_TIME, workOrderModel.getStartTime())
                    .notNull(MesExtConstWords.END_TIME, workOrderModel.getEndTime())
                    .notNull(MesExtConstWords.ERP_WARE_HOUSE, workOrderModel.getErpWarehouse())
                    .notNull(MesExtConstWords.ORDER_STATUS, workOrderModel.getOrderStatus())
                    .notNull(MesExtConstWords.SAP_SEQ, workOrderModel.getSapSeq())
                    .notNull(MesExtConstWords.WORK_VER, workOrderModel.getWorkVer());

            MesWorkOrderExt workOrderExt = workOrderExtRepository.getByProperty(
                    new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED, MesExtConstWords.IS_VALID, MesExtConstWords.ORDER_NO},
                    new Object[]{model.getOrganizeCode(), CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue(), workOrderModel.getOrderNo()});
            if (null == workOrderExt) {
                if (MesExtEnumUtil.SAP_WORK_ORDER_STATUS.CREATE.getValue() == workOrderModel.getOrderStatus()) {
                    MesWorkOrderExt woe = new MesWorkOrderExt();
                    BeanUtils.copyProperties(workOrderModel, woe, MesExtConstWords.ID);
                    woe.setCompleteQty(new Double(0));
                    woe.setRepairQty(new Double(0));
                    woe.setScrapQty(new Double(0));
                    woe.setWorkOrderStatus(MesExtEnumUtil.WORK_ORDER_STATUS.CREATE.getValue());
                    woe.setWorkOrderType(MesExtEnumUtil.WORK_ORDER_TYPE.STANDARD_ORDER.getValue());
                    if (!CollectionUtils.isEmpty(workVerMap) && workVerMap.containsKey(workOrderModel.getWorkVer())) {
                        MesWorkCenter workCenter = workVerMap.get(workOrderModel.getWorkVer()).get(0);
                        if (null != workCenter) {
                            woe.setWorkCenterCode(workCenter.getWorkCenterCode());
                            woe.setAreaCode(workCenter.getAreaCode());
                        }
                    }
                    woe.setWorkOrderSource(MesExtEnumUtil.WORK_ORDER_SOURCE.SAP_GENERATE.getValue());
                    woe.setPrintStatus(MesEnumUtil.WORK_ORDER_PRINT_STATUS.UNPRINTED.getValue());
                    woe.setPlanQty(new Double(0));
                    woe.setPlanCompleteQty(new Double(0));
                    woe.setMissingQty(new Double(0));
                    woe.setSnCreateStatus(MesExtEnumUtil.WORK_ORDER_SN_CREATE_STATUS.UN_CREATE.getValue());
                    if (!CollectionUtils.isEmpty(partNoMap) && partNoMap.containsKey(workOrderModel.getPartNo())) {
                        MesPartExt partExt = partNoMap.get(workOrderModel.getPartNo()).get(0);
                        if (!StringUtils.isEmpty(partExt.getIsCreateSn()) && CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue() == partExt.getIsCreateSn()) {
                            woe.setSnCreateStatus(MesExtEnumUtil.WORK_ORDER_SN_CREATE_STATUS.NO_CREATE.getValue());
                        }
                    }
                    woe.setOrganizeCode(model.getOrganizeCode());
                    ConvertBean.serviceModelInitialize(woe, MesExtConstWords.SAP);
                    if (workOrderModel.getOrderStatus().equals(MesExtEnumUtil.SAP_WORK_ORDER_STATUS.CLOSE.getValue())){
                        woe.setWorkOrderStatus(MesExtEnumUtil.WORK_ORDER_STATUS.CLOSE.getValue());
                    }else if (workOrderModel.getOrderStatus().equals(MesExtEnumUtil.SAP_WORK_ORDER_STATUS.DELETE.getValue())){
                        woe.setWorkOrderStatus(MesExtEnumUtil.WORK_ORDER_STATUS.REMOVE.getValue());
                    }
                    newWorkOrderList.add(woe);
                    workOrderModel.setIsInsert(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue());
                    log.info("工单信息：{}", workOrderModel);
                    newWmsWorkOrderList.add(workOrderModel);
                }
            } else {
                if (MesExtEnumUtil.WORK_ORDER_STATUS.CREATE.getValue() == workOrderExt.getWorkOrderStatus()) {
                    workOrderExt.setPartNo(workOrderModel.getPartNo());
                    workOrderExt.setPartNameRdd(workOrderModel.getPartNameRdd());
                    workOrderExt.setQty(workOrderModel.getQty());
                    workOrderExt.setStartTime(workOrderModel.getStartTime());
                    workOrderExt.setEndTime(workOrderModel.getEndTime());
                    workOrderExt.setErpWarehouse(workOrderModel.getErpWarehouse());
                    if (!CollectionUtils.isEmpty(workVerMap) && workVerMap.containsKey(workOrderModel.getWorkVer())) {
                        MesWorkCenter workCenter = workVerMap.get(workOrderModel.getWorkVer()).get(0);
                        if (null != workCenter) {
                            workOrderExt.setWorkCenterCode(workCenter.getWorkCenterCode());
                            workOrderExt.setAreaCode(workCenter.getAreaCode());
                        }
                    }
                    workOrderExt.setSnCreateStatus(MesExtEnumUtil.WORK_ORDER_SN_CREATE_STATUS.UN_CREATE.getValue());
                    if (!CollectionUtils.isEmpty(partNoMap) && partNoMap.containsKey(workOrderModel.getPartNo())) {
                        MesPartExt partExt = partNoMap.get(workOrderModel.getPartNo()).get(0);
                        if (!StringUtils.isEmpty(partExt.getIsCreateSn()) && CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue() == partExt.getIsCreateSn()) {
                            workOrderExt.setSnCreateStatus(MesExtEnumUtil.WORK_ORDER_SN_CREATE_STATUS.NO_CREATE.getValue());
                        }
                    }
                    if (workOrderModel.getOrderStatus().equals(MesExtEnumUtil.SAP_WORK_ORDER_STATUS.CLOSE.getValue())){
                        workOrderExt.setWorkOrderStatus(MesExtEnumUtil.WORK_ORDER_STATUS.CLOSE.getValue());
                    }else if (workOrderModel.getOrderStatus().equals(MesExtEnumUtil.SAP_WORK_ORDER_STATUS.DELETE.getValue())){
                        workOrderExt.setWorkOrderStatus(MesExtEnumUtil.WORK_ORDER_STATUS.REMOVE.getValue());
                    }
                    ConvertBean.serviceModelUpdate(workOrderExt, MesExtConstWords.SAP);
                    /*if (workOrderModel.getOrderStatus().equals(MesExtEnumUtil.SAP_WORK_ORDER_STATUS.CLOSE.getValue())){
                        workOrderExt.setWorkOrderStatus(MesExtEnumUtil.WORK_ORDER_STATUS.CLOSE.getValue());
                    }else if (workOrderModel.getOrderStatus().equals(MesExtEnumUtil.SAP_WORK_ORDER_STATUS.DELETE.getValue())){
                        workOrderExt.setWorkOrderStatus(MesExtEnumUtil.WORK_ORDER_STATUS.REMOVE.getValue());
                    }*/
                    newWorkOrderList.add(workOrderExt);
                    workOrderModel.setIsInsert(CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue());
                    newWmsWorkOrderList.add(workOrderModel);
                } else if (MesExtEnumUtil.WORK_ORDER_STATUS.PAUSE.getValue() == workOrderExt.getWorkOrderStatus()) {
                    /*if (MesExtEnumUtil.SAP_WORK_ORDER_STATUS.CLOSE.getValue() == workOrderModel.getOrderStatus()) {
                        workOrderExt.setWorkOrderStatus(MesExtEnumUtil.WORK_ORDER_STATUS.CLOSE.getValue());
                    }*/
                    if (workOrderModel.getOrderStatus().equals(MesExtEnumUtil.SAP_WORK_ORDER_STATUS.CLOSE.getValue())){
                        workOrderExt.setWorkOrderStatus(MesExtEnumUtil.WORK_ORDER_STATUS.CLOSE.getValue());
                    }else if (workOrderModel.getOrderStatus().equals(MesExtEnumUtil.SAP_WORK_ORDER_STATUS.DELETE.getValue())){
                        if (workOrderExt.getCompleteQty() == 0){
                            workOrderExt.setWorkOrderStatus(MesExtEnumUtil.WORK_ORDER_STATUS.REMOVE.getValue());
                        }
                    }
                    ConvertBean.serviceModelUpdate(workOrderExt, MesExtConstWords.SAP);
                    newWorkOrderList.add(workOrderExt);
                    workOrderModel.setIsInsert(CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue());
                    newWmsWorkOrderList.add(workOrderModel);
                }
            }
        }

        List<MesWorkOrderExt> insertData = CollectionUtils.isEmpty(newWorkOrderList) ? null :
                newWorkOrderList.stream().filter(o -> (null != o && StringUtils.isEmpty(o.getId()))).collect(Collectors.toList());
        Double maxSeq = new Double(0);
        if (!CollectionUtils.isEmpty(insertData)) {
            maxSeq = getWorkOrderExtMaxSeq(model.getOrganizeCode(), insertData.size());
        }
        for (MesWorkOrderExt item : newWorkOrderList) {
            if (null == item) {
                continue;
            }
            item.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
            new ConvertBeanExt(item).convertBean(item);
            if (StringUtils.isEmpty(item.getId())) {
                maxSeq = MathOperation.add(maxSeq, new Double(1));
                item.setSeq(maxSeq);
                orderSetSeq1(model.getOrganizeCode(),item);
                workOrderExtRepository.insert(item);
            } else {
                workOrderExtRepository.save(item);
            }
            insertMesWorkOrderLog(item);
        }

        model.setWorkOrderList(newWmsWorkOrderList);
        model.setResult(true);
        log.info("工单信息集合：{}",newWmsWorkOrderList);
        return model;
    }

    private void orderSetSeq1(String organizeCode, MesWorkOrderExt mesWorkOrderExt) {

        //获取计划日期年月的最大seq1

        DdlPackBean packBeanSeq1 = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getStringLikerPack(mesWorkOrderExt.getStartTime().substring(0,4)+mesWorkOrderExt.getStartTime().substring(5,7), "seq1", packBeanSeq1);
        DdlPreparedPack.getOrderByPack(new Object[]{CommonEnumUtil.ASC_OR_DESC.DESC.getValue()}, new String[]{"seq1"}, packBeanSeq1);
        MesWorkOrderExt workOrderSeq1 = workOrderExtRepository.getByProperty(packBeanSeq1);

        //seq1加1
        if (null == workOrderSeq1){
            mesWorkOrderExt.setSeq1(mesWorkOrderExt.getStartTime().substring(0,4) + mesWorkOrderExt.getStartTime().substring(5,7) +"00001");
        }else {
            String maxSeq1Time = workOrderSeq1.getSeq1().substring(0,6);
            Integer maxSeq1Num = Integer.valueOf(workOrderSeq1.getSeq1().substring(6,11));
            Integer maxSeq1Num1 = maxSeq1Num + 1;
            if (!maxSeq1Time.equals((mesWorkOrderExt.getStartTime().substring(0,4) + mesWorkOrderExt.getStartTime().substring(5,7)))){
                mesWorkOrderExt.setSeq1(mesWorkOrderExt.getStartTime().substring(0,4) + mesWorkOrderExt.getStartTime().substring(5,7)+"00001");
            }else {
                StringBuilder zero = new StringBuilder();
                if (maxSeq1Num1.toString().length() < 5){
                    for (int i = 0; i < 5 - maxSeq1Num1.toString().length(); i++) {
                        zero.append("0");
                    }
                }
                mesWorkOrderExt.setSeq1(maxSeq1Time +zero+ maxSeq1Num1);
            }
        }

    }


}
