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.*;
import cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.print.IPrintTemplateStrategyService;
import cn.estsh.i3plus.ext.mes.pcn.apiservice.util.MesPcnException;
import cn.estsh.i3plus.ext.mes.pcn.pojo.context.MesProductionAssemblyContext;
import cn.estsh.i3plus.ext.mes.pcn.pojo.context.MesProductionAssemblyNosortContext;
import cn.estsh.i3plus.ext.mes.pcn.pojo.context.MesProductionAssemblySortContext;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.MesPartModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.MesProduceSnPrintModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.MesReworkTaskModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.MesReworkTaskRequestModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.mes.pcn.api.iservice.busi.ISyncFuncService;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.tool.TimeTool;
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.tool.DdlPreparedPack;
import cn.estsh.i3plus.pojo.base.util.StringUtil;
import cn.estsh.i3plus.pojo.mes.bean.*;
import cn.estsh.i3plus.pojo.mes.bean.nc.MesPartInspection;
import cn.estsh.i3plus.pojo.mes.bean.nc.MesPartInspectionDetail;
import cn.estsh.i3plus.pojo.mes.bean.rework.MesReworkTask;
import cn.estsh.i3plus.pojo.mes.bean.rework.MesReworkTaskDetail;
import cn.estsh.i3plus.pojo.mes.model.GenSerialNoModel;
import cn.estsh.i3plus.pojo.mes.model.MesProductionAssemblyModel;
import cn.estsh.i3plus.pojo.mes.repository.*;
import cn.estsh.i3plus.pojo.mes.util.MesExtEnumUtil;
import cn.estsh.impp.framework.boot.auth.AuthUtil;
import cn.estsh.impp.framework.boot.exception.ImppBusiException;
import cn.estsh.impp.framework.boot.util.ResultBean;
import cn.estsh.impp.framework.boot.util.SpringContextsUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;


/**
 * @Description: 查询返工单
 * @Author: zxw
 * @Date: 2024/5/21 14:16
 * @Modify:
 */
@Service
@Slf4j
public class MesReworkTaskServiceImpl implements IMesReworkTaskService {

    private static final Logger LOGGER = LoggerFactory.getLogger(MesReworkTaskServiceImpl.class);


    @Autowired
    private MesReworkTaskRepository mesReworkTaskRepository;

    @Autowired
    private MesPartTypePictureRepository mesPartTypePictureRepository;

    @Autowired
    private MesPartRepository mesPartRepository;

    @Autowired
    private MesPartInspectionRepository mesPartInspectionRepository;

    @Autowired
    private MesPartInspectionDetailRepository mesPartInspectionDetailRepository;

    @Autowired
    private MesReworkTaskDetailRepository mesReworkTaskDetailRepository;

    @Autowired
    private MesProductionAssemblyRepository mesProductionAssemblyRepository;

    @Autowired
    private MesProduceSnRepository mesProduceSnRepository;

    @Autowired
    private IMesTemplateService mesTemplateService;

    @Autowired
    private ISyncFuncService syncFuncService;

    @Autowired
    private IMesPartService mesPartService;

    @Autowired
    private MesMoveRepository moveRepository;

    @Autowired
    private MesProductionRecordRepository mesProductionRecordRepository;

    @Autowired
    private IMesProdOrgExtService prodOrgExtService;

    @Autowired
    private IMesNumberRuleMatchDispatchService numberRuleMatchDispatchService;

    @Autowired
    private IMesProduceSnExtService produceSnExtService;

    @Autowired
    private IMesAssemblyExtService mesAssemblyExtService;

    @Autowired
    private MesProductionAssemblyUniqueRepository mesProductionAssemblyUniqueRepository;

    @Autowired
    private IMesConfigService mesConfigService;

    @Autowired
    private IMesProductionRecordService mesProductionRecordService;

    @Autowired
    private IMesWorkOrderService mesWorkOrderService;

    @Autowired
    private IMesProductVersionService mesProductVersionService;

    @Autowired
    private MesQmsScrapRepository mesQmsScrapRepository;

    @Autowired
    private IMesWorkOrderExtService workOrderExtService;

    @Autowired
    private MesWorkOrderRepository workOrderRepository;

    @Autowired
    private MesProductVersionRepository productVersionRepository;

    @Autowired
    private MesProductionRecordRepository productionRecordRepository;

    @Autowired
    private IMesMoveRuleRepository mesMoveRuleRepository;

    @Autowired
    private MesWorkOrderPartRepository workOrderPartRepository;

    @Autowired
    private MesPartProdGroupRepository mesPartProdGroupRao;

    @Autowired
    private IMesEquipmentExtService equipmentExtService;

    @Override
    public ListPager<MesReworkTask> queryReworkTask(MesReworkTask mesReworkTask, Pager pager) {
        String organizeCode = !StringUtils.isEmpty(mesReworkTask.getOrganizeCode())?mesReworkTask.getOrganizeCode():AuthUtil.getOrganizeCode();
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        if (mesReworkTask.getSn() != null) {
            MesProduceSn produceSn = (MesProduceSn) workOrderExtService.getWorkOrderSort(organizeCode, mesReworkTask.getSn(), false);
            if(!StringUtil.isEmpty(produceSn)){
                DdlPreparedPack.getStringEqualPack(produceSn.getProductSn(), "sn", packBean);
            }else {
                DdlPreparedPack.getStringEqualPack(mesReworkTask.getSn(), "sn", packBean);
            }
        }
        DdlPreparedPack.getStringEqualPack(mesReworkTask.getReworkOrder(), "reworkOrder", packBean);
        DdlPreparedPack.getNumEqualPack(MesExtEnumUtil.REWORK_TASK_STATUS.CREATE.getValue(), "status", packBean);
        DdlPreparedPack.getOrderByPack(new Object[]{CommonEnumUtil.ASC_OR_DESC.DESC.getValue()}, new String[]{"createDatetime"}, packBean);

        pager = PagerHelper.getPager(pager, mesReworkTaskRepository.findByHqlWhereCount(packBean));

        List<MesReworkTask> resultList = mesReworkTaskRepository.findByHqlWherePage(packBean, pager);

        return new ListPager<>(resultList, pager);
    }


    @Override
    public MesReworkTaskModel queryReworkTaskModel(MesReworkTaskRequestModel requestModel){
        /**
         * 获取返工单信息
         */
        MesReworkTask res = getMesReworkTask(requestModel);

        /**
         * 获取返工单信息
         */
        List<MesReworkTaskDetail> reworkTaskDetails = getMesReworkTaskDetail(res);
        /**
         * 获取零件图片信息
         */
        MesPartTypePicture mesPartTypePicture = getMesPartTypePicture(res);
        /**
         * 获取缺陷记录
         */
        MesPartInspection mesPartInspection = getMesPartInspection(res);

        List<MesPartInspectionDetail> mesPartInspectionDetails = null;
        if (!CollectionUtils.isEmpty(reworkTaskDetails)) {
            /**
             * 获取零件缺陷明细列表
             */
            mesPartInspectionDetails = getMesPartInspectionDetail(reworkTaskDetails);
        }
        /**
         * 组装返回信息
         */
        MesReworkTaskModel mesReworkTaskModel = MesReworkTaskModel.builder()
                .mesReworkTask(res)
                .reworkOrder(res.getReworkOrder())
                .sn(res.getSn())
                .mesPartTypePicture(mesPartTypePicture)
                .mesPartInspection(mesPartInspection)
                .mesPartInspectionDetails(mesPartInspectionDetails)
                .centerType(StringUtils.isEmpty(requestModel.getCenterType()) ? MesExtEnumUtil.WORK_CENTER_TYPE.NOSORT.getValue() : requestModel.getCenterType())
                .build();


        return mesReworkTaskModel;
    }

    @Override
    public void reworkRecord(long detailId,String userName,String organizeCode) {

        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getNumEqualPack(detailId, "partInspectionDetailId", packBean);

        List<MesReworkTaskDetail> mesReworkTaskDetailList = mesReworkTaskDetailRepository.findByHqlWhere(packBean);
        if (CollectionUtils.isEmpty(mesReworkTaskDetailList)) {
            MesPcnException.throwMesBusiException("返工单详情不存在");
        }
        mesReworkTaskDetailList.forEach(mesReworkTaskDetail->{
            mesReworkTaskDetail.setStatus(MesExtEnumUtil.REWORK_TASK_DETAIL_STATUS.REWORK_TASK_DETAIL_STATUS_20.getValue());
            ConvertBean.serviceModelUpdate(mesReworkTaskDetail,userName);
        });
        mesReworkTaskDetailRepository.saveAll(mesReworkTaskDetailList);

    }


    @Override
    public List<MesProductionAssembly> assemblyQuery(MesReworkTaskRequestModel requestModel) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(requestModel.getOrganizeCode());
        DdlPreparedPack.getStringEqualPack(requestModel.getCustSn(), "custSn", packBean);
        DdlPreparedPack.getNumEqualPack(requestModel.getIsOrigSn(), "isOrigSn", packBean);

        //DdlPreparedPack.getStringEqualPack(requestModel.getPartNo(), "partNo", packBean);
        if (!StringUtils.isEmpty(requestModel.getAssemblyPartNo())) {
            DdlPreparedPack.getStringEqualPack(requestModel.getAssemblyPartNo(), "assemblyPartNo", packBean);
        }
        if (!Objects.isNull(requestModel.getAssemblyPartStatus())) {
            DdlPreparedPack.getNumEqualPack(requestModel.getAssemblyPartStatus(), "assemblyStatus", packBean);
        }

