package com.crm.rely.backend.util;

import com.google.common.base.Joiner;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by max on 2020/4/1.
 */
public class StampUtil {

    private static List<String> codes = new ArrayList<>();

    static {
        String[] codesArray = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
                "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
                "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};
        Collections.addAll(codes, codesArray);
    }


    public static String getStamp(String innerCode) {
        String[] innerCodeSplit = innerCode.split("");
        String first = innerCodeSplit[innerCodeSplit.length - 2];
        String last = innerCodeSplit[innerCodeSplit.length - 1];
        /*
            处理last
		 */
        int lastIndex = 0;
        for (int i = 0; i < codes.size(); i++) {
            if (codes.get(i).equals(last)) {
                lastIndex = i;
                break;
            }
        }
        if (lastIndex == codes.size() - 1) {
            last = codes.get(0);
            int firstIndex = 0;
            for (int j = 0; j < codes.size(); j++) {
                if (codes.get(j).equals(first)) {
                    firstIndex = j;
                    break;
                }
            }
            if (firstIndex == codes.size() - 1) {
                return null;
            }
            innerCodeSplit[innerCodeSplit.length - 1] = codes.get(0);
            innerCodeSplit[innerCodeSplit.length - 2] = codes.get(firstIndex + 1);
        } else {
            innerCodeSplit[innerCodeSplit.length - 1] = codes.get(lastIndex + 1);
        }
        Joiner joiner = Joiner.on("");
        return joiner.join(innerCodeSplit);
    }

    public static Integer getCodeByteSum(String innerCode) {
        byte[] bytes = innerCode.getBytes();
        Integer sum = 0;

        for (int i = 0; i < bytes.length; i++) {
            sum += (bytes.length - i) * (72) * bytes[i];
        }

        return sum;
    }

    public static boolean compareStamp(String one, String two) {

        byte[] bs1 = one.getBytes();
        byte[] bs2 = two.getBytes();
        boolean rs = false;

        if (bs1.length != bs2.length){
            return false;
        }

        for (int i = 0; i < bs1.length; i++) {
            if (bs1[i] < bs2[i]) {
                rs = true;
                break;
            }
        }

        return rs;

    }

    public static String formatIdStamp(Long id, String pIdStamp) {
        return String.format("%s_%d", (StringUtils.isEmpty(pIdStamp) ? "01" : pIdStamp), id);
    }

}
