package cn.net.caoyao.cpzshandset.service.thread.impl.chinatex;

import java.io.IOException;
import java.net.BindException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import android.os.Handler;
import android.os.Message;
import cn.net.caoyao.cpzshandset.common.config.Config;
import cn.net.caoyao.cpzshandset.common.config.RequestConstant;
import cn.net.caoyao.cpzshandset.common.config.TConfig;
import cn.net.caoyao.cpzshandset.common.util.LogUtil;
import cn.net.cpzslibs.prot.Prot02Logout;
import cn.net.cpzslibs.prot.SocketCreate;
import cn.net.cpzslibs.prot.handset.bean.req.Prot20019ReqBean;
import cn.net.cpzslibs.prot.handset.newProt.Prot20019ChaXun;

/**
 * @author 作者 李扬:
 * @date 创建时间：2017-5-8 上午9:15:25
 * @version 1.0
 * @parameter
 * @since
 * @return
 */
public class ChinatexSubmitQueryThread implements Runnable {
	private long deviceId;
	private Handler mHandler;

	private String label, iemi;

	public ChinatexSubmitQueryThread(long deviceId, Handler mHandler,
			String label, String iemi) {
		this.deviceId = deviceId;
		this.mHandler = mHandler;
		this.label = label;
		this.iemi = iemi;
	}

	@Override
	public void run() {
		SocketCreate create = new SocketCreate(Config.ip, Config.port, "");

		try {
			LogUtil.d(TConfig.Echo, "登录");
			create.createLoginCpzsHandset(deviceId);
			if (create.isResult()) {
				submitQueryInfo(create);
			} else {
				Message msg = new Message();
				msg.what = RequestConstant.REQUEST_PROT01_LOGIN_FAIL;
				msg.arg1 = create.getiErrCode();
				msg.obj = create.getErrMsg();
				mHandler.sendMessage(msg);
			}
		} catch (BindException e) {
			e.printStackTrace();
			mHandler.sendEmptyMessage(RequestConstant.REQUEST_FAIL);
		} catch (ConnectException e) {
			e.printStackTrace();
			mHandler.sendEmptyMessage(RequestConstant.REQUEST_FAIL);
		} catch (SocketTimeoutException e) {
			e.printStackTrace();
			mHandler.sendEmptyMessage(RequestConstant.REQUEST_FAIL_SOCKET_TIMEOUT);
		} catch (UnknownHostException e) {
			e.printStackTrace();
			mHandler.sendEmptyMessage(RequestConstant.REQUEST_FAIL);
		} catch (IOException e) {
			e.printStackTrace();
			mHandler.sendEmptyMessage(RequestConstant.REQUEST_FAIL);
		} finally {
			new Prot02Logout().dealLogout(create);
		}

	}

	private void submitQueryInfo(SocketCreate create) throws IOException {
		Prot20019ChaXun p219 = new Prot20019ChaXun();
		p219.dealQuery(create, new Prot20019ReqBean(iemi, label));
		int res = p219.getResBean().getiResult();
		Message msg = new Message();
		if (res == 0) {// 查询成功
			msg.what = RequestConstant.PROT_CHECK_LABEL_SUCCESS;
			msg.obj = p219.getResBean();
			mHandler.sendMessage(msg);
		} else {// 查询失败
			msg.what = RequestConstant.PROT_CHECK_LABEL_FAIL;
			msg.arg1 = res;
			// msg.obj = create.getErrMsg();
			mHandler.sendMessage(msg);
		}

	}

}
