package com.liquidnet.service.adam.util;

import com.liquidnet.commons.lang.util.MD5;

import java.nio.charset.StandardCharsets;
import java.util.Calendar;
import java.util.Random;

/**
 * 会员码相关工具类
 */
public class MemberUtil {

    /**
     * 获取
     *
     * @return
     */
    public static boolean getOneFromRepertory() {
        return false;
    }

    public static String buyCode() {
        return genMemberCode(0);
    }

    public static String freeCode() {
        return genMemberCode(1);
    }

    public static String genMemberCode(Integer type) {
        String code = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        Random rand = new Random();
        String word = String.valueOf(code.charAt(rand.nextInt(code.length())));

        Calendar calendar = Calendar.getInstance();
        String month = String.valueOf(calendar.get(Calendar.MONTH - 1));
        String day = String.valueOf(calendar.get(Calendar.DAY_OF_MONTH));
        String time = String.valueOf(calendar.getTimeInMillis()).substring(5, 10);
        String microTime = String.valueOf(calendar.getTimeInMillis() * 1000).substring(2, 5);
        String  sign = word.concat(month).concat(day).concat(time).concat(microTime);
        sign =  String.format(sign + "%02d", rand.nextInt(99));
        sign = MD5.getStrMD5(sign);

        String s = "0123456789ABCDEFGHIJKLMNOPQRSTUV";

        char[] chars = sign.toCharArray();
        String g = "";
        char[] sChar = s.toCharArray();
        for (int i = 0;i < 8;i++) {
            int a = ord(chars[i]);
            int f = ord(chars[i + 8]);
            int index = (a ^ f) - a & 0x1F;
            char sc = sChar[index];
            g += sc;
        }
        String randomPre = String.valueOf(sChar[rand.nextInt(s.length())]);
        if (1 == type) { // 赠送
            g = "G".concat(randomPre).concat(g);
        } else { // 购买
            g = "B".concat(randomPre).concat(g);
        }
        return g;
    }

    public static int ord(String s){
        return s.length() > 0 ? (s.getBytes(StandardCharsets.UTF_8)[0] & 0xff) : 0;
    }

    public static int ord (char c){
        return 0 < 0x80 ? c : ord(Character.toString(c));
    }
}
