package com.engine.organization.util.coderule;

import com.engine.hrm.entity.RuleCodeType;
import com.engine.hrm.util.CodeRuleManager;
import com.engine.organization.entity.codesetting.po.CodeRulePO;
import com.engine.organization.mapper.codesetting.CodeRuleMapper;
import com.engine.organization.util.db.MapperProxyFactory;
import weaver.general.Util;

/**
 * @description:
 * @author:dxfeng
 * @createTime: 2022/06/06
 * @version: 1.0
 */
public class CodeRuleUtil {
    /**
     * 自动编号
     *
     * @param ruleCodeType
     * @param code
     * @return
     */
    public static String generateCode(RuleCodeType ruleCodeType, String code) {
        try {
            return CodeRuleManager.getCodeRuleManager().generateRuleCode(ruleCodeType, code);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 复制过程 自动生成编号
     *
     * @param ruleCodeType
     * @param code
     * @param timeMillis
     * @return
     */
    public static String generateCode(RuleCodeType ruleCodeType, String code, long timeMillis) {
        if (isAutoCode(ruleCodeType)) {
            return generateCode(ruleCodeType, "");
        } else {
            return generateCode(ruleCodeType, Util.null2String(code) + "_" + timeMillis);
        }
    }

    private static boolean isAutoCode(RuleCodeType ruleCodeType) {
        CodeRulePO codeRuleByType = MapperProxyFactory.getProxy(CodeRuleMapper.class).getCodeRuleByType(ruleCodeType.getValue());
        return null != codeRuleByType && "1".equals(codeRuleByType.getSerialEnable());
    }
}
