CodeEnum.java 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package com.sd.business.util;
  2. import cn.hutool.core.convert.Convert;
  3. import cn.hutool.core.date.DateUtil;
  4. import cn.hutool.core.text.CharSequenceUtil;
  5. import cn.hutool.core.util.ObjectUtil;
  6. import cn.hutool.extra.spring.SpringUtil;
  7. import com.baomidou.mybatisplus.extension.service.IService;
  8. import com.ruoyi.common.exception.ServiceException;
  9. import lombok.Getter;
  10. import java.util.Date;
  11. import java.util.Map;
  12. @Getter
  13. public enum CodeEnum {
  14. ;
  15. // 编码前缀
  16. private final String prefix;
  17. // 编码加日期规则
  18. private final String dateFormat;
  19. // 长度
  20. private final Integer length;
  21. // 编码字段名
  22. private final String codeFieldName;
  23. // service
  24. private final IService<?> service;
  25. CodeEnum(String prefix, String dateFormat, String codeFieldName, Integer length, Class<? extends IService<?>> serviceCls) {
  26. this.prefix = prefix;
  27. this.dateFormat = dateFormat;
  28. this.length = length;
  29. this.codeFieldName = codeFieldName;
  30. this.service = SpringUtil.getBean(serviceCls);
  31. }
  32. /**
  33. * 不够位数的在前面补0,保留num的长度位数字
  34. */
  35. private static String autoGenericCode(int length, Integer codeNum) {
  36. return String.format("%0" + length + "d", codeNum + 1);
  37. }
  38. // /**
  39. // * 获取键值对
  40. // */
  41. // public String getCode(String code) {
  42. // if (ObjectUtil.isNotEmpty(code)) {
  43. // Long count = service.query().eq(codeFieldName, code).count();
  44. // if (count != 0) {
  45. // throw new ServiceException("编码已存在");
  46. // }
  47. // return code;
  48. // } else {
  49. // return getCode();
  50. // }
  51. // }
  52. /**
  53. * 获取键值对
  54. */
  55. public String getCode() {
  56. String itemPrefix;
  57. if (ObjectUtil.isNotEmpty(dateFormat)) {
  58. Date date = new Date();
  59. String format = DateUtil.format(date, dateFormat);
  60. itemPrefix = prefix + format;
  61. } else {
  62. itemPrefix = prefix;
  63. }
  64. Object obj = service.query()
  65. .likeRight(codeFieldName, itemPrefix)
  66. .orderByDesc(codeFieldName)
  67. .last("limit 1")
  68. .one();
  69. if (obj == null) {
  70. return itemPrefix + autoGenericCode(length, 0);
  71. }
  72. Map<String, Object> map = Convert.toMap(String.class, Object.class, obj);
  73. String code = Convert.toStr(map.get(CharSequenceUtil.toCamelCase(codeFieldName)));
  74. Integer codeNum = Convert.toInt(code.substring(itemPrefix.length()));
  75. if (ObjectUtil.isEmpty(codeNum)) {
  76. throw new ServiceException("自定义编码与系统编码生成规则冲突,暂时无法生成编码,请联系管理员");
  77. }
  78. return itemPrefix + autoGenericCode(length, codeNum);
  79. }
  80. }