package cn.quantgroup.customer.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.*;
import java.util.Calendar;

public class IdUtil {
    /** .log */
    private final static Logger logger = LoggerFactory.getLogger(IdUtil.class);
    /** The FieldPosition. */
    private static final FieldPosition HELPER_POSITION = new FieldPosition(0);
    /** This Format for format the data to special format. */
    private final static Format dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
    /** This Format for format the number to special format. */
    private final static NumberFormat numberFormat = new DecimalFormat("000");
    /** This int is the sequence number ,the default value is 0. */
    private static int seq = 0;

    private static final int MAX = 999;

    /**
     * 时间格式生成序列
     *
     * @return String
     */
    public static String generateSequenceNo() {
        return generateSequenceNo("Q");
    }
    /**
     * 时间格式生成序列
     *
     * @return String
     */
    public static synchronized String generateSequenceNo(String prefix) {
        Calendar rightNow = Calendar.getInstance();
        StringBuffer sb = new StringBuffer();
        dateFormat.format(rightNow.getTime(), sb, HELPER_POSITION);
        numberFormat.format(seq, sb, HELPER_POSITION);

        if (seq == MAX) {
            seq = 0;
        } else {
            seq++;
        }

        if(StringUtils.isEmpty(prefix)){
            prefix = "C";
        }
        String ip = IpAddrUtils.getHostIp();
        Integer ipValue = Integer.parseInt(ip.split("\\.")[ip.split("\\.").length - 1]);
        StringBuffer ipStr = new StringBuffer();
        numberFormat.format(ipValue,ipStr,HELPER_POSITION);
        String idNo = prefix + sb.toString() + ipStr.toString();
        logger.debug("THE SQUENCE IS :" + idNo);
        return idNo;
    }

    public static void main(String[] args) {
//        for (int i = 0; i < 1000; i++) {
//            System.out.println(generateSequenceNo());
//        }
        System.out.println(System.currentTimeMillis());
        //System.out.println(dateFormat.format(Calendar.getInstance().getTime().getTime(), new StringBuffer(), HELPER_POSITION));
    }
}
