package net.northking.cctp.element.internal.protocol.socket.cups8583;

import org.apache.commons.lang3.StringUtils;

import java.text.DecimalFormat;
import java.util.BitSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CupsUtils {

    public int hex2int(String str) {
        String myStr[] = {"a", "b", "c", "d", "e", "f"};
        int result = 0;
        int n = 1;
        for (int i = str.length() - 1; i >= 0; i--) {
            String param = str.substring(i, i + 1);
            for (int j = 0; j < myStr.length; j++) {
                if (param.equalsIgnoreCase(myStr[j])) {
                    param = "1" + String.valueOf(j);
                }
            }
            result += Integer.parseInt(param) * n;
            n *= 16;
        }
        return result;
    }

    public static String int2char2(int val) {
        DecimalFormat fmt = new DecimalFormat("00");

        if ((val < 0) || (val > 99))
            return null;
        return fmt.format(val);
    }

    public static String int2char3(int val) {
        DecimalFormat fmt = new DecimalFormat("000");

        if ((val < 0) || (val > 999))
            return null;
        return fmt.format(val);
    }

    public static String int2char4(int val) {
        DecimalFormat fmt = new DecimalFormat("0000");

        if ((val < 0) || (val > 9999))
            return null;
        return fmt.format(val);
    }

    /**
     * BCD码转为10进制串
     */
    public static String bcd2String(byte[] bytes, boolean deleteflag) {
        StringBuffer sb = new StringBuffer(bytes.length * 2);
        for (int i = 0; i < bytes.length; i++) {
            sb.append((byte) ((bytes[i] & 0xf0) >>> 4)).append(
                    (byte) (bytes[i] & 0x0f));
        }
        return deleteflag ? sb.substring(1) : sb.toString();
    }


    /**
     * 10进制转为BCD码
     * 前补0
     */
    public static byte[] string2Bcd(String str) {
        String s = str.toUpperCase();
        if (s.length() % 2 != 0)
            s = "0" + s;
        byte[] buffer = new byte[s.length() / 2];
        for (int i = 0; i < buffer.length; i++) {
            int i1, i2;
            char c1, c2;
            c1 = s.charAt(2 * i);
            if (c1 - 'A' >= 0) {
                i1 = c1 - 'A' + 10;
            } else {
                i1 = c1 - '0';
            }
            c2 = s.charAt(2 * i + 1);
            if (c2 - 'A' >= 0) {
                i2 = c2 - 'A' + 10;
            } else {
                i2 = c2 - '0';
            }
            buffer[i] = (byte) (i1 * 0x10 + i2);
        }
        return buffer;
    }

    /**
     * 字符串转制成ASCII码，返回字节数组
     */
    public static byte[] getAsciiBytes(String input) {
        char[] c = input.toCharArray();
        byte[] b = new byte[c.length];
        for (int i = 0; i < c.length; i++)
            b[i] = (byte) (c[i] & 0x007F);

        return b;
    }

    public static BitSet getBitMap(byte[] bitmap, int len) {
        if (bitmap == null)
            return null;
        BitSet bs = new BitSet(128 + 1);
        for (int i = 0; i < len * 8; i++) {
            if (((bitmap[i / 8]) & 0xff & (0x80 >>> (i % 8))) != 0)
                bs.set(i + 1, true);
        }
        return bs;
    }

    public static String bytes2BinaryStr(byte... bs) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < bs.length; i++) {
            sb.append(StringUtils.leftPad(Integer.toBinaryString(bs[i] & 0xFF), 8, "0"));
        }
        return sb.toString();
    }

    public static String byte2BinaryStr(byte b) {
        return StringUtils.leftPad(Integer.toBinaryString(b & 0xFF), 8, "0");
    }

    /**
     * 二进制字符串转字节数组
     */
    public static byte[] binaryStr2Bytes(String binaryStr) {
        int n = binaryStr.length() % 8;
        if (n != 0) {
            binaryStr = StringUtils.leftPad(binaryStr, 8 - n, "0");
        }
        int len = binaryStr.length() / 8;
        byte[] bytes = new byte[len];
        for (int k = 0; k < len; k++) {
            String s = StringUtils.substring(binaryStr, k * 8, (k + 1) * 8);
            bytes[k] = binaryStr2Byte(s);
        }
        return bytes;
    }

    /**
     * 二进制字符串转字节
     */
    public static byte binaryStr2Byte(String binaryStr) {
        if (binaryStr.length() > 8) {
            throw new IllegalArgumentException("长度限制8位，已超长");
        }
        binaryStr = StringUtils.leftPad(binaryStr, 8, "0");
        byte b = 0x00;
        for (int i = binaryStr.length() - 1, j = 0; i >= 0; i--, j++) {
            b += Byte.parseByte(binaryStr.charAt(i) + "") * Math.pow(2, j);
        }
        return b;
    }

    public static String leftPad(String str, int size, String padStr) {
        if (size <= 0) {
            return str;
        }
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < size; i++) {
            sb.append(padStr);
        }
        return sb.toString() + str;
    }

    public static String rightPad(String str, int size, String padStr) {
        if (size <= 0) {
            return str;
        }
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < size; i++) {
            sb.append(padStr);
        }
        return str + sb.toString();
    }

    public static String byte2Hex(byte[] bs, int len) {
        return byte2Hex(bs, 0, len);
    }

    public static String byte2Hex(byte[] bs, int offset, int len) {
        StringBuffer sb = new StringBuffer();
        byte hi, lo;
        for (int i = offset; i < offset + len; i++) {
            hi = (byte) ((bs[i] >> 4) & 0x0f);
            lo = (byte) (bs[i] & 0x0f);

            hi = (hi < 10 ? (byte) (hi + '0') : (byte) (hi - 10 + 'A'));
            lo = (lo < 10 ? (byte) (lo + '0') : (byte) (lo - 10 + 'A'));

            sb.append((char) hi);
            sb.append((char) lo);
        }
        return new String(sb);
    }

    /**
     * 是否数字字符串
     */
    public static boolean isNumberStr(String str) {
        char ch;
        for (int i = 0; i < str.length(); i++) {
            ch = str.charAt(i);
            if (ch < '0' || ch > '9')
                return false;
        }
        return true;
    }

    /**
     * 是否二进制字符串
     */
    public static boolean isBinaryStr(String str) {
        char ch;
        for (int i = 0; i < str.length(); i++) {
            ch = str.charAt(i);
            if (ch != '0' && ch != '1')
                return false;
        }
        return true;
    }

    public static String toHexString(String s) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            int ch = s.charAt(i);
            String s4 = Integer.toHexString(ch);
            sb.append(s4);
        }
        return sb.toString();
    }

    /**
     * 把字节数组转换成16进制字符串
     */
    public static String bytes2HexString(byte[] bytes) {
        if (bytes == null) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            sb.append(String.format("%02X", bytes[i]));
        }
        return sb.toString();
    }

    /**
     * 16进制字符串转字节数组
     */
    public static byte[] hexString2Bytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (char2Byte(hexChars[pos]) << 4 | (char2Byte(hexChars[pos + 1])) & 0xff);
        }
        return d;
    }

    private static byte char2Byte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    public static String ascii2String(byte[] hex) {
        if (hex.length == 0)
            return null;
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < hex.length; i++) {
            int ci = hex[i];
            char c = (char) ci;
            buf.append(c);
        }
        return buf.toString();
    }

    /**
     * 16进制字符串转换成字节数组
     */
    public static byte[] hexString2Byte(String hex) {
        int len = (hex.length() / 2);
        byte[] result = new byte[len];
        char[] chars = hex.toCharArray();
        for (int i = 0; i < len; i++) {
            int pos = i * 2;
            result[i] = (byte) (char2Byte(chars[pos]) << 4 | (char2Byte(chars[pos + 1])) & 0xff);
        }
        return result;
    }

    /**
     * 对字节数组分组后做异或运算
     */
    public static String getXorString(byte[] xorbyte) {
        String hexString = "";
        int len = xorbyte.length;// 做异或运算数组的长度
        int remainderlen = 0;// 余数
        int addlen = 0;
        byte[] addbyte = new byte[8];
        if (len % 8 != 0) {
            remainderlen = len % 8;// 余数
            addlen = 8 - remainderlen;
            for (int i = 0; i < addlen; i++) {
                addbyte[i] = 0x00;
            }
        }
        byte[] Xorbyte = new byte[len + addlen];
        System.arraycopy(xorbyte, 0, Xorbyte, 0, len);
        if (addlen > 0) {
            System.arraycopy(addbyte, 0, Xorbyte, len, addlen);
        }

        int number = (len + addlen) / 8;// 循环次数
        // 分组进行异或运算
        byte[] xorCycleA = new byte[8];// 异或运算的数组
        byte[] xorCycleB = new byte[8];// 异或运算的数组
        byte[] resultCycle = new byte[8];// 异或运算的结果数组
        if (number > 2) {
            // 先做第一组和第二组的异或
            System.arraycopy(Xorbyte, 0, xorCycleA, 0, 8);
            System.arraycopy(Xorbyte, 8, xorCycleB, 0, 8);
            resultCycle = getXorbyte(xorCycleA, xorCycleB);
            for (int i = 2; i < number; i++) {
                System.arraycopy(resultCycle, 0, xorCycleA, 0, 8);
                System.arraycopy(Xorbyte, i * 8, xorCycleB, 0, 8);
                resultCycle = getXorbyte(xorCycleA, xorCycleB);
            }
            hexString = CupsUtils.bytes2HexString(resultCycle);
        } else if (number == 2) {
            System.arraycopy(Xorbyte, 0, xorCycleA, 0, 8);
            System.arraycopy(Xorbyte, 8, xorCycleB, 0, 8);
            resultCycle = getXorbyte(xorCycleA, xorCycleB);
            hexString = CupsUtils.bytes2HexString(resultCycle);
        } else {// 只有8个字节时是否需要做异或？
            hexString = "";
        }

        return hexString;
    }

    public static byte[] getXorbyte(byte[] xorCycleA, byte[] xorCycleB) {
        byte[] resultCycle = new byte[8];// 结果为8个字节
        for (int i = 0; i < xorCycleA.length; i++) {
            resultCycle[i] = (byte) (xorCycleA[i] ^ xorCycleB[i]);
        }
        return resultCycle;
    }

    /**
     * 得到字符串中汉字的数量
     */
    public static int countChinChar(String str) {
        int count = 0;
        String regEx = "[\\u4e00-\\u9fa5]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        while (m.find()) {
            count += 1;
        }
        return count;
    }

    /**
     * 10进制转为BCD码
     * 后补0
     * *
     */
    public static byte[] string2BcdFillRightZero(String str) {
        String s = str.toUpperCase();
        if (s.length() % 2 != 0)
            s = s + "0";
        byte[] buffer = new byte[s.length() / 2];
        for (int i = 0; i < buffer.length; i++) {
            int i1, i2;
            char c1, c2;
            c1 = s.charAt(2 * i);
            if (c1 - 'A' >= 0) {
                i1 = c1 - 'A' + 10;
            } else {
                i1 = c1 - '0';
            }
            c2 = s.charAt(2 * i + 1);
            if (c2 - 'A' >= 0) {
                i2 = c2 - 'A' + 10;
            } else {
                i2 = c2 - '0';
            }
            buffer[i] = (byte) (i1 * 0x10 + i2);
        }
        return buffer;
    }

}