/**
 * bobotuan.com Inc.
 * Copyright (c) 2004-2020 All Rights Reserved.
 */
package com.qs.mp.system.service.id;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 业务ID生成器
 *
 * @author chunping.zhongcp
 * @version $Id: BizIdGenerator.java, v 0.1 2020/5/28 chunping.zhongcp Exp $
 */
@Component
public class BizIdGenerator {

    @Autowired
    private SnowflakeIdWorker bizIdWorker;

    /**
     * 这个方法只提供给拿不到租户ID（cust_id）的场景下使用，其他一律使用newIdWithUidSharding方法
     * 长度20位
     * @return
     */
    public String newId(){
        return String.valueOf(bizIdWorker.nextId());
    }

    /**
     * 长度22位，最后两位为分表位
     *
     * @param custId
     * @return
     */
    public String newIdWithUidSharding(String custId){
        return String.valueOf(bizIdWorker.nextId()) + getSharding(custId);
    }

    /**
     * 获取用户ID的分表位
     * @param custId
     * @return
     */
    private String getSharding(String custId){
        int length = custId.length();
        if (length > 1) {
            return custId.substring(length - 2, length);
        } else {
            return custId;
        }
    }
}
