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

import cn.estsh.i3plus.ext.mes.pcn.api.base.*;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.IWorkOrderLogExtService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.*;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.*;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.*;
import cn.estsh.i3plus.ext.mes.pcn.pojo.sqlpack.MesPcnExtHqlPack;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.ConvertBeanExt;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtEnumUtil;
import cn.estsh.i3plus.mes.pcn.api.iservice.busi.IDataAuthService;
import cn.estsh.i3plus.mes.pcn.api.iservice.busi.ISyncFuncService;
import cn.estsh.i3plus.mes.pcn.util.PcnHttpUtil;
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.JsonUtilTool;
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.enumutil.MesPcnEnumUtil;
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.MesPackageDetailRepository;
import cn.estsh.i3plus.pojo.mes.repository.MesWorkCenterRepository;
import cn.estsh.i3plus.pojo.mes.repository.MesWorkOrderRepository;
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 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.stream.Collectors;

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

    @Autowired
    private MesWorkOrderExtRepository workOrderExtRepository;

    @Autowired
    private MesWorkOrderRepository workOrderRepository;

    @Autowired
    private IWorkOrderLogExtService workOrderLogExtService;

    @Autowired
    private MesWorkOrderLogExtRepository workOrderLogRepository;

    @Autowired
    private IPartExtService partExtService;

    @Autowired
    private MesWorkCenterRepository workCenterRepository;

    @Autowired
    private ISyncFuncService syncFuncService;

    @Autowired
    private IDataAuthService dataAuthService;

    @Autowired
    private MesWorkCenterRepository mesWorkCenterRDao;

    @Autowired
    private MesAffiliatedStartConfigRepository affiliatedStartConfigRepository;

    @Autowired
    private ISxPcnHttpService pcnHttpService;

    @Autowired
    private IWorkCenterExtService workCenterExtService;

    @Autowired
    private MesProdBindRecordExtRepository prodBindRecordExtRepository;

    @Autowired
    private MesPackageExtRepository packageExtRepository;

    @Autowired
    private MesPackageRecordRepository packageRecordRepository;

    @Autowired
    private MesBusiConfigRepository busiConfigRepository;

    @Autowired
    private MesProduceSnRepairRepository produceSnRepairRepository;

    @Autowired
    private MesProduceSnExtRepository produceSnExtRepository;

    @Autowired
    private MesPackageDetailRepository packageDetailRepository;

    @Resource(name = MesPcnExtConstWords.REDIS_RES_PCN)
    private ImppRedis redisMesPcn;

    /**
     * 生成生产工单
     *
     * @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(MesPcnExtEnumUtil.WORK_ORDER_SOURCE.MANUALLY_GENERATE.getValue());
        insertNewWorkOrder(mesWorkOrderExt);
    }

    private void insertNewWorkOrder(MesWorkOrderExt mesWorkOrderExt) {
        String organizeCode = AuthUtil.getOrganize().getOrganizeCode();
        Integer workOrderType = mesWorkOrderExt.getWorkOrderType();
        MesPartExt partExt = partExtService.getPartExt(organizeCode, mesWorkOrderExt.getPartNo());
        if (partExt == null) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("物料【】号不存在", mesWorkOrderExt.getPartNo())
                    .build();
        }
        //如果是返工工单 设置是否生成条码为不生成
        if (MesPcnExtEnumUtil.WORK_ORDER_TYPE.REWORK_ORDER.getValue() == workOrderType) {
            mesWorkOrderExt.setSnCreateStatus(MesPcnExtEnumUtil.WORK_ORDER_SN_CREATE_STATUS.NO_CREATE.getValue());
        } else {
            //不是返工工单
            //判断物料是否需要生成条码
            //if (!ObjectUtils.isEmpty(partExt))
            Integer isCreateSn = partExt.getIsCreateSn();
            if (CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue() == isCreateSn) {
                mesWorkOrderExt.setSnCreateStatus(MesPcnExtEnumUtil.WORK_ORDER_SN_CREATE_STATUS.UN_CREATE.getValue());
            } else {
                mesWorkOrderExt.setSnCreateStatus(MesPcnExtEnumUtil.WORK_ORDER_SN_CREATE_STATUS.NO_CREATE.getValue());
            }
        }

        mesWorkOrderExt.setWorkOrderStatus(MesPcnExtEnumUtil.WORK_ORDER_STATUS.LANDED.getValue());
        mesWorkOrderExt.setOrganizeCode(organizeCode);
//        mesWorkOrderExt.setSeq(getSeqMax() + 1);
        mesWorkOrderExt.setSeq(MathOperation.add(getWorkOrderExtMaxSeq(organizeCode, 1), new Double(1)));

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

    private synchronized Double getWorkOrderExtMaxSeq(String organizeCode, Integer count) {
        Double maxSeq = new Double(0);
        try {
            String requestUrl = pcnHttpService.getRequestUrl(organizeCode, MesPcnExtConstWords.WORK_ORDER_MAX_SEQ_URL);
            Map<String, String> params = new HashMap<>();
            params.put(MesPcnExtConstWords.ORGANIZE_CODE, organizeCode);
            params.put(MesPcnExtConstWords.COUNT, count.toString());
            String data = PcnHttpUtil.doPost(requestUrl, params);
            BaseResultBean baseResultBean = null;
            if (!StringUtils.isEmpty(data)) {
                baseResultBean = JsonUtilTool.decode(data, BaseResultBean.class);
            } else {
                log.error("HTTP[{}]调用主接口失败", requestUrl);
            }
            if (null != baseResultBean && baseResultBean.success) {
                LinkedHashMap resultObject = (LinkedHashMap) baseResultBean.getResultObject();
                maxSeq = JsonUtilTool.decode(JSONObject.toJSONString(resultObject), Double.class);
            }
        } catch (Exception e) {
        }
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getOrderByPack(new Object[]{CommonEnumUtil.ASC_OR_DESC.DESC.getValue()}, new String[]{MesPcnExtConstWords.SEQ}, packBean);
        MesWorkOrderExt workOrderExt = workOrderExtRepository.getByProperty(packBean);
        if (null != workOrderExt) {
            if (MathOperation.compareTo(maxSeq, workOrderExt.getSeq()) < 0) {
                maxSeq = workOrderExt.getSeq();
            }
        }
        return maxSeq;
    }


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

    private void updateWorkOrder(MesWorkOrderExt mesWorkOrderExt) {
        //在更新时导入的工单如果状态不是创建或暂停的工单，进行异常提醒。
        Integer workOrderStatus = mesWorkOrderExt.getWorkOrderStatus();
        boolean isCreate = MesPcnExtEnumUtil.WORK_ORDER_STATUS.CREATE.getValue() == workOrderStatus;
        boolean isPause = MesPcnExtEnumUtil.WORK_ORDER_STATUS.PAUSE.getValue() == workOrderStatus;
        //从SAP获取的订单如果状态不是创建或者暂停的工单，忽略更新。
        if (isCreate || isPause) {
            mesWorkOrderExt.setSystemSyncStatus(MesPcnExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
            if(mesWorkOrderExt.getWorkOrderType() != MesPcnExtEnumUtil.WORK_ORDER_TYPE.REWORK_ORDER.getValue()){
                mesWorkOrderExt.setSnCreateStatus(MesPcnExtEnumUtil.WORK_ORDER_SN_CREATE_STATUS.UN_CREATE.getValue());
            }
            ConvertBean.serviceModelUpdate(mesWorkOrderExt, AuthUtil.getSessionUser().getUserName());
            new ConvertBeanExt(mesWorkOrderExt).convertBean(mesWorkOrderExt);
            MesWorkOrderExt workOrderExt = workOrderExtRepository.save(mesWorkOrderExt);
            insertMesWorkOrderLog(workOrderExt);
        } else {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.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});
        return  mesWorkOrderExt;
    }

    /**
     * excel导入生成生产工单
     *
     * @param mesWorkOrderExtList mes工作单et列表
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importGenerate(List<ExcelWorkOrderDto> mesWorkOrderExtList) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sf = new SimpleDateFormat("yyyy/MM/dd");
        MesPart partExt;

        Integer i = 2;

        String organizeCode = AuthUtil.getOrganize().getOrganizeCode();
        for (ExcelWorkOrderDto excelWorkOrderDto : mesWorkOrderExtList) {

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

            //判断日期格式是否正确,正确则转换格式
            try {
                excelWorkOrderDto.setStartTime(sdf.format(sf.parse(excelWorkOrderDto.getStartTime())));
                excelWorkOrderDto.setEndTime(sdf.format(sf.parse(excelWorkOrderDto.getEndTime())));
            } catch (ParseException e) {
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("第【%s】行的时间格式不正确，应该为yyyy/MM/dd格式", i)
                        .build();
            }

            //根据零件号查询零件信息
            partExt = partExtService.getPartExt(organizeCode, excelWorkOrderDto.getPartNo());

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

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

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

            MesWorkOrderExt mesWorkOrderExt = new MesWorkOrderExt();

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


            if(haveWorkOrder !=null) {
                BeanUtils.copyProperties(excelWorkOrderDto, haveWorkOrder);
                updateWorkOrder(haveWorkOrder);
            }else {
                BeanUtils.copyProperties(excelWorkOrderDto, mesWorkOrderExt);
                mesWorkOrderExt.setAreaCode(mesWorkCenter.getAreaCode());
                mesWorkOrderExt.setWorkOrderSource(MesPcnExtEnumUtil.WORK_ORDER_SOURCE.IMPORT_GENERATE.getValue());
                mesWorkOrderExt.setWorkOrderType(MesPcnExtEnumUtil.WORK_ORDER_TYPE.STANDARD_ORDER.getValue());
                insertNewWorkOrder(mesWorkOrderExt);
            }

        }
    }

    /**
     * 调整工作顺序
     *
     * @param generateWorkOrderDto 生成工作单dto
     */
    @Override
    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("调整后的计划数量不能低于当前生产的数量");
        }
        BeanUtils.copyProperties(generateWorkOrderDto,mesWorkOrderExt);
        //
        updateWorkOrder(mesWorkOrderExt);
    }

    /**
     * 工单新增/编辑-校验
     *
     * @param organizeCode 组织代码
     */
    private boolean isHavePart(String partNo, String organizeCode) {
        MesPart mesPart = partExtService.getPartExt(organizeCode, partNo);
        return null != mesPart;
    }


    private String getOrderNo(String userName, String organizeCode) {
        String orderNo = "";
        BaseResultBean oneCodeResult = syncFuncService.syncSerialNo(new GenSerialNoModel(MesPcnExtEnumUtil.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_PCN.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);
        DdlPreparedPack.getStringLikerPack(workOrderQueryDto.getOrderNo(), "orderNo", ddlPackBean);
        DdlPreparedPack.getStringLikerPack(workOrderQueryDto.getPartNo(), "partNo", ddlPackBean);
        DdlPreparedPack.getStringEqualPack(workOrderQueryDto.getWorkCenterCode(), "workCenterCode", ddlPackBean);
        DdlPreparedPack.getNumEqualPack(workOrderQueryDto.getWorkOrderStatus(), "workOrderStatus", ddlPackBean);
        DdlPreparedPack.getNumEqualPack(workOrderQueryDto.getWorkOrderType(), "workOrderType", ddlPackBean);
        DdlPreparedPack.getStringLikerPack(workOrderQueryDto.getCreateUser(), "createUser", ddlPackBean);

        if (!StringUtils.isEmpty(workOrderQueryDto.getStartTimeStart()) || !StringUtils.isEmpty(workOrderQueryDto.getStartTimeEnd())) {
            DdlPreparedPack.timeBuilder(workOrderQueryDto.getStartTimeStart(), workOrderQueryDto.getStartTimeEnd(), "startTime", ddlPackBean, true);
        }
        if (!StringUtils.isEmpty(workOrderQueryDto.getEndTimeStart()) || !StringUtils.isEmpty(workOrderQueryDto.getEndTimeEnd())) {
            DdlPreparedPack.timeBuilder(workOrderQueryDto.getEndTimeStart(), workOrderQueryDto.getEndTimeEnd(), "endTime", ddlPackBean, true);
        }

        if (StringUtils.isEmpty(workOrderQueryDto.getOrderByParam())) {
            DdlPreparedPack.getOrderByPack(new Object[]{MesEnumUtil.ASC_OR_DESC.DESC.getValue()}, new String[]{MesPcnExtConstWords.MODIFY_DATE_TIME}, ddlPackBean);
        } else {
            if (workOrderQueryDto.getOrderByParam().equals(MesPcnExtConstWords.SEQ) ||
                    workOrderQueryDto.getOrderByParam().equals(MesPcnExtConstWords.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(), MesPcnExtConstWords.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>>() {
        });

        List<MesWorkCenterExt> workCenterExtList = workCenterExtService.getWorkCenterExtList(organizeCode);
        Map<String, String> workCenterCodeMap = CollectionUtils.isEmpty(workCenterExtList) ? new HashMap<>() :
                workCenterExtList.stream().filter(o -> null != o).collect(Collectors.toMap(MesWorkCenter::getWorkCenterCode, MesWorkCenter::getWorkCenterName));

        if (!CollectionUtils.isEmpty(workOrderPageVos)) {
            for (WorkOrderPageVo workOrderPageVo : workOrderPageVos) {
                Integer workOrderStatus = workOrderPageVo.getWorkOrderStatus();
                String workOrderStatusName = MesPcnExtEnumUtil.WORK_ORDER_STATUS.valueOfDescription(workOrderStatus);
                workOrderPageVo.setWorkOrderStatusName(workOrderStatusName);

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

                workOrderPageVo.setWorkCenterName(!StringUtils.isEmpty(workOrderPageVo.getWorkCenterCode()) ? workCenterCodeMap.get(workOrderPageVo.getWorkCenterCode()) : null);
                //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 (MesPcnExtEnumUtil.WORK_ORDER_STATUS.CREATE.getValue() == workOrderStatus) {
            mesButtonFlagModel.setUpdateButton(true);
            mesButtonFlagModel.setTransmitButton(true);
        }

        if (MesPcnExtEnumUtil.WORK_ORDER_STATUS.LANDED.getValue() == workOrderStatus) {
            mesButtonFlagModel.setStartUpButton(true);
            mesButtonFlagModel.setSuspendButton(true);
        }
        if (MesPcnExtEnumUtil.WORK_ORDER_STATUS.PAUSE.getValue() == workOrderStatus) {
            mesButtonFlagModel.setStartUpButton(true);
            mesButtonFlagModel.setCloseButton(true);
        }
        if (MesPcnExtEnumUtil.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 = MesPcnExtEnumUtil.WORK_ORDER_STATUS.CREATE.getValue() == workOrderStatus;
        boolean isLanded = MesPcnExtEnumUtil.WORK_ORDER_STATUS.LANDED.getValue() == workOrderStatus;
        boolean isOpen = MesPcnExtEnumUtil.WORK_ORDER_STATUS.OPEN.getValue() == workOrderStatus;
        if (isCreate || isLanded || isOpen) {
            haveWorkOrder.setWorkOrderStatus(MesPcnExtEnumUtil.WORK_ORDER_STATUS.PAUSE.getValue());
            haveWorkOrder.setSystemSyncStatus(MesPcnExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
            ConvertBean.serviceModelUpdate(haveWorkOrder, AuthUtil.getSessionUser().getUserName());
            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 = MesPcnExtEnumUtil.WORK_ORDER_STATUS.LANDED.getValue() == workOrderStatus;
        boolean isPause = MesPcnExtEnumUtil.WORK_ORDER_STATUS.PAUSE.getValue() == workOrderStatus;

        if (isLanded) {
            haveWorkOrder.setWorkOrderStatus(MesPcnExtEnumUtil.WORK_ORDER_STATUS.OPEN.getValue());
            haveWorkOrder.setSystemSyncStatus(MesPcnExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
            ConvertBean.serviceModelUpdate(haveWorkOrder, AuthUtil.getSessionUser().getUserName());
            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 = MesPcnExtEnumUtil.WORK_ORDER_STATUS.PAUSE.getValue() == workOrderStatus1;
                        if(isPause1){
                            MesWorkOrderLog mesWorkOrderLog2 = mesWorkOrderLogs.get(size - 2);
                            Integer workOrderStatus2 = mesWorkOrderLog2.getWorkOrderStatus();
                            haveWorkOrder.setWorkOrderStatus(workOrderStatus2);
                            haveWorkOrder.setSystemSyncStatus(MesPcnExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
                            ConvertBean.serviceModelUpdate(haveWorkOrder, AuthUtil.getSessionUser().getUserName());
                            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(MesPcnExtEnumUtil.WORK_ORDER_STATUS.CLOSE.getValue());
            haveWorkOrder.setSystemSyncStatus(MesPcnExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
            ConvertBean.serviceModelUpdate(haveWorkOrder, AuthUtil.getSessionUser().getUserName());
            new ConvertBeanExt(haveWorkOrder).convertBean(haveWorkOrder);
            MesWorkOrderExt mesWorkOrderExt = workOrderExtRepository.save(haveWorkOrder);
            insertMesWorkOrderLog(mesWorkOrderExt);
        }

        Integer workOrderStatus = haveWorkOrder.getWorkOrderStatus();
        boolean isPause = MesPcnExtEnumUtil.WORK_ORDER_STATUS.PAUSE.getValue() == workOrderStatus;
        if(isPause){
            //更改为关闭状态
            haveWorkOrder.setWorkOrderStatus(MesPcnExtEnumUtil.WORK_ORDER_STATUS.CLOSE.getValue());
            haveWorkOrder.setSystemSyncStatus(MesPcnExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
            ConvertBean.serviceModelUpdate(haveWorkOrder, AuthUtil.getSessionUser().getUserName());
            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 = MesPcnExtEnumUtil.WORK_ORDER_STATUS.CREATE.getValue() == workOrderStatus;

        if(isCreate){
            haveWorkOrder.setWorkOrderStatus(MesPcnExtEnumUtil.WORK_ORDER_STATUS.LANDED.getValue());
            haveWorkOrder.setSystemSyncStatus(MesPcnExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
            ConvertBean.serviceModelUpdate(haveWorkOrder, AuthUtil.getSessionUser().getUserName());
            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 insertBeforeOrderNo = workOrderSeq.getInsertBeforeOrderNo();
        String insertAfterOrderNo = workOrderSeq.getInsertAfterOrderNo();
        String needUpdateOrderNo = workOrderSeq.getNeedUpdateOrderNo();

        MesWorkOrderExt workOrder1 = isHaveWorkOrder(insertBeforeOrderNo, organizeCode);
        MesWorkOrderExt workOrder2 = isHaveWorkOrder(insertAfterOrderNo, organizeCode);
        MesWorkOrderExt workOrder3 = isHaveWorkOrder(needUpdateOrderNo, 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());
        workOrder3.setSystemSyncStatus(MesPcnExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
        ConvertBean.serviceModelUpdate(workOrder3, AuthUtil.getSessionUser().getUserName());
        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();
        String userInfo = AuthUtil.getSessionUser().getUserName();

        //获取所有数据
        List<MesWorkOrderExt> workOrderExtList = new ArrayList<>();
        for (String orderNo : orderNoList) {
            MesWorkOrderExt workOrderExt = getWorkOrderExtByOrderNo(organizeCode, orderNo);
            if (null == workOrderExt) {
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                        .setErrorDetail("生产工单[%s]不存在", orderNo)
                        .build();
            }
            workOrderExtList.add(workOrderExt);
        }

        Map<Integer, List<MesWorkOrderExt>> listMap = workOrderExtList.stream().filter(o -> null != o).collect(Collectors.groupingBy(MesWorkOrderExt::getWorkOrderStatus));
        if (listMap.size() > 1) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("只能批量%s状态一样的生产工单", MesEnumUtil.PLAN_ORDER_STATUS.valueOfDescription(workOrderStatus))
                    .build();
        } else if (listMap.size() == 1 && MesPcnExtEnumUtil.WORK_ORDER_STATUS.OPEN.getValue() == workOrderStatus) {
            Map<String, List<MesWorkOrderExt>> listMapWorkCenterCode = workOrderExtList.stream().filter(o -> null != o).collect(Collectors.groupingBy(MesWorkOrderExt::getWorkCenterCode));
            for (String workCenterCode : listMapWorkCenterCode.keySet()) {
                if (StringUtils.isEmpty(workCenterCode)) {
                    continue;
                }
                if (listMapWorkCenterCode.get(workCenterCode).size() > 1) {
                    throw ImppExceptionBuilder.newInstance()
                            .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                            .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                            .setErrorDetail("同生产线下只能启动一条工单")
                            .build();
                }
            }
        }

        // 一个工单号下的多个工单
        for (MesWorkOrderExt workOrderExt : workOrderExtList) {
            Integer lastWorkOrderStatus = null;
            //启动
            if (MesPcnExtEnumUtil.WORK_ORDER_STATUS.OPEN.getValue() == workOrderStatus) {
                if (MesPcnExtEnumUtil.WORK_ORDER_STATUS.LANDED.getValue() == workOrderExt.getWorkOrderStatus()) {
                    //调用启动工单附属启动的方法
                    //校验是否存在已经启动的工单
                    List<MesWorkOrderExt> landedOrderList = getWorkOrderListByCenterAndStatus(organizeCode, workOrderExt.getWorkCenterCode(), MesPcnExtEnumUtil.WORK_ORDER_STATUS.LANDED.getValue());
                    if (CollectionUtils.isEmpty(landedOrderList)) {
                        throw ImppExceptionBuilder.newInstance()
                                .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                                .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                                .setErrorDetail("生产线[%s]暂无下达状态的工单,请刷新界面重试", workOrderExt.getWorkCenterCode())
                                .build();
                    }
                    if (!landedOrderList.get(0).getOrderNo().equals(workOrderExt.getOrderNo())) {
                        throw ImppExceptionBuilder.newInstance().setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                                .setErrorDetail("工单[%s]的工单序号不是生产线[%s]下工单中最小的序号", workOrderExt.getOrderNo(), workOrderExt.getWorkCenterCode())
                                .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                                .build();
                    }

                    if (MesPcnExtEnumUtil.WORK_ORDER_SN_CREATE_STATUS.UN_CREATE.getValue() == workOrderExt.getSnCreateStatus()) {
                        throw ImppExceptionBuilder.newInstance()
                                .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                                .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                                .setErrorDetail("工单[%s]未生成产品条码,不能启动", workOrderExt.getOrderNo())
                                .build();
                    }
                } else if (MesPcnExtEnumUtil.WORK_ORDER_STATUS.PAUSE.getValue() == workOrderExt.getWorkOrderStatus()) {
                    //更改未暂停前状态
                    //获取暂停前的状态
                    List<MesWorkOrderLog> workOrderLogList = workOrderLogExtService.getWorkOrderLogList(organizeCode, workOrderExt.getOrderNo());
                    if (CollectionUtils.isEmpty(workOrderLogList)) {
                        throw ImppExceptionBuilder.newInstance().setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                                .setErrorDetail("工单号[%s]缺失履历信息,操作失败", workOrderExt.getOrderNo())
                                .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                                .build();
                    }
                    workOrderLogList = workOrderLogList.stream().sorted(Comparator.comparing(MesWorkOrderLog::getModifyDatetime).reversed()).collect(Collectors.toList());
                    lastWorkOrderStatus = MesPcnExtEnumUtil.WORK_ORDER_STATUS.LANDED.getValue();
                    for (MesWorkOrderLog workOrderLog : workOrderLogList) {
                        if (null == workOrderLog) {
                            continue;
                        }
                        if (workOrderLog.getWorkOrderStatus() != MesPcnExtEnumUtil.WORK_ORDER_STATUS.PAUSE.getValue()) {
                            lastWorkOrderStatus = workOrderLog.getWorkOrderStatus();
                            break;
                        }
                    }

                    if (lastWorkOrderStatus == MesPcnExtEnumUtil.WORK_ORDER_STATUS.OPEN.getValue()) {
                        if (MesPcnExtEnumUtil.WORK_ORDER_SN_CREATE_STATUS.UN_CREATE.getValue() == workOrderExt.getSnCreateStatus()) {
                            throw ImppExceptionBuilder.newInstance()
                                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                                    .setErrorDetail("工单[%s]未生成产品条码,不能启动", workOrderExt.getOrderNo())
                                    .build();
                        }
                    }
                }else {
                    throw ImppExceptionBuilder.newInstance()
                            .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                            .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                            .setErrorDetail("工单[%s]状态为[%s],不能启动",
                                    workOrderExt.getOrderNo(), MesPcnExtEnumUtil.WORK_ORDER_STATUS.valueOfDescription(workOrderExt.getWorkOrderStatus()))
                            .build();
                }

                if (workOrderExt.getWorkOrderType() != MesPcnExtEnumUtil.WORK_ORDER_TYPE.REWORK_ORDER.getValue() &&
                        MesPcnExtEnumUtil.WORK_ORDER_STATUS.OPEN.getValue() == workOrderStatus &&
                        (null == lastWorkOrderStatus || MesPcnExtEnumUtil.WORK_ORDER_STATUS.OPEN.getValue() == lastWorkOrderStatus)) {
                    DdlPackBean ddlPackBean = DdlPackBean.getDdlPackBean(organizeCode);
                    List<MesAffiliatedStartConfig> mesAffiliatedStartConfigs = affiliatedStartConfigRepository.findByHqlWhere(ddlPackBean);
                    int totalConfigSize = CollectionUtils.isEmpty(mesAffiliatedStartConfigs) ? 0 : mesAffiliatedStartConfigs.size();
                    log.info("总配置类信息" + mesAffiliatedStartConfigs + "总配置数量" + totalConfigSize);
                    for (MesAffiliatedStartConfig mesAffiliatedStartConfig : mesAffiliatedStartConfigs) {
                        try {
                            log.info("点检启动配置类信息" + mesAffiliatedStartConfig);
                            IWorkOrderStartService workOrderStartService = (IWorkOrderStartService) SpringContextsUtil.getBean(mesAffiliatedStartConfig.getAffiliatedStartClass());
                            log.info(workOrderStartService.getClass().getName() + "点检开始执行调用");
                            workOrderStartService.doGenCheckOrder(workOrderExt, userInfo);
                            log.info(workOrderStartService.getClass().getName() + "点检开始执行结束");
                        } catch (Exception e) {
                            log.error("点检开始执行异常" + e.getMessage());
                            StackTraceElement[] stackTrace = e.getStackTrace();
                            log.error(Arrays.toString(stackTrace));
                        }
                    }
                }
            } else if (MesPcnExtEnumUtil.WORK_ORDER_STATUS.PAUSE.getValue() == workOrderStatus) {
                //暂停
                //校验工单是否是启动状态
                boolean isCreate = MesPcnExtEnumUtil.WORK_ORDER_STATUS.CREATE.getValue() == workOrderExt.getWorkOrderStatus();
                boolean isLanded = MesPcnExtEnumUtil.WORK_ORDER_STATUS.LANDED.getValue() == workOrderExt.getWorkOrderStatus();
                boolean isOpen = MesPcnExtEnumUtil.WORK_ORDER_STATUS.OPEN.getValue() == workOrderExt.getWorkOrderStatus();
                if (!isCreate && !isLanded && !isOpen) {
                    throw ImppExceptionBuilder.newInstance()
                            .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                            .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                            .setErrorDetail("工单[%s]的状态不是启动,下达,创建状态,不能暂停", workOrderExt.getOrderNo())
                            .build();
                }
                String key = new StringJoiner(MesPcnExtConstWords.COLON).add("MES-PAUSE-ORDER").add(workOrderExt.getOrderNo()).toString();
                redisMesPcn.putObject(key, workOrderExt.getOrderNo(), MesPcnEnumUtil.EXPIRE_TIME.ONE_MIN.getValue());
            } else if (MesPcnExtEnumUtil.WORK_ORDER_STATUS.CLOSE.getValue() == workOrderStatus) {
                /*//关闭
                //校验工单是否是暂停状态
                if (MesPcnExtEnumUtil.WORK_ORDER_STATUS.PAUSE.getValue() != workOrderExt.getWorkOrderStatus()) {
                    throw ImppExceptionBuilder.newInstance()
                            .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                            .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                            .setErrorDetail("工单[%s]的状态不是暂停状态,不能关闭", workOrderExt.getOrderNo())
                            .build();
                }*/
            } else if (MesPcnExtEnumUtil.WORK_ORDER_STATUS.CLOSE.getValue() == workOrderStatus) {
                //完成
                //校验工单是否是暂停状态
                //修改返工工单状态
                //if(workOrderExt.getWorkOrderType() == MesPcnExtEnumUtil.WORK_ORDER_TYPE.REWORK_ORDER.getValue()) {
                //
                //    List<String> waterPurifierCodeList = !Optional.ofNullable(waterPurifierCode).isPresent() || StringUtils.isEmpty(waterPurifierCode.getCfgValue()) ? new ArrayList<>() : Arrays.asList(waterPurifierCode.getCfgValue().split(MesPcnExtConstWords.COMMA));
                //    if(CollectionUtils.isEmpty(waterPurifierCodeList) || !waterPurifierCodeList.contains(workOrderExt.getWorkCenterCode())){
                //        // 手动点击完成工单,存在未下线条码
                //        if(!workOrderExt.getQty().equals(workOrderExt.getCompleteQty())) {
                //            List<MesProduceSnRepair> produceSnRepairList = queryProduceSnRepairList(organizeCode, workOrderExt.getOrderNo());
                //            if(!CollectionUtils.isEmpty(produceSnRepairList)) {
                //                // 未下线条码
                //                produceSnRepairList = produceSnRepairList.stream().filter(o -> StringUtils.isEmpty(o.getOutWorkCenterTime())).collect(Collectors.toList());
                //
                //                if(!CollectionUtils.isEmpty(produceSnRepairList)){
                //                    List<String> serialNumberList = produceSnRepairList.stream().map(MesProduceSnRepair::getSerialNumber).collect(Collectors.toList());
                //
                //                    updateProduceSnRepair(organizeCode, serialNumberList);
                //
                //                    updatePackage(organizeCode, serialNumberList);
                //
                //                    unbindReworkRangeList(organizeCode, workOrderExt, serialNumberList, userInfo);
                //
                //                    clearProdBindRecord(organizeCode, workOrderExt, TimeTool.getNowTime(true), serialNumberList, userInfo);
                //                }
                //            }
                //        }
                //
                //        //reworkOrderRepository.updateByProperties(new String[]{MesPcnExtConstWords.REWORK_ORDER_NO}, new Object[]{workOrderExt.getOrderNo()},
                //        //        new String[]{ MesPcnExtConstWords.WORK_ORDER_STATUS, MesPcnExtConstWords.SYSTEM_SYNC_STATUS, MesPcnExtConstWords.MODIFY_USER, MesPcnExtConstWords.MODIFY_DATE_TIME},
                //        //        new Object[]{MesPcnExtEnumUtil.WORK_ORDER_STATUS.CLOSE.getValue(), MesPcnExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue(), AuthUtil.getSessionUser().getUserName(), TimeTool.getNowTime(true)});
                //    }
                //}
                /*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 (MesPcnExtEnumUtil.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 (workOrderExt.getCompleteQty() > 0){
                    throw ImppExceptionBuilder.newInstance().setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                            .setErrorDetail("工单号【%s】的完成数量大于0，不能删除", workOrderExt.getOrderNo())
                            .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                            .setErrorSolution("校验生产工单表数据")
                            .build();
                }else if(workOrderExt.getCompleteQty() == 0){
                    // 要自动解绑已绑定的关键件 看一下是什么
                    DdlPackBean packBeanBind = DdlPackBean.getDdlPackBean(organizeCode);
                    DdlPreparedPack.getStringEqualPack(workOrderExt.getOrderNo(),MesPcnExtConstWords.WORK_ORDER_NO,packBeanBind);
                    List<MesProdBindRecordExt> prodBindRecordExtList = prodBindRecordExtRepository.findByHqlWhere(packBeanBind);
                    prodBindRecordExtList.forEach(p -> {
                        p.setActionType(MesPcnExtEnumUtil.MES_ACTION_TYPE.UNTYING.getValue());
                        ConvertBean.serviceModelUpdate(p, userInfo);
                        new ConvertBeanExt(p).convertBean(p);
                        prodBindRecordExtRepository.update(p);
                    });
                }
            }

            if (null == lastWorkOrderStatus) {
                workOrderExt.setWorkOrderStatus(workOrderStatus);
            } else {
                workOrderExt.setWorkOrderStatus(lastWorkOrderStatus);
            }
            ConvertBean.serviceModelUpdate(workOrderExt, userInfo);
            workOrderExt.setSystemSyncStatus(MesPcnExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
            new ConvertBeanExt(workOrderExt).convertBean(workOrderExt);
            MesWorkOrderExt mesWorkOrderDb = workOrderExtRepository.save(workOrderExt);

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

    }

    private List<MesProduceSnRepair> queryProduceSnRepairList(String organizeCode, String orderNo) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getStringEqualPack(orderNo, MesPcnExtConstWords.WORK_ORDER_NO, packBean);
        return produceSnRepairRepository.findByHqlWhere(packBean);
    }

    private void updateProduceSnRepair(String organizeCode, List<String> serialNumberList) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getInPackList(serialNumberList, MesPcnExtConstWords.SERIAL_NUMBER, packBean);
        List<MesProduceSnExt> produceSnExtList = produceSnExtRepository.findByHqlWhere(packBean);
        //String nowTime = TimeTool.getNowTime(true);
        produceSnExtList.forEach(o -> {
            o.setSnStatus(MesPcnExtEnumUtil.PRODUCE_SN_STATUS.OFFLINE.getValue());
            //o.setModifyUserExt(AuthUtil.getSessionUser().getUserName());
            //o.setModifyDatetimeExt(nowTime);
            //o.setModifyUser(AuthUtil.getSessionUser().getUserName());
            //o.setModifyDatetime(nowTime);
            o.setSystemSyncStatus(MesPcnExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
            o.setSystemSyncStatusExt(MesPcnExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
        });
        produceSnExtRepository.saveAll(produceSnExtList);
    }

    private void updatePackage(String organizeCode, List<String> serialNumberList) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getInPackList(serialNumberList, MesPcnExtConstWords.SERIAL_NUMBER, packBean);
        List<MesPackageDetail> packageDetailList = packageDetailRepository.findByHqlWhere(packBean);
        List<String> packageNoList = packageDetailList.stream().map(MesPackageDetail::getPackageNo).distinct().collect(Collectors.toList());

        packBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getInPackList(packageNoList, MesPcnExtConstWords.PACKAGENO, packBean);
        List<MesPackageExt> packageExtList = packageExtRepository.findByHqlWhere(packBean);
        packageExtList.forEach(o -> {
            o.setLastWorkOrderNo(o.getWorkOrderNo());
        });
        packageExtRepository.saveAll(packageExtList);
    }

    private void unbindReworkRangeList(String organizeCode, MesWorkOrderExt mesWorkOrder, List<String> serialNumberList, String userName) {
        try {
            String requestUrl = pcnHttpService.getRequestUrl(organizeCode, MesPcnExtConstWords.UNBIND_REWORK_RANGE_LIST_URL);
            Map<String, String> params = new HashMap<>();
            params.put(MesPcnExtConstWords.ORGANIZE_CODE, organizeCode);
            params.put(MesPcnExtConstWords.WORK_ORDER_NO, mesWorkOrder.getOrderNo());
            params.put(MesPcnExtConstWords.SERIAL_NUMBER, JSONObject.toJSONString(serialNumberList));
            params.put(MesPcnExtConstWords.USER_NAME, userName);
            String data = PcnHttpUtil.doPost(requestUrl, params);
            BaseResultBean baseResultBean = null;
            if (!StringUtils.isEmpty(data)) {
                baseResultBean = JsonUtilTool.decode(data, BaseResultBean.class);
            } else {
                log.error("HTTP[{}]调用主接口失败", requestUrl);
            }
            if (!baseResultBean.success) {
                throw ImppExceptionBuilder.newInstance().setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail(baseResultBean.getErrorMsg())
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                        .build();
            }
        } catch (Exception e) {
            throw ImppExceptionBuilder.newInstance().setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("返工范围与当前工单解除关联失败")
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .build();
        }
        //BaseResultBean baseResultBean = reworkRangeCloud.unbindReworkRangeList(mesWorkOrder.getOrderNo(), serialNumberList, organizeCode, AuthUtil.getSessionUser().getUserName());
        //if (!baseResultBean.success) {
        //    throw ImppExceptionBuilder.newInstance().setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
        //            .setErrorDetail(baseResultBean.getErrorMsg())
        //            .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
        //            .build();
        //}

        //DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        //DdlPreparedPack.getStringEqualPack(mesWorkOrder.getOrderNo(), MesExtConstWords.REWORK_ORDER_NO, packBean);
        //List<MesReworkRange> reworkRangeList = reworkRangeRepository.findByHqlWhere(packBean);
        //
        //reworkRangeList = reworkRangeList.stream().filter(o -> serialNumberList.contains(o.getSerialNumber())).collect(Collectors.toList());
        //
        //reworkRangeList.forEach(o-> {
        //    o.setModifyUser(AuthUtil.getSessionUser().getUserName());
        //    o.setModifyDatetime(nowTime);
        //    o.setBindStatus(MesExtEnumUtil.PACKAGE_BIND_STATUS.BINGDING.getValue());
        //    o.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
        //    o.setReworkOrderNo("");
        //});
        //
        //reworkRangeRepository.saveAll(reworkRangeList);
    }

    private void clearProdBindRecord(String organizeCode, MesWorkOrderExt mesWorkOrder, String nowTime, List<String> serialNumberList, String userName) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getStringEqualPack(mesWorkOrder.getOrderNo(), MesPcnExtConstWords.WORK_ORDER_NO, packBean);
        DdlPreparedPack.getInPackList(serialNumberList, MesPcnExtConstWords.SERIAL_NUMBER, packBean);
        List<MesProdBindRecordExt> prodBindRecordExtList = prodBindRecordExtRepository.findByHqlWhere(packBean);
        prodBindRecordExtList.forEach(o -> {
            o.setIsDeletedExt(MesPcnExtEnumUtil.IS_VAILD.VAILD.getValue());
            o.setIsValidExt(MesPcnExtEnumUtil.IS_VAILD.INVAILD.getValue());
            o.setModifyDatetimeExt(nowTime);
            o.setModifyDatetime(nowTime);
            o.setModifyUser(userName);
            o.setModifyUserExt(AuthUtil.getSessionUser().getUserName());
        });

        prodBindRecordExtRepository.saveAll(prodBindRecordExtList);
    }

    @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(MesPcnExtEnumUtil.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;
        //根据产线分组数据
        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_PCN.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_PCN.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) {
                //根据零件号查询生产节拍信息
//                mesPartTakt = mesPartTaktRDao.getByProperty(
//                        new String[]{"partNo", "workCenterCode", "organizeCode", "isValid", "isDeleted"},
//                        new Object[]{workOrder.getPartNo(), workOrder.getWorkCenterCode(),
//                                workOrder.getOrganizeCode(), CommonEnumUtil.IS_VAILD.VAILD.getValue(),
//                                CommonEnumUtil.IS_DEAL.NO.getValue()});
//
//                if (mesPartTakt == null) {
//                    throw ImppExceptionBuilder.newInstance()
//                            .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
//                            .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
//                            .setErrorDetail("零件号【%s】和产线代码【%s】在生产节拍信息中不存在数据",
//                                    workOrder.getPartNo(), workOrder.getWorkCenterCode())
//                            .build();
//                }
//
//                planEndTime = getPlanEndTime(planStartTime, mesPartTakt.getPlanTakt(), workOrder.getQty().intValue(), 0);
//
//                workOrder.setStartTime(planStartTime);
//                workOrder.setEndTime(planEndTime);

                ConvertBean.serviceModelUpdate(workOrder, AuthUtil.getSessionUser().getUserName());
                workOrder.setSystemSyncStatus(MesPcnExtEnumUtil.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(MesPcnExtEnumUtil.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_PCN.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("日期解析失败，请检查参数")
                        .build();
            } else {
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("第【%s】行的日期解析失败，请检查参数", i)
                        .build();
            }

        }
        return sdf.format(afterDate);
    }

    @Override
    public MesWorkOrderExt getWorkOrderExtByOrderNo(String organizeCode, String orderNo) {
        if (StringUtils.isEmpty(organizeCode) || StringUtils.isEmpty(orderNo) ) {
            return null;
        }
        return workOrderExtRepository.getByProperty(
                new String[]{MesPcnExtConstWords.ORGANIZE_CODE, MesPcnExtConstWords.IS_DELETED, MesPcnExtConstWords.IS_VALID, MesPcnExtConstWords.ORDER_NO},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue(), orderNo});
    }

    @Override
    public MesWorkOrder getWorkOrderByOrderNo(String organizeCode, String orderNo) {
        if (StringUtils.isEmpty(organizeCode) || StringUtils.isEmpty(orderNo) ) {
            return null;
        }
        return workOrderRepository.getByProperty(
                new String[]{MesPcnExtConstWords.ORGANIZE_CODE, MesPcnExtConstWords.IS_DELETED, MesPcnExtConstWords.IS_VALID, MesPcnExtConstWords.ORDER_NO},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue(), orderNo});
    }

    @Override
    public List<MesWorkOrderExt> getWorkOrderListByCenterAndStatus(String organizeCode, String workCenterCode, Integer workOrderStatus) {
        if (StringUtils.isEmpty(organizeCode) || StringUtils.isEmpty(workCenterCode) || StringUtils.isEmpty(workOrderStatus)) {
            return null;
        }
        return workOrderExtRepository.findByProperty(
                new String[]{MesPcnExtConstWords.ORGANIZE_CODE, MesPcnExtConstWords.IS_DELETED, MesPcnExtConstWords.IS_VALID,
                        MesPcnExtConstWords.WORK_CENTER_CODE, MesPcnExtConstWords.WORK_ORDER_STATUS},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue(),
                        workCenterCode, workOrderStatus}, "order by seq asc");
    }

    @Override
    public List<MesWorkOrderExt> getWorkOrderListByCenterAndStatusOrderByStartTime(String organizeCode, String workCenterCode, Integer workOrderStatus) {
        if (StringUtils.isEmpty(organizeCode) || StringUtils.isEmpty(workCenterCode) || StringUtils.isEmpty(workOrderStatus)) {
            return null;
        }
        return workOrderExtRepository.findByProperty(
                new String[]{MesPcnExtConstWords.ORGANIZE_CODE, MesPcnExtConstWords.IS_DELETED, MesPcnExtConstWords.IS_VALID,
                        MesPcnExtConstWords.WORK_CENTER_CODE, MesPcnExtConstWords.WORK_ORDER_STATUS},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue(),
                        workCenterCode, workOrderStatus}, "order by startTime desc");
    }

    @Override
    public void saveSnCreateStatus(MesWorkOrderExt workOrder, String userName, Integer snCreateStatus) {
        workOrder.setSnCreateStatus(snCreateStatus);
        ConvertBean.serviceModelUpdate(workOrder, userName);
        workOrder.setSystemSyncStatus(MesPcnExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
        new ConvertBeanExt(workOrder).convertBean(workOrder);
        workOrderExtRepository.save(workOrder);
//        insertMesWorkOrderLog(workOrder);
    }

    @Override
    public void saveSnCreateStatusNewRequires(MesWorkOrderExt workOrder, String userName, Integer snCreateStatus) {
        saveSnCreateStatus(workOrder, userName, snCreateStatus);
    }

    @Override
    public ListPager queryWindowWorkOrderExtListPage(WorkOrderQueryDto workOrderQueryDto, Pager pager) {
        DdlPackBean hqlPack = MesPcnExtHqlPack.getWindowWorkOrderExt(workOrderQueryDto);
        if (StringUtils.isEmpty(workOrderQueryDto.getOrderByParam())) {
            DdlPreparedPack.getOrderByPack(new Object[]{MesEnumUtil.ASC_OR_DESC.ASC.getValue()}, new String[]{MesPcnExtConstWords.SEQ}, hqlPack);
        } else {
            if (workOrderQueryDto.getOrderByParam().equals(MesPcnExtConstWords.SEQ) ||
                    workOrderQueryDto.getOrderByParam().equals(MesPcnExtConstWords.START_TIME)  ||
                    workOrderQueryDto.getOrderByParam().equals(MesPcnExtConstWords.ORDER_NO) ) {
                DdlPreparedPack.getOrderByPack(new Object[]{workOrderQueryDto.getAscOrDesc()}, new String[]{workOrderQueryDto.getOrderByParam()}, hqlPack);
            } else {
                DdlPreparedPack.getOrderByPack(new Object[]{workOrderQueryDto.getAscOrDesc(), MesEnumUtil.ASC_OR_DESC.ASC.getValue()},
                        new String[]{workOrderQueryDto.getOrderByParam(), MesPcnExtConstWords.SEQ}, hqlPack);
            }
        }
        pager = PagerHelper.getPager(pager, workOrderExtRepository.findByHqlWhereCount(hqlPack));
        List<MesWorkOrderExt> workOrderExtList = workOrderExtRepository.findByHqlWherePage(hqlPack, pager);
        List<WorkOrderPageVo> resultList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(workOrderExtList)) {
            for (MesWorkOrderExt workOrderExt : workOrderExtList) {
                if (null == workOrderExt) {
                    continue;
                }
                WorkOrderPageVo result = new WorkOrderPageVo();
                BeanUtils.copyProperties(workOrderExt, result);

                result.setWorkOrderStatusName(MesPcnExtEnumUtil.WORK_ORDER_STATUS.valueOfDescription(workOrderExt.getWorkOrderStatus()));
                result.setWorkOrderTypeName(MesPcnExtEnumUtil.WORK_ORDER_TYPE.valueOfDescription(workOrderExt.getWorkOrderType()));
                resultList.add(result);
            }
        }
        return new ListPager(resultList, pager);
    }

    @Override
    public ListPager queryBuWindowWorkOrderExtListPage(WorkOrderQueryDto workOrderQueryDto, Pager pager) {
        DdlPackBean hqlPack = MesPcnExtHqlPack.getWindowWorkOrderExt(workOrderQueryDto);
        if (StringUtils.isEmpty(workOrderQueryDto.getOrderByParam())) {
            DdlPreparedPack.getOrderByPack(new Object[]{MesEnumUtil.ASC_OR_DESC.DESC.getValue()}, new String[]{MesPcnExtConstWords.MODIFY_DATE_TIME}, hqlPack);
        } else {
            DdlPreparedPack.getOrderByPack(new Object[]{workOrderQueryDto.getAscOrDesc()}, new String[]{workOrderQueryDto.getOrderByParam()}, hqlPack);
        }
        pager = PagerHelper.getPager(pager, workOrderExtRepository.findByHqlWhereCount(hqlPack));
        List<MesWorkOrderExt> workOrderExtList = workOrderExtRepository.findByHqlWherePage(hqlPack, pager);
        List<WorkOrderPageVo> resultList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(workOrderExtList)) {
            for (MesWorkOrderExt workOrderExt : workOrderExtList) {
                if (null == workOrderExt) {
                    continue;
                }
                WorkOrderPageVo result = new WorkOrderPageVo();
                BeanUtils.copyProperties(workOrderExt, result);

                result.setWorkOrderStatusName(MesPcnExtEnumUtil.WORK_ORDER_STATUS.valueOfDescription(workOrderExt.getWorkOrderStatus()));
                result.setWorkOrderTypeName(MesPcnExtEnumUtil.WORK_ORDER_TYPE.valueOfDescription(workOrderExt.getWorkOrderType()));
                resultList.add(result);
            }
        }
        return new ListPager(resultList, pager);
    }

    @Override
    public MesWorkOrder getFirstOpenedRemadeWorkOrderByWorkCenterCode(String organizeCode, String workCenterCode) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getStringEqualPack(workCenterCode, MesPcnExtConstWords.WORK_CENTER_CODE, packBean);
        DdlPreparedPack.getNumEqualPack(MesPcnExtEnumUtil.WORK_ORDER_STATUS.OPEN.getValue(), MesPcnExtConstWords.WORK_ORDER_STATUS, packBean);
        DdlPreparedPack.getNumEqualPack(MesPcnExtEnumUtil.WORK_ORDER_TYPE.REWORK_ORDER.getValue(), MesPcnExtConstWords.WORK_ORDER_TYPE, packBean);
        DdlPreparedPack.getOrderByPack(new Object[]{MesEnumUtil.ASC_OR_DESC.ASC.getValue()}, new String[]{MesPcnExtConstWords.SEQ}, packBean);
        return workOrderRepository.getByProperty(packBean);
    }

    @Override
    public void packageSnUnbind(String packageSn, String organizeCode, String userName) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getStringEqualPack(packageSn, MesPcnExtConstWords.PACKAGENO, packBean);
        MesPackageExt mesPackageExt = packageExtRepository.getByProperty(packBean);
        if(mesPackageExt == null){
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("包装条码[%s]不存在",packageSn)
                    .build();
        }

        mesPackageExt.setIsValid(MesPcnExtEnumUtil.IS_VAILD.INVAILD.getValue());
        ConvertBean.serviceModelUpdate(mesPackageExt, userName);
        new ConvertBeanExt(mesPackageExt).convertBean(mesPackageExt);
        packageExtRepository.save(mesPackageExt);

        packBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getStringEqualPack(mesPackageExt.getWorkOrderNo(), MesPcnExtConstWords.ORDER_NO, packBean);
        MesWorkOrder workOrder = workOrderRepository.getByProperty(packBean);

        //修改工单完成数量
        workOrder.setCompleteQty(workOrder.getCompleteQty() - mesPackageExt.getQty());
        workOrderRepository.save(workOrder);

        //进行包装条码记录
        MesPackageRecord packageRecord = new MesPackageRecord();
        BeanUtils.copyProperties(mesPackageExt,packageRecord);
        ConvertBean.serviceModelInitialize(packageRecord, userName);
        packageRecordRepository.insert(packageRecord);

    }

    @Override
    public List<MesWorkOrder> queryMesWorkOrderByOrderNoList(List<String> workOrderNoList, String organizeCode) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getInPackList(workOrderNoList, MesPcnExtConstWords.ORDER_NO, packBean);
        return workOrderRepository.findByHqlWhere(packBean);
    }
}
