/**
 * Project Name: warehouse
 * File Name: CommonUtils
 * Package Name: com.starcharge.warehouse.utils
 * Date: 2020/10/22 13:38
 * Copyright (c) 2020,All Rights Reserved.
 */
package com.boco.nbd.wios.manage.util;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.boco.nbd.wios.manage.contants.WiosConstant;
import com.ihidea.component.cache.redis.RedisClient;
import com.ihidea.core.support.exception.ServiceException;
import com.ihidea.core.util.DateUtilsEx;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.RandomUtils;

import java.util.Date;

/**
 * Description
 *
 * @author lvpeng
 * @date 2020/10/22 13:38
 */
public class CommonUtils {

    private final static String LOCK_ID = "warehouse:lock:singleId:";

    private final static int LOCK_EXPIRE = 10;
    private final static int RANDOM_SIZE = 4;
    private final static int RANDOM_NEXT = 9999;

    /**
     * url统一处理=》没有前缀的统一加上
     *
     * @param url
     * @return
     */
    public static String urlHandle(String url) {
        if (StringUtils.startsWithIgnoreCase(url, WiosConstant.FILE_UPLOAD_URL_PREFIX)) {
            return url;
        }
        return (WiosConstant.FILE_UPLOAD_DEFAULT_URL + url);
    }

    /**
     * 生成单据编号
     *
     * @return
     */
    public static String singleId() {
        String singleId = DateUtilsEx.formatToString(new Date(), DatePattern.PURE_DATETIME_PATTERN)
                + StringUtils.leftPad(String.valueOf(RandomUtils.nextInt(RANDOM_NEXT)), RANDOM_SIZE, "0");
        if (!RedisClient.getLock(LOCK_ID + singleId, LOCK_EXPIRE)) {
            return singleId();
        }
        return singleId;
    }
}