package com.wsm.admin.device.tcp;

import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * 井盖报文解析
 */
public class ConvertData {

	private List<Rule> ruleList = new ArrayList<>();

	public ConvertData() {
		ruleList.add(new Rule("sn1", "string", 22, 26));
		ruleList.add(new Rule("sn2", null, 26, 46));
		ruleList.add(new Rule("yyyy", "int", 46, 48));
		ruleList.add(new Rule("MM", "int", 48, 50));
		ruleList.add(new Rule("dd", "int", 50, 52));
		ruleList.add(new Rule("HH", "int", 52, 54));
		ruleList.add(new Rule("mm", "int", 54, 56));
		ruleList.add(new Rule("ss", "int", 56, 58));
		ruleList.add(new Rule("x", "int", 58, 62));
		ruleList.add(new Rule("y", "int", 62, 66));
		ruleList.add(new Rule("z", "int", 66, 70));
		ruleList.add(new Rule("CSQ", "int", 74, 78));
		ruleList.add(new Rule("RSRQ", "int", 78, 82));
		ruleList.add(new Rule("SNR", "int", 82, 86));
		ruleList.add(new Rule("RSRP", "int", 86, 90));
		ruleList.add(new Rule("经度方向", "string", 90, 92));
		ruleList.add(new Rule("经度", "string", 92, 112));
		ruleList.add(new Rule("纬度方向", "string", 112, 114));
		ruleList.add(new Rule("纬度", "string", 114, 134));
		ruleList.add(new Rule("status", null, 134, 142));
		ruleList.add(new Rule("type", "int", 142, 144));

	}

	public Map<String, Object> convert(String date) {
		//此例子没做对数据的校验
		Map<String, Object> reHm = new TreeMap<>();
		for (Rule rule : ruleList) {
			if (rule.getStart() < date.length() && rule.getEnd() < date.length()) {
				String inString = date.substring(rule.getStart(), rule.getEnd());
				if ("int".equals(rule.getType())) {
					reHm.put(rule.getName(), hexStr2Int(inString));
				} else if ("string".equals(rule.getType())) {
					reHm.put(rule.getName(), hexStr2String(inString));
				} else {
					reHm.put(rule.getName(), inString);
				}
			}
		}
		return reHm;
	}

	private int hexStr2Int(String hexString) {
		int ret = Integer.parseInt(hexString, 16);
		ret = ((ret & 0x8000) > 0) ? (ret - 0x10000) : (ret);
		return ret;
	}

	private String hexStr2String(String hexStr) {
		String str = "0123456789ABCDEF";
		char[] hexs = hexStr.toCharArray();
		byte[] bytes = new byte[hexStr.length() / 2];
		int n;
		for (int i = 0; i < bytes.length; i++) {
			n = str.indexOf(hexs[2 * i]) * 16;
			n += str.indexOf(hexs[2 * i + 1]);
			bytes[i] = (byte) (n & 0xff);
		}
		return new String(bytes);
	}

	public static void main(String[] args) {
		String d = "010001004A0000A3010044514300010003020100000001130C12031632FFF6000000FA00000000000000000000453131332E3536393635364E3032322E3337363732360000000055550000000000006140";
		System.out.println(d.length());
		ConvertData cd = new ConvertData();
		Map<String, Object> hm = cd.convert(d);
		System.out.println(JSON.toJSONString(hm));
	}

}

