package cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.busi.bu.bu3;

import cn.estsh.i3plus.ext.mes.pcn.api.base.ISxPcnHttpService;
import cn.estsh.i3plus.ext.mes.pcn.api.base.ISxWorkOrderExtService;
import cn.estsh.i3plus.ext.mes.pcn.api.base.IWorkOrderStartService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.IWorkOrderLogExtService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.bu3.ISxBuWorkOrderExtService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.bu3.ISxUnbindProduceSnService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.*;
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.ext.mes.pcn.pojo.util.SxDateRangeUtils;
import cn.estsh.i3plus.mes.pcn.util.PcnHttpUtil;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.exception.ImppExceptionEnum;
import cn.estsh.i3plus.platform.common.tool.JsonUtilTool;
import cn.estsh.i3plus.platform.common.tool.TimeTool;
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.MesPackageDetail;
import cn.estsh.i3plus.pojo.mes.bean.MesWorkOrderLog;
import cn.estsh.i3plus.pojo.mes.repository.MesPackageDetailRepository;
import cn.estsh.impp.framework.boot.auth.AuthUtil;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import cn.estsh.impp.framework.boot.util.SpringContextsUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
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.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

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

    @Autowired
    private ISxWorkOrderExtService sxWorkOrderExtService;

    @Autowired
    private ISxUnbindProduceSnService unbindProduceSnService;

    @Autowired
    private MesWorkOrderExtRepository workOrderExtRepository;

    @Autowired
    private IWorkOrderLogExtService workOrderLogExtService;

    @Autowired
    private MesAffiliatedStartConfigRepository affiliatedStartConfigRepository;

    @Autowired
    private ISxPcnHttpService pcnHttpService;

    @Autowired
    private MesProdBindRecordExtRepository prodBindRecordExtRepository;

    @Autowired
    private MesPackageExtRepository packageExtRepository;

    @Autowired
    private MesBusiConfigRepository busiConfigRepository;

    @Autowired
    private MesProduceSnRepairRepository produceSnRepairRepository;

    @Autowired
    private MesProduceSnExtRepository produceSnExtRepository;

    @Autowired
    private MesPackageDetailRepository packageDetailRepository;

    @Autowired
    private MesReworkOrderRepository reworkOrderRepository;


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

    /**
     * 生产工单状态批量调整
     *
     * @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 = sxWorkOrderExtService.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();
                }
            }
        }

        MesBusiConfig waterPurifierCode = busiConfigRepository.getByProperty(
                new String[]{MesPcnExtConstWords.ORGANIZE_CODE, MesPcnExtConstWords.IS_DELETED, MesPcnExtConstWords.IS_VALID, MesPcnExtConstWords.CFG_CODE},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue(), MesPcnExtConstWords.WATER_PURIFIER_CODE});
        // 一个工单号下的多个工单
        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 = sxWorkOrderExtService.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 (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();
                }
            } 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);
        }

    }

    @Override
    public ListPager<MesUnbindProduceSn> queryMesUnbindSnByPager(MesUnbindProduceSn produceSn, Pager pager) {
        produceSn.setBindStatus(MesPcnExtEnumUtil.BIND_STATUS.UNBIND.getValue());
        if (!StringUtils.isEmpty(produceSn.getStartTimeStart()) && !StringUtils.isEmpty(produceSn.getStartTimeEnd())) {
            produceSn.setCreateDateTimeStart(produceSn.getStartTimeStart());
            produceSn.setCreateDateTimeEnd(produceSn.getStartTimeEnd());
        } else {
            String curMonth = TimeTool.getNowTime(MesPcnExtConstWords.DATE_FORMAT_YM);
            produceSn.setStartTimeStart(curMonth + MesPcnExtConstWords.APPEND_ONE_DAY_ZERO_HH_MM_SS);
            produceSn.setStartTimeStart(SxDateRangeUtils.getLastDayTimeOfMonth(curMonth));
        }
        return unbindProduceSnService.queryUnbindProduceSnByPager(produceSn, pager);
    }

    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);
    }
}
