package net.northking.cctp.element.mobile.utils;



import org.apache.commons.lang3.RandomStringUtils;

import java.io.UnsupportedEncodingException;
import java.util.Random;

/**
 * 随机数组件
 *
 * @author fengxiang.zhang
 * @since 1.0
 */

public class RandomUtil {



    /**
     * 在指定字符中随机生成指定长度的字符串。
     * Example:
     * <pre>
     * randomString(32, "abcdefghijkmnopqrstuvwxyz")    = opknnsvybvgzdnfxwxizfgtbxpspbjjq
     * </pre>
     *
     * @param count 长度
     * @return 字符串
     */
    public static String randomString(
             int count,
             String type) {
        if ("string".equals(type)){
            StringBuilder result= new StringBuilder();
            while (count!=0){
                double randomType=Math.random()*2;
                int randomCount;
                if (count==1){
                    randomCount =1;
                    count=0;
                }else {
                    randomCount= (int) (Math.random() * count) +1;
                    count-=randomCount;
                }
                if(randomType>=0&&randomType<1){
                    result.append(RandomStringUtils.randomAlphanumeric(randomCount));
                }else if(randomType>=1&&randomType<=2){
                    result.append(randomChinese(randomCount));
                }
            }
            return result.toString();
        }else if ("int".equals(type)){
            return  RandomStringUtils.randomNumeric(count);
        }else if ("chinese".equals(type)){
            return randomChinese(count);
        }else if ("english".equals(type)){
            return  RandomStringUtils.randomAlphabetic(count);
        }
        return RandomStringUtils.random(count);
    }

    /**
     * 生成随机中文
     * @param count
     * @return
     */
    private static String randomChinese( int count){
        StringBuilder ret= new StringBuilder();
        for(int i=0;i<count;i++) {
            String str = null;
            Random random = new Random();
            int highPos = (176 + Math.abs(random.nextInt(39))); //获取高位值
            int lowPos = (161 + Math.abs(random.nextInt(93))); //获取低位值
            byte[] b = new byte[2];
            b[0] = ((byte) highPos);
            b[1] = ((byte) lowPos);
            try {
                str = new String(b, "GBk"); //转成中文
            } catch (UnsupportedEncodingException ex) {
                System.out.println(ex.getMessage());
            }
            ret.append(str);
        }
        return ret.toString();
    }
}