        List<MesProductionAssembly> mesProductionAssemblies = mesProductionAssemblyRepository.findByHqlWhere(packBean);
        if (CollectionUtils.isEmpty(mesProductionAssemblies)) {
            MesPcnException.throwFlowException("装配件信息不存在");
        }
        //装配件是自制件，查询自制件经过的装配件记录
        recursionAssemblySn(mesProductionAssemblies,requestModel);

        return mesProductionAssemblies;
    }

    @Override
    public List<MesProductionAssemblyModel> queryAssemblyTree(MesReworkTaskRequestModel requestModel) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(requestModel.getOrganizeCode());
        DdlPreparedPack.getStringEqualPack(requestModel.getCustSn(), "custSn", packBean);
        DdlPreparedPack.getStringEqualPack(requestModel.getAssemblyPartNo(), "assemblyPartNo", packBean);
        DdlPreparedPack.getNumEqualPack(MesExtEnumUtil.ASSEMBLY_STATUS.ASSEMBLY_STATUS_10.getValue(), "assemblyStatus", packBean);

        List<MesProductionAssembly> mesProductionAssemblies = mesProductionAssemblyRepository.findByHqlWhere(packBean);
        if (CollectionUtils.isEmpty(mesProductionAssemblies)) {
            MesPcnException.throwFlowException("装配件信息不存在");
        }
        //查询装配树
        List<MesProductionAssemblyModel> assemblyTree = parseArray(mesProductionAssemblies);
        recursionAssemblySnTree(assemblyTree, requestModel,-1);
        return assemblyTree;
    }

    @Override
    public void doReworkSuccess(MesReworkTaskRequestModel requestModel) {

        MesReworkTask mesReworkTask = getMesReworkTask(requestModel);

        /**
         * 获取返工单信息
         */
        List<MesReworkTaskDetail> reworkTaskDetails = getMesReworkTaskDetail(mesReworkTask);
        if (!CollectionUtils.isEmpty(reworkTaskDetails)) {
            MesPcnException.throwFlowException("还有位置未返工完成,请检查");
        }
        MesPartInspection mesPartInspection = null;
        if (!StringUtils.isEmpty(mesReworkTask.getId())){
            DdlPackBean packBean = DdlPackBean.getDdlPackBean(mesReworkTask.getOrganizeCode());
            DdlPreparedPack.getNumEqualPack(mesReworkTask.getId(), "reworkTaskId", packBean);
            mesPartInspection = mesPartInspectionRepository.getByProperty(packBean);
            if (!Objects.isNull(mesPartInspection)){
                if(!CollectionUtils.isEmpty(requestModel.getAssemblyModelList())){
                    mesPartInspection.setNcStatus(MesExtEnumUtil.PART_INSPECTION_NC_STATUS.DISASSEMBLY.getValue());
                }
                mesPartInspection.setQmsSync(CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue());
                /**
                 * 修复bug 44178 不要修改NC判定人
                 */
//                ConvertBean.serviceModelUpdate(mesPartInspection, requestModel.getUserName());
                mesPartInspectionRepository.update(mesPartInspection);
            }
            // 是否头零件模式
            boolean headModel = true;
            if (!StringUtil.isEmpty(requestModel.getSn())) {
                // 判断是头零件还是散件   查询加工记录
                DdlPackBean productionPackBean = DdlPackBean.getDdlPackBean(mesReworkTask.getOrganizeCode());
                DdlPreparedPack.getStringEqualPack(requestModel.getSn(), "productSn", productionPackBean);
                DdlPreparedPack.getNumNOEqualPack(MesExtEnumUtil.REPORT_STATUS.REPORT_STATUS_30.getValue(), "reportStatus", productionPackBean);
                DdlPreparedPack.getNumEqualPack(MesExtEnumUtil.MES_REPORT_TYPE.CUSTOMER_SUPPLY_MOVE.getValue(), "reportType", productionPackBean);
                MesProductionRecord record = productionRecordRepository.getByProperty(productionPackBean);
                if (record != null) {
                    headModel = false;
                }
            }
            // 如果是散件模式，需要查询出对应明细
            List<MesPartModel> mesPartModels = new ArrayList<>();
            if (!headModel) {
                DdlPackBean partPackBean = DdlPackBean.getDdlPackBean(mesReworkTask.getOrganizeCode());
                DdlPreparedPack.getStringEqualPack(requestModel.getSn(), "workOrderNo", partPackBean);
                List<MesWorkOrderPart> workOrderParts = workOrderPartRepository.findByHqlWhere(partPackBean);
                if (!CollectionUtils.isEmpty(workOrderParts)) {
                    DdlPackBean partProdBean = DdlPackBean.getDdlPackBean(mesReworkTask.getOrganizeCode());
                    DdlPreparedPack.getStringEqualPack(mesPartInspection.getWorkCenterCode(), "workCenterCode", partProdBean);
                    List<MesPartProdGroup> mesPartProdGroupList = mesPartProdGroupRao.findByHqlTopWhere(partProdBean, 1);
                    for (MesWorkOrderPart workOrderPart : workOrderParts) {
                        MesPart partInfo = mesPartService.getMesPartByPartNo(workOrderPart.getPartNo(), mesReworkTask.getOrganizeCode());
                        String esd = partInfo.getEsd();

                        // 查询移库规则
                        DdlPackBean movePackBean = DdlPackBean.getDdlPackBean(mesReworkTask.getOrganizeCode());
                        DdlPreparedPack.getStringEqualPack(esd, "srcType", movePackBean);
                        DdlPreparedPack.getStringEqualPack(mesPartProdGroupList.get(0).getPartProdGroupCode(), "code", movePackBean);
                        List<MesMoveRule> moveRules = mesMoveRuleRepository.findByHqlWhere(movePackBean);
                        if (!CollectionUtils.isEmpty(moveRules)) {
                            MesPartModel mesPartModel = new MesPartModel();
                            mesPartModel.setPartNo(workOrderPart.getPartNo());
                            mesPartModel.setLocateNo(moveRules.get(0).getErpDestLocateNo());
                            mesPartModels.add(mesPartModel);
                        }
                    }
                }
            }



            String  target = mesConfigService.getCfgValue(requestModel.getOrganizeCode(), "UMLGO");
            String workCenterCode = "";
            if (mesPartInspection != null) {
                workCenterCode = mesPartInspection.getWorkCenterCode();
                requestModel.setSn(mesPartInspection.getSn());
            }
            requestModel.setReworkedQty(mesReworkTask.getQty());
            if (MesExtEnumUtil.NC_TYPE.REWORK.getValue() == requestModel.getType()) {
                if (!headModel && !CollectionUtils.isEmpty(mesPartModels) && mesPartModels.size() > 0) {
                    String destLocateNo = getDestLocateNo(requestModel.getOrganizeCode(), mesPartInspection.getId());
                    for (MesPartModel mesPartModel : mesPartModels) {
                        doCreateReworkMove(requestModel,destLocateNo, target, workCenterCode, mesPartModel.getPartNo(), mesPartInspection.getId());
                    }
                } else {
                    doCreateReworkMove(requestModel, getDestLocateNo(requestModel.getOrganizeCode(), mesPartInspection.getId()), target, workCenterCode, mesReworkTask.getPartNo(), mesPartInspection.getId());
                }
            }
        }
        if (MesExtEnumUtil.PART_INSPECTION_SOURCE_TYPE.LOT.getValue() == mesReworkTask.getType()) {
            mesReworkTask.setReworkedQty(requestModel.getReworkedQty());
            mesReworkTask.setScrapQty(requestModel.getScrapQty());
            // 如果是批次还需要移库
            DdlPackBean ddlPackBean = DdlPackBean.getDdlPackBean(mesReworkTask.getOrganizeCode());
            DdlPreparedPack.getStringEqualPack(requestModel.getPartNo(), "partNo", ddlPackBean);

            MesProductVersion version = productVersionRepository.getByProperty(ddlPackBean);
            String  target = mesConfigService.getCfgValue(requestModel.getOrganizeCode(), "LGORT");
            if (version != null) {
                target = version.getReceiveInventoryPoint();
            }
            String workCenterCode = "";
            // 获取替换条码信息列表

            if (mesPartInspection != null) {
                workCenterCode = mesPartInspection.getWorkCenterCode();
            }
            doCreateReworkMove(requestModel,getDestLocateNo(requestModel.getOrganizeCode(), mesPartInspection.getId()),target,workCenterCode,mesReworkTask.getPartNo(), mesPartInspection.getId());

        } else {
            //拆解
            if(!CollectionUtils.isEmpty(requestModel.getAssemblyModelList())){
                doAssemblyDisassembly(requestModel, mesReworkTask.getSn(),Objects.isNull(mesPartInspection)?"":mesPartInspection.getResponsibleParty());
            }

            if (MesExtEnumUtil.NC_TYPE.REWORK.getValue() == requestModel.getType()) {
                mesReworkTask.setReworkedQty(mesReworkTask.getQty());
            } else if (MesExtEnumUtil.NC_TYPE.SCRAP.getValue() == requestModel.getType()) {
                //更新条码状态为报废
                requestModel.setSn(mesReworkTask.getSn());
                updateMesProduceSn(requestModel);
                //更新返工数量
                mesReworkTask.setScrapQty(mesReworkTask.getQty());
            }
        }

        mesReworkTask.setStatus(MesExtEnumUtil.REWORK_TASK_STATUS.FINISH.getValue());
        ConvertBean.serviceModelUpdate(mesReworkTask,requestModel.getUserName());
        mesReworkTaskRepository.save(mesReworkTask);
    }

    @Override
    public void doSortOrderDismantle(MesReworkTaskRequestModel requestModel) {

        DdlPackBean packBean = DdlPackBean.getDdlPackBean(requestModel.getOrganizeCode());
        DdlPreparedPack.getStringEqualPack(requestModel.getReworkOrder(), MesPcnExtConstWords.REWORK_ORDER, packBean);
        DdlPreparedPack.getNumEqualPack(MesExtEnumUtil.REWORK_TASK_STATUS.CREATE.getValue(), MesPcnExtConstWords.STATUS, packBean);
        MesReworkTask reworkTask = mesReworkTaskRepository.getByProperty(packBean);
        if (null == reworkTask) MesPcnException.throwBusiException(String.format("返工单[%s]信息不存在!", requestModel.getReworkOrder()));

        MesProduceSn produceSn = (MesProduceSn) workOrderExtService.getWorkOrderSort(requestModel.getOrganizeCode(), reworkTask.getSn(), false);
        if (null == produceSn) MesPcnException.throwBusiException(String.format("返工单[%s]关联的条码[%s]信息不存在!", requestModel.getReworkOrder(), reworkTask.getSn()));

        MesWorkOrder workOrder = workOrderExtService.getWorkOrder(requestModel.getOrganizeCode(), produceSn.getWorkOrderNo());
        if (null == produceSn) MesPcnException.throwBusiException(String.format("返工单[%s]关联的条码[%s]对应的加工单[%s]信息不存在!", requestModel.getReworkOrder(), reworkTask.getSn(), produceSn.getWorkOrderNo()));
        
        if (workOrder.getWorkOrderStatus().compareTo(MesExtEnumUtil.ORDER_STATUS.DISMANTLE.getValue()) == 0)
            MesPcnException.throwBusiException(String.format("返工单[%s]关联的条码[%s]对应的加工单[%s]信息当前状态已为[%s]!",
                    requestModel.getReworkOrder(), reworkTask.getSn(), produceSn.getWorkOrderNo(), MesExtEnumUtil.ORDER_STATUS.valueOfDescription(workOrder.getWorkOrderStatus())));

        //修改返工表状态为完成
        reworkTask.setStatus(MesExtEnumUtil.REWORK_TASK_STATUS.FINISH.getValue());
        ConvertBean.serviceModelUpdate(reworkTask, requestModel.getUserName());
        reworkTask.setSystemSyncStatus(CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue());
        mesReworkTaskRepository.updateNoSync(reworkTask);

        //修改NC-零件检测-单据表 NC状态为拆解; qmsSync状态是否变更待确认
        packBean = DdlPackBean.getDdlPackBean(requestModel.getOrganizeCode());
        DdlPreparedPack.getNumEqualPack(reworkTask.getId(), MesPcnExtConstWords.REWORK_TASK_ID, packBean);
        mesPartInspectionRepository.updateByPropertiesNoSync(
                new String[]{MesPcnExtConstWords.MODIFY_USER, MesPcnExtConstWords.MODIFY_DATE_TIME, MesPcnExtConstWords.SYSTEM_SYNC_STATUS, MesPcnExtConstWords.NC_STATUS},
                new Object[]{requestModel.getUserName(), TimeTool.getNowTime(true), CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), MesExtEnumUtil.PART_INSPECTION_NC_STATUS.DISASSEMBLY.getValue()},
                packBean);

        //修改工单状态为已拆解
        workOrder.setWorkOrderStatus(MesExtEnumUtil.ORDER_STATUS.DISMANTLE.getValue());
        workOrder.setModifyUser(requestModel.getUserName());
        workOrder.setModifyDatetime((new SimpleDateFormat(MesPcnExtConstWords.DATE_FORMAT_SSS)).format(new Date()));
        workOrder.setSystemSyncStatus(CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue());
        workOrderRepository.updateNoSync(workOrder);

        //修改条码状态为总成拆解
        packBean = DdlPackBean.getDdlPackBean(requestModel.getOrganizeCode());
        DdlPreparedPack.getStringEqualPack(produceSn.getProductSn(), MesPcnExtConstWords.PRODUCT_SN, packBean);
        DdlPreparedPack.getStringEqualPack(produceSn.getWorkOrderNo(), MesPcnExtConstWords.WORK_ORDER_NO, packBean);
        produceSnExtService.saveProduceSnStatusByDdlPackBean(packBean, requestModel.getUserName(), MesExtEnumUtil.PRODUCE_SN_STATUS.ASSEMBLY_DISASSEMBLY.getValue());

        //查询装配件绑定记录表
        List<MesProductionAssembly> productionAssemblyList = mesAssemblyExtService.getProductionAssemblySortList(requestModel.getOrganizeCode(), workOrder.getWorkOrderNo());
        productionAssemblyList = CollectionUtils.isEmpty(productionAssemblyList) ? null :
                productionAssemblyList.stream().filter(o -> (null != o && o.getAssemblyStatus().compareTo(MesExtEnumUtil.ASSEMBLY_STATUS.ASSEMBLY_STATUS_20.getValue()) != 0)).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(productionAssemblyList)) return;

        //将自制件类型的装配件对应的零件条码状态改成已拆解
        for (MesProductionAssembly productionAssembly : productionAssemblyList) {
            if (null == productionAssembly) continue;
            if (productionAssembly.getMatchType().compareTo(MesExtEnumUtil.ASSEMBLY_MATCH_TYPE.MATCH_TYPE_10.getValue()) != 0) continue;
            if (StringUtils.isEmpty(productionAssembly.getAssemblySn()) || StringUtils.isEmpty(productionAssembly.getAssemblyPartNo())) continue;
            packBean = DdlPackBean.getDdlPackBean(requestModel.getOrganizeCode());
            DdlPreparedPack.getStringEqualPack(productionAssembly.getAssemblySn(), MesPcnExtConstWords.PRODUCT_SN, packBean);
            DdlPreparedPack.getStringEqualPack(productionAssembly.getAssemblyPartNo(), MesPcnExtConstWords.PART_NO, packBean);
            DdlPreparedPack.getNumEqualPack(MesExtEnumUtil.PRODUCE_SN_STATUS.ASSEMBLY.getValue(), MesPcnExtConstWords.SN_STATUS, packBean);
            produceSnExtService.saveProduceSnStatusByDdlPackBean(packBean, requestModel.getUserName(), MesExtEnumUtil.PRODUCE_SN_STATUS.ASSEMBLY_BACK.getValue());
        }

        //将装配件绑定记录表的非解绑状态的记录改为解绑状态
        packBean = DdlPackBean.getDdlPackBean(requestModel.getOrganizeCode());
        DdlPreparedPack.getStringEqualPack(produceSn.getProductSn(), MesPcnExtConstWords.PRODUCT_SN, packBean);
        DdlPreparedPack.getNumNOEqualPack(MesExtEnumUtil.ASSEMBLY_STATUS.ASSEMBLY_STATUS_20.getValue(), MesPcnExtConstWords.ASSEMBLY_STATUS, packBean);
        mesAssemblyExtService.saveProductionAssemblyStatusByDdlPackBean(packBean, requestModel.getUserName(), MesExtEnumUtil.ASSEMBLY_STATUS.ASSEMBLY_STATUS_20.getValue());

        //将装配件绑定唯一性记录表的非解绑状态的记录改为解绑状态;条件公用
        mesAssemblyExtService.saveProductionAssemblyUniqueStatusByDdlPackBean(packBean, requestModel.getUserName(), MesExtEnumUtil.ASSEMBLY_STATUS.ASSEMBLY_STATUS_20.getValue());

        //将工单装配件表的非解绑状态的记录改为解绑状态;条件公用,增加工单条件
        DdlPreparedPack.getStringEqualPack(produceSn.getWorkOrderNo(), MesPcnExtConstWords.WORK_ORDER_NO, packBean);
        mesAssemblyExtService.saveWorkOrderAssemblyStatusByDdlPackBean(packBean, requestModel.getUserName(), MesExtEnumUtil.ASSEMBLY_STATUS.ASSEMBLY_STATUS_20.getValue());

    }

    @Override
    public MesProduceSnPrintModel doPrint(MesReworkTaskRequestModel requestModel) {
        String organizeCode = requestModel.getOrganizeCode();
        String userName = requestModel.getUserName();

        MesReworkTask mesReworkTask = getMesReworkTask(requestModel);
        List<MesReworkTaskDetail> reworkTaskDetails = getMesReworkTaskDetail(mesReworkTask);
        if (!CollectionUtils.isEmpty(reworkTaskDetails)) {
            MesPcnException.throwFlowException("还有位置未返工完成,请检查");
        }
        MesProduceSn sn = getMesProduceSn(organizeCode,requestModel.getSn());
        //查询物料信息
        MesPart mesPart = mesPartService.getMesPartByPartNo(sn.getPartNo(), organizeCode);
        String prodLabelTemplate = sn.getProdLabelTemplate();
        if (StringUtils.isEmpty(prodLabelTemplate)) {
            MesPcnException.throwMesBusiException("零件号[%s]的模板代码[%s]的模板信息丢失,请配置!", sn.getPartNo(), prodLabelTemplate);
        }
        MesProduceSnPrintModel mesProduceSnPrintModel = new MesProduceSnPrintModel();
        // 查模板代码
        MesLabelTemplate labelTemplate = mesTemplateService.getMesLabelTemplate(prodLabelTemplate,organizeCode);
        //根据反射获取策略类--封装打印数据
        String methodCode = labelTemplate.getMethodCode();
        //模板信息丢失抛出异常
        if (methodCode == null) {
            MesPcnException.throwMesBusiException("零件号[%s]的模板代码[%s]的反射类丢失,请配置!", sn.getPartNo(), prodLabelTemplate);
        }
        mesProduceSnPrintModel.setMesLabelTemplate(labelTemplate);
        mesProduceSnPrintModel.setProductSn(sn.getProductSn());
        mesProduceSnPrintModel.setPartNo(sn.getPartNo());
        mesProduceSnPrintModel.setOrganizeCode(organizeCode);
        List<MesProduceSn> snList = new ArrayList<>();
        sn.setDescription(String.format("源条码：%s",sn.getProductSn()));
        sn.setLotNo(TimeTool.getToday());
        sn.setProductSn(doGererateSerialNo(mesPart, organizeCode, requestModel.getUserName()));
        snList.add(sn);
        mesProduceSnPrintModel.getMesProduceSnList().addAll(snList);
        //发送新老条码关系给WMS
        doCreateMove(requestModel.getSn(),sn.getProductSn(),organizeCode,requestModel.getUserName());
        //更新条码
        ConvertBean.serviceModelUpdate(sn,requestModel.getUserName());
        mesProduceSnRepository.update(sn);
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getStringEqualPack(requestModel.getSn(),"productSn",packBean);
        DdlPreparedPack.getStringEqualPack(sn.getPartNo(),"partNo",packBean);
        //更新加工记录
        mesProductionRecordRepository.updateByProperties(new String[]{"modifyUser", "modifyDatetime", "productSn", "description", "systemSyncStatus"},
                new Object[]{userName, TimeTool.getNowTime(true), sn.getProductSn(), sn.getDescription(), CommonEnumUtil.FALSE}, packBean);
        //更新装配记录
        mesProductionAssemblyRepository.updateByProperties(new String[]{"modifyUser", "modifyDatetime", "productSn", "description", "systemSyncStatus"},
                new Object[]{userName, TimeTool.getNowTime(true), sn.getProductSn(), sn.getDescription(), CommonEnumUtil.FALSE}, packBean);
        //更新返工记录
        packBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getStringEqualPack(requestModel.getSn(), "sn", packBean);
        DdlPreparedPack.getStringEqualPack(sn.getPartNo(), "partNo", packBean);
        mesReworkTaskRepository.updateByProperties(new String[]{"modifyUser", "modifyDatetime", "sn", "description", "systemSyncStatus"},
                new Object[]{userName, TimeTool.getNowTime(true), sn.getProductSn(), sn.getDescription(), CommonEnumUtil.FALSE}, packBean);
        IPrintTemplateStrategyService strategyService = (IPrintTemplateStrategyService) SpringContextsUtil.getBean(methodCode);
        return strategyService.execute(null, mesProduceSnPrintModel, null, null, null, true);
    }

    @Override
    public void doAssemblySnRepeatByScan(MesReworkTaskRequestModel requestModel) {
        boolean checkResult = true;
        //查询装配记录
        requestModel.setAssemblyPartStatus(MesExtEnumUtil.ASSEMBLY_STATUS.ASSEMBLY_STATUS_10.getValue());
        List<MesProductionAssembly> productionAssemblies = assemblyQuery(requestModel).stream().filter(t -> CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue() == t.getIsOrigSn()).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(productionAssemblies)) MesPcnException.throwFlowException("未查询到没有替换的装配件记录");
        Map<String,MesWorkCenter> mesWorkCenterMap = new HashMap<>();
        //匹配装配件
        for (MesProductionAssembly assembly : productionAssemblies) {
            Object context = getContext(requestModel, assembly, mesWorkCenterMap);
            //匹配规则
            Map<String, Object> result = numberRuleMatchDispatchService.matchNumberRule(requestModel.getOrganizeCode(), requestModel.getSn(), context);
            //匹配成功
            if ((Boolean) result.get(MesPcnExtConstWords.RESULT)){
                // 需要变更之前的记录
                assembly.setAssemblyStatus(MesExtEnumUtil.ASSEMBLY_STATUS.ASSEMBLY_STATUS_20.getValue());

                // 需要新增一条替换条码的记录
                MesProductionAssembly mesProductionRepeatAssembly = new MesProductionAssembly();
                BeanUtils.copyProperties(assembly, mesProductionRepeatAssembly,MesPcnExtConstWords.ID);
                mesProductionRepeatAssembly.setAssemblySn(requestModel.getSn());
                mesProductionRepeatAssembly.setAssemblyStatus(MesExtEnumUtil.ASSEMBLY_STATUS.ASSEMBLY_STATUS_10.getValue());
                mesProductionRepeatAssembly.setIsOrigSn(CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue());
                mesProductionRepeatAssembly.setFid(UUID .randomUUID().toString());
                ConvertBean.serviceModelInitialize(mesProductionRepeatAssembly,requestModel.getUserName());

                assembly.setRepeatAssemblySn(requestModel.getSn());
                // 原装配件记录为已解绑
                ConvertBean.serviceModelUpdate(assembly,requestModel.getUserName());
                mesProductionAssemblyRepository.update(assembly);
                // 新装配件记录为已装配
                MesProductionAssembly productionAssembly = mesProductionAssemblyRepository.insert(mesProductionRepeatAssembly);
                //唯一性校验数据更新
                if (MesExtEnumUtil.ASSEMBLY_MATCH_TYPE.MATCH_TYPE_30.getValue() == assembly.getMatchType()) {
                    saveProductionAssemblyUnique(requestModel, assembly.getAssemblySn(), productionAssembly);
                }
                //自制件更新条码状态
                if(MesExtEnumUtil.ASSEMBLY_MATCH_TYPE.MATCH_TYPE_10.getValue() == assembly.getMatchType()){
                    updateProductSn(requestModel, assembly, (MesProductionAssemblyContext) context);
                }
                checkResult = false;
                break;
            }
        }
        if(checkResult) MesPcnException.throwFlowException("装配件替换失败，未匹配到符合规则的已装配数据");
        /**
         * 需要更新NC标记后进入的表明细状态为已处理
         */
        for (String detailId : requestModel.getDetailIds().split(",")) {
            reworkRecord(Long.parseLong(detailId),requestModel.getUserName(),requestModel.getOrganizeCode());
        }
    }

    @Override
    public boolean validateSn(MesReworkTaskRequestModel requestModel) {
        //
        List<String> snList = Arrays.asList(requestModel.getSn().split(","));
        List<String> idList = Arrays.asList(requestModel.getAssemblyIds().split(","));
        // 判断数量是否一致
        if (snList.size() != idList.size()) MesPcnException.throwFlowException("选中的装配件个数和输入的个数不一致");
        // 判断顺序是否一致
        Map<String, String> map = IntStream.range(0, snList.size()).boxed().collect(Collectors.toMap(idList::get, snList::get, (a, b) -> b));
        List<Long> idLonglist = idList.stream().map(str -> Long.parseLong(str)).collect(Collectors.toList());

        DdlPackBean ddlPackBean = DdlPackBean.getDdlPackBean();
        DdlPreparedPack.getInPackList(idLonglist, "id", ddlPackBean);
        List<MesProductionAssembly> mesProductionAssemblies = mesProductionAssemblyRepository.findByHqlWhere(ddlPackBean);
        if (CollectionUtils.isEmpty(mesProductionAssemblies)) {
            MesPcnException.throwFlowException("装配件记录不存在");
        }
        Map<Long, String> mapProduction = mesProductionAssemblies.stream().collect(Collectors.toMap(mesProductionAssembly -> mesProductionAssembly.getId(), mesProductionAssembly -> mesProductionAssembly.getPartNo()));
        map.forEach((k, v) -> {
            MesProductionAssembly mesProductionAssembly = mesProductionAssemblyRepository.getById(Long.parseLong(k));
            if (!Objects.equals(mapProduction.get(k), mesProductionAssembly.getPartNo())) {
                MesPcnException.throwFlowException(String.format("装配件记录不匹配id=【%s】,sn=【%s】", k, v));
            }
        });

        return false;
    }

    /**
     * map id和sn对应关系
     * mapProductionAssemble  id 和物料对应关系
     * mapProduceSn 物料和条码对应关系
     *
     * 根据mapProductionAssemble id找map的sn
     * 根据mapProductionAssemble 物料找mmapProduceSn的sn
     * 两者必须一致才允许
     *
     * @param requestModel
     */
    @Override
    public void doAssemblySnRepeat(MesReworkTaskRequestModel requestModel) {

        try {
            //
            List<String> snList = Arrays.asList(requestModel.getSn().split(","));
            snList = snList.stream().distinct().collect(Collectors.toList());
            List<String> idList = Arrays.asList(requestModel.getAssemblyIds().split(","));
            // 判断数量是否一致
            if (snList.size() != idList.size()) MesPcnException.throwFlowException("选中的装配件个数和输入的个数不一致");
            // 判断顺序是否一致  key = id, value = sn
            Map<String, String> map = IntStream.range(0, snList.size()).boxed().collect(Collectors.toMap(idList::get, snList::get, (a, b) -> b));
            List<Long> idLonglist = idList.stream().map(str -> Long.parseLong(str)).collect(Collectors.toList());

            // 获取装配件记录列表
            DdlPackBean ddlPackBean = DdlPackBean.getDdlPackBean();
            DdlPreparedPack.getInPackList(idLonglist, "id", ddlPackBean);
            List<MesProductionAssembly> mesProductionAssemblies = mesProductionAssemblyRepository.findByHqlWhere(ddlPackBean);
            if (CollectionUtils.isEmpty(mesProductionAssemblies)) {
                MesPcnException.throwFlowException("装配件记录不存在");
            }
            Map<Long, String> mapProductionAssemble = mesProductionAssemblies.stream().collect(Collectors.toMap(mesProductionAssembly -> mesProductionAssembly.getId(), mesProductionAssembly -> mesProductionAssembly.getAssemblyPartNo()));

            List<Integer> snStatusList = Stream.of(MesExtEnumUtil.PRODUCE_SN_STATUS.OFFLINE.getValue(), MesExtEnumUtil.PRODUCE_SN_STATUS.ASSEMBLY_BACK.getValue()).collect(Collectors.toList());
            // 获取替换条码信息列表
            DdlPackBean snDdlPackBean = DdlPackBean.getDdlPackBean();
            DdlPreparedPack.getInPackList(snList, "productSn", snDdlPackBean);
            DdlPreparedPack.getInPackList(snStatusList, "snStatus", snDdlPackBean);

            List<MesProduceSn> mesProduceSnList = mesProduceSnRepository.findByHqlWhere(snDdlPackBean);
            if (CollectionUtils.isEmpty(mesProductionAssemblies)) {
                MesPcnException.throwFlowException("零件条码不存在");
            }
            List<MesProduceSn> mesProduceSns =  new ArrayList<>();
            Map<String, List<MesProduceSn>>  productSnListMap = mesProduceSnList.stream().collect(Collectors.groupingBy(mesProduceSn -> mesProduceSn.getProductSn()));
            Map<String, MesProduceSn> productSnMap = new HashedMap();
            productSnListMap.forEach((k,v) -> {
                MesProduceSn produceSn = v.stream().sorted(Comparator.comparing(MesProduceSn::getCreateDatetime).reversed()).findFirst().get();
                mesProduceSns.add(produceSn);
                productSnMap.put(produceSn.getProductSn(), produceSn);
            });

            Map<String, String> mapProduceSn = mesProduceSns.stream().collect(Collectors.toMap(mesProduceSn -> mesProduceSn.getPartNo(), mesProduceSn -> mesProduceSn.getProductSn()));

            mapProductionAssemble.forEach((k, v) -> {
                String sn = map.get(k + "");
                String newSn = mapProduceSn.get(v);
                if (!Objects.equals(sn, newSn)) {
                    MesPcnException.throwFlowException(String.format("装配件记录不匹配id=【%s】,sn=【%s】", k, sn));
                }
            });

            for (String sn : snList) {
                MesProduceSn mesProduceSn = productSnMap.get(sn);
                if (mesProduceSn == null) {
                    MesPcnException.throwFlowException("条码信息不存在");
                }
                requestModel.setAssemblyPartNo(mesProduceSn.getPartNo());
                requestModel.setAssemblyPartStatus(MesExtEnumUtil.ASSEMBLY_STATUS.ASSEMBLY_STATUS_10.getValue());
                List<MesProductionAssembly> mesProductionAssemblieList = assemblyQuery(requestModel);
                if (CollectionUtils.isEmpty(mesProductionAssemblieList)) {
                    MesPcnException.throwFlowException("未匹配到该条码的零件号");
                }
                // 需要变更之前的记录
                MesProductionAssembly mesProductionAssembly = mesProductionAssemblieList.get(0);
                mesProductionAssembly.setAssemblyStatus(MesExtEnumUtil.ASSEMBLY_STATUS.ASSEMBLY_STATUS_20.getValue());


                // 需要新增一条替换条码的记录
                MesProductionAssembly mesProductionRepeatAssembly = new MesProductionAssembly();
                BeanUtils.copyProperties(mesProductionAssembly, mesProductionRepeatAssembly,MesPcnExtConstWords.ID);
                mesProductionRepeatAssembly.setAssemblySn(sn);
                mesProductionRepeatAssembly.setAssemblyStatus(MesExtEnumUtil.ASSEMBLY_STATUS.ASSEMBLY_STATUS_10.getValue());
                mesProductionRepeatAssembly.setIsOrigSn(CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue());
                mesProductionRepeatAssembly.setFid(UUID .randomUUID().toString());

                mesProductionAssembly.setRepeatAssemblySn(sn);
                // 更新新替换得条码为已装配
                updateNewSn(mesProduceSn,requestModel.getUserName());
                // 更新原条码状态为已拆解
                ConvertBean.serviceModelUpdate(mesProductionAssembly,requestModel.getUserName());
                updateOldSn(mesProductionAssembly.getOrganizeCode(),mesProductionAssembly.getAssemblySn(),requestModel.getUserName(), null);
                // 原装配件记录为已解绑
                mesProductionAssemblyRepository.update(mesProductionAssembly);
                // 新装配件记录为已装配
                ConvertBean.serviceModelInitialize(mesProductionRepeatAssembly,requestModel.getUserName());
                MesProductionAssembly productionAssembly = mesProductionAssemblyRepository.insert(mesProductionRepeatAssembly);
                //唯一性校验数据更新
                if (MesExtEnumUtil.ASSEMBLY_MATCH_TYPE.MATCH_TYPE_30.getValue() == mesProductionAssembly.getMatchType()) {
                    saveProductionAssemblyUnique(requestModel, mesProductionAssembly.getAssemblySn(), productionAssembly);
                }
            }
            /**
             * 需要更新NC标记后进入的表明细状态为已处理
             */
            for (String detailId : requestModel.getDetailIds().split(",")) {
                reworkRecord(Long.parseLong(detailId),requestModel.getUserName(),requestModel.getOrganizeCode());
            }
        } catch (Exception e) {
            log.error("替换条码异常", e);
            throw e;
        }

    }

    public void recursionAssemblySnTree(List<MesProductionAssemblyModel> assemblyTree, MesReworkTaskRequestModel requestModel,long pid) {
        for (MesProductionAssemblyModel assembly : assemblyTree) {
            assembly.setPid(pid);
            if(MesExtEnumUtil.ASSEMBLY_MATCH_TYPE.MATCH_TYPE_10.getValue() == assembly.getMatchType() && !StringUtils.isEmpty(assembly.getAssemblySn())){
                DdlPackBean packBean = DdlPackBean.getDdlPackBean(requestModel.getOrganizeCode());
                DdlPreparedPack.getStringEqualPack(assembly.getAssemblySn(), "productSn", packBean);
                DdlPreparedPack.getStringEqualPack(requestModel.getAssemblyPartNo(), "assemblyPartNo", packBean);
                DdlPreparedPack.getNumEqualPack(MesExtEnumUtil.ASSEMBLY_STATUS.ASSEMBLY_STATUS_10.getValue(), "assemblyStatus", packBean);
                List<MesProductionAssembly> mesProductionAssemblies = mesProductionAssemblyRepository.findByHqlWhere(packBean);
                if (!CollectionUtils.isEmpty(mesProductionAssemblies)) {
                    assembly.setChildren(parseArray(mesProductionAssemblies));
                    recursionAssemblySnTree(assembly.getChildren(), requestModel, assembly.getId());
                }
            }
        }
    }

    private List<MesProductionAssemblyModel> parseArray(List<MesProductionAssembly> mesProductionAssemblies) {
        return JSONArray.parseArray(JSONArray.toJSONString(mesProductionAssemblies), MesProductionAssemblyModel.class);
    }


    public void recursionAssemblySn(List<MesProductionAssembly> mesProductionAssemblyList,MesReworkTaskRequestModel requestModel){
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(requestModel.getOrganizeCode());
        DdlPreparedPack.getInPackList(mesProductionAssemblyList.stream().map(MesProductionAssembly::getAssemblySn).distinct().collect(Collectors.toList()), "productSn", packBean);
        DdlPreparedPack.getNumEqualPack(requestModel.getIsOrigSn(), "isOrigSn", packBean);
        DdlPreparedPack.getStringEqualPack(requestModel.getAssemblyPartNo(), "assemblyPartNo", packBean);
        DdlPreparedPack.getNumEqualPack(requestModel.getAssemblyPartStatus(), "assemblyStatus", packBean);
        List<MesProductionAssembly> mesProductionAssemblies = mesProductionAssemblyRepository.findByHqlWhere(packBean);
        if(!CollectionUtils.isEmpty(mesProductionAssemblies)){
            recursionAssemblySn(mesProductionAssemblies,requestModel);
            mesProductionAssemblyList.addAll(mesProductionAssemblies);
        }
    }

    private void updateNewSn(MesProduceSn mesProduceSn,String userName) {
        mesProduceSn.setSnStatus(MesExtEnumUtil.PRODUCE_SN_STATUS.ASSEMBLY.getValue());
        ConvertBean.serviceModelUpdate(mesProduceSn, userName);
        mesProduceSnRepository.update(mesProduceSn);
    }

    private void updateOldSn(String organizeCode, String productSn, String userName, Integer qcStatus) {
        MesProduceSn oldProduceSn = getMesProduceSn(organizeCode,productSn);
        if(!Objects.isNull(qcStatus)){
            oldProduceSn.setQcStatus(qcStatus);
        }
        oldProduceSn.setSnStatus(MesExtEnumUtil.PRODUCE_SN_STATUS.ASSEMBLY_BACK.getValue());
        ConvertBean.serviceModelUpdate(oldProduceSn,userName);
        mesProduceSnRepository.update(oldProduceSn);
    }

    private void doAssemblyDisassembly(MesReworkTaskRequestModel requestModel, String productSn,String responsibleParty) {
        //报废目标库位
        String destLocateNo = getDestLocateNo(requestModel.getOrganizeCode(), productSn);
        //总成拆解
        doProductReportReversal(requestModel,productSn,destLocateNo);
        //装配件数据处理
        doRecursionCheck(requestModel.getAssemblyModelList(), requestModel.getOrganizeCode(), requestModel.getUserName(),destLocateNo,responsibleParty);
    }

    private void doProductReportReversal(MesReworkTaskRequestModel requestModel, String productSn,String locateNo) {
        //更新条码状态为总成拆解
        MesProduceSn produceSnDb = getMesProduceSn(requestModel.getOrganizeCode(), productSn);
        produceSnDb.setSnStatus(MesExtEnumUtil.PRODUCE_SN_STATUS.ASSEMBLY_DISASSEMBLY.getValue());
        ConvertBean.serviceModelUpdate(produceSnDb, requestModel.getUserName());
        mesProduceSnRepository.update(produceSnDb);
        //拆解返工单完成后，总成反向移库（NC责任人对应库位（MesMove最后一条记录的库位）-->默认库位（生产版本中的receive_inventory_point）），若总成已汇报，自动做一个报工调整
        List<MesProductionRecord> productionRecordList = mesProductionRecordService.findProductionRecordList(produceSnDb.getOrganizeCode(), produceSnDb.getProductSn(), produceSnDb.getPartNo());
        if(CollectionUtils.isEmpty(productionRecordList)){
            return;
        }
        Optional<MesProductionRecord> optional = productionRecordList.stream().filter(o -> (null != o && MesExtEnumUtil.REPORT_STATUS.REPORT_STATUS_20.getValue() == o.getReportStatus())).findFirst();
        if (!optional.isPresent() || StringUtils.isEmpty(optional.get().getWorkOrderNo())) {
            return;
        }
        //报工调整
        // 2024-11-27    物料报解后AME或者质量如何快速把正确委件返回流?A变B流程怎么走?-物料拆解需要去掉自动负报工接口，待开发
        MesWorkOrder mesWorkOrderDb = mesWorkOrderService.findMesWorkOrderList(requestModel.getOrganizeCode(), optional.get().getWorkOrderNo());
        MesProductVersion productVersion = getProductVersion(mesWorkOrderDb);
         /*
        mesWorkOrderDb.setNum(MesPcnExtConstWords.ONE);
        mesWorkOrderService.doProductReportReversal(mesWorkOrderDb,productVersion, requestModel.getUserName());*/
        //移库
        requestModel.setSn(produceSnDb.getProductSn());
        doCreateMove(requestModel,locateNo,productVersion.getReceiveInventoryPoint(),mesWorkOrderDb.getErpWorkCenter(),mesWorkOrderDb.getPartNo());
    }

    private MesProductVersion getProductVersion(MesWorkOrder mesWorkOrderDb) {
        MesProductVersion mesProductVersion = mesProductVersionService.getMesProductVersion(mesWorkOrderDb.getOrganizeCode(),mesWorkOrderDb.getPartNo(),mesWorkOrderDb.getProductVersion());
        if (null == mesProductVersion) {
            MesPcnException.throwMesBusiException("物料【%s】生产版本【%s】信息不存在", mesWorkOrderDb.getPartNo(), mesWorkOrderDb.getProductVersion());
        }
        return mesProductVersion;
    }

    public void doRecursionCheck(List<MesProductionAssemblyModel> assemblyModelList,String organizeCode,String userName,String destLocate,String responsibleParty){
        for (MesProductionAssemblyModel assemblyModel : assemblyModelList) {
            //勾选
            if (assemblyModel.getFlag() == CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue()) {
                //报废
                if(MesExtEnumUtil.ASSEMBLY_MATCH_TYPE.MATCH_TYPE_10.getValue() == assemblyModel.getMatchType()){
                    updateOldSn(organizeCode,assemblyModel.getAssemblySn(), userName, MesExtEnumUtil.PRODUCE_QC_STATUS.SCRAP.getValue());
                }
                //对于已勾选报废的子件，对于有零件号的项，产生移库（产线的材料库位->报废库（系统参数配置））。移库数量为报废时的明细数量；
                if(!StringUtils.isEmpty(assemblyModel.getAssemblyPartNo())){
                    //移库
                    doCreateMove(getMesWorkCenter(organizeCode, assemblyModel.getWorkCenterCode()),destLocate, assemblyModel,userName);
                    //报废
                    doCreateScrap(assemblyModel,userName,responsibleParty,organizeCode);
                }

                //循环处理数据
                if(!CollectionUtils.isEmpty(assemblyModel.getChildren())){
                    doRecursionCheck(assemblyModel.getChildren(),organizeCode,userName,destLocate,responsibleParty);
                }
            } else if (assemblyModel.getFlag() == CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue()) {
                //装配解绑
                saveProductionAssembly(organizeCode, userName, assemblyModel.getAssemblySn());
                //自制件更新条码状态 条码状态可用
                if(MesExtEnumUtil.ASSEMBLY_MATCH_TYPE.MATCH_TYPE_10.getValue() == assemblyModel.getMatchType()){
                    updateOldSn(organizeCode,assemblyModel.getAssemblySn(), userName, null);
                    //唯一性表中删除
                }else if(MesExtEnumUtil.ASSEMBLY_MATCH_TYPE.MATCH_TYPE_30.getValue() == assemblyModel.getMatchType()){
                    saveProductionAssemblyUnique(organizeCode, userName, assemblyModel.getAssemblySn());
                }
            }
        }
    }

    private void updateProductSn(MesReworkTaskRequestModel requestModel, MesProductionAssembly assembly, MesProductionAssemblyContext context) {
        List<MesProduceSn> produceSnList = produceSnExtService.getProduceSnList(requestModel.getOrganizeCode(), requestModel.getSn());
        if (CollectionUtils.isEmpty(produceSnList)) MesPcnException.throwFlowException("零件条码[%s]信息不存在!", requestModel.getSn());
        Optional<MesProduceSn> optional = produceSnList.stream().filter(sn->sn.getId().equals(context.getProductSnId())).findFirst();
        if (!optional.isPresent()) MesPcnException.throwFlowException("零件条码[%s]信息不存在!", requestModel.getSn());
        // 更新新替换得条码为已装配
        updateNewSn(optional.get(), requestModel.getUserName());
        //更新原条码状态为已拆解
        updateOldSn(assembly.getOrganizeCode(),assembly.getAssemblySn(),requestModel.getUserName(), null);
    }

    private void saveProductionAssemblyUnique(MesReworkTaskRequestModel requestModel, String assemblySN, MesProductionAssembly productionAssembly) {
        //绑定数据解绑
        saveProductionAssemblyUnique(requestModel.getOrganizeCode(),requestModel.getUserName(), assemblySN);
        //唯一性校验数据保存
        saveProductionAssemblyUnique(productionAssembly);
    }

    private void saveProductionAssemblyUnique(String organizeCode,String userName, String assemblySN) {
        List<MesProductionAssemblyUnique> assemblyUniqueList = mesAssemblyExtService.getProductionAssemblyUniqueList(organizeCode, assemblySN);
        if(!CollectionUtils.isEmpty(assemblyUniqueList)){
            assemblyUniqueList.forEach(t->{
                t.setSystemSyncStatus(CommonEnumUtil.FALSE);
                t.setAssemblyStatus(MesExtEnumUtil.ASSEMBLY_STATUS.ASSEMBLY_STATUS_20.getValue());
                ConvertBean.serviceModelUpdate(t, userName);
            });
            mesProductionAssemblyUniqueRepository.saveAll(assemblyUniqueList);
        }
    }

    private void saveProductionAssembly(String organizeCode,String userName, String assemblySN) {
        List<MesProductionAssembly> assemblyList = mesAssemblyExtService.getProductionAssemblyList(organizeCode, assemblySN);
        if(CollectionUtils.isEmpty(assemblyList)){
            return;
        }
        assemblyList = assemblyList.stream().filter(o->MesExtEnumUtil.ASSEMBLY_STATUS.ASSEMBLY_STATUS_10.getValue() == o.getAssemblyStatus()).collect(Collectors.toList());
        if(!CollectionUtils.isEmpty(assemblyList)){
            assemblyList.forEach(t->{
                t.setSystemSyncStatus(CommonEnumUtil.FALSE);
                t.setAssemblyStatus(MesExtEnumUtil.ASSEMBLY_STATUS.ASSEMBLY_STATUS_20.getValue());
                ConvertBean.serviceModelUpdate(t, userName);
            });
            mesProductionAssemblyRepository.saveAll(assemblyList);
        }
    }

    private void saveProductionAssemblyUnique(MesProductionAssembly productionAssembly) {
        MesProductionAssemblyUnique productionAssemblyUnique = new MesProductionAssemblyUnique();
        BeanUtils.copyProperties(productionAssembly, productionAssemblyUnique, MesPcnExtConstWords.ID);
        productionAssemblyUnique.setPid(productionAssembly.getId());
        mesProductionAssemblyUniqueRepository.insert(productionAssemblyUnique);
    }

    private Object getContext(MesReworkTaskRequestModel requestModel, MesProductionAssembly mesProductionAssembly, Map<String,MesWorkCenter> mesWorkCenterMap) {
        if(StringUtils.isEmpty(mesProductionAssembly.getWorkCenterCode())) MesPcnException.throwFlowException("产线代码不存在");
        MesWorkCenter workCenterDb;
        //产线类型
        if(!mesWorkCenterMap.containsKey(mesProductionAssembly.getWorkCenterCode())){
            workCenterDb = getMesWorkCenter(requestModel.getOrganizeCode(), mesProductionAssembly.getWorkCenterCode());
            mesWorkCenterMap.put(mesProductionAssembly.getWorkCenterCode(),workCenterDb);
        } else{
            workCenterDb = mesWorkCenterMap.get(mesProductionAssembly.getWorkCenterCode());
        }

        //获取不可用规则
        String prodRuleIgnoreCfg = getProdRuleIgnoreCfg(requestModel.getOrganizeCode(), workCenterDb.getCenterType(), mesProductionAssembly.getSourceId(), mesProductionAssembly.getEquipmentCode());

        return MesExtEnumUtil.WORK_CENTER_TYPE.SORT.getValue() == workCenterDb.getCenterType()
                ? new MesProductionAssemblySortContext().copy(mesProductionAssembly).prodRuleIgnoreCfg(prodRuleIgnoreCfg)
                : new MesProductionAssemblyNosortContext().copy(mesProductionAssembly).prodRuleIgnoreCfg(prodRuleIgnoreCfg);
    }

    //获取不可用规则
    private String getProdRuleIgnoreCfg(String organizeCode, Integer centerType, Long sourceId, String equipmentCode) {
        if (StringUtils.isEmpty(organizeCode) || StringUtils.isEmpty(centerType) || StringUtils.isEmpty(sourceId) || StringUtils.isEmpty(equipmentCode)) return null;
        Long sourceId2IgnoreCfg = null;
        if (MesExtEnumUtil.WORK_CENTER_TYPE.SORT.getValue() == centerType) {
            MesWorkOrderAssembly workOrderAssembly = mesAssemblyExtService.getWorkOrderAssembly(organizeCode, sourceId);
            if (null != workOrderAssembly && !StringUtils.isEmpty(workOrderAssembly.getPid())) sourceId2IgnoreCfg = workOrderAssembly.getPid();
        } else sourceId2IgnoreCfg = sourceId;
        Integer dataSource = MesExtEnumUtil.WORK_CENTER_TYPE.SORT.getValue() == centerType ? MesExtEnumUtil.PROD_RULE_IGNORE_DATA_SOURCE.DATA_SOURCE10.getValue() : MesExtEnumUtil.PROD_RULE_IGNORE_DATA_SOURCE.DATA_SOURCE30.getValue();
        if (StringUtils.isEmpty(sourceId2IgnoreCfg)) return null;
        List<MesProdRuleIgnoreCfg> prodRuleIgnoreCfgList = equipmentExtService.getProdRuleIgnoreCfgList(organizeCode, equipmentCode, dataSource, sourceId2IgnoreCfg);
        if (CollectionUtils.isEmpty(prodRuleIgnoreCfgList)) return null;
        return JSONObject.toJSONString(prodRuleIgnoreCfgList);
    }

    private MesProduceSn getMesProduceSn(String organizeCode, String productSn) {
        DdlPackBean oldSnPackBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getStringEqualPack(productSn, "productSn", oldSnPackBean);
        DdlPreparedPack.getOrderByPack(new Object[]{CommonEnumUtil.ASC_OR_DESC.DESC.getValue()}, new String[]{"createDatetime"}, oldSnPackBean);

        MesProduceSn produceSnDb = mesProduceSnRepository.getByProperty(oldSnPackBean);
        if (produceSnDb == null) {
            produceSnDb = (MesProduceSn) workOrderExtService.getWorkOrderSort(organizeCode, productSn, false);
            if (produceSnDb == null) {
                MesPcnException.throwFlowException(String.format("条码【%s】信息不存在", productSn));
            }
        }
        return produceSnDb;
    }

    private MesWorkCenter getMesWorkCenter(String organizeCode, String workCenterCode) {
        MesWorkCenter workCenterDb = prodOrgExtService.getWorkCenterDb(organizeCode,workCenterCode);
        if(Objects.isNull(workCenterDb)) MesPcnException.throwFlowException(String.format("产线【%s】信息不存在", workCenterCode));
        return workCenterDb;
    }

    private String doGererateSerialNo(MesPart part,String organizeCode,String userName) {
        if(StringUtils.isEmpty(part.getProductMatchRule())) MesPcnException.throwMesBusiException("请检查零件信息,零件[%s]信息未维护零件条码编码规则!", part.getPartNo());
        return syncFuncService.syncSerialNo(
                new GenSerialNoModel(part.getProductMatchRule()).partNo(part.getPartNo()).putDataMap(MesPart.class.getSimpleName(), part).organizeCode(organizeCode),
                userName, organizeCode, 1).getResultList().get(0).toString();
    }

    private String getDestLocateNo(String organizeCode, Long partInspectionId) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getNumEqualPack(partInspectionId, "partInspectionId", packBean);
        DdlPreparedPack.getOrderBy(null, null, packBean);
        MesMove mesMove = moveRepository.getByProperty(packBean);
        return Objects.isNull(mesMove) ? null : mesMove.getUmlgo();
    }

    private String getDestLocateNo(String organizeCode, String productSn) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getStringEqualPack(productSn, "productSn", packBean);
        DdlPreparedPack.getOrderBy(null, null, packBean);
        MesMove mesMove = moveRepository.getByProperty(packBean);
        return Objects.isNull(mesMove) ? null : mesMove.getUmlgo();
    }
    private MesPartInspection getMesPartInspection(MesReworkTask mesReworkTask) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(mesReworkTask.getOrganizeCode());
        DdlPreparedPack.getStringEqualPack(mesReworkTask.getSn(), "sn", packBean);
        return mesPartInspectionRepository.getByProperty(packBean);
    }

    private List<MesPartInspectionDetail> getMesPartInspectionDetail(List<MesReworkTaskDetail> reworkTaskDetails) {

        List<Long> ids = reworkTaskDetails.stream().map(MesReworkTaskDetail::getPartInspectionDetailId).collect(Collectors.toList());

        DdlPackBean packBean = DdlPackBean.getDdlPackBean(reworkTaskDetails.get(0).getOrganizeCode());
        DdlPreparedPack.getInPackList(ids, "id", packBean);

        return mesPartInspectionDetailRepository.findByHqlWhere(packBean);
    }

    private MesPartTypePicture getMesPartTypePicture(MesReworkTask mesReworkTask) {
        DdlPackBean partBean = DdlPackBean.getDdlPackBean(mesReworkTask.getOrganizeCode());
        DdlPreparedPack.getStringEqualPack(mesReworkTask.getPartNo(), "partNo", partBean);
        MesPart mesPart = mesPartRepository.getByProperty(partBean);
        if (mesPart == null) {
            MesPcnException.throwFlowException(String.format("零件信息不存在,根据物料号查询[%s]", mesReworkTask.getPartNo()));
        }

        DdlPackBean pictureBean = DdlPackBean.getDdlPackBean(mesReworkTask.getOrganizeCode());
        DdlPreparedPack.getStringEqualPack(mesPart.getPartTypeCode(), "partTypeCode", pictureBean);

        return mesPartTypePictureRepository.getByProperty(pictureBean);
    }

    private MesReworkTask getMesReworkTask(MesReworkTaskRequestModel requestModel) {
        String workCenterCode = null;
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(requestModel.getOrganizeCode());
        if (!StringUtils.isEmpty(requestModel.getSn())) {
            //根据零件条码查询
            MesProduceSn produceSn = produceSnExtService.getProduceSnCreateDatetimeDesc(requestModel.getOrganizeCode(), requestModel.getSn());
            //不存在则进行二次查询排序条码
            if (null == produceSn) produceSn = (MesProduceSn) workOrderExtService.getWorkOrderSort(requestModel.getOrganizeCode(), requestModel.getSn(), false);
            if (null != produceSn) {
                workCenterCode = produceSn.getWorkCenterCode();
                DdlPreparedPack.getStringEqualPack(produceSn.getProductSn(), "sn", packBean);
            }else {
                DdlPreparedPack.getStringEqualPack(requestModel.getSn(), "sn", packBean);
            }
        }
        if (!StringUtils.isEmpty(requestModel.getReworkOrder())) {
            DdlPreparedPack.getStringEqualPack(requestModel.getReworkOrder(), "reworkOrder", packBean);
        }
        DdlPreparedPack.getNumEqualPack(MesExtEnumUtil.REWORK_TASK_STATUS.CREATE.getValue(), "status", packBean);

        MesReworkTask res = mesReworkTaskRepository.getByProperty(packBean);
        if (res == null) {
            throw new ImppBusiException("返工单信息不存在");
        }

        //选择返工工单场景下 根据返工工单信息里面的条码进行反查生产线
        if (!StringUtils.isEmpty(requestModel.getReworkOrder())) {
            MesProduceSn produceSn = produceSnExtService.getProduceSnCreateDatetimeDesc(requestModel.getOrganizeCode(), res.getSn());
            if (null == produceSn) produceSn = (MesProduceSn) workOrderExtService.getWorkOrderSort(requestModel.getOrganizeCode(), res.getSn(), false);
            if (null != produceSn) workCenterCode = produceSn.getWorkCenterCode();
        }

        if (!StringUtils.isEmpty(workCenterCode)) {
            //获取生产线类型, 用于前端判断, 支持点击 拆解按钮 还是 排序拆解按钮, 同时 返工完成按钮 根据生产线类型调用的接口不一样
            MesWorkCenter workCenter = prodOrgExtService.getWorkCenterDb(requestModel.getOrganizeCode(), workCenterCode);
            if (null != workCenter) requestModel.setCenterType(workCenter.getCenterType());
        }
        return res;
    }
    private List<MesReworkTaskDetail> getMesReworkTaskDetail(MesReworkTask mesReworkTask) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(mesReworkTask.getOrganizeCode());
        DdlPreparedPack.getNumEqualPack(mesReworkTask.getId(), "pid", packBean);
        DdlPreparedPack.getNumEqualPack(MesExtEnumUtil.REWORK_TASK_DETAIL_STATUS.REWORK_TASK_DETAIL_STATUS_10.getValue(), "status", packBean);

        return mesReworkTaskDetailRepository.findByHqlWhere(packBean);
    }

    private void updateMesProduceSn(MesReworkTaskRequestModel requestModel) {
        MesProduceSn produceSn = getMesProduceSn(requestModel.getOrganizeCode(),requestModel.getSn());
        produceSn.setQcStatus(MesExtEnumUtil.PRODUCE_QC_STATUS.SCRAP.getValue());
        ConvertBean.serviceModelUpdate(produceSn,requestModel.getUserName());
        mesProduceSnRepository.update(produceSn);
        //排序产线 更新工单的 qcStatus
        MesWorkCenter centerDb = prodOrgExtService.getWorkCenterDb(requestModel.getOrganizeCode(), produceSn.getWorkCenterCode());
        if (!StringUtil.isEmpty(centerDb)){
            if(centerDb.getCenterType() == MesExtEnumUtil.WORK_CENTER_TYPE.SORT.getValue()){
                MesWorkOrder workOrder = getWorkOrder(requestModel.getOrganizeCode(),produceSn.getWorkOrderNo());
                if (!StringUtil.isEmpty(workOrder)){
                    workOrder.setQcStatus(MesExtEnumUtil.PRODUCE_QC_STATUS.SCRAP.getValue());
                    ConvertBean.serviceModelUpdate(workOrder, requestModel.getUserName());
                    workOrderRepository.update(workOrder);
                }
            }
        }
    }
    public MesWorkOrder getWorkOrder(String organizeCode, String workOrderNo) {
        if (StringUtils.isEmpty(organizeCode) || StringUtils.isEmpty(workOrderNo)) return null;
        return workOrderRepository.getByProperty(
                new String[]{MesPcnExtConstWords.ORGANIZE_CODE, MesPcnExtConstWords.IS_DELETED, MesPcnExtConstWords.IS_VALID, MesPcnExtConstWords.WORK_ORDER_NO},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue(), workOrderNo});
    }
    private MesMove doCreateMove(String oldSn, String sn, String organizeCode, String userName) {
        MesMove move = new MesMove();
        move.setOrganizeCode(organizeCode);
        move.setFactoryCode(organizeCode);
        move.setPostDate(TimeTool.getToday());
        move.setPostTime(TimeTool.getTimeShortWithColon());
        move.setMoveType(MesExtEnumUtil.MOVE_TYPE.REWORK_REPLACE.getValue());
        move.setProductSn(sn);
        move.setProductSnOld(oldSn);
        ConvertBean.serviceModelInitialize(move, userName);
        return moveRepository.insert(move);
    }

    private void doCreateScrap(MesProductionAssemblyModel assemblyModel,String userName,String responsibleParty,String organizeCode) {
        //新增一条数据到报废表中
        MesQmsScrap mesQmsScrap = new MesQmsScrap();
        mesQmsScrap.setOrganizeCode(organizeCode);
        mesQmsScrap.setAsnNo("");
        mesQmsScrap.setSource("MES");
        mesQmsScrap.setRejectQty(assemblyModel.getScrapQty());
        mesQmsScrap.setPartNo(assemblyModel.getAssemblyPartNo());
        mesQmsScrap.setPartName(assemblyModel.getAssemblyPartName());
        mesQmsScrap.setDefectTypeName("拆解报废");
        mesQmsScrap.setReponsibilityId(responsibleParty);
        mesQmsScrap.setNcJudger(userName);
        ConvertBean.serviceModelInitialize(mesQmsScrap, userName);
        mesQmsScrapRepository.insert(mesQmsScrap);
    }

    private void doCreateMove(MesWorkCenter mesWorkCenter, String destLocate, MesProductionAssemblyModel assemblyModel,String userName) {
        MesMove move = new MesMove();
        move.setMatnr(assemblyModel.getAssemblyPartNo());
        move.setOrganizeCode(mesWorkCenter.getOrganizeCode());
        move.setFactoryCode(mesWorkCenter.getOrganizeCode());
        move.setLgort(mesWorkCenter.getRawLocate());
        move.setUmlgo(destLocate);
        move.setMenge(assemblyModel.getScrapQty());
        move.setPostDate(TimeTool.getToday());
        move.setPostTime(TimeTool.getTimeShortWithColon());
        move.setMoveType(MesExtEnumUtil.MOVE_TYPE.SCRAP_MOVE.getValue());
        move.setProductSn(assemblyModel.getAssemblySn());
        move.setWorkCenter(mesWorkCenter.getErpWorkCenter());
        ConvertBean.serviceModelInitialize(move, userName);
        moveRepository.insert(move);
    }

    private void doCreateMove(MesReworkTaskRequestModel requestModel,String srcLocate, String destLocate,String workCenterCode,String partNo) {
        MesPartSap mesPartSap = mesPartService.getMesPartSapByPartNo(partNo, requestModel.getOrganizeCode());
        MesMove move = new MesMove();
        move.setMatnr(mesPartSap.getPartNo());
        move.setOrganizeCode(requestModel.getOrganizeCode());
        move.setFactoryCode(requestModel.getOrganizeCode());
        move.setLgort(srcLocate);
        move.setUmlgo(destLocate);
        move.setMenge(1d);
        move.setMeins(mesPartSap.getUnit());
        move.setPostDate(TimeTool.getToday());
        move.setPostTime(TimeTool.getTimeShortWithColon());
        move.setMoveType(MesExtEnumUtil.MOVE_TYPE.SCRAP_MOVE.getValue());
        move.setProductSn(requestModel.getSn());
        move.setWorkCenter(workCenterCode);
        ConvertBean.serviceModelInitialize(move, requestModel.getUserName());
        moveRepository.insert(move);
    }


    private void doCreateReworkMove(MesReworkTaskRequestModel requestModel,String srcLocate, String destLocate,String workCenterCode,String partNo,Long partInspectionId) {
        MesPartSap mesPartSap = mesPartService.getMesPartSapByPartNo(partNo, requestModel.getOrganizeCode());

        GenSerialNoModel serialNoModel = new GenSerialNoModel("INPUT_DEFECT_ZRSUM");
        serialNoModel.setPartNo(mesPartSap.getPartNo());
        ResultBean rb = syncFuncService.syncSerialNo(serialNoModel, requestModel.getUserName(), requestModel.getOrganizeCode(), 1);
        String zrsum = "";
        if (null != rb && !CollectionUtils.isEmpty(rb.getResultList())) {
            zrsum = (rb.getResultList().get(0)).toString();
        }

        MesMove move = new MesMove();
        move.setMatnr(mesPartSap.getPartNo());
        move.setOrganizeCode(requestModel.getOrganizeCode());
        move.setFactoryCode(requestModel.getOrganizeCode());
        move.setLgort(srcLocate);
        move.setUmlgo(destLocate);
        move.setPartInspectionId(partInspectionId);
        move.setMenge(requestModel.getReworkedQty());
        move.setZrsum(zrsum);
        move.setMeins(mesPartSap.getUnit());
        move.setPostDate(TimeTool.getToday());
        move.setPostTime(TimeTool.getTimeShortWithColon());
        move.setMoveType(MesExtEnumUtil.MOVE_TYPE.RETURN_MOVE.getValue());
        move.setProductSn(requestModel.getSn());
        move.setWorkCenter(prodOrgExtService.getErpWorkCenterCode(requestModel.getOrganizeCode(), workCenterCode));
        ConvertBean.serviceModelInitialize(move, requestModel.getUserName());
        moveRepository.insert(move);
    }
}
