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

import java.io.IOException;
import java.net.BindException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Map;

import cn.net.caoyao.cpzshandset.bean.UploadBean;
import cn.net.caoyao.cpzshandset.common.config.Config;
import cn.net.caoyao.cpzshandset.common.config.HandsetOperation;
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.caoyao.cpzshandset.common.util.OnUploadProcessListener;
import cn.net.caoyao.cpzshandset.common.util.UpCarPicture;
import cn.net.caoyao.cpzshandset.db.dal.yunCar.YunCarConfigDal;
import cn.net.caoyao.cpzshandset.service.bll.UploadStatusBll;
import cn.net.cpzslibs.prot.Prot02Logout;
import cn.net.cpzslibs.prot.SocketCreate;
import cn.net.cpzslibs.prot.bean.res.ProtStatusResBean;
import cn.net.cpzslibs.prot.handset.bean.req.Prot20062ReqBean;
import cn.net.cpzslibs.prot.handset.newProt.Prot20062YunCarSale;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class YunCarUpAllSaleInFo implements Runnable {
	private long deviceId;
	private Handler mHandler;
	private YunCarConfigDal canConfigDal;
	//private String url = "https://www.cpzs.org/UpFromAndroid?key="; 
	//private String url = "http://218.245.0.109:8080/jymf/UpFromAndroid?key="; // 图片测试连接
	private String url = Config.urlPicture; // 图片测试连接
	private int resPic = 1;
	private int option_type = HandsetOperation.OPERATION_SALE_CONSTANT
			.getOption();
	private UploadStatusBll uploadStatusBll;
	public YunCarUpAllSaleInFo(Handler mHandler, long deviceId,
			YunCarConfigDal canConfigDal,UploadStatusBll uploadStatusBll) {
		this.mHandler = mHandler;
		this.deviceId = deviceId;
		this.canConfigDal = canConfigDal;
		this.uploadStatusBll = uploadStatusBll;
	}

	@Override
	public void run() {
		SocketCreate create = new SocketCreate(Config.ip, Config.port, "");
		try {
			LogUtil.d(TConfig.Echo, "登录");

			create.createLoginCpzsHandset(deviceId);

			if (create.isResult()) {
				UpCarSaleList(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 UpCarSaleList(SocketCreate create) throws IOException {
		Prot20062YunCarSale p62 = new Prot20062YunCarSale();
		List<Map<String, String>> list = canConfigDal.querySaleInfo();
		Prot20062ReqBean reqBean = null;
		List<Integer> out_id = null;
		String car_number="";
		String car_date="" ;
		for (int i = 0; i < list.size(); i++) {
			car_number = list.get(i).get("car_no");
			String engine_number =list.get(i).get("engine_number");
			String vin =list.get(i).get("vin");
			String mobile  =  list.get(i).get("client_tel");
			String label_id = list.get(i).get("label_id");
			car_date = list.get(i).get("carNodate");
			
			out_id = canConfigDal.querySaleOutId(car_number, car_date);
			reqBean = new Prot20062ReqBean(car_number, engine_number, vin, mobile, label_id, out_id);
			
			p62.submitActivateInfo(create, reqBean);

		}
		ProtStatusResBean res = p62.getResBean();
		if (res.getResult() != 0) {
			// 请求失败
			canConfigDal.upErrCode(Config.SUBMIT_STATUS_SUBMIT_FAIL,
					res.getErrcode() + "", list.get(0).get("car_no"));
			Message msg = mHandler.obtainMessage();
			msg.what = RequestConstant.REQUEST_YUNCAR_LIST_FAIL;
			msg.obj = res;
			mHandler.sendMessage(msg);
			return;
		}

		if (!canConfigDal.querySaleInfoPictrueCount()) {// 有图片开始传图片
			String path = canConfigDal.querySaleInfoPictrue();
			String label = list.get(0).get("label_id");
			if (!"".equals(path) || null != path) {
				upPic(create, label, path);
			}

			if (resPic == 0) {// 图片上传成功 有图片成功。
				uploadStatusBll.insertUploadStatus(getUploadBean());
				canConfigDal.deleteAllSaleInfo();
				canConfigDal.deleteSaleInfoCarNoID(car_number, car_date);
				mHandler.sendEmptyMessage(RequestConstant.REQUEST_YUNCAR_LIST__SUCCESS);
			} else {// 图片上传失败
			// String errCode = "51"+ String.valueOf(resPic);
				String errCode = String.valueOf(resPic);
				canConfigDal.upErrCode(Config.SUBMIT_STATUS_PIC_SUBMIT_FAIL,
						errCode + "", list.get(0).get("car_no"));
				Message msg = mHandler.obtainMessage();
				msg.what = RequestConstant.REQUEST_YUNCAR_LIST_FAIL;
				msg.obj = res;
				mHandler.sendMessage(msg);
			}

		} else {// 无图片 直接报错
			/*uploadStatusBll.insertUploadStatus(getUploadBean());
			canConfigDal.deleteAllSaleInfo();*/
			
			String errCode = String.valueOf(resPic);
			canConfigDal.upErrCode(Config.SUBMIT_STATUS_PIC_SUBMIT_FAIL,
					errCode + "", list.get(0).get("car_no"));
			Message msg = mHandler.obtainMessage();
			msg.what = RequestConstant.REQUEST_YUNCAR_LIST_FAIL;
			msg.obj = res;
			mHandler.sendMessage(msg);
		}

	}

	private void upPic(SocketCreate create, String label_Id, String imaPtah) {

		UpCarPicture.getInstance().setOnUploadProcessListener(
				new OnUploadProcessListener() {

					@Override
					public void onUploadProcess(int uploadSize) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onUploadDone(int responseCode, String message) {

						if (responseCode == UpCarPicture.SUCCESS) {// 上传图片成功
							resPic = 0;
							canConfigDal.deleteAllSaleInfoPicture();
						} else {
							// canConfigDal.deleteAllSaleInfoPicture();
							resPic = responseCode;
						}

					}

					@Override
					public void initUpload(int fileSize) {
						// TODO Auto-generated method stub

					}
				});

	
		//companyId_document_labelId
		String key = create.getiCompanyId() + "_document_" + label_Id;
		Log.d("--==tag", "--==key" + key + "----url" + url);
		UpCarPicture.getInstance().uploadFile(
				key, imaPtah, "image", url+key);

	}

	private UploadBean getUploadBean() {
		UploadBean b = new UploadBean();

		b.setLabel_count(1);

		b.setOption_type(option_type);
		return b;
	}

}
