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 cn.net.cpzslibs.prot.ProtBase;
import cn.net.cpzslibs.prot.SocketCreate;
import cn.net.cpzslibs.prot.handset.bean.Prot33PankuBean;

/**
 * 盘库操作
 * 
 * @author zwj 2015-9-1
 */
public class Prot33CarPanku extends ProtBase {

	private final short iTaskCode33 = 33;
	// 任务号33： 盘库统计时，上行的统计方式不对，iErrCode=0xFFC9
	public final int errUpType = 0xFFC9;
	// 任务号33： 盘库按labelID统计时，没有对应的产品ID，iErrCode=0xFFC8
	public final int errNoProductId = 0xFFC8;

	public String jsonData;// 获取到json数据
	public String errMsg;// 错误信息
	private Prot33PankuBean pankuBean;

	public void dealProt(SocketCreate create, String label) throws SocketTimeoutException, IOException {
		if (label == null || "".equals(label)) {
			label = "0";
		}
		dealProt(create, Long.valueOf(label));
	}
	public void dealProt(SocketCreate create, long iLabel) throws SocketTimeoutException, IOException {
		short type = 1;
		String Nid = "";
		sendProt(create.getDos(), iTaskCode33, type, iLabel, Nid);
		recProt(create.getDis(), iTaskCode33);
	}

	private void recProt(DataInputStream dis, short iTaskCode) throws IOException {
		recHeader(dis);
		System.out.println("1");
		if (isFFFF()) {
		
			recFFFF(dis, iTaskCode);
			if (getiRecErrcode() == errUpType) {
				errMsg = "	盘库统计时，上行的统计方式不对(" + getiRecErrcode() + ")";
			} else if (getiRecErrcode() == errNoProductId) {
				errMsg = "	盘库按labelID统计时，没有对应的产品ID(" + getiRecErrcode() + ")";
			} else {
				errMsg = "盘库异常(" + getiRecErrcode() + ")";
			}
			setSuccess(false);
			//errMsg = "盘库异常(" + getiRecErrcode() + ")";
		} else {
			setSuccess(true);
			// {
			// “rukuNum”:”20”,
			// “chukuNum”: ”20”,
			// “fankuNum”: ”20”,
			// “productName”:”汽车配件”
			// }
			short iJsonLength = dis.readShort();
			jsonData = getUTF8(dis, iJsonLength);
			Gson gson = new Gson();
			pankuBean = gson.fromJson(jsonData, Prot33PankuBean.class);
			recCheckCode(dis);
		}
	}
	public String getJsonData() {
		return jsonData;
	}

	public Prot33PankuBean getPankuBean(){
		return pankuBean;
	}
	
	public String getErrMsg() {
		if (errMsg == null) {
			errMsg = "盘库异常(未知)";
		}
		return errMsg;
	}
	private void sendProt(DataOutputStream dos, short iTaskCode, short type, long iLabel, String Nid)
			throws SocketTimeoutException, IOException {
		byte[] Nids = string2bytes(Nid);
		short iNIdSize = (short) Nids.length;
		short iBodySize = countBodySize(type, iLabel, iNIdSize, Nids);
		sendHeader(dos, iTaskCode, iBodySize);
		dos.writeShort(type);
		sendiLabel(dos, iLabel);
		dos.writeShort(iNIdSize);
		dos.write(Nids);
		sendCheckCode(dos);
	}

}
