package elect;

public class ValidationCodeGenerater {
	/**
	 * 生成验证码
	 * 
	 * @param bufSend 
	 * @return
	 */
	public static byte[] generateValidatitonCode(byte[] bufSend) {
		//bufSend是除总数据长度、校验码外的所有包数据
		
		// string strLen=bufSend.Length.ToString("000");
		String strLen = leftPad((String.valueOf(bufSend.length)), 3, "0");
		System.out.println(String.valueOf(bufSend.length) + strLen);
		// byte[] bufTmp = new byte[bufSend.length];
		byte[] bufPack = new byte[bufSend.length + 5];
		byte CheckMac = 0;
		byte[] bufLen = strLen.getBytes();
		//加总数据长度
		System.arraycopy(bufLen, 0, bufPack, 0, 3);
		//加全部包数据
		System.arraycopy(bufSend, 0, bufPack, 3, bufSend.length);
		
		//计算校验码
		CheckMac = (byte) (CheckMac ^ (bufPack[0]));
		CheckMac = (byte) (CheckMac ^ (bufPack[1]));
		CheckMac = (byte) (CheckMac ^ (bufPack[2]));
		for (int i = 0; i < bufSend.length; i++)
			CheckMac = (byte) (CheckMac ^ bufSend[i]);
		//System.arraycopy(bufSend, 0, bufPack, 3, bufSend.length);
		
		byte[] buf1 = new byte[1];
		buf1[0] = CheckMac;
		byte[] buf2 = dat_bcdtoasc(buf1, buf1.length);
		//System.out.println(new String(buf2));
		//加校验码
		System.arraycopy(buf2, 0, bufPack, 3 + bufSend.length, buf2.length);
		return bufPack;
	}


	
	public static byte[] dat_bcdtoasc(byte[] bcd, int bcd_len) {
		byte[] asc = new byte[bcd_len * 2];
		int i, j = 0;
		int ch, cl;
		for (i = 0; i < bcd_len; i++) {
			if (bcd[i] > 0)// 如果不为零
			{
				ch = bcd[i] / 16 + '0';
				cl = bcd[i] % 16 + '0';
				if (ch > '9')
					ch += ('A' - '9' - 1);// 如果大于9
				if (cl > '9')
					cl += ('A' - '9' - 1);
			} else {
				ch = '0';
				cl = '0';
			}
			asc[j++] = (byte) ch;
			asc[j++] = (byte) cl;
		}
		return asc;
	}
	
	/**
	 * 
	 * @param s1
	 * @param n
	 * @param s2
	 * @return 往s1左边补(n-s1.length)个s2后的新字符串
	 */
	public static String leftPad(String s1, int n, String s2) {
		String temp = "";
		int len = s1.length();
		int sum = n - len;
		for (int i = 0; i < sum; i++)
			temp += s2;
		return temp + s1;
	}
	
	public static void main(String[] args) {
		//0921008085PC711|43181349|1462849227000|ff04c2fff657b9b11ceeaaa2b050d430|4601|66721026#20120419
		//ValidationCodeGenerater vcg = new ValidationCodeGenerater();
		//System.out.println("PC711|43181349|1462849227000|ff04c2fff657b9b11ceeaaa2b050d430|4601|66721026#201204".length());
		//System.out.println("1008085PC711|43181349|1462849227000|ff04c2fff657b9b11ceeaaa2b050d430|4601|66721026#201204".length());
		//0981008085WAN001|43181512|1464749346406|31a3eefa7ac1f382509a79838e2
		byte []  data = ValidationCodeGenerater.generateValidatitonCode("1008088WAN001|43181512|1464715205109.38|4a05f3bc2d27a6d014c0628a3f97c7b1|4601|0800050052781700#999999".getBytes());
		System.out.println(new String(data));
		
	}
}
