CodeEnum.java 2.9 KB

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