package cn.net.cpzslibs.prot.handset;

import com.google.gson.Gson;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.Map;

import cn.net.cpzslibs.prot.ProtBase;
import cn.net.cpzslibs.prot.SocketCreate;
import cn.net.cpzslibs.prot.handset.bean.Prot37ReturnedBean;

/**
 * 车牌号验证，获取对应的车架号和发动机号
 * 
 * @author zwj
 * 
 * @date 2015-12-29 下午3:52:34
 */
public class Prot37CarReturned extends ProtBase {
	private final short iTaskCode37 = 37;
	private String rJson;

	public void dealProt(SocketCreate socketCreate, String[] labels) throws IOException {
		Gson gson = new Gson();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("labels", labels);
		String sJson = gson.toJson(map);
		sendProt(socketCreate.getDos(), iTaskCode37, sJson);
		recProt(socketCreate.getDis(), iTaskCode37);
	}

	/**
	 * 没数据为null
	 */
	public String getJson() {
		return rJson;
	}

	public Prot37ReturnedBean getReturnedBean() {
		if (rJson == null || rJson.isEmpty() || !isSuccess()) {
			return null;
		}
		Gson gson = new Gson();
		Prot37ReturnedBean bean = gson.fromJson(rJson, Prot37ReturnedBean.class);
		return bean;
	}

	private void recProt(DataInputStream dis, short iTaskCode) throws IOException {
		recHeader(dis);
		if (isTaskCode(iTaskCode)) {
			setSuccess(true);
			int iBodySize = getiRecBodySize();
			rJson = getUTF8(dis, iBodySize - 2);
			recCheckCode(dis);
		} else {
			setSuccess(false);
			if (isFFFF()) {
				recFFFF(dis, iTaskCode);
			} else {

			}
		}

	}
	private void sendProt(DataOutputStream dos, short iTaskCode, String json) throws SocketTimeoutException,
			IOException {
		byte[] sendCarNums = string2bytes(json);
		short iBodySize = countBodySize(sendCarNums);
		sendHeader(dos, iTaskCode, iBodySize);
		dos.write(sendCarNums);
		sendCheckCode(dos);
	}
}
