xiejun
2023-11-17 566c542d3f1eb0ad9e918bd1fa9586ab1ed7ec86
Source/UBCS/ubcs-service/ubcs-code/src/main/java/com/vci/ubcs/code/service/impl/MdmProductCodeServiceImpl.java
@@ -2,7 +2,9 @@
import com.alibaba.nacos.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.vci.ubcs.code.algorithm.CustomSerialEnum;
import com.vci.ubcs.code.bo.CodeClassifyFullInfoBO;
import com.vci.ubcs.code.dto.CodeCustomSerialDTO;
import com.vci.ubcs.code.dto.CodeOrderSecDTO;
import com.vci.ubcs.code.entity.CodeAllCode;
import com.vci.ubcs.code.entity.CodeClassifyValue;
@@ -36,15 +38,16 @@
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
@@ -105,7 +108,7 @@
         //主要是为了录入最大流水号和allcode
         //SessionInfo sessionInfo = VciBaseUtil.getCurrentUserSessionInfo();
         List<CodeAllCode> allCodeDOList = new CopyOnWriteArrayList<>();
         Map<String/**流水依据**/, Map<String/**码段的主键**/,Double/**最大流水号**/>> maxSerialMap = new HashMap<>();
         Map<String/**流水依据**/, ConcurrentHashMap<String/**码段的主键**/,String/**最大流水号**/>> maxSerialMap = new ConcurrentHashMap<>();
         // TODO 多线程流引发的问题已修改
         dataCBOList.parallelStream().forEach(cbo->{
            log.info("code:----->"+cbo.getId());
@@ -120,6 +123,7 @@
            List<CodeBasicSecVO> secVOList = finalRuleVO.getSecVOList().stream().sorted(((o1, o2) -> o1.getOrderNum().compareTo(o2.getOrderNum()))).collect(Collectors.toList());
            Map<String/**码段的主键**/,String/**码段的值**/> serialValueMap = new HashMap<>();
            Map<String, CodeBasicSecVO> secVOMap = secVOList.stream().collect(Collectors.toMap(s -> s.getOid(), t -> t));
            Map<String,Integer> serialSecOidIndexMap=new HashMap<>();
            for (int i = 0; i < secLengths.length; i++) {
               CodeBasicSecVO secVO = secVOList.get(i);
               String thisSecValue  = "";
@@ -137,38 +141,59 @@
               //   }
               if(VciBaseUtil.getBoolean(secVO.getSerialDependFlag())){
                  serialUnitList.add(thisSecValue);
                  serialSecOidIndexMap.put(secVO.getOid(),i);
               }
               if(CodeSecTypeEnum.CODE_SERIAL_SEC.getValue().equalsIgnoreCase(secVO.getSecType())){
                  serialValueMap.put(secVO.getOid(),thisSecValue);
               }
            }
            String serialUnitString = serialUnitList.size() == 0 ? EMPTY_SERIAL_UNIT : serialUnitList.stream().collect(Collectors.joining(SERIAL_UNIT_SPACE));
            List<String> serialUnFileStringList = new ArrayList<>();
            AtomicReference<String> newSerialUnitString = new AtomicReference<>("");
            if(!CollectionUtils.isEmpty(serialValueMap)){
               AtomicInteger index= new AtomicInteger();
               serialValueMap.forEach((secOid,secValue)->{
                  //要看是不是补位的
                  CodeBasicSecVO secVO = secVOMap.get(secOid);
                  Double serialDb = null;
                  List<String >newSerialUnitList=new ArrayList<>();
                  newSerialUnitList.addAll(serialUnitList);
                  if(index.get() ==0){
                     if(serialSecOidIndexMap.containsKey(secOid)) {
                        int num = serialSecOidIndexMap.get(secOid);
                        newSerialUnitList.set(num, "");
                     }
                  }
                  String serialUnitString = newSerialUnitList.size() == 0 ? EMPTY_SERIAL_UNIT : newSerialUnitList.stream().collect(Collectors.joining(SERIAL_UNIT_SPACE));
                  newSerialUnitString.set(serialUnitString);
                  index.getAndIncrement();
                  String serialDb = "";
                  // 截取掉前后缀之后的码段
                  String subSecValue = killPriffixSuffix(secValue, secVO.getPrefixCode(), secVO.getSuffixCode());
                  if(OsCodeFillTypeEnum.NONE.getValue().equalsIgnoreCase(secVO.getCodeFillType())){
                     //不补码
                     //把所有不是数字的去掉,因为可能会是老数据,新规则
                     serialDb = VciBaseUtil.getDouble(killUnNumberChar(subSecValue));
                  //   serialDb = VciBaseUtil.getDouble(killUnNumberChar(subSecValue));
                     //serialDb = killUnNumberChar(subSecValue);
                     serialDb=subSecValue;
                  }else {
                     //左右填充的,我们需要
                     serialDb = VciBaseUtil.getDouble(killUnNumberChar(killFillChar(subSecValue,secVO.getCodeFillSeparator(),
                        OsCodeFillTypeEnum.LEFT.getValue().equalsIgnoreCase(secVO.getCodeFillType()))));
                     /*serialDb = VciBaseUtil.getDouble(killUnNumberChar(killFillChar(subSecValue,secVO.getCodeFillSeparator(),
                        OsCodeFillTypeEnum.LEFT.getValue().equalsIgnoreCase(secVO.getCodeFillType()))));*/
                     serialDb = killFillChar(subSecValue,secVO.getCodeFillSeparator(),
                        OsCodeFillTypeEnum.LEFT.getValue().equalsIgnoreCase(secVO.getCodeFillType()));
                  }
                  Map<String, Double> thisUnitMaxMap = maxSerialMap.getOrDefault(serialUnitString, new HashMap<>());
                  Double maxValue=serialDb;
                  Double newSerialDb= CustomSerialEnum.getDoubleCustomSerialValue(secValue,secVO.getCustomCodeSerialType());
                  ConcurrentHashMap<String, String> thisUnitMaxMap = maxSerialMap.getOrDefault(serialUnitString, new ConcurrentHashMap<>());
                  Double maxValue=newSerialDb;
                  if(thisUnitMaxMap.containsKey(secOid)){
                     maxValue=  thisUnitMaxMap.getOrDefault(secOid,new Double(-1));
                     if(maxValue<serialDb){
                        maxValue=serialDb;
                     String    newMaxValue=  thisUnitMaxMap.getOrDefault(secOid,"");
                     maxValue=StringUtils.isBlank(newMaxValue)?-1:VciBaseUtil.getDouble(newMaxValue);
                     if(maxValue<newSerialDb){
                        maxValue=newSerialDb;
                     }
                  }
                  thisUnitMaxMap.put(secOid,maxValue);
                  String newMaxValue=CustomSerialEnum.getStringCustomSerialValue(maxValue,secVO.getCustomCodeSerialType());
                  serialDb=CustomSerialEnum.getStringCustomSerialValue(newSerialDb,secVO.getCustomCodeSerialType());
                  thisUnitMaxMap.put(secOid,newMaxValue);
                  maxSerialMap.put(serialUnitString,thisUnitMaxMap);
                  serialUnFileStringList.add(String.valueOf(serialDb));
               });
@@ -181,7 +206,7 @@
            allCodeDO.setCodeClassifyTemplateOid(templateVO.getOid());
            allCodeDO.setCreateCodeBtm(cbo.getBtmname());
            allCodeDO.setCreateCodeOid(cbo.getOid());
            allCodeDO.setSerialUnit(serialUnitString);
            allCodeDO.setSerialUnit(newSerialUnitString.get());
            String unFillSerial =serialUnFileStringList.size()==1?serialUnFileStringList.get(0)+ SERIAL_VALUE_SPACE:serialUnFileStringList.stream().collect(Collectors.joining(SERIAL_VALUE_SPACE));
            allCodeDO.setUnFillSerial(unFillSerial);
            allCodeDO.setLcStatus(cbo.getLcStatus());
@@ -204,7 +229,7 @@
               if (!CollectionUtils.isEmpty(serialValueDOS)) {
                  CodeSerialValue serialValueDO = serialValueDOS.get(0);
                  log.info("oldmaxSerial--->"+serialValueDO.getMaxSerial()+"---- newmaxSerial---->"+maxSerial);
                  if(VciBaseUtil.getDouble(serialValueDO.getMaxSerial())<maxSerial){
                  if(VciBaseUtil.getDouble(serialValueDO.getMaxSerial())<VciBaseUtil.getDouble(maxSerial)){
                     serialValueDO.setMaxSerial(String.valueOf(maxSerial));
                     DefaultAttrAssimtUtil.updateDefaultAttrAssimt(serialValueDO);
                     editSerialValueList.add(serialValueDO);
@@ -295,7 +320,7 @@
               List<CodeAllCode> codeAllCodes = codeAllCodeService.selectByWrapper(wrapper);
               List<CodeAllCode> takeBack = codeAllCodes.stream().filter(e -> e.getLcStatus().equals("TakeBack")).collect(Collectors.toList());
               if(codeAllCodes.size()>takeBack.size()){
                  throw new ServiceException("生成编码数据ID已有历史记录,请确认如下生成的ID数据:"+ addCodeDOs.stream().map(CodeAllCode::getId).collect(Collectors.toList()));
                  throw new ServiceException("生成编码数据ID已有历史记录,请确认如下生成的ID数据:"+ codeAllCodes.stream().map(CodeAllCode::getId).collect(Collectors.toList()));
               }
               for (CodeAllCode codeAllCode : takeBack) {
                  codeAllCode.setTs(new Date());
@@ -320,13 +345,6 @@
//            try {
            mdmEngineService.insertBatchByType(dataCBOList.get(0).getBtmname(),dataCBOList);
               // 提交事务
               //transactionTemplate.getTransactionManager().commit(status);
//            }catch (Exception e){
//               // 出现异常时回滚事务
//               transactionTemplate.getTransactionManager().rollback(status);
//            }
         }
         return codeList;
      }else {
@@ -341,7 +359,7 @@
            switchSecValue(secVO, secValueMap, classifyFullInfoBO, serialSecVOList, attrSecVOList, serialUnitList, secValueList);
         }
         //处理属性码段和流水码段
         Map<String/**流水码段的主键**/, Map<String/**流水依据**/, Double>> lastMaxSerialValueMap = new HashMap<>();
         Map<String/**流水码段的主键**/, Map<String/**流水依据**/, String>> lastMaxSerialValueMap = new HashMap<>();
         List<CodeAllCode> allCodeDOList = new ArrayList<>();
         //已经存储的最大流水号的内容
@@ -366,7 +384,7 @@
            switchAttrSecValue(attrSecVOList, cbo, thisSecValueList, attrSevIsSerialDepend, thisSerialUnitList);
            String serialUnitString = thisSerialUnitList.size() == 0 ? EMPTY_SERIAL_UNIT : thisSerialUnitList.stream().collect(Collectors.joining(SERIAL_UNIT_SPACE));
            switchSerialSecValue(serialSecVOList, attrSevIsSerialDepend, finalRuleVO, serialUnitString, maxSerialValueMap, thisSecValueList, lastMaxSerialValueMap, i == 0);
            switchSerialSecValue(cbo,serialSecVOList, attrSevIsSerialDepend, finalRuleVO, serialUnitString, maxSerialValueMap, thisSecValueList, lastMaxSerialValueMap, i == 0);
            //组装编码的值
            cbo.setId(thisSecValueList.stream().collect(Collectors.joining()));
@@ -375,9 +393,9 @@
            //把码段里面都找一下流水号
            for (int j = 0; j < serialSecVOList.size(); j++) {
               CodeBasicSecVO secVO = serialSecVOList.get(j);
               Double serialValue = lastMaxSerialValueMap.getOrDefault(secVO.getOid(), new HashMap<>()).getOrDefault(serialUnitString, 0d);
               String serialValue = lastMaxSerialValueMap.getOrDefault(secVO.getOid(), new HashMap<>()).getOrDefault(serialUnitString, "");
               if (serialValue != null) {
                  sb.append(String.valueOf(serialValue.longValue())).append(SERIAL_VALUE_SPACE);
                  sb.append(serialValue).append(SERIAL_VALUE_SPACE);
               }
            }
            //要存储最后的全部allcode
@@ -389,14 +407,10 @@
         allCodeDOList.stream().forEach(
            allCode -> {DefaultAttrAssimtUtil.addDefaultAttrAssimt(allCode,"codeallcode");allCode.setLctid("codeAllCodeLC");}
         );
         Map<String, String> statusMap = allCodeDOList.stream().collect(Collectors.toMap(s -> s.getOid(), s -> s.getLcStatus()));
         allCodeDOList.stream().filter(s -> StringUtils.equalsIgnoreCase("codeallcode",s.getBtmname())).forEach(s -> {
            s.setLcStatus(statusMap.get(s.getOid()));
         });
         //通过ID来进行去重
         List<CodeAllCode> distinctCodeAllCOdes = allCodeDOList.stream().collect(Collectors
            .collectingAndThen(
@@ -411,7 +425,7 @@
         List<CodeAllCode> codeAllCodes = codeAllCodeService.selectByWrapper(wrapper);
         List<CodeAllCode> takeBack = codeAllCodes.stream().filter(e -> e.getLcStatus().equals("TakeBack")).collect(Collectors.toList());
         if(codeAllCodes.size()>takeBack.size()){
            throw new ServiceException("生成编码数据ID已有历史记录,请确认如下生成的ID数据:"+ allCodeDOList.stream().map(CodeAllCode::getId).collect(Collectors.toList()));
               throw new ServiceException("生成编码数据ID已有历史记录,请确认如下生成的ID数据:"+ codeAllCodes.stream().map(CodeAllCode::getId).collect(Collectors.toList()));
         }
         for (CodeAllCode codeAllCode : takeBack) {
@@ -428,12 +442,19 @@
               }
            }
         }
            mdmEngineService.insertBatchByType(dataCBOList.get(0).getBtmname(), dataCBOList);
         if(takeBack.size()>0){
            codeAllCodeService.updateBatchById(takeBack);
         }
         codeAllCodeService.saveBatch(allCodeDOList);
//         iCodeWupinService.saveBatch(dataCBOList);
         mdmEngineService.insertBatchByType(dataCBOList.get(0).getBtmname(),dataCBOList);
            // 提交事务
         //   transactionTemplate.getTransactionManager().commit(status);
         //}catch (Exception e){
            // 出现异常时回滚事务
         //   transactionTemplate.getTransactionManager().rollback(status);
         //   throw e;
         //}
//         batchCBO.getCreateCbos().stream().filter(s -> StringUtils.equalsIgnoreCase("codeallcode",s.getBtmName())).forEach(s -> {
//            s.setLcStatus(statusMap.get(s.getOid()));
//            try {
@@ -504,13 +525,27 @@
    * @param lastMaxSerialValueMap 封装后
    * @param firstData 是否为第一条数据
    */
   private void switchSerialSecValue(List<CodeBasicSecVO> serialSecVOList,boolean attrSevIsSerialDepend,
   private void switchSerialSecValue(BaseModel cbo, List<CodeBasicSecVO> serialSecVOList,boolean attrSevIsSerialDepend,
                             CodeRuleVO ruleVO,String serialUnitString,
                             Map<String/**码段的主键**/,Map<String/**流水依据**/,CodeSerialValue>> maxSerialValueMap,List<String> thisSecValueList,
                             Map<String/**码段的主键**/,Map<String/**流水依据**/, Double>> lastMaxSerialValueMap,boolean firstData){
                             Map<String/**码段的主键**/,Map<String/**流水依据**/, String>> lastMaxSerialValueMap,boolean firstData){
      if (!CollectionUtils.isEmpty(serialSecVOList)) {
         Map<String,String> secIdserialValueMap=new LinkedHashMap<>();
         for (int j = 0; j < serialSecVOList.size(); j++) {
            CodeBasicSecVO secVO = serialSecVOList.get(j);
            String secVOValue="";
            AtomicReference<String> newSerialUnitString= new AtomicReference<>(serialUnitString);
            if(j==0){
               secVOValue="";
               newSerialUnitString.set(serialUnitString.replace("${" + secVO.getOid() + "}", secVOValue));
            }else{
               CodeBasicSecVO upSecVO =serialSecVOList.get(j-1);
               secIdserialValueMap.forEach((key,vaule)->{
                  newSerialUnitString.set(serialUnitString.replace("${"+key+"}", vaule));
               });
            }
            if (attrSevIsSerialDepend || firstData) {
               //如果属性码段也是依赖,则每次都要查询,如果属性码段不是依赖,则只查询一次
//               Map<String, String> conditionMap = new HashMap<>();
@@ -519,8 +554,9 @@
//               //这个字段是为了解决多个流水的问题
//               conditionMap.put("codeSecOid", secVO.getOid());
               QueryWrapper<CodeSerialValue> codeSerialWrapper = new QueryWrapper<>();
               codeSerialWrapper.eq("codeRuleOid", ruleVO.getOid());
               codeSerialWrapper.eq("serialUnit", serialUnitString);
               codeSerialWrapper.eq("serialUnit", newSerialUnitString.get());
               codeSerialWrapper.eq("codeSecOid", secVO.getOid());
               List<CodeSerialValue> serialValueDOS = serialValueMapper.selectList(codeSerialWrapper);
               if (!CollectionUtils.isEmpty(serialValueDOS)) {
@@ -530,25 +566,41 @@
                  maxSerialValueMap.put(secVO.getOid(), unitSerialMap);
               }
            }
            Double startValue = null;
            if(maxSerialValueMap.containsKey(secVO.getOid()) && maxSerialValueMap.get(secVO.getOid()).containsKey(serialUnitString)){
               startValue = VciBaseUtil.getDouble(maxSerialValueMap.get(secVO.getOid()).get(serialUnitString).getMaxSerial());
            String serialString="";
            String thisSerialValue = "";
            String startValue = null;
            if (maxSerialValueMap.containsKey(secVO.getOid()) && maxSerialValueMap.get(secVO.getOid()).containsKey(newSerialUnitString.get())) {
               startValue = maxSerialValueMap.get(secVO.getOid()).get(newSerialUnitString.get()).getMaxSerial();
            }
            if(lastMaxSerialValueMap.containsKey(secVO.getOid()) && lastMaxSerialValueMap.get(secVO.getOid()).containsKey(serialUnitString)){
            if (lastMaxSerialValueMap.containsKey(secVO.getOid()) && lastMaxSerialValueMap.get(secVO.getOid()).containsKey(newSerialUnitString.get())) {
               //说明多个申请,之前已经加了流水号了
               startValue = lastMaxSerialValueMap.get(secVO.getOid()).get(serialUnitString);
               startValue = lastMaxSerialValueMap.get(secVO.getOid()).get(newSerialUnitString.get());
            }
            Double thisSerialValue = 0d;
            if(StringUtils.isNotBlank(secVO.getCustomCodeSerialClass())){//自定义流水处理
               String currentFlowValue=startValue;
               CodeCustomSerialDTO codeCustomSerialDTO=new CodeCustomSerialDTO();
               codeCustomSerialDTO.setSerialUnitString(newSerialUnitString.get());
               codeCustomSerialDTO.setSerialCodeCodeBasicSec(secVO);
               codeCustomSerialDTO.setCurrentFlowValue(startValue);
               codeCustomSerialDTO.setCodeBasicSecVOList(ruleVO.getSecVOList());
               codeCustomSerialDTO.setCodeRuleOid(ruleVO.getOid());
               codeCustomSerialDTO.setBaseModel(cbo);
               thisSerialValue=customCodeSerial(secVO.getCustomCodeSerialClass(),codeCustomSerialDTO);
               log.info(secVO.getCustomCodeSerialClassText()+"---->"+thisSerialValue);
            }else {
               Double newThisSerialValue = 0d;
            if (startValue == null) {
               //第一个编码
               thisSerialValue = VciBaseUtil.getDouble(secVO.getSerialStart());
                  newThisSerialValue = VciBaseUtil.getDouble(secVO.getSerialStart());
            } else {
               //流水号肯定是数字
               thisSerialValue = startValue + (j + 1) * secVO.getSerialStep();
                  newThisSerialValue = Double.parseDouble(startValue) + (j + 1) * secVO.getSerialStep();
            }
            //要看是否超过最大的流水值
            if (thisSerialValue >= secVO.getCodeFillLimit()) {
               if (newThisSerialValue >= secVO.getCodeFillLimit()) {
               throw new VciBaseException("流水号已经超过允许的最大流水值{0}",new String[]{secVO.getCodeFillLimit().toString()});
               }
               thisSerialValue=String.valueOf(newThisSerialValue.intValue());
            }
            //要看补位的内容
            Integer fillLength = VciBaseUtil.getInt(secVO.getCodeFillLength());
@@ -556,8 +608,9 @@
               //防止在添加的地方没有控制正确
               fillLength = VciBaseUtil.getInt(secVO.getCodeSecLength());
            }
            String serialString = String.valueOf(thisSerialValue.longValue());
            serialString = thisSerialValue;
            serialString = fillString(fillLength, OsCodeFillTypeEnum.forValue(secVO.getCodeFillType()), serialString, secVO.getCodeFillSeparator());
            for (int z = 0; z < thisSecValueList.size(); z++) {
               String secValue = thisSecValueList.get(z);
               if (secValue.equalsIgnoreCase("${" + secVO.getOid() + "}")) {
@@ -565,13 +618,36 @@
                  thisSecValueList.set(z, joinPreffixAndSuffix(secVO, serialString));
               }
            }
            Map<String, Double> unitSerialMap = lastMaxSerialValueMap.getOrDefault(secVO.getOid(), new HashMap<>());
            unitSerialMap.put(serialUnitString, thisSerialValue);
            secIdserialValueMap.put(secVO.getOid(),thisSerialValue);//记录流水码段当前的值
            Map<String, String> unitSerialMap = lastMaxSerialValueMap.getOrDefault(secVO.getOid(), new HashMap<>());
            unitSerialMap.put(newSerialUnitString.get(), String.valueOf(thisSerialValue));
            lastMaxSerialValueMap.put(secVO.getOid(),unitSerialMap);
         }
      }
   }
    private String customCodeSerial(String className, CodeCustomSerialDTO codeCustomSerialDTO){
      String result = "";
      try {
         Class classInstance=Class.forName(className);
         Object obj =classInstance.newInstance();
         Method method= classInstance.getMethod("serialGenerate",CodeCustomSerialDTO.class);
         method.setAccessible(Boolean.TRUE);
         //method.invoke(obj);
         Object  o= method.invoke(obj,codeCustomSerialDTO);
         result= Func.isEmpty(o) ?"":o.toString();
      } catch (ClassNotFoundException e) {
         throw new VciBaseException("未找到自定义流水算法类文件");
      } catch (InvocationTargetException e) {
         throw new VciBaseException("执行自定义流水算法处理方法出现异常");
      } catch (NoSuchMethodException e) {
         throw new VciBaseException("未找到自定义流水算法处理方法");
      } catch (IllegalAccessException e) {
         throw new VciBaseException("执行自定义流水算法处理方法出现异常");
      } catch (InstantiationException e) {
         e.printStackTrace();
      }
      return result;
   }
   /**
    * 转换码值的内容
    * @param secVO 码段的内容
@@ -769,7 +845,7 @@
    * @param maxSerialValueMap 依据存储的最大流水的内容
    */
   private void saveSerialValue(CodeRuleVO ruleVO,
                         Map<String/**码段的主键**/,Map<String, Double>> lastMaxSerialValueMap,
                         Map<String/**码段的主键**/,Map<String, String>> lastMaxSerialValueMap,
                         Map<String/**码段的主键**/,Map<String, CodeSerialValue>> maxSerialValueMap){
      List<CodeSerialValue> editSerialValueDOList = new ArrayList<>();
      List<CodeSerialValue> addSerialValueDOList = new ArrayList<>